Search in sources :

Example 66 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project robovm by robovm.

the class X509CRLEntryObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("      userCertificate: ").append(this.getSerialNumber()).append(nl);
    buf.append("       revocationDate: ").append(this.getRevocationDate()).append(nl);
    buf.append("       certificateIssuer: ").append(this.getCertificateIssuer()).append(nl);
    Extensions extensions = c.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("   crlEntryExtensions:").append(nl);
            while (e.hasMoreElements()) {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                Extension ext = extensions.getExtension(oid);
                if (ext.getExtnValue() != null) {
                    byte[] octs = ext.getExtnValue().getOctets();
                    ASN1InputStream dIn = new ASN1InputStream(octs);
                    buf.append("                       critical(").append(ext.isCritical()).append(") ");
                    try {
                        if (oid.equals(X509Extension.reasonCode)) {
                            buf.append(CRLReason.getInstance(ASN1Enumerated.getInstance(dIn.readObject()))).append(nl);
                        } else if (oid.equals(X509Extension.certificateIssuer)) {
                            buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl);
                        } else {
                            buf.append(oid.getId());
                            buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                        }
                    } catch (Exception ex) {
                        buf.append(oid.getId());
                        buf.append(" value = ").append("*****").append(nl);
                    }
                } else {
                    buf.append(nl);
                }
            }
        }
    }
    return buf.toString();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) X509Extension(org.bouncycastle.asn1.x509.X509Extension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) Extensions(org.bouncycastle.asn1.x509.Extensions) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) IOException(java.io.IOException) CRLException(java.security.cert.CRLException)

Example 67 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project zm-mailbox by Zimbra.

the class CertUtil method printCRLDistributionPoints.

private void printCRLDistributionPoints(PrintStream outStream) throws Exception {
    outStream.format("X509v3 CRL Distribution Points: \n");
    // 2.5.29.31
    String extOid = X509Extension.cRLDistributionPoints.getId();
    byte[] extVal = cert.getExtensionValue(extOid);
    if (extVal == null) {
        return;
    }
    /* http://download.oracle.com/javase/6/docs/api/java/security/cert/X509Extension.html#getExtensionValue(java.lang.String)
         *
           The ASN.1 definition for this is:

             Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension

             Extension  ::=  SEQUENCE  {
                 extnId        OBJECT IDENTIFIER,
                 critical      BOOLEAN DEFAULT FALSE,
                 extnValue     OCTET STRING
                               -- contains a DER encoding of a value
                               -- of the type registered for use with
                               -- the extnId object identifier value
             }
         */
    byte[] extnValue = DEROctetString.getInstance(ASN1Object.fromByteArray(extVal)).getOctets();
    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(ASN1Object.fromByteArray(extnValue));
    DistributionPoint[] distPoints = crlDistPoint.getDistributionPoints();
    for (DistributionPoint distPoint : distPoints) {
        DistributionPointName distPointName = distPoint.getDistributionPoint();
        int type = distPointName.getType();
        if (DistributionPointName.FULL_NAME == type) {
            outStream.format("Full Name: \n");
            GeneralNames generalNames = GeneralNames.getInstance(distPointName.getName());
            GeneralName[] names = generalNames.getNames();
            for (GeneralName generalname : names) {
                int tag = generalname.getTagNo();
                if (GeneralName.uniformResourceIdentifier == tag) {
                    DEREncodable name = generalname.getName();
                    DERIA5String str = DERIA5String.getInstance(name);
                    String value = str.getString();
                    outStream.format("    %s\n", value);
                } else {
                    outStream.format("tag %d not yet implemented", tag);
                }
            }
        } else {
            outStream.format("type %d not yet implemented", type);
        }
    }
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) DEREncodable(org.bouncycastle.asn1.DEREncodable) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 68 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project nifi by apache.

the class CertificateUtils method generateIssuedCertificate.

/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 */
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // (3) subjectAlternativeName
        if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Example 69 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project nifi by apache.

the class TlsToolkitStandalone method createNifiKeystoresAndTrustStores.

public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig) throws GeneralSecurityException, IOException {
    File baseDir = standaloneConfig.getBaseDir();
    if (!baseDir.exists() && !baseDir.mkdirs()) {
        throw new IOException(baseDir + " doesn't exist and unable to create it.");
    }
    if (!baseDir.isDirectory()) {
        throw new IOException("Expected directory to output to");
    }
    String signingAlgorithm = standaloneConfig.getSigningAlgorithm();
    int days = standaloneConfig.getDays();
    String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm();
    int keySize = standaloneConfig.getKeySize();
    File nifiCert = new File(baseDir, NIFI_CERT + ".pem");
    File nifiKey = new File(baseDir, NIFI_KEY + ".key");
    X509Certificate certificate;
    KeyPair caKeyPair;
    if (logger.isInfoEnabled()) {
        logger.info("Running standalone certificate generation with output directory " + baseDir);
    }
    if (nifiCert.exists()) {
        if (!nifiKey.exists()) {
            throw new IOException(nifiCert + " exists already, but " + nifiKey + " does not, we need both certificate and key to continue with an existing CA.");
        }
        try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) {
            certificate = TlsHelper.parseCertificate(pemEncodedCertificate);
        }
        try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) {
            caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair);
        }
        certificate.verify(caKeyPair.getPublic());
        if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) {
            throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert);
        }
        if (logger.isInfoEnabled()) {
            logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey);
        }
    } else if (nifiKey.exists()) {
        throw new IOException(nifiKey + " exists already, but " + nifiCert + " does not, we need both certificate and key to continue with an existing CA.");
    } else {
        TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager(standaloneConfig);
        KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager.getOrGenerateCertificateAuthority();
        certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0];
        caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey());
        try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(certificate));
        }
        try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) {
            pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair));
        }
        if (logger.isInfoEnabled()) {
            logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey);
        }
    }
    NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory();
    boolean overwrite = standaloneConfig.isOverwrite();
    List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions();
    if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG + " specified, not generating any host certificates or configuration.");
    }
    for (InstanceDefinition instanceDefinition : instanceDefinitions) {
        String hostname = instanceDefinition.getHostname();
        File hostDir;
        int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber();
        if (hostIdentifierNumber == 1) {
            hostDir = new File(baseDir, hostname);
        } else {
            hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber);
        }
        TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig);
        File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase());
        File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase());
        if (hostDir.exists()) {
            if (!hostDir.isDirectory()) {
                throw new IOException(hostDir + " exists but is not a directory.");
            } else if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting any existing ssl configuration in " + hostDir);
                }
                keystore.delete();
                if (keystore.exists()) {
                    throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted.");
                }
                truststore.delete();
                if (truststore.exists()) {
                    throw new IOException("Truststore " + truststore + " already exists and couldn't be deleted.");
                }
            } else {
                throw new IOException(hostDir + " exists and overwrite is not set.");
            }
        } else if (!hostDir.mkdirs()) {
            throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath());
        } else if (logger.isInfoEnabled()) {
            logger.info("Writing new ssl configuration to " + hostDir);
        }
        tlsClientConfig.setKeyStore(keystore.getAbsolutePath());
        tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword());
        tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword());
        tlsClientConfig.setTrustStore(truststore.getAbsolutePath());
        tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword());
        TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig);
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        Extensions sanDnsExtensions = TlsHelper.createDomainAlternativeNamesExtensions(tlsClientConfig.getDomainAlternativeNames(), tlsClientConfig.calcDefaultDn(hostname));
        tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY, CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname), keyPair.getPublic(), sanDnsExtensions, certificate, caKeyPair, signingAlgorithm, days), certificate);
        tlsClientManager.setCertificateEntry(NIFI_CERT, certificate);
        tlsClientManager.addClientConfigurationWriter(new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory, new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber()));
        tlsClientManager.write(outputStreamFactory);
        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber + " in " + hostDir);
        }
    }
    List<String> clientDns = standaloneConfig.getClientDns();
    if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) {
        logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG + " specified, not generating any client certificates.");
    }
    List<String> clientPasswords = standaloneConfig.getClientPasswords();
    for (int i = 0; i < clientDns.size(); i++) {
        String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i));
        String clientDnFile = getClientDnFile(reorderedDn);
        File clientCertFile = new File(baseDir, clientDnFile + ".p12");
        if (clientCertFile.exists()) {
            if (overwrite) {
                if (logger.isInfoEnabled()) {
                    logger.info("Overwriting existing client cert " + clientCertFile);
                }
            } else {
                throw new IOException(clientCertFile + " exists and overwrite is not set.");
            }
        } else if (logger.isInfoEnabled()) {
            logger.info("Generating new client certificate " + clientCertFile);
        }
        KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
        X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn, keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days);
        KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString());
        keyStore.load(null, null);
        keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null, new Certificate[] { clientCert, certificate });
        String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile, clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated());
        try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) {
            fileWriter.write(password);
        }
        if (logger.isInfoEnabled()) {
            logger.info("Successfully generated client certificate " + clientCertFile);
        }
    }
    if (logger.isInfoEnabled()) {
        logger.info("tls-toolkit standalone completed successfully");
    }
}
Also used : InstanceDefinition(org.apache.nifi.toolkit.tls.configuration.InstanceDefinition) KeyPair(java.security.KeyPair) TlsClientManager(org.apache.nifi.toolkit.tls.manager.TlsClientManager) PemWriter(org.bouncycastle.util.io.pem.PemWriter) FileWriter(java.io.FileWriter) IOException(java.io.IOException) TlsCertificateAuthorityManager(org.apache.nifi.toolkit.tls.manager.TlsCertificateAuthorityManager) Extensions(org.bouncycastle.asn1.x509.Extensions) NiFiPropertiesWriterFactory(org.apache.nifi.toolkit.tls.properties.NiFiPropertiesWriterFactory) NifiPropertiesTlsClientConfigWriter(org.apache.nifi.toolkit.tls.manager.writer.NifiPropertiesTlsClientConfigWriter) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) TlsClientConfig(org.apache.nifi.toolkit.tls.configuration.TlsClientConfig) FileReader(java.io.FileReader) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 70 with Extensions

use of org.openecard.bouncycastle.asn1.x509.Extensions in project nifi by apache.

the class TlsHelperTest method extractSanFromCsr.

private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }
    return sans;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)55 Extension (org.bouncycastle.asn1.x509.Extension)52 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)44 DEROctetString (org.bouncycastle.asn1.DEROctetString)37 IOException (java.io.IOException)36 HashSet (java.util.HashSet)33 Enumeration (java.util.Enumeration)30 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 Date (java.util.Date)23 X500Name (org.bouncycastle.asn1.x500.X500Name)23 Set (java.util.Set)21 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)21 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)21 GeneralName (org.bouncycastle.asn1.x509.GeneralName)21 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)20 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)20 BigInteger (java.math.BigInteger)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 CertificateException (java.security.cert.CertificateException)17 X509Certificate (java.security.cert.X509Certificate)17