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.cesecore.util.provider.EkuPKIXCertPathCheckerTest.java

License:Open Source License

/** @return true if the extendedKeyUsage was accepted */
private boolean validateCert(KeyPair keyPair, boolean isCa, List<String> actualOids, List<String> requiredOids)
        throws Exception {
    final long now = System.currentTimeMillis();
    final List<Extension> additionalExtensions = new ArrayList<Extension>();
    if (actualOids != null) {
        List<KeyPurposeId> actual = new ArrayList<KeyPurposeId>();
        for (final String oid : actualOids) {
            actual.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(oid)));
        }/*from   ww w  .j  av  a 2s  . c om*/
        final ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(actual.toArray(new KeyPurposeId[0]));
        final ASN1Sequence seq = ASN1Sequence.getInstance(extendedKeyUsage.toASN1Primitive());
        final Extension extension = new Extension(Extension.extendedKeyUsage, true, seq.getEncoded());
        additionalExtensions.add(extension);
    }
    final int ku;
    if (isCa) {
        ku = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign;
    } else {
        ku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;
    }
    final X509Certificate cert = CertTools.genSelfCertForPurpose("CN=dummy", new Date(now - 3600000L),
            new Date(now + 3600000L), null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, isCa, ku, null, null, BouncyCastleProvider.PROVIDER_NAME,
            true, additionalExtensions);
    final PKIXCertPathChecker pkixCertPathChecker = new EkuPKIXCertPathChecker(requiredOids);
    final Collection<String> unresolvedCritExts = new ArrayList<String>(
            Arrays.asList(new String[] { Extension.extendedKeyUsage.getId() }));
    pkixCertPathChecker.check(cert, unresolvedCritExts);
    return !unresolvedCritExts.contains(Extension.extendedKeyUsage.getId());
}

From source file:org.conscrypt.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages,
        List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints,
        List<GeneralSubtree> excludedNameConstraints, BigInteger serialNumber) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;/*  www .j av a 2s . c o m*/
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha256WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha256WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    if (serialNumber == null) {
        byte[] serialBytes = new byte[16];
        new SecureRandom().nextBytes(serialBytes);
        serialNumber = new BigInteger(1, serialBytes);
    }

    X509v3CertificateBuilder x509cg = new X509v3CertificateBuilder(X500Name.getInstance(issuer.getEncoded()),
            serialNumber, start, end, X500Name.getInstance(subject.getEncoded()),
            SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
    if (keyUsage != 0) {
        x509cg.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    if (!subjectAltNames.isEmpty()) {
        x509cg.addExtension(Extension.subjectAlternativeName, false,
                new GeneralNames(subjectAltNames.toArray(new GeneralName[0])).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(Extension.nameConstraints, true,
                new NameConstraints(
                        permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]),
                        excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }

    X509CertificateHolder x509holder = x509cg
            .build(new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey));
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    X509Certificate x509c = (X509Certificate) certFactory
            .generateCertificate(new ByteArrayInputStream(x509holder.getEncoded()));
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java

License:Open Source License

protected void addExtendedKeyUsage(X509v3CertificateBuilder certificateBuilder) throws CertIOException {
    certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
            new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

License:Open Source License

@Test
public void test07ExtensionOverride() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Create some crazy extensions to see that we get them when using
    // extension override.
    // We should not get our values when not using extension override
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // SubjectAltName
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dnsName=foo.bar.com");
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    // KeyUsage//w  w w .java  2  s .  c  o  m
    int bcku = 0;
    bcku = X509KeyUsage.decipherOnly;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, ku);
    // Extended Key Usage
    List<KeyPurposeId> usage = new ArrayList<KeyPurposeId>();
    usage.add(KeyPurposeId.id_kp_codeSigning);
    ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(usage);
    extgen.addExtension(Extension.extendedKeyUsage, false, eku);
    // OcspNoCheck
    extgen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE);
    // Netscape cert type
    extgen.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false,
            new NetscapeCertType(NetscapeCertType.objectSigningCA));
    // My completely own
    extgen.addExtension(new ASN1ObjectIdentifier("1.1.1.1.1"), false, new DERIA5String("PrimeKey"));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    // First test without extension override
    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is nonRepudiation for KeyId2
    boolean[] kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertTrue(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertFalse(kubits[8]);
    // Our own ext should not be here
    assertNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));

    // Skip confirmation message, we have tested that several times already

    //
    // Do the same with keyId4, that has full extension override
    one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null,
            null, null, null);
    req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId4", 567);

    ir = (CertReqMessages) req.getBody().getContent();
    reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is decipherOnly for KeyId4
    kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertFalse(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertTrue(kubits[8]);
    // Our own ext should not be here
    assertNotNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNotNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNotNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    List<String> l = cert.getExtendedKeyUsage();
    assertEquals(1, l.size());
    String s = l.get(0);
    assertEquals(KeyPurposeId.id_kp_codeSigning.getId(), s);

    // Skip confirmation message, we have tested that several times already
}

From source file:org.fuin.esmp.EventStoreCertificateMojo.java

License:Open Source License

private static X509Certificate generateCertificate(final String domain, final KeyPair pair) {
    try {//from  w  ww .  j  av  a 2s.  c o  m
        final X500Name issuerName = new X500Name("CN=" + domain);
        final X500Name subjectName = issuerName;
        final BigInteger serial = BigInteger.valueOf(new Random().nextInt());
        final Date notBefore = Date.from(LocalDateTime.of(2016, 1, 1, 0, 0).toInstant(ZoneOffset.UTC));
        final Date notAfter = Date.from(LocalDateTime.of(2099, 1, 1, 0, 0).toInstant(ZoneOffset.UTC));
        final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore,
                notAfter, subjectName, pair.getPublic());
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        final ASN1EncodableVector purposes = new ASN1EncodableVector();
        purposes.add(KeyPurposeId.id_kp_serverAuth);
        builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));
        return signCertificate(builder, pair.getPrivate());
    } catch (final CertIOException ex) {
        throw new RuntimeException("Couldn't generate certificate", ex);
    }
}

From source file:org.hyperledger.fabric.sdk.security.certgen.TLSCertificateBuilder.java

License:Open Source License

private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san)
        throws Exception {
    X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair);

    // Basic constraints
    BasicConstraints constraints = new BasicConstraints(false);
    certBuilder.addExtension(Extension.basicConstraints, true, constraints.getEncoded());
    // Key usage/*from  ww w  . j  ava  2  s  . c o m*/
    KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature);
    certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded());
    // Extended key usage
    certBuilder.addExtension(Extension.extendedKeyUsage, false, certType.keyUsage().getEncoded());

    if (san != null) {
        addSAN(certBuilder, san);
    }

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    X509CertificateHolder holder = certBuilder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    converter.setProvider(new BouncyCastleProvider());
    return converter.getCertificate(holder);
}

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  www .j a  v 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.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;//www  . j a va 2  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>// w w w.  j a  va 2  s  .c o 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.utils.BouncyCastleUtils.java

License:Open Source License

/**
 * Generates a new certificate using the Bouncy Castle implementation.
 * <p>//from  ww w. j a  v  a2s  . c  o 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 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);
    }
}