Example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter getCertificate

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter getCertificate

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter getCertificate.

Prototype

public X509Certificate getCertificate(X509CertificateHolder certHolder) throws CertificateException 

Source Link

Document

Use the configured converter to produce a X509Certificate object from a X509CertificateHolder object.

Usage

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates.
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate
 * CA certificate//from  www .  j  a v  a2 s . c om
 * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification
 * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path
 * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.)
 * @return an intermediate CA certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateIntermediateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";

    //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName());
    final X500Name issuer = new X500Name(
            StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName()));
    final UUID intermediateUUID = UUID.randomUUID();
    // provide items to X500Principal in reverse order
    final X500Principal x500Principal = new X500Principal(
            "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org");
    final X500Name subject = new X500Name(x500Principal.getName());
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(myPublicKey.getEncoded()));
    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            subject, publicKeyInfo);

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(pathLengthConstraint)); // is a CA certificate with specified certification path length

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
            // certificates
            KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                   // information
                    KeyUsage.cRLSign);

    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }

    return x509Certificate;
}

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication
 * and for message signing.//from  w  w  w  .jav  a 2  s  .  c om
 *
 * @param myPublicKey the public key for this certificate
 * @param issuerPrivateKey the issuer's private key
 * @param issuerCertificate the issuer's certificate
 * @param uid the subject UID
 * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime
 * @return a signed end-use certificate
 *
 * @throws CertificateParsingException when the certificate cannot be parsed
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 */
public static X509Certificate generateX509Certificate(final PublicKey myPublicKey,
        final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid,
        final String domainComponent)
        throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert myPublicKey != null : "myPublicKey must not be null";
    assert issuerPrivateKey != null : "issuerPrivateKey must not be null";
    assert issuerCertificate != null : "issuerCertificate must not be null";
    assert uid != null : "uid must not be null";

    final String x500PrincipalString;
    // provide items to X500Principal in reverse order
    if (domainComponent == null || domainComponent.isEmpty()) {
        x500PrincipalString = "UID=" + uid + ", CN=texai.org";
    } else {
        x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org";
    }
    final X500Principal x500Principal = new X500Principal(x500PrincipalString);

    LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName());

    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(StringUtils
                    .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            new X500Name(x500Principal.getName()), // subject,
            new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    // Add authority key identifier
    x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate));

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(false)); // is not a CA certificate

    // add key usage
    final KeyUsage keyUsage = new KeyUsage(
            // the digitalSignature usage indicates that the subject public key may be used with a digital signature
            // mechanism to support security services other than non-repudiation, certificate signing, or revocation
            // information signing
            KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures
                                        // used to provide a non-repudiation service which protects against the signing entity falsely denying some
                                        // action, excluding certificate or CRL signing
                    KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the
                                              // exchange of efficient symmetric keys in SSL
                    KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data,
                                               // other than cryptographic keys
                    KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a
                                                // Diffie-Hellman key is to be used for key management
                    KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
                                            // certificates
                    KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                           // information
                    KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL
                                       // client authorization
                    KeyUsage.encipherOnly);
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate x509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey);
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        x509Certificate = makeCanonicalX509Certificate(
                jcaX509CertificateConverter.getCertificate(x509CertificateHolder));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        x509Certificate.checkValidity();
        x509Certificate.verify(issuerCertificate.getPublicKey());
    } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new TexaiException(ex);
    }
    assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage";

    return x509Certificate;
}

From source file:org.texai.x509.X509Utils.java

License:Open Source License

/** Generates a self-signed certificate to use as a CA root certificate.
 *
 * @param keyPair the root public/private key pair
 * @return a self-signed CA root certificate
 *
 * @throws CertificateEncodingException when the certificate cannot be encoded
 * @throws NoSuchProviderException when an invalid provider is given
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws SignatureException when the an invalid signature is present
 * @throws InvalidKeyException when the given key is invalid
 * @throws IOException if an input/output error occurs while processing the serial number file
 *///from   w ww  .  jav a  2s.co m
protected static X509Certificate generateRootX509Certificate(final KeyPair keyPair)
        throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, IOException {
    //Preconditions
    assert keyPair != null : "keyPair must not be null";

    final UUID rootUUID = UUID.randomUUID();
    // provide items to X500Principal in reverse order
    final X500Principal rootX500Principal = new X500Principal(
            "UID=" + rootUUID + ", O=Texai Certification Authority, CN=texai.org");
    final X500Name subject = new X500Name(rootX500Principal.getName());
    final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
            new X500Name(rootX500Principal.getName()), // issuer,
            getNextSerialNumber(), // serial
            new Date(System.currentTimeMillis() - 10000L), // notBefore,
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter,
            subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()))); // publicKeyInfo

    // see http://www.ietf.org/rfc/rfc3280.txt
    // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication
    final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils();

    // Add subject key identifier
    x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical
            jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyPair.getPublic()));

    // add basic constraints
    x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical
            new BasicConstraints(true)); // is a CA certificate with an unlimited certification path length

    final KeyUsage keyUsage = new KeyUsage(
            // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on
            // certificates
            KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation
                                   // information
                    KeyUsage.cRLSign);

    // add key usage
    x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical
            keyUsage);

    X509Certificate rootX509Certificate;
    try {
        final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM)
                .setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate());
        final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);
        final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
        rootX509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder);
    } catch (CertificateException | OperatorCreationException ex) {
        throw new TexaiException(ex);
    }

    //Postconditions
    try {
        rootX509Certificate.checkValidity();
        rootX509Certificate.verify(keyPair.getPublic());

        return rootX509Certificate;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException
            | CertificateException ex) {
        throw new TexaiException(ex);
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests the behaviour when certificate exception occurs when verifying", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateCertificateFromCSR3() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //Prepare mock objects
    JcaX509CertificateConverter mock = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock);
    Mockito.when(mock.getCertificate(Matchers.any(X509CertificateHolder.class)))
            .thenThrow(new CertificateException());
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withAnyArguments().thenReturn(mock);
    //prepare input parameters
    CSRGenerator csrGeneration = new CSRGenerator();
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
    byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
    PKCS10CertificationRequest certificationRequest;
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
    certificationRequest = new PKCS10CertificationRequest(csrData);
    generator.generateCertificateFromCSR(privateKeyCA, certificationRequest,
            certCA.getIssuerX500Principal().getName());

}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when the Certificate provider does not exist", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateX509Certificate1() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //prepare mock objects
    X509Certificate mock = Mockito.mock(X509Certificate.class);
    PowerMockito.doThrow(new NoSuchProviderException()).when(mock).verify(Matchers.any());
    JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
    Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
    generator.generateX509Certificate();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when the Certificate Algorithm does not exist", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateX509Certificate2() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //prepare mock objects
    X509Certificate mock = Mockito.mock(X509Certificate.class);
    PowerMockito.doThrow(new NoSuchAlgorithmException()).when(mock).verify(Matchers.any());
    JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
    Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
    generator.generateX509Certificate();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when the Signature validation fails", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateX509Certificate3() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //prepare mock objects
    X509Certificate mock = Mockito.mock(X509Certificate.class);
    PowerMockito.doThrow(new SignatureException()).when(mock).verify(Matchers.any());
    JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
    Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
    generator.generateX509Certificate();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when the Certificate exception occurs", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateX509Certificate4() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //prepare mock objects
    X509Certificate mock = Mockito.mock(X509Certificate.class);
    PowerMockito.doThrow(new CertificateException()).when(mock).verify(Matchers.any());
    JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
    Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
    generator.generateX509Certificate();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when the Certificate key is invalid", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateX509Certificate5() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //prepare mock objects
    X509Certificate mock = Mockito.mock(X509Certificate.class);
    PowerMockito.doThrow(new InvalidKeyException()).when(mock).verify(Matchers.any());
    JcaX509CertificateConverter conv = Mockito.mock(JcaX509CertificateConverter.class);
    Mockito.when(conv.setProvider(Mockito.anyString())).thenReturn(conv);
    Mockito.when(conv.getCertificate(Mockito.any())).thenReturn(mock);
    PowerMockito.whenNew(JcaX509CertificateConverter.class).withNoArguments().thenReturn(conv);
    generator.generateX509Certificate();
}

From source file:uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateGenerator.java

License:Apache License

public X509Certificate generateJca(String cn, String[] sans) {
    try {//from  w  w  w.  j  av  a  2s.c  om
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
        X509CertificateHolder certificate = generate(cn, sans);
        return converter.getCertificate(certificate);
    } catch (CertificateException ex) {
        throw new CertificateGenerationException(ex);
    }
}