Example usage for org.bouncycastle.cert.bc BcX509ExtensionUtils BcX509ExtensionUtils

List of usage examples for org.bouncycastle.cert.bc BcX509ExtensionUtils BcX509ExtensionUtils

Introduction

In this page you can find the example usage for org.bouncycastle.cert.bc BcX509ExtensionUtils BcX509ExtensionUtils.

Prototype

public BcX509ExtensionUtils() 

Source Link

Document

Create a utility class pre-configured with a SHA-1 digest calculator based on the BC implementation.

Usage

From source file:com.linkedin.mitm.services.AbstractX509CertificateService.java

License:Open Source License

/**
 * Create subjectKeyIdentifier/*from  w  w  w.j av  a 2 s  .  c om*/
 * The Subject Key Identifier extension identifies the public key certified by this certificate.
 * This extension provides a way of distinguishing public keys if more than one is available for
 * a given subject name.
 * i.e.
 *     Identifier: Subject Key Identifier - 2.5.29.14
 *       Critical: no
 *        Key Identifier:
 *          3B:46:83:85:27:BC:F5:9D:8E:63:E3:BE:79:EF:AF:79:
 *          9C:37:85:84
 *
 * */
protected SubjectKeyIdentifier createSubjectKeyIdentifier(PublicKey publicKey) throws IOException {
    try (ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
            ASN1InputStream ais = new ASN1InputStream(bais)) {
        ASN1Sequence asn1Sequence = (ASN1Sequence) ais.readObject();
        SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(asn1Sequence);
        return new BcX509ExtensionUtils().createSubjectKeyIdentifier(subjectPublicKeyInfo);
    }
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

License:Open Source License

/**
 * Returns a {@code SubjectKeyIdentifier} for the received {@code Key}.
 *
 * @param key//  w  w w  .  jav a 2  s .  co m
 *            the key for generating the identifier
 * @return a {@code SubjectKeyIdentifier} for the received {@code Key}
 * @throws IOException
 *             if any problem occurs while reading the key
 */
private final SubjectKeyIdentifier createSubjectKeyIdentifier(final Key key) throws IOException {
    final ASN1Sequence seq; // Sequence for the key info
    ASN1InputStream stream = null; // Stream for reading the key

    try {
        stream = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
        seq = (ASN1Sequence) stream.readObject();
    } finally {
        IOUtils.closeQuietly(stream);
    }

    return new BcX509ExtensionUtils().createSubjectKeyIdentifier(new SubjectPublicKeyInfo(seq));
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to create PKCS12 file that stores the certificates.
 * @param pfxOut: the output of pkcs12 file (in OutputStream) 
 * @param key: private key that is associated with the credential
 * @param chain: chain of certificates (within the credential)
 * @param keyPasswd: key password/*from w w w.  j ava  2 s.  c  om*/
 * @throws Exception
 */
public static void createPKCS12FileBc(OutputStream pfxOut, AsymmetricKeyParameter key,
        X509CertificateHolder[] chain, char[] keyPasswd) throws Exception {

    OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine()))
                    .build(keyPasswd);

    PKCS12SafeBagBuilder taCertBagBuilder = null;
    PKCS12SafeBagBuilder caCertBagBuilder = null;
    PKCS12SafeBagBuilder eeCertBagBuilder = null;
    SubjectKeyIdentifier pubKeyId = null;

    // identify the type of certificate from the given certificate chain
    for (int i = 0; i < chain.length; i++) {
        Extensions exs = chain[i].getExtensions();
        if (exs != null) {
            KeyUsage ku = KeyUsage.fromExtensions(exs);
            if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 32))) {
                // end entity certificate
                eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
                BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils();
                eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                        new DERBMPString("Eric's Key"));
                pubKeyId = extUtils.createSubjectKeyIdentifier(chain[i].getSubjectPublicKeyInfo());
                eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
            } else if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 4 | 2))) {
                // intermediate certificate
                caCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
                caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                        new DERBMPString("BETaaS Intermediate Certificate"));
            }
        } else {
            // root certificate
            taCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
            taCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                    new DERBMPString("BETaaS Primary Certificate"));
        }
    }

    //    PKCS12SafeBagBuilder taCertBagBuilder = new PKCS12SafeBagBuilder(chain[2]);

    //    PKCS12SafeBagBuilder caCertBagBuilder = new PKCS12SafeBagBuilder(chain[1]);

    //    PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[0]);

    // the ECPrivateKey, consists of the key itself and the ECParams
    BigInteger dPriv = ((ECPrivateKeyParameters) key).getD();
    X9ECParameters ecParams = new X9ECParameters(((ECKeyParameters) key).getParameters().getCurve(),
            ((ECKeyParameters) key).getParameters().getG(), ((ECKeyParameters) key).getParameters().getN(),
            ((ECKeyParameters) key).getParameters().getH(), ((ECKeyParameters) key).getParameters().getSeed());
    ECPrivateKey privParams = new ECPrivateKey(dPriv, ecParams);

    // include the ecParams
    AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecParams);

    //    PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(key);

    PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(new PrivateKeyInfo(sigAlg, privParams),
            encOut);

    keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key"));
    if (pubKeyId != null)
        keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();

    builder.addData(keyBagBuilder.build());

    // no need to insert SHA1Digest() because it is the default Digest algorithm
    // check each of the certbagbuilder
    if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder != null) {
        // include all types of certificate in the file --> root own's credential
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build(),
                        taCertBagBuilder.build() });
    } else if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder == null) {
        // only root and intermediate --> signer credential
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { caCertBagBuilder.build(), taCertBagBuilder.build() });
    } else if (caCertBagBuilder == null && taCertBagBuilder == null) {
        // only end entity --> e.g. application, user, etc
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build() });
    } else if (caCertBagBuilder != null && taCertBagBuilder == null && eeCertBagBuilder != null) {
        // only intermediate and end entity --> common GW certificate
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build() });
    }

    //    PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(
    //          new SHA256Digest(), 
    //          new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), keyPasswd);
    PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), keyPasswd);
    // make sure we don't include indefinite length encoding
    pfxOut.write(pfx.getEncoded(ASN1Encoding.DL));

    pfxOut.close();
}

From source file:fi.aalto.cs.drumbeat.CertificateCommons.java

License:Open Source License

public static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) throws IOException {
    ASN1InputStream is = null;/* w  w w  .  j a  v a  2 s  . c o m*/
    try {
        is = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()));
        ASN1Sequence seq = (ASN1Sequence) is.readObject();
        @SuppressWarnings("deprecation")
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq);
        return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
    } finally {
        is.close();
    }
}

From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java

License:Apache License

public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey,
        String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
    X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);

    List<GeneralName> generalNames = new ArrayList<>();
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }//from   w w  w .  j  a  va 2s.  co m

    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }

    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory
            .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
    X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(),
            new BigInteger(128, new Random()), certStartTime, certEndTime,
            new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic())
                    .addExtension(Extension.authorityKeyIdentifier, false,
                            extensionUtils.createAuthorityKeyIdentifier(holder))
                    .addExtension(Extension.subjectKeyIdentifier, false,
                            extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
                    .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
                    .addExtension(Extension.keyUsage, true,
                            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
                new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }

    if (crlPath != null) {
        DistributionPointName distPointOne = new DistributionPointName(
                new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));

        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
                new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
    }

    if (ocspPort != null) {
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod,
                new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
    }

    return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.SubjectKeyIdentifier.java

License:Open Source License

@Override
public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca,
        final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey,
        CertificateValidity val) throws CertificateExtensionException {
    SubjectPublicKeyInfo spki;/*w  ww  . j  a v a2 s  . c o  m*/
    try {
        spki = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(userPublicKey.getEncoded()))
                        .readObject());
    } catch (IOException e) {
        throw new CertificateExtensionException("IOException parsing user public key: " + e.getMessage(), e);
    }

    X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
    return x509ExtensionUtils.createSubjectKeyIdentifier(spki);
}

From source file:org.cesecore.keys.util.KeyTools.java

License:Open Source License

/**
 * create the subject key identifier.//from ww w. j a  va  2  s .  com
 * 
 * @param pubKey
 *            the public key
 * 
 * @return SubjectKeyIdentifer asn.1 structure
 */
public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) {
    try {
        final ASN1Sequence keyASN1Sequence;
        ASN1InputStream pubKeyAsn1InputStream = new ASN1InputStream(
                new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            final Object keyObject = pubKeyAsn1InputStream.readObject();
            if (keyObject instanceof ASN1Sequence) {
                keyASN1Sequence = (ASN1Sequence) keyObject;
            } else {
                // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead.
                final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC")
                        .translateKey(pubKey);
                ASN1InputStream altKeyAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(altKey.getEncoded()));
                try {
                    keyASN1Sequence = (ASN1Sequence) altKeyAsn1InputStream.readObject();
                } finally {
                    altKeyAsn1InputStream.close();
                }
            }
            X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
            return x509ExtensionUtils.createSubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence));
        } finally {
            pubKeyAsn1InputStream.close();
        }
    } catch (Exception e) {
        final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD
        e2.initCause(e);
        throw e2;
    }
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;/*from   w ww.  ja va  2s  . com*/
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java

License:Open Source License

private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, OperatorCreationException, CertificateException, IOException {
    int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    // Create self signed certificate
    Date firstDate = new Date();
    // Set starting date to tomorrow
    firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000));
    Date lastDate = new Date();
    // Set Expiry in two days
    lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from   w w w .  j  a  v  a 2s . c  o  m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        } catch (NullPointerException e) {
            publicKey = pubKey;
        }
    } else {
        publicKey = pubKey;
    }
    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn),
            pkinfo);
    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }
    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            ASN1InputStream spkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream apkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) spkiAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) apkiAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                spkiAsn1InputStream.close();
                apkiAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }
    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.xwiki.crypto.pkix.internal.extension.DefaultX509ExtensionBuilder.java

License:Open Source License

@Override
public X509ExtensionBuilder addAuthorityKeyIdentifier(CertifiedPublicKey issuer) {
    if (issuer == null) {
        return this;
    }//from   w  w w.j a va 2s .  co m

    return addExtension(Extension.authorityKeyIdentifier, false,
            new BcX509ExtensionUtils().createAuthorityKeyIdentifier(BcUtils.getX509CertificateHolder(issuer)));
}