Search in sources :

Example 1 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project kafka by apache.

the class TestSslUtils method generateCertificate.

/**
     * Create a self-signed X.509 Certificate.
     * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
     *
     * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
     * @param pair the KeyPair
     * @param days how many days from now the Certificate is valid for
     * @param algorithm the signing algorithm, eg "SHA1withRSA"
     * @return the self-signed certificate
     * @throws CertificateException thrown if a security error or an IO error occurred.
     */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException {
    try {
        Security.addProvider(new BouncyCastleProvider());
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
        X500Name name = new X500Name(dn);
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000L);
        BigInteger sn = new BigInteger(64, new SecureRandom());
        X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
        X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    } catch (CertificateException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CertificateException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EOFException(java.io.EOFException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 2 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project Openfire by igniterealtime.

the class CertificateManagerTest method testServerIdentitiesCommonNameOnly.

/**
     * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
     * <ul>
     *     <li>the Common Name</li>
     * </ul>
     *
     * when a certificate contains:
     * <ul>
     *     <li>no other identifiers than its CommonName</li>
     * </ul>
     */
@Test
public void testServerIdentitiesCommonNameOnly() throws Exception {
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    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 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());
    assertEquals(subjectCommonName, serverIdentities.get(0));
}
Also used : 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) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 3 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder 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) Date(java.util.Date) 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 4 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project Openfire by igniterealtime.

the class CertificateManagerTest method testServerIdentitiesDNS.

/**
     * {@link CertificateManager#getServerIdentities(X509Certificate)} should return:
     * <ul>
     *     <li>the DNS subjectAltName value</li>
     *     <li>explicitly not the Common Name</li>
     * </ul>
     *
     * when a certificate contains:
     * <ul>
     *     <li>a subjectAltName entry of type DNS </li>
     * </ul>
     */
@Test
public void testServerIdentitiesDNS() throws Exception {
    // Setup fixture.
    final String subjectCommonName = "MySubjectCommonName";
    final String subjectAltNameDNS = "MySubjectAltNameDNS";
    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 GeneralNames generalNames = new GeneralNames(new GeneralName(GeneralName.dNSName, subjectAltNameDNS));
    builder.addExtension(Extension.subjectAlternativeName, false, generalNames);
    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(subjectAltNameDNS));
    assertFalse(serverIdentities.contains(subjectCommonName));
}
Also used : 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) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 5 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project Openfire by igniterealtime.

the class OCSPChecker method check.

@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
    Log.debug("OCSPChecker: check called");
    InputStream in = null;
    OutputStream out = null;
    try {
        // Examine OCSP properties
        X509Certificate responderCert = null;
        //defaults to issuers cert
        boolean haveResponderCert = true;
        X500Principal responderSubjectName = null;
        boolean haveIssuerCert = false;
        // If we set the subject name, we need to find the certificate
        if (ocspServerSubject != null) {
            haveResponderCert = false;
            responderSubjectName = new X500Principal(ocspServerSubject);
        }
        X509Certificate issuerCert = null;
        X509Certificate currCert = (X509Certificate) cert;
        // Set the issuer certificate if we were passed a chain
        if (certIndex != 0) {
            issuerCert = certs[certIndex];
            haveIssuerCert = true;
            if (haveResponderCert) {
                responderCert = certs[certIndex];
            }
        }
        if (!haveIssuerCert || !haveResponderCert) {
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Looking for responder's certificate");
            }
            if (!haveIssuerCert) {
                Log.debug("OCSPChecker: Looking for issuer's certificate");
            }
            // Extract the anchor certs
            Iterator anchors = pkixParams.getTrustAnchors().iterator();
            if (!anchors.hasNext()) {
                throw new CertPathValidatorException("Must specify at least one trust anchor");
            }
            X500Principal certIssuerName = currCert.getIssuerX500Principal();
            while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
                TrustAnchor anchor = (TrustAnchor) anchors.next();
                X509Certificate anchorCert = anchor.getTrustedCert();
                X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
                // Check if this anchor cert is the issuer cert
                if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
                    issuerCert = anchorCert;
                    haveIssuerCert = true;
                    //If we have not set the responderCert at this point, set it to the issuer
                    if (haveResponderCert && responderCert == null) {
                        responderCert = anchorCert;
                        Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
                    }
                }
                // Check if this anchor cert is the responder cert
                if (!haveResponderCert) {
                    if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
                        responderCert = anchorCert;
                        haveResponderCert = true;
                    }
                }
            }
            if (issuerCert == null) {
                //No trust anchor was found matching the issuer
                throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
            }
            // Check cert stores if responder cert has not yet been found
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
                if (responderSubjectName != null) {
                    X509CertSelector filter = new X509CertSelector();
                    filter.setSubject(responderSubjectName.getName());
                    List<CertStore> certStores = pkixParams.getCertStores();
                    for (CertStore certStore : certStores) {
                        Iterator i = certStore.getCertificates(filter).iterator();
                        if (i.hasNext()) {
                            responderCert = (X509Certificate) i.next();
                            haveResponderCert = true;
                            break;
                        }
                    }
                }
            }
        }
        // Could not find the responder cert
        if (!haveResponderCert) {
            throw new CertPathValidatorException("Cannot find the responder's certificate.");
        }
        // Construct an OCSP Request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
        gen.addRequest(certID);
        OCSPReq ocspRequest = gen.build();
        URL url;
        if (ocspServerUrl != null) {
            try {
                url = new URL(ocspServerUrl);
            } catch (MalformedURLException e) {
                throw new CertPathValidatorException(e);
            }
        } else {
            throw new CertPathValidatorException("Must set OCSP Server URL");
        }
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        byte[] bytes = ocspRequest.getEncoded();
        con.setRequestProperty("Content-length", String.valueOf(bytes.length));
        out = con.getOutputStream();
        out.write(bytes);
        out.flush();
        // Check the response
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
        }
        in = con.getInputStream();
        OCSPResp ocspResponse = new OCSPResp(in);
        BigInteger serialNumber = currCert.getSerialNumber();
        BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
        try {
            if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
                throw new CertPathValidatorException("OCSP response is not verified");
            }
        } catch (Exception e) {
            throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
        }
        SingleResp[] singleResp = brep.getResponses();
        boolean foundResponse = false;
        for (SingleResp resp : singleResp) {
            CertificateID respCertID = resp.getCertID();
            if (respCertID.equals(certID)) {
                Object status = resp.getCertStatus();
                if (status == CertificateStatus.GOOD) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
                    foundResponse = true;
                    break;
                } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
                    throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
                } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
                    throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
                } else {
                    Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
                    throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
                }
            }
        }
        // Check that response applies to the cert that was supplied
        if (!foundResponse) {
            throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
        }
    } catch (CertPathValidatorException cpve) {
        throw cpve;
    } catch (Exception e) {
        throw new CertPathValidatorException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) OutputStream(java.io.OutputStream) X509CertSelector(java.security.cert.X509CertSelector) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) HttpURLConnection(java.net.HttpURLConnection) Iterator(java.util.Iterator) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) InputStream(java.io.InputStream) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) TrustAnchor(java.security.cert.TrustAnchor) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidatorException(java.security.cert.CertPathValidatorException) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CertStore(java.security.cert.CertStore)

Aggregations

X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)29 X509Certificate (java.security.cert.X509Certificate)19 X500Name (org.bouncycastle.asn1.x500.X500Name)18 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)18 Date (java.util.Date)16 BigInteger (java.math.BigInteger)14 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)12 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)12 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)12 IOException (java.io.IOException)11 SecureRandom (java.security.SecureRandom)11 ContentSigner (org.bouncycastle.operator.ContentSigner)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)7 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)7 GeneralSecurityException (java.security.GeneralSecurityException)6 KeyPair (java.security.KeyPair)6 PrivateKey (java.security.PrivateKey)6 CertificateException (java.security.cert.CertificateException)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 Test (org.junit.Test)6