Example usage for org.bouncycastle.jce PKCS10CertificationRequest getPublicKey

List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest getPublicKey

Introduction

In this page you can find the example usage for org.bouncycastle.jce PKCS10CertificationRequest getPublicKey.

Prototype

public PublicKey getPublicKey(String provider)
            throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException 

Source Link

Usage

From source file:chapter6.PKCS10CertCreateExample.java

public static X509Certificate[] buildChain() throws Exception {
    // Create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // Create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // Validate the certification request
    if (request.verify("BC") == false) {
        System.out.println("Request failed to verify!!");
        System.exit(1);/*from   w  w  w  .  j  a  v a2 s.com*/
    }

    // Create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded()));
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // Extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i < attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // Process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java

License:Apache License

public static X509Certificate[] buildChain() throws Exception {
    // create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);//from  w ww  .j  a  v a 2s .  c  o m
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:io.aos.crypto.spl08.CertReqSolution.java

License:Apache License

public static void main(String... args) throws Exception {
    // create the CA certificates
    X500PrivateCredential rootCredential = Utils.createRootCredential();
    X500PrivateCredential interCredential = Utils.createIntermediateCredential(rootCredential.getPrivateKey(),
            rootCredential.getCertificate());

    // parse the request
    PEMReader pRd = new PEMReader(new InputStreamReader(new FileInputStream("pkcs10.req")));

    PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();

    // get our validation certificate
    X509Certificate caCert = interCredential.getCertificate();

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // provide some basic extensions and mark the certificate as appropriate for signing and encipherment
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    // create the chain
    List chain = Arrays/*from www  .ja va 2 s  . co m*/
            .asList(new Certificate[] { certGen.generateX509Certificate(interCredential.getPrivateKey(), "BC"),
                    interCredential.getCertificate(), rootCredential.getCertificate() });

    // create the CertPath
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    CertPath path = fact.generateCertPath(chain);

    // write it out
    FileOutputStream fOut = new FileOutputStream("pkcs7.pth");

    fOut.write(path.getEncoded("PKCS7"));

    fOut.close();
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

License:Mozilla Public License

/**
 * Handles the nitty gritty of signing a CSR
 *
 * @param rootCert The certificate of the root authority who will vouch for the entity
 * @param rootPrivKey The private key of the root authority who will vouch for the entity
 * @param csr The entitie's CSR//from www . j  a  va  2s  .c  o m
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return A certificate chain as an array of X509Certificate instances or null if an
 * error occurred
 */
private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey,
        PKCS10CertificationRequest csr, String keyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    try {
        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(rootCert.getSubjectX500Principal());
        certGen.setNotBefore(validFrom);
        certGen.setNotAfter(validTo);
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setPublicKey(csr.getPublicKey("BC"));

        if (keyType.toLowerCase().equals("rsa"))
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        if (keyType.toLowerCase().equals("dsa"))
            certGen.setSignatureAlgorithm("DSAWithSHA1");

        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(rootCert));
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

        X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC");
        return new X509Certificate[] { issuedCert, rootCert };
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

License:Open Source License

protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException {
    X509Certificate cert;/*ww w.  j  a  v a  2s  . c o m*/
    try {
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal());
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setNotBefore(getCertStartDate());
        certGen.setNotAfter(getCertEndDate());
        certGen.setPublicKey(csr.getPublicKey("BC"));
        certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM);
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(getRootCertificate()));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

        ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
        for (int i = 0; i != attributes.size(); i++) {
            Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
            if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                @SuppressWarnings("rawtypes")
                Enumeration e = extensions.oids();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    X509Extension ext = extensions.getExtension(oid);
                    certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
                }
            }
        }

        KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(),
                rootService.getRootCertificateAlias(), rootService.getRootKeyPassword());
        cert = certGen.generate(rootKeyPair.getPrivate(), "BC");
    } catch (CertificateParsingException e) {
        throw new CertException(e);
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    }
    LOG.debug("Certificate generated for subject: " + cert.getSubjectDN());
    return cert;
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * generates new certificate chain and returns it..
 * first certificate in the returned chain is the issued certificate and the second one is CA certificate
 * /*from   www  .ja  v a2  s .  co m*/
 * @return certificates 
 * @throws Exception
 */
public static X509Certificate[] createCertificateChain() throws Exception {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    // create the keys
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair pair = keyGen.generateKeyPair();

    X509Certificate rootCert = generateRootCertificate(pair);

    //Create certificate request
    PKCS10CertificationRequest request = createCertificateRequest();

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    X509Certificate issuedCert = certGen.generate(pair.getPrivate());
    X509Certificate[] chain = { issuedCert, rootCert };

    //Write certificates to file so we are able to retrieve the also te private key
    /* URL certURL = CertificateUtils.class.getResource( "createdCerts.pem" );
             
     URLConnection connection = certURL.openConnection();
    InputStream is = connection.getInputStream();
     CertificateFactory servercf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) servercf.generateCertificate(is);
            
    PEMWriter        testWriter = new PEMWriter(new OutputStreamWriter(System.out));
    testWriter.writeObject(cert);*/
    return chain;
}