Example usage for org.bouncycastle.asn1.x509 Extension extendedKeyUsage

List of usage examples for org.bouncycastle.asn1.x509 Extension extendedKeyUsage

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension extendedKeyUsage.

Prototype

ASN1ObjectIdentifier extendedKeyUsage

To view the source code for org.bouncycastle.asn1.x509 Extension extendedKeyUsage.

Click Source Link

Document

Extended Key Usage

Usage

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

License:Open Source License

@Override
public X509ExtensionBuilder addExtendedKeyUsage(boolean critical, ExtendedKeyUsages usages) {
    if (usages == null || usages.isEmpty()) {
        return this;
    }/*ww w  .ja  va2s .c o  m*/

    return addExtension(Extension.extendedKeyUsage, critical,
            BcExtensionUtils.getExtendedKeyUsage(usages.getAll()));
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

License:Apache License

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return/*from  w  w  w  .ja  v  a2 s . c  o m*/
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth,
                KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE,
                new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

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

License:Apache License

public X509CertificateHolder generate(String cn, String[] sans) {
    try {/*from  w  w  w . j  av  a 2  s.  co  m*/
        /* basic certificate structure */
        //serial = serial.add(BigInteger.ONE);
        // TODO: temporary workaround as reusing serial numbers makes Firefox complain
        serial = new BigInteger(Long.toString(System.currentTimeMillis()));

        Calendar notBefore = new GregorianCalendar(UTC);
        notBefore.add(Calendar.HOUR, -1);

        Calendar notAfter = new GregorianCalendar(UTC);
        notAfter.add(Calendar.HOUR, 24);

        X500Name subject = new X500NameBuilder().addRDN(BCStyle.CN, cn).build();

        BcX509ExtensionUtils utils = new BcX509ExtensionUtils();
        X509v3CertificateBuilder builder = new BcX509v3CertificateBuilder(ca.getCertificate(), serial,
                notBefore.getTime(), notAfter.getTime(), subject, keyPair.getPublic());

        /* subjectAlernativeName extension */
        if (sans.length > 0) {
            GeneralName[] names = new GeneralName[sans.length];
            for (int i = 0; i < names.length; i++) {
                names[i] = new GeneralName(GeneralName.dNSName, sans[i]);
            }
            builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(names));
        }

        /* basicConstraints extension */
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        /* subjectKeyIdentifier extension */
        builder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(keyPair.getPublic()));

        /* authorityKeyIdentifier extension */
        builder.addExtension(Extension.authorityKeyIdentifier, false,
                utils.createAuthorityKeyIdentifier(ca.getPublicKey()));

        /* keyUsage extension */
        int usage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyAgreement;
        builder.addExtension(Extension.keyUsage, true, new KeyUsage(usage));

        /* extendedKeyUsage extension */
        KeyPurposeId[] usages = { KeyPurposeId.id_kp_serverAuth };
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(usages));

        /* create the signer */
        AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("SHA1withRSA");
        AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder()
                .find(signatureAlgorithm);
        ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm)
                .build(ca.getPrivateKey());

        /* build and sign the certificate */
        return builder.build(signer);
    } catch (IOException | OperatorCreationException ex) {
        throw new CertificateGenerationException(ex);
    }
}