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

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

Introduction

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

Prototype

ASN1ObjectIdentifier basicConstraints

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

Click Source Link

Document

Basic Constraints

Usage

From source file:org.iotivity.cloud.accountserver.resources.credprov.cert.CertificateStorage.java

License:Open Source License

/**
 * Generates CA X509Certificate and private key and stores it to key storage.
 *
 * @return certificate and private key//w w  w. j a  va 2  s . c  om
 */
private static void generate() throws GeneralSecurityException, OperatorCreationException, IOException {
    if (ROOT_PRIVATE_KEY == null) {
        KeyPairGenerator g = KeyPairGenerator.getInstance(KEY_GENERATOR_ALGORITHM, SECURITY_PROVIDER);
        g.initialize(ECNamedCurveTable.getParameterSpec(CURVE), new SecureRandom());
        KeyPair pair = g.generateKeyPair();
        ROOT_PRIVATE_KEY = pair.getPrivate();
        ROOT_CERTIFICATE = new CertificateBuilder(CA_ISSUER, pair.getPublic(),
                new CertificateExtension(Extension.basicConstraints, false, new BasicConstraints(true)))
                        .build();
        keyStore.setCertificateEntry(CA_ALIAS, ROOT_CERTIFICATE);
        keyStore.setKeyEntry(CA_ALIAS, ROOT_PRIVATE_KEY, PASSWORD.toCharArray(),
                new Certificate[] { ROOT_CERTIFICATE });
        store();
    }
}

From source file:org.keycloak.common.util.CertificateUtils.java

License:Apache License

/**
 * Generates version 3 {@link java.security.cert.X509Certificate}.
 *
 * @param keyPair the key pair//from w  w  w .java 2  s. c  o  m
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 * 
 * @return the x509 certificate
 * 
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey,
        X509Certificate caCert, String subject) throws Exception {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);

        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));

        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);

        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(
                new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN,
                subjPubKeyInfo);

        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);

        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));

        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));

        // Key Usage
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;

        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));

        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(caPrivateKey);

        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}

From source file:org.kontalk.certgen.X509Bridge.java

License:Open Source License

/**
 * Creates a self-signed certificate from a public and private key. The
 * (critical) key-usage extension is set up with: digital signature,
 * non-repudiation, key-encipherment, key-agreement and certificate-signing.
 * The (non-critical) Netscape extension is set up with: SSL client and
 * S/MIME. A URI subjectAltName may also be set up.
 *
 * @param pubKey//from w ww.  j ava  2s.  c om
 *            public key
 * @param privKey
 *            private key
 * @param subject
 *            subject (and issuer) DN for this certificate, RFC 2253 format
 *            preferred.
 * @param startDate
 *            date from which the certificate will be valid
 *            (defaults to current date and time if null)
 * @param endDate
 *            date until which the certificate will be valid
 *            (defaults to start date and time if null)
 * @param subjectAltName
 *            URI to be placed in subjectAltName
 * @return self-signed certificate
 */
private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject,
        Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData)
        throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException,
        CertificateException, NoSuchProviderException, IOException, OperatorCreationException {

    /*
     * Sets the signature algorithm.
     */
    BcContentSignerBuilder signerBuilder;
    String pubKeyAlgorithm = pubKey.getAlgorithm();
    if (pubKeyAlgorithm.equals("DSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
    } else if (pubKeyAlgorithm.equals("RSA")) {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("SHA1WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    }
    /*
    else if (pubKeyAlgorithm.equals("ECDSA")) {
    // TODO is this even legal?
    certGenerator.setSignatureAlgorithm("SHA1WithECDSA");
    }
    */
    else {
        throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm);
    }

    AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer = signerBuilder.build(keyp);

    /*
     * Sets up the validity dates.
     */
    if (startDate == null) {
        startDate = new Date(System.currentTimeMillis());
    }
    if (endDate == null) {
        endDate = startDate;
    }

    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
            /*
             * Sets up the subject distinguished name.
             * Since it's a self-signed certificate, issuer and subject are the
             * same.
             */
            subject,
            /*
             * The serial-number of this certificate is 1. It makes sense
             * because it's self-signed.
             */
            BigInteger.ONE, startDate, endDate, subject,
            /*
             * Sets the public-key to embed in this certificate.
             */
            SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject()));

    /*
     * Adds the Basic Constraint (CA: true) extension.
     */
    certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    /*
     * Adds the Key Usage extension.
     */
    certBuilder.addExtension(Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
                    | KeyUsage.keyAgreement | KeyUsage.keyCertSign));

    /*
     * Adds the Netscape certificate type extension.
     */
    certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime));

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    /*
     * Adds the subject key identifier extension.
     */
    SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);

    /*
     * Adds the authority key identifier extension.
     */
    AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey);
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

    /*
     * Adds the subject alternative-name extension.
     */
    if (subjectAltName != null) {
        GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }

    /*
     * Adds the PGP public key block extension.
     */
    SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData);
    certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension);

    /*
     * Creates and sign this certificate with the private key
     * corresponding to the public key of the certificate
     * (hence the name "self-signed certificate").
     */
    X509CertificateHolder holder = certBuilder.build(signer);

    /*
     * Checks that this certificate has indeed been correctly signed.
     */
    X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder);
    cert.verify(pubKey);

    return cert;
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

protected List<Extension> createExtensions(PublicKey publicKey, X509Certificate issuerCertificate)
        throws CertIOException, NoSuchAlgorithmException, IOException {

    List<Extension> extensions = new ArrayList<>();

    String certType = getProperty(PROPERTY_CERT_TYPE, CERT_TYPE_TLS);

    // backward compatibility
    if (CERT_TYPE_CA_OLD.equals(certType)) {
        certType = CERT_TYPE_CA;/*from  w w w . j a v  a2 s.co  m*/
    }

    // subject key identifier
    boolean criticalKeyIdentifier = getProperty(PROPERTY_CERT_CRITICAL_KEY_IDENTIFIER, false);
    extensions.add(new Extension(Extension.subjectKeyIdentifier, criticalKeyIdentifier,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getEncoded()));

    // basic constraints
    if (CERT_TYPE_CA.equals(certType)) {
        boolean criticalCaConstraints = getProperty(PROPERTY_CERT_CRITICAL_CA, true);
        int chainLengthConstraint = getProperty(PROPERTY_CERT_CHAIN_LENGTH, 0);
        if (chainLengthConstraint > 0) {
            extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints,
                    new BasicConstraints(chainLengthConstraint).getEncoded()));
        } else {
            extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints,
                    new BasicConstraints(true).getEncoded()));
        }
    }

    // key usage
    int keyUsageInt = getKeyUsage(certType);
    if (keyUsageInt != 0) {
        // FIXME: test whether we can default to true here
        boolean criticalKeyUsage = getProperty(PROPERTY_CERT_CRITICAL_KEY_USAGE, false);
        KeyUsage keyUsage = new KeyUsage(keyUsageInt);
        extensions.add(new Extension(Extension.keyUsage, criticalKeyUsage, keyUsage.getEncoded()));
    }

    // extended key usage
    KeyPurposeId[] keyPurposeDefault = null;
    if (CERT_TYPE_TLS.equals(certType)) {
        // defaults for TLS
        keyPurposeDefault = new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth };
    }
    boolean criticalKeyPurpose = getProperty(PROPERTY_CERT_CRITICAL_KEY_PURPOSE, false);
    KeyPurposeId[] keyPurpose = createKeyPurposeIds(keyPurposeDefault);
    if (keyPurpose != null) {
        extensions.add(new Extension(Extension.extendedKeyUsage, criticalKeyPurpose,
                new ExtendedKeyUsage(keyPurpose).getEncoded()));
    }

    // subjectAlternativeName
    List<ASN1Encodable> subjectAlternativeNames = extractAlternativeNames(PROPERTY_PREFIX_CERT_NAME);
    if (!subjectAlternativeNames.isEmpty()) {
        boolean criticalNames = getProperty(PROPERTY_CERT_CRITICAL_NAMES, false);
        DERSequence subjectAlternativeNamesExtension = new DERSequence(
                subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
        extensions.add(new Extension(Extension.subjectAlternativeName, criticalNames,
                subjectAlternativeNamesExtension.getEncoded()));
    }

    if (issuerCertificate == null) {
        // crl distribution point
        DistributionPoint[] crlDistributionPoints = createCrlDistributionPoints();
        if (crlDistributionPoints != null) {
            boolean criticalCrlDistPoints = getProperty(PROPERTY_CERT_CRITICAL_CRL_DISTRIBUTION_POINTS, false);
            extensions.add(new Extension(Extension.cRLDistributionPoints, criticalCrlDistPoints,
                    new CRLDistPoint(crlDistributionPoints).getEncoded()));
        }

        // authority information access
        AccessDescription[] accessDescriptions = createAccessDescriptions();
        if (accessDescriptions != null) {
            boolean criticalAuthorityInformationAccess = getProperty(
                    PROPERTY_CERT_CRITICAL_AUTHORITY_INFORMATION_ACCESS, false);
            extensions.add(new Extension(Extension.authorityInfoAccess, criticalAuthorityInformationAccess,
                    new AuthorityInformationAccess(accessDescriptions).getEncoded()));
        }
    } else {
        copyExtension(Extension.cRLDistributionPoints, issuerCertificate, extensions);
        copyExtension(Extension.authorityInfoAccess, issuerCertificate, extensions);
    }
    return extensions;
}

From source file:org.opcfoundation.ua.transport.security.BcCertificateProvider.java

License:Open Source License

/**
 * Generates a new certificate using the Bouncy Castle implementation.
 * <p>/*from   w ww  . ja v a2 s .co m*/
 * The method is used from
 * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)}
 * and
 * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)}
 * 
 * @param domainName
 *            the X500 domain name for the certificate
 * @param publicKey
 *            the public key of the cert
 * @param privateKey
 *            the private key of the cert
 * @param issuerKeys
 *            the certificate and private key of the issuer
 * @param from
 *            validity start time
 * @param to
 *            validity end time
 * @param serialNumber
 *            a unique serial number for the certificate
 * @param applicationUri
 *            the OPC UA ApplicationUri of the application - added to
 *            SubjectAlternativeName
 * @param hostNames
 *            the additional host names to add to SubjectAlternativeName
 * @return the generated certificate
 * @throws GeneralSecurityException
 *             if the generation fails
 * @throws IOException
 *             if the generation fails due to an IO exception
 */
@Override
public X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey,
        KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames)
        throws IOException, GeneralSecurityException {

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    X509v3CertificateBuilder certBldr;
    AuthorityKeyIdentifier authorityKeyIdentifier;
    PrivateKey signerKey;
    if (issuerKeys == null) {
        X500Name dn = new X500Name(domainName);
        certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey);
        signerKey = privateKey;
    } else {
        X509Certificate caCert = issuerKeys.getCertificate().getCertificate();
        certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName),
                publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert);
        signerKey = issuerKeys.getPrivateKey().getPrivateKey();
    }
    certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier)
            .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey))
            .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension(
                    Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                            | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    // BC 1.49:
    certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
            new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth }));
    // create the extension value

    // URI Name
    List<GeneralName> names = new ArrayList<GeneralName>();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));

    // Add DNS name from ApplicationUri
    boolean hasDNSName = false;
    String uriHostName = null;
    try {
        String[] appUriParts = applicationUri.split("[:/]");
        if (appUriParts.length > 1) {
            uriHostName = appUriParts[1];
            if (!uriHostName.toLowerCase().equals("localhost")) {
                GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName);
                names.add(dnsName);
                hasDNSName = true;
            }
        }
    } catch (Exception e) {
        logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri);
    }

    // Add other DNS Names
    List<GeneralName> ipAddressNames = new ArrayList<GeneralName>();
    if (hostNames != null)
        for (String hostName : hostNames) {
            boolean isIpAddress = hostName.matches("^[0-9.]+$");
            if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) {
                GeneralName dnsName = new GeneralName(
                        hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName);
                if (isIpAddress)
                    ipAddressNames.add(dnsName);
                else {
                    names.add(dnsName);
                    hasDNSName = true;
                }
            }
        }
    // Add IP Addresses, if no host names are defined
    if (!hasDNSName)
        for (GeneralName n : ipAddressNames)
            names.add(n);

    final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0]));
    certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);

    // ***** generate certificate ***********/
    try {

        ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm())
                .setProvider("BC").build(signerKey);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.opcfoundation.ua.transport.security.BcCertificateProvider.java

License:Open Source License

/**
 * Build a X509 V3 certificate to use as an issuer (CA) certificate. The
 * certificate does not define OPC UA specific fields, so it cannot be used
 * for an application instance certificate.
 * /*from   w  ww  .  j a  v a  2  s. co m*/
 * @param publicKey
 *            the public key to use for the certificate
 * @param privateKey
 *            the private key corresponding to the publicKey
 * @param issuerKeys
 *            the certificate and private key of the certificate issuer: if
 *            null a self-signed certificate is created.
 * @param commonName
 *            the CommonName to use for the subject of the certificate.
 * @param serialNr
 * @param startDate
 * @param expiryDate
 * @throws OperatorCreationException
 */
@Override
public X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys,
        String commonName, BigInteger serialNr, Date startDate, Date expiryDate)
        throws GeneralSecurityException, IOException {
    JcaX509v3CertificateBuilder certBldr;
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier authorityKeyIdentifier;
    if (issuerKeys == null) {
        X500Name dn = new X500Name(commonName);
        certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey);
    } else {
        X509Certificate caCert = issuerKeys.getCertificate().getCertificate();
        certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate,
                new X500Principal(commonName), publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert);
    }

    certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier)
            .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm())
                .setProvider("BC").build(privateKey);
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException("Failed to sign the certificate", e);
    }
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}

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

License:Open Source License

/**
 * Build a X509 V3 certificate to use as an issuer (CA) certificate. The
 * certificate does not define OPC UA specific fields, so it cannot be used
 * for an application instance certificate.
 * /*from   w  w w  .java 2s . co m*/
 * @param publicKey
 *            the public key to use for the certificate
 * @param privateKey
 *            the private key corresponding to the publicKey
 * @param issuerKeys
 *            the certificate and private key of the certificate issuer: if
 *            null a self-signed certificate is created.
 * @param commonName
 *            the CommonName to use for the subject of the certificate.
 * @param serialNr
 * @param startDate
 * @param expiryDate
 * @throws OperatorCreationException
 */
public static X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys,
        String commonName, BigInteger serialNr, Date startDate, Date expiryDate)
        throws GeneralSecurityException, IOException {
    JcaX509v3CertificateBuilder certBldr;
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    AuthorityKeyIdentifier authorityKeyIdentifier;
    if (issuerKeys == null) {
        X500Name dn = new X500Name(commonName);
        certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey);
    } else {
        X509Certificate caCert = issuerKeys.getCertificate().getCertificate();
        certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate,
                new X500Principal(commonName), publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert);
    }

    certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier)
            .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm())
                .setProvider("BC").build(privateKey);
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException("Failed to sign the certificate", e);
    }
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}

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

License:Open Source License

/**
 * Generates a new certificate using the Bouncy Castle implementation.
 * <p>/* w  ww . j  a  v  a  2s .c  om*/
 * The method is used from
 * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)}
 * and
 * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)}
 * 
 * @param domainName
 *            the X500 domain name for the certificate
 * @param publicKey
 *            the public key of the cert
 * @param privateKey
 *            the private key of the cert
 * @param issuerKeys
 *            the certificate and private key of the issuer
 * @param from
 *            validity start time
 * @param to
 *            validity end time
 * @param serialNumber
 *            a unique serial number for the certificate
 * @param applicationUri
 *            the OPC UA ApplicationUri of the application - added to
 *            SubjectAlternativeName
 * @param hostNames
 *            the additional host names to ass to SubjectAlternativeName
 * @return the generated certificate
 * @throws GeneralSecurityException
 *             if the generation fails
 * @throws IOException
 *             if the generation fails due to an IO exception
 */
public static X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey,
        KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames)
        throws IOException, GeneralSecurityException {

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    X509v3CertificateBuilder certBldr;
    AuthorityKeyIdentifier authorityKeyIdentifier;
    PrivateKey signerKey;
    if (issuerKeys == null) {
        X500Name dn = new X500Name(domainName);
        certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey);
        signerKey = privateKey;
    } else {
        X509Certificate caCert = issuerKeys.getCertificate().getCertificate();
        certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName),
                publicKey);
        authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert);
        signerKey = issuerKeys.getPrivateKey().getPrivateKey();
    }
    certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier)
            .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey))
            .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension(
                    Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                            | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
            new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth }));

    //      Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    //      extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    //      extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    //      certBldr.addExtension(Extension.extendedKeyUsage, false,
    //            new ExtendedKeyUsage(extendedKeyUsages));

    // BC 1.49:
    //      certBldr.addExtension(X509Extension.extendedKeyUsage, false,
    //            new ExtendedKeyUsage(new KeyPurposeId[] {
    //                  KeyPurposeId.id_kp_serverAuth,
    //                  KeyPurposeId.id_kp_clientAuth }));
    // create the extension value

    // URI Name
    List<GeneralName> names = new ArrayList<GeneralName>();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));

    // Add DNS name from ApplicationUri
    boolean hasDNSName = false;
    String uriHostName = null;
    try {
        String[] appUriParts = applicationUri.split("[:/]");
        if (appUriParts.length > 1) {
            uriHostName = appUriParts[1];
            if (!uriHostName.toLowerCase().equals("localhost")) {
                GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName);
                names.add(dnsName);
                hasDNSName = true;
            }
        }
    } catch (Exception e) {
        logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri);
    }

    // Add other DNS Names
    List<GeneralName> ipAddressNames = new ArrayList<GeneralName>();
    if (hostNames != null)
        for (String hostName : hostNames) {
            boolean isIpAddress = hostName.matches("^[0-9.]+$");
            if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) {
                GeneralName dnsName = new GeneralName(
                        hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName);
                if (isIpAddress)
                    ipAddressNames.add(dnsName);
                else {
                    names.add(dnsName);
                    hasDNSName = true;
                }
            }
        }
    // Add IP Addresses, if no host names are defined
    if (!hasDNSName)
        for (GeneralName n : ipAddressNames)
            names.add(n);

    final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0]));
    certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);

    //***** generate certificate ***********/
    try {
        ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm())
                .setProvider("BC").build(signerKey);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.openfact.common.util.CertificateUtils.java

License:Apache License

/**
 * Generates version 3 {@link X509Certificate}.
 *
 * @param keyPair the key pair//ww  w  .  jav  a 2s. c o  m
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 *
 * @return the x509 certificate
 *
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey,
        X509Certificate caCert, String subject) throws Exception {

    try {
        X500Name subjectDN = new X500Name("CN=" + subject);

        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));

        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);

        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(
                new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN,
                subjPubKeyInfo);

        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);

        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));

        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));

        // Key Usage
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;

        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));

        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(caPrivateKey);

        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}

From source file:org.parosproxy.paros.security.SslCertificateServiceImpl.java

License:Apache License

@Override
public KeyStore createCertForHost(String hostname)
        throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException,
        SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {

    if (hostname == null) {
        throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
    }//from  ww w  .j a  v  a  2  s  .com

    if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
        throw new MissingRootCertificateException(
                this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
    }

    final KeyPair mykp = this.createKeyPair();
    final PrivateKey privKey = mykp.getPrivate();
    final PublicKey pubKey = mykp.getPublic();

    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, hostname);
    namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
    namebld.addRDN(BCStyle.O, "OWASP");
    namebld.addRDN(BCStyle.C, "xx");
    namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
            new X509CertificateHolder(caCert.getEncoded()).getSubject(),
            BigInteger.valueOf(serial.getAndIncrement()),
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);

    certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

    ContentSigner sigGen;
    try {
        sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
    } catch (OperatorCreationException e) {
        throw new CertificateException(e);
    }
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(caPubKey);

    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    final Certificate[] chain = new Certificate[2];
    chain[1] = this.caCert;
    chain[0] = cert;
    ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
    return ks;
}