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

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

Introduction

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

Prototype

ASN1ObjectIdentifier BasicConstraints

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

Click Source Link

Document

Basic Constraints

Usage

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 w w w  .  ja va 2s  . c  om
            .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:io.spikex.core.Main.java

License:Apache License

private void createKeyStore(final YamlDocument conf) {

    YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE);
    boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE);

    if (generate) {

        Path keyStorePath = Paths
                .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString()))
                .toAbsolutePath().normalize();

        if (!Files.exists(keyStorePath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }//from   w  w w  .j a  va 2s .  co m

            String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD);
            String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName());
            List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList());

            try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) {

                m_logger.info("Generating keystore: {}", keyStorePath);

                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                        BouncyCastleProvider.PROVIDER_NAME);

                SecureRandom rnd = new SecureRandom();
                generator.initialize(2048, rnd);
                KeyPair pair = generator.generateKeyPair();

                // DN
                X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
                nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU"));
                nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate");
                nameBuilder.addRDN(BCStyle.OU, "For testing purposes only");
                nameBuilder.addRDN(BCStyle.O, "Spike.x");
                nameBuilder.addRDN(BCStyle.CN, hostFqdn);

                long oneDay = 24 * 60 * 60 * 1000;
                Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday
                Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years

                BigInteger serialNum = BigInteger.valueOf(rnd.nextLong());
                X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
                        serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic());

                //
                // Extensions
                //
                x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                x509v3Builder.addExtension(X509Extensions.KeyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

                GeneralName[] dnsNames = new GeneralName[subjAltNames.size()];
                for (int i = 0; i < subjAltNames.size(); i++) {
                    String name = subjAltNames.get(i);
                    m_logger.info("Adding subject alt name: {}", name);
                    dnsNames[i] = new GeneralName(GeneralName.dNSName, name);
                }
                x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new GeneralNames(dnsNames));

                ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate());

                X509Certificate cert = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate(x509v3Builder.build(signer));

                // Validate
                cert.checkValidity(new Date());
                cert.verify(cert.getPublicKey());

                // Save in keystore
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert });

                m_logger.info("Created self-signed certificate: {}", hostFqdn);
                ks.store(out, password.toCharArray());

            } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
                    | NoSuchProviderException | OperatorCreationException | InvalidKeyException
                    | SignatureException e) {
                throw new RuntimeException("Failed to create keystore: " + keyStorePath, e);
            }
        }
    }
}

From source file:krypto.KryptoService.java

License:Apache License

/**
 * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist.
 * @return/*  www .  ja  va2  s  .  c om*/
 * @throws Exception
 */
public static X509Certificate generateCertificate(String algorithm) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    KeyPair pair = null;

    try {
        pair = generateKeyPair(algorithm, 1024);
    } catch (Exception e) {
        try {
            pair = generateKeyPair(algorithm, 512);
        } catch (Exception e2) {
            System.out.println(e2.getMessage());
        }
    }

    long day = 24 * 60 * 60 * 1000; // 1 Tag gltig

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + day));
    certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    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, "test@test.test")));

    X509Certificate cert = null;
    try {
        cert = certGen.generate(pair.getPrivate(), "BC");
    } catch (CertificateEncodingException e) {
        System.out.println("CertificateEncodingException");
    } catch (InvalidKeyException e2) {
        System.out.println("InvalidKeyException: " + e2.getMessage());
    } catch (Exception e3) {
        // do nothing
    }

    return cert;

}

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());//  www.  j  a  v a2s  .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 caCertificate(boolean ca) throws Exception {
    extensionValue(X509Extensions.BasicConstraints, new BasicConstraints(ca));
    criticalExtension(X509Extensions.BasicConstraints);
    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;/*  ww w.jav  a 2 s .  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.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$
    }/* ww w.  ja v  a  2 s  .c om*/
    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

/**
 * Utility method for generating a "standard" server certificate. Recognized by most
 * browsers as valid for SSL/TLS.  These certificates are generated de novo, not from
 * a template, so they will not retain the structure of the original certificate and may
 * not be suitable for applications that require Extended Validation/High Assurance SSL
 * or other distinct extensions or EKU.//from   w w  w .ja  v a 2s .c  om
 *
 * @param newPubKey
 * @param caCert
 * @param caPrivateKey
 * @param hostname
 * @return
 * @throws CertificateParsingException
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
@SuppressWarnings({ "deprecation", "unused" })
public static X509Certificate generateStdSSLServerCertificate(final PublicKey newPubKey,
        final X509Certificate caCert, final PrivateKey caPrivateKey, final String subject)
        throws CertificateParsingException, SignatureException, InvalidKeyException,
        CertificateExpiredException, CertificateNotYetValidException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.setSubjectDN(new X500Principal(subject));
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);
    v3CertGen.setPublicKey(newPubKey);
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 30L * 60 * 60 * 24 * 30 * 12));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30 * 12));
    v3CertGen.setIssuerDN(caCert.getSubjectX500Principal());

    // Firefox actually tracks serial numbers within a CA and refuses to validate if it sees duplicates
    // This is not a secure serial number generator, (duh!) but it's good enough for our purposes.
    v3CertGen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis())));

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

    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(newPubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert.getPublicKey()));

    //       Firefox 2 disallows these extensions in an SSL server cert.  IE7 doesn't care.
    //      v3CertGen.addExtension(
    //            X509Extensions.KeyUsage,
    //            false,
    //            new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature ) );

    DEREncodableVector typicalSSLServerExtendedKeyUsages = new DEREncodableVector();

    typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.clientAuth));
    typicalSSLServerExtendedKeyUsages
            .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.netscapeServerGatedCrypto));
    typicalSSLServerExtendedKeyUsages
            .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.msServerGatedCrypto));

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

    //  Disabled by default.  Left in comments in case this is desired.
    //
    //      v3CertGen.addExtension(
    //            X509Extensions.AuthorityInfoAccess,
    //            false,
    //            new AuthorityInformationAccess(new DERObjectIdentifier(OID_ID_AD_CAISSUERS),
    //                  new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + subject + "/aia")));

    //      v3CertGen.addExtension(
    //            X509Extensions.CRLDistributionPoints,
    //            false,
    //            new CRLDistPoint(new DistributionPoint[] {}));

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

    return cert;
}

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 av a2  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 ww  .j  av a  2 s.  c om*/
 *
 * @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;
}