Search in sources :

Example 21 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project Openfire by igniterealtime.

the class CertificateManager method createSigningRequest.

/**
 * Creates and returns the content of a new singing request for the specified certificate. Signing
 * requests are required by Certificate Authorities as part of their signing process. The signing request
 * contains information about the certificate issuer, subject DN, subject alternative names and public key.
 * Private keys are not included. After the Certificate Authority verified and signed the certificate a new
 * certificate is going to be returned.
 *
 * @param cert the certificate to create a signing request.
 * @param privKey the private key of the certificate.
 * @return the content of a new singing request for the specified certificate.
 * @throws OperatorCreationException if there was a problem creating the CSR
 * @throws IOException if there was a problem creating the CSR
 * @throws CertificateParsingException if there was a problem creating the CSR
 */
public static String createSigningRequest(X509Certificate cert, PrivateKey privKey) throws OperatorCreationException, IOException, CertificateParsingException {
    JcaPKCS10CertificationRequestBuilder csrBuilder = new // 
    JcaPKCS10CertificationRequestBuilder(// 
    cert.getSubjectX500Principal(), // 
    cert.getPublicKey());
    // Add SubjectAlternativeNames (SANs)
    final ASN1EncodableVector subjectAlternativeNames = new ASN1EncodableVector();
    final Collection<List<?>> certSans = cert.getSubjectAlternativeNames();
    if (certSans != null) {
        for (final List<?> certSan : certSans) {
            final int nameType = (Integer) certSan.get(0);
            // this is either a string, or a byte-array that represents the ASN.1 DER encoded form.
            final Object value = certSan.get(1);
            switch(nameType) {
                case 0:
                    // OtherName: search for "id-on-xmppAddr" or 'sRVName' or 'userPrincipalName'
                    try (final ASN1InputStream decoder = new ASN1InputStream((byte[]) value)) {
                        // By specification, OtherName instances must always be an ASN.1 Sequence.
                        final ASN1Primitive object = decoder.readObject();
                        final ASN1Sequence otherNameSeq = (ASN1Sequence) object;
                        // By specification, an OtherName instance consists of:
                        // - the type-id (which is an Object Identifier), followed by:
                        // - a tagged value, of which the tag number is 0 (zero) and the value is defined by the type-id.
                        final ASN1ObjectIdentifier typeId = (ASN1ObjectIdentifier) otherNameSeq.getObjectAt(0);
                        final ASN1TaggedObject taggedValue = (ASN1TaggedObject) otherNameSeq.getObjectAt(1);
                        final int tagNo = taggedValue.getTagNo();
                        if (tagNo != 0) {
                            throw new IllegalArgumentException("subjectAltName 'otherName' sequence's second object is expected to be a tagged value of which the tag number is 0. The tag number that was detected: " + tagNo);
                        }
                        subjectAlternativeNames.add(new DERTaggedObject(false, GeneralName.otherName, new DERSequence(new ASN1Encodable[] { typeId, taggedValue })));
                    } catch (Exception e) {
                        Log.warn("Unable to parse certificate SAN 'otherName' value", e);
                    }
                    break;
                case 2:
                    // DNS
                    subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, (String) value));
                    break;
                case 6:
                    // URI
                    subjectAlternativeNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, (String) value));
                    break;
                default:
                    // Not applicable to XMPP, so silently ignore them
                    break;
            }
        }
    }
    final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames));
    final ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    String signatureAlgorithm = "SHA256WITH" + cert.getPublicKey().getAlgorithm();
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);
    PKCS10CertificationRequest csr = csrBuilder.build(signer);
    StringWriter string = new StringWriter();
    PemWriter pemWriter = new PemWriter(string);
    PemObjectGenerator objGen = new MiscPEMGenerator(csr);
    pemWriter.writeObject(objGen);
    pemWriter.close();
    return string.toString();
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemWriter(org.bouncycastle.util.io.pem.PemWriter) ContentSigner(org.bouncycastle.operator.ContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertException(org.bouncycastle.cert.CertException) CertificateParsingException(java.security.cert.CertificateParsingException) PKCSException(org.bouncycastle.pkcs.PKCSException) CertificateException(java.security.cert.CertificateException) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) BigInteger(java.math.BigInteger) JcaMiscPEMGenerator(org.bouncycastle.openssl.jcajce.JcaMiscPEMGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 22 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project neo4j by neo4j.

the class SelfSignedCertificateFactory method createSelfSignedCertificate.

public void createSelfSignedCertificate(Path certificatePath, Path privateKeyPath, String hostName) throws GeneralSecurityException, IOException, OperatorCreationException {
    installCleanupHook(certificatePath, privateKeyPath);
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ENCRYPTION);
    keyGen.initialize(2048, random);
    KeyPair keypair = keyGen.generateKeyPair();
    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + hostName);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(owner, new BigInteger(64, random), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic());
    // Subject alternative name (part of SNI extension, used for hostname verification)
    GeneralNames subjectAlternativeName = new GeneralNames(new GeneralName(GeneralName.dNSName, hostName));
    builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeName);
    PrivateKey privateKey = keypair.getPrivate();
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").build(privateKey);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    // check so that cert is valid
    cert.verify(keypair.getPublic());
    // write to disk
    writePem("CERTIFICATE", cert.getEncoded(), certificatePath);
    writePem("PRIVATE KEY", privateKey.getEncoded(), privateKeyPath);
    // Mark as done so we don't clean up certificates
    cleanupRequired = false;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 23 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project neo4j by neo4j.

the class CertificateChainFactory method generateCertificate.

private static X509Certificate generateCertificate(X509Certificate issuingCert, PrivateKey issuingPrivateKey, KeyPair certKeyPair, String certName, String ocspURL, Path certificatePath, Path keyPath, BouncyCastleProvider bouncyCastleProvider) throws Exception {
    X509v3CertificateBuilder builder;
    if (issuingCert == null) {
        builder = new JcaX509v3CertificateBuilder(// issuer authority
        new X500Name("CN=" + certName), // serial number of certificate
        BigInteger.valueOf(new Random().nextInt()), // start of validity
        NOT_BEFORE, // end of certificate validity
        NOT_AFTER, // subject name of certificate
        new X500Name("CN=" + certName), // public key of certificate
        certKeyPair.getPublic());
    } else {
        builder = new JcaX509v3CertificateBuilder(// issuer authority
        issuingCert, // serial number of certificate
        BigInteger.valueOf(new Random().nextInt()), // start of validity
        NOT_BEFORE, // end of certificate validity
        NOT_AFTER, // subject name of certificate
        new X500Name("CN=" + certName), // public key of certificate
        certKeyPair.getPublic());
    }
    // key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature));
    builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // embed ocsp URI
    builder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(new AccessDescription(AccessDescription.id_ad_ocsp, new GeneralName(GeneralName.uniformResourceIdentifier, ocspURL + "/" + certName))));
    X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(bouncyCastleProvider).build(// self sign if root cert
    issuingPrivateKey == null ? certKeyPair.getPrivate() : issuingPrivateKey)));
    writePem("CERTIFICATE", certificate.getEncoded(), certificatePath);
    writePem("PRIVATE KEY", certKeyPair.getPrivate().getEncoded(), keyPath);
    return certificate;
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) Random(java.util.Random) SecureRandom(java.security.SecureRandom) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 24 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project gitblit by gitblit.

the class X509Utils method newSSLCertificate.

/**
 * Creates a new SSL certificate signed by the CA private key and stored in
 * keyStore.
 *
 * @param sslMetadata
 * @param caPrivateKey
 * @param caCert
 * @param targetStoreFile
 * @param x509log
 */
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
    try {
        KeyPair pair = newKeyPair();
        X500Name webDN = buildDistinguishedName(sslMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        // support alternateSubjectNames for SSL certificates
        List<GeneralName> altNames = new ArrayList<GeneralName>();
        if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
            altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
        }
        if (altNames.size() > 0) {
            GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(caSigner));
        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());
        // Save to keystore
        KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
        serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[] { cert, caCert });
        saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);
        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
        // update serial number in metadata object
        sslMetadata.serialNumber = cert.getSerialNumber().toString();
        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate SSL certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 25 with GeneralName

use of org.mozilla.jss.netscape.security.x509.GeneralName in project oxAuth by GluuFederation.

the class CRLCertificateVerifier method getCrlUri.

public String getCrlUri(X509Certificate certificate) throws IOException {
    ASN1Primitive obj;
    try {
        obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId());
    } catch (IOException ex) {
        log.error("Failed to get CRL URL", ex);
        return null;
    }
    if (obj == null) {
        return null;
    }
    CRLDistPoint distPoint = CRLDistPoint.getInstance(obj);
    DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
    for (DistributionPoint distributionPoint : distributionPoints) {
        DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
        if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
            continue;
        }
        GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
        GeneralName[] names = generalNames.getNames();
        for (GeneralName name : names) {
            if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
                continue;
            }
            DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
            return derStr.getString();
        }
    }
    return null;
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) IOException(java.io.IOException) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)238 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)113 IOException (java.io.IOException)110 ArrayList (java.util.ArrayList)76 DERIA5String (org.bouncycastle.asn1.DERIA5String)53 X500Name (org.bouncycastle.asn1.x500.X500Name)52 X509Certificate (java.security.cert.X509Certificate)51 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)48 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)47 List (java.util.List)40 BigInteger (java.math.BigInteger)37 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)37 DEROctetString (org.bouncycastle.asn1.DEROctetString)36 ContentSigner (org.bouncycastle.operator.ContentSigner)35 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)31 GeneralName (com.github.zhenwei.core.asn1.x509.GeneralName)30 Date (java.util.Date)30 X500Principal (javax.security.auth.x500.X500Principal)29 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)29 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)29