Example usage for org.bouncycastle.asn1.x509 X509Extensions KeyUsage

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions KeyUsage

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions KeyUsage.

Prototype

ASN1ObjectIdentifier KeyUsage

To view the source code for org.bouncycastle.asn1.x509 X509Extensions KeyUsage.

Click Source Link

Document

Key Usage

Usage

From source file:me.it_result.ca.bouncycastle.BouncyCABase.java

License:Open Source License

protected X509V3CertificateGenerator assembleCertificate(PublicKey publicKey, PublicKey caPublicKey,
        String subjectDN, String issuerDN, BigInteger serialNumber, boolean ca, int validityDays)
        throws CertificateParsingException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchAlgorithmException, SignatureException, FileNotFoundException {
    certGen.setIssuerDN(new X509Principal(issuerDN));
    certGen.setNotBefore(new Date());
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.DAY_OF_MONTH, validityDays);
    certGen.setNotAfter(cal.getTime());//from   w  w  w .  j a va 2 s  .c o m
    certGen.setPublicKey(publicKey);
    certGen.setSerialNumber(serialNumber);
    certGen.setSignatureAlgorithm(signatureAlgorithm);
    certGen.setSubjectDN(new X509Principal(subjectDN));
    X509KeyUsage keyUsage;
    if (ca)
        keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign);
    else
        keyUsage = new X509KeyUsage(X509KeyUsage.keyEncipherment | X509KeyUsage.digitalSignature);
    certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage.getDEREncoded());
    BasicConstraints basicConstraints = new BasicConstraints(ca);
    certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints.getDEREncoded());
    SubjectKeyIdentifierStructure subjectKeyId = new SubjectKeyIdentifierStructure(publicKey);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyId.getDEREncoded());
    AuthorityKeyIdentifierStructure authorityKeyId = new AuthorityKeyIdentifierStructure(caPublicKey);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyId.getDEREncoded());
    return certGen;
}

From source file:me.it_result.ca.X509Assertions.java

License:Open Source License

public X509Assertions keyUsage(int expectedKeyUsage) {
    int actualKeyUsage = 0;
    for (int i = 0; i < 8; i++) {
        int bit = cert.getKeyUsage()[i] ? 1 : 0;
        actualKeyUsage = (actualKeyUsage << 1) | bit;
    }// w ww.j av  a  2  s.c om
    assertEquals(expectedKeyUsage, actualKeyUsage);
    criticalExtension(X509Extensions.KeyUsage);
    return this;
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert)
        throws Exception {
    Date validFrom, validTo;//from  ww  w. j a v a  2s.c  o  m

    // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider 
    // make the range before 1950 and after 2050. The BD-J spec recommends
    // using the default validity period used below
    Calendar calendar = Calendar.getInstance();
    calendar.set(0000, 1, 1);
    validFrom = calendar.getTime();
    calendar.clear();
    calendar.set(9999, 1, 1);
    validTo = calendar.getTime();

    // Generate a new keypair for this certificate
    KeyPair keyPair = generateKeyPair();

    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();
    X509Name name = new X509Name(issuer, new X509BDJEntryConverter());

    // Generate Serial Number
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    BigInteger serNo = new BigInteger(32, prng);
    cg.setSerialNumber(serNo);
    if (!isRootCert) {
        appCertSerNo = serNo;
    }
    cg.setIssuerDN(name);
    cg.setNotBefore(validFrom);
    cg.setNotAfter(validTo);
    cg.setSubjectDN(name);
    cg.setPublicKey(keyPair.getPublic());
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    if (isRootCert) {
        // Need to add root cert extensions.
        if (isBindingUnitCert) {
            // This certificate is used only for signing
            cg.addExtension(X509Extensions.KeyUsage.getId(), true,
                    new X509KeyUsage(X509KeyUsage.digitalSignature));
        } else {
            int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign;
            cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage));
        }
        cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName));
        cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true));
    }
    // For an app cert, most of the extensions will be added when generating
    // a certificate in response to the certificate request file.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    Certificate cert = cg.generate(keyPair.getPrivate());
    store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert });
    FileOutputStream fos = new FileOutputStream(keystoreFile);
    store.store(fos, keystorePassword.toCharArray());
    fos.close();
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception {
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile));
    String subject = csr.getCertificationRequestInfo().getSubject().toString();

    // Generate the app certificate
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();/*  ww w  . j  a  v a2  s.  c  o  m*/
    X509Certificate rootCert = (X509Certificate) store.getCertificate(alias);
    if (rootCert == null) {
        System.out
                .println("ERROR: Aborting application certificate creation." + " No root certificate to sign.");
        cleanup(); // removes the self signed certificate from the keystore
        System.exit(1);
    }
    cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter()));
    cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter()));
    cg.setNotBefore(rootCert.getNotBefore());
    cg.setNotAfter(rootCert.getNotAfter());
    cg.setPublicKey(csr.getPublicKey());
    cg.setSerialNumber(appCertSerNo);

    // BD-J mandates using SHA1WithRSA as a signature Algorithm
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature));

    // FIXME: Ideally this should be pulled out from the original app cert's
    // extension. Email on X500Name is not encoded with UTF8String.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    // Assuming that the root certificate was generated using our tool,
    // the certificate should have IssuerAlternativeNames as an extension.
    if (rootCert.getIssuerAlternativeNames() == null) {
        System.out.println("ERROR: the root certificate must have an alternate name");
        System.exit(1);
    }
    List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next();
    cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false,
            getRfc822Name((String) issuerName.get(1)));
    PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray());
    X509Certificate cert = cg.generate(privateKey);

    // Now, write leaf certificate
    System.out.println("Writing cert to " + certfile + ".");
    FileOutputStream str = new FileOutputStream(certfile);
    str.write(cert.getEncoded());
    str.close();
}

From source file:net.laubenberger.bogatyr.service.crypto.CertificateProviderImpl.java

License:Open Source License

@Override
public X509Certificate generateCertificate(final KeyPair pair, final String issuerDN, final String subjectDN,
        final String generalName, final Date start, final Date end)
        throws NoSuchAlgorithmException, IllegalStateException, CertificateEncodingException,
        InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException { //$JUnit$
    if (null == pair) {
        throw new RuntimeExceptionIsNull("pair"); //$NON-NLS-1$
    }/*from   www .j  av  a2  s  . com*/
    if (null == issuerDN) {
        throw new RuntimeExceptionIsNull("issuerDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(issuerDN)) {
        throw new RuntimeExceptionIsEmpty("issuerDN"); //$NON-NLS-1$
    }
    if (null == subjectDN) {
        throw new RuntimeExceptionIsNull("subjectDN"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(subjectDN)) {
        throw new RuntimeExceptionIsEmpty("subjectDN"); //$NON-NLS-1$
    }
    if (null == generalName) {
        throw new RuntimeExceptionIsNull("generalName"); //$NON-NLS-1$
    }
    if (!HelperString.isValid(generalName)) {
        throw new RuntimeExceptionIsEmpty("generalName"); //$NON-NLS-1$
    }
    if (null == start) {
        throw new RuntimeExceptionIsNull("start"); //$NON-NLS-1$
    }
    if (null == end) {
        throw new RuntimeExceptionIsNull("end"); //$NON-NLS-1$
    }
    if (start.after(end)) {
        throw new RuntimeExceptionMustBeBefore("start", start, end); //$NON-NLS-1$
    }

    // generate the certificate
    final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal(issuerDN));
    certGen.setNotBefore(start);
    certGen.setNotAfter(end);
    certGen.setSubjectDN(new X500Principal(subjectDN));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //$NON-NLS-1$

    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));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, generalName)));

    return certGen.generate(pair.getPrivate(), provider.getName());
}

From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * @param keyPair/*from ww  w .j a  v  a 2 s. com*/
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    //Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen
            .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    //Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();

    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages));

    X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}

From source file:org.apache.kerby.pkix.EndEntityGenerator.java

License:Apache License

/**
 * Generate certificate./*from w w  w. j a  v  a 2s.com*/
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    // MAY set BasicConstraints=false or not at all.
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

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

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

    ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector();
    keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon);
    //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth );
    DERSequence keyPurposeOids = new DERSequence(keyPurposeVector);

    // If critical, will throw unsupported EKU.
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids);

    ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector();
    pkinitSanVector.add(ID_PKINIT_SAN);
    pkinitSanVector.add(new DERTaggedObject(0, new DERSequence()));
    DERSequence pkinitSan = new DERSequence(pkinitSanVector);

    String dnsName = "localhost";

    GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan);
    GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName);

    GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder();

    genNamesBuilder.addName(name1);
    genNamesBuilder.addName(name2);

    GeneralNames sanGeneralNames = genNamesBuilder.build();

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames);

    /*
     * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId
     * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's
     * X.509 certificate.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the client's X.509 certificate is restricted with
     * the id-pkinit-KPClientAuth EKU.
     */

    /*
     * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId
     * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as
     * there are a large number of X.509 client certificates deployed for use
     * with PKINIT that have this EKU.
     */

    // KDC
    /*
     * In addition, unless the client can otherwise verify that the public key
     * used to verify the KDC's signature is bound to the KDC of the target realm,
     * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension
     * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined
     * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the
     * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]).
     */

    /*
     * Unless the client knows by some other means that the KDC certificate is
     * intended for a Kerberos KDC, the client MUST require that the KDC certificate
     * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the KDC's X.509 certificate is restricted with the
     * id-pkinit-KPKdc EKU.
     */

    /*
     * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san
     * SAN, this certificate is certified by the issuing CA as a KDC certificate,
     * therefore the id-pkinit-KPKdc EKU is not required.
     */

    /*
     * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth
     * EKU [RFC3280].
     */

    /*
     * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth
     * EKU, and the id-ms-kp-sc-logon EKU.
     */

    /*
     * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC.
     * 
     * MS:  dNSName SAN containing the domain name of the KDC
     *      id-pkinit-KPKdc EKU
     *      id-kp-serverAuth EKU.
     */

    /*
     * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs
     * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and
     * the id-ms-kp-sc-logon EKU.  The id-ms-san-sc-logon-upn SAN contains a
     * UTF8-encoded string whose value is that of the Directory Service attribute
     * UserPrincipalName of the client account object, and the purpose of including
     * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate
     * the client mapping (in other words, the client's public key is bound to
     * the account that has this UserPrincipalName value).
     */

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.apache.kerby.pkix.IntermediateCaGenerator.java

License:Apache License

/**
 * Create certificate./*from w  w w .  ja va2  s .  c o m*/
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

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

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

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

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.apache.kerby.pkix.TrustAnchorGenerator.java

License:Apache License

/**
 * Create CA certificate./* w  w w.  j  a v a  2s . co m*/
 *
 * @param publicKey
 * @param privateKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(PublicKey publicKey, PrivateKey privateKey, String dn, int validityDays,
        String friendlyName) throws InvalidKeyException, SecurityException, SignatureException,
        NoSuchAlgorithmException, DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    X509Principal x509Principal = new X509Principal(dn);
    certGen.setIssuerDN(x509Principal);
    certGen.setSubjectDN(x509Principal);

    certGen.setNotBefore(new Date());

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

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

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

    X509Certificate cert = certGen.generate(privateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.browsermob.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * @param keyPair/*from   w w  w. j a va2 s.c o m*/
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    //Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 48 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    //Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();

    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages));

    X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}