Search in sources :

Example 11 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames in project Openfire by igniterealtime.

the class CertificateManagerTest method testServerIdentitiesXmppAddr.

/**
 * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
 * <ul>
 *     <li>the 'xmppAddr' subjectAltName value</li>
 *     <li>explicitly not the Common Name</li>
 * </ul>
 *
 * when a certificate contains:
 * <ul>
 *     <li>a subjectAltName entry of type otherName with an ASN.1 Object Identifier of "id-on-xmppAddr"</li>
 * </ul>
 */
@Test
public void testServerIdentitiesXmppAddr() throws Exception {
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameXmppAddr = "MySubjectAltNameXmppAddr";
    final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// Issuer
    new X500Name("CN=MyIssuer"), // Random serial number
    BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), // Not before 30 days ago
    new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30)), // Not after 99 days from now
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99)), // Subject
    new X500Name("CN=" + subjectCommonName), subjectKeyPair.getPublic());
    final DERSequence otherName = new DERSequence(new ASN1Encodable[] { XMPP_ADDR_OID, new DERUTF8String(subjectAltNameXmppAddr) });
    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, otherName));
    builder.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
    final X509CertificateHolder certificateHolder = builder.build(contentSigner);
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    // Execute system under test
    final List<String> serverIdentities = CertificateManager.getServerIdentities(cert);
    // Verify result
    assertEquals(1, serverIdentities.size());
    assertTrue(serverIdentities.contains(subjectAltNameXmppAddr));
    assertFalse(serverIdentities.contains(subjectCommonName));
}
Also used : SecureRandom(java.security.SecureRandom) 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) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Test(org.junit.Test)

Example 12 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames 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 13 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames 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 14 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames 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 15 with GeneralNames

use of com.github.zhenwei.core.asn1.x509.GeneralNames 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

GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)140 GeneralName (org.bouncycastle.asn1.x509.GeneralName)124 IOException (java.io.IOException)68 X509Certificate (java.security.cert.X509Certificate)46 X500Name (org.bouncycastle.asn1.x500.X500Name)45 ContentSigner (org.bouncycastle.operator.ContentSigner)41 ArrayList (java.util.ArrayList)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)40 BigInteger (java.math.BigInteger)33 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)32 List (java.util.List)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)27 Date (java.util.Date)26 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)26 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)25 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)23 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)23 X500Principal (javax.security.auth.x500.X500Principal)22 DERIA5String (org.bouncycastle.asn1.DERIA5String)20