Example usage for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier

List of usage examples for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier.

Prototype

int uniformResourceIdentifier

To view the source code for org.bouncycastle.asn1.x509 GeneralName uniformResourceIdentifier.

Click Source Link

Usage

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException {
    if (valuex.startsWith(DNS_)) {
        final String dns = valuex.substring(DNS_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }//from w w  w .  java  2s  . c  o  m
    if (valuex.startsWith(DNS_Name_)) {
        final String dns = valuex.substring(DNS_Name_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }
    if (valuex.startsWith(URI_)) {
        final String uri = valuex.substring(URI_.length());
        return new GeneralName(GeneralName.uniformResourceIdentifier, uri);
    }
    if (valuex.startsWith(RID_)) {
        final String rid = valuex.substring(RID_.length());
        return new GeneralName(GeneralName.registeredID, rid);
    }
    if (valuex.startsWith(email_)) {
        final String mail = valuex.substring(email_.length());
        return new GeneralName(GeneralName.rfc822Name, mail);
    }
    if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) {
        final int idx = valuex.charAt(2) == ':' ? 3 : 11;
        String[] vals = valuex.substring(idx).split("\\.|::");
        final byte[] ip = new byte[vals.length];
        for (int i = 0; i < vals.length; i++) {
            ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff);
        }
        return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip));
    }
    if (valuex.startsWith("other")) { // otherName || othername
        final String other = valuex.substring(otherName_.length());
        return new GeneralName(GeneralName.otherName, other);
    }
    if (valuex.startsWith("dir")) { // dirName || dirname
        final String dir = valuex.substring(dirName_.length());
        return new GeneralName(GeneralName.directoryName, dir);
    }

    throw new IOException("could not parse SubjectAltName: " + valuex);

}

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

License:Apache License

/**
 * Retrieves a list of CRL distribution points from CRLDP v3 certificate extension
 * See <a href="www.nakov.com/blog/2009/12/01/x509-certificate-validation-in-java-build-and-verify-cchain-and-verify-clr-with-bouncy-castle/">CRL validation</a>
 * @param cert/*  www. j a v  a 2  s . c o m*/
 * @return
 * @throws IOException
 */
public static List<String> getCRLDistributionPoints(X509Certificate cert) throws IOException {
    byte[] data = cert.getExtensionValue(CRL_DISTRIBUTION_POINTS_OID);
    if (data == null) {
        return Collections.emptyList();
    }

    List<String> distributionPointUrls = new LinkedList<>();
    DEROctetString octetString;
    try (ASN1InputStream crldpExtensionInputStream = new ASN1InputStream(new ByteArrayInputStream(data))) {
        octetString = (DEROctetString) crldpExtensionInputStream.readObject();
    }
    byte[] octets = octetString.getOctets();

    CRLDistPoint crlDP;
    try (ASN1InputStream crldpInputStream = new ASN1InputStream(new ByteArrayInputStream(octets))) {
        crlDP = CRLDistPoint.getInstance(crldpInputStream.readObject());
    }

    for (DistributionPoint dp : crlDP.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            GeneralName[] names = GeneralNames.getInstance(dpn.getName()).getNames();
            for (GeneralName gn : names) {
                if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    String url = DERIA5String.getInstance(gn.getName()).getString();
                    distributionPointUrls.add(url);
                }
            }
        }
    }

    return distributionPointUrls;
}

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

License:Apache License

/**
 * Extracts OCSP responder URI from X509 AIA v3 extension, if available. There can be
 * multiple responder URIs encoded in the certificate.
 * @param cert/*www  . j  av  a 2  s.  c om*/
 * @return a list of available responder URIs.
 * @throws CertificateEncodingException
 */
private static List<String> getResponderURIs(X509Certificate cert) throws CertificateEncodingException {

    LinkedList<String> responderURIs = new LinkedList<>();
    JcaX509CertificateHolder holder = new JcaX509CertificateHolder(cert);
    Extension aia = holder.getExtension(Extension.authorityInfoAccess);
    if (aia != null) {
        try {
            ASN1InputStream in = new ASN1InputStream(aia.getExtnValue().getOctetStream());
            ASN1Sequence seq = (ASN1Sequence) in.readObject();
            AuthorityInformationAccess authorityInfoAccess = AuthorityInformationAccess.getInstance(seq);
            for (AccessDescription ad : authorityInfoAccess.getAccessDescriptions()) {
                if (ad.getAccessMethod().equals(AccessDescription.id_ad_ocsp)) {
                    // See https://www.ietf.org/rfc/rfc2560.txt, 3.1 Certificate Content
                    if (ad.getAccessLocation().getTagNo() == GeneralName.uniformResourceIdentifier) {
                        DERIA5String value = DERIA5String.getInstance(ad.getAccessLocation().getName());
                        responderURIs.add(value.getString());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return responderURIs;
}

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

License:Apache License

private DistributionPoint[] createCrlDistributionPoints() {
    List<DistributionPoint> list = new ArrayList<>();
    Set<String> keys = getArrayKeys(PROPERTY_PREFIX_CRL_DISTRIBUTION_POINT);
    for (String dpPrefix : keys) {
        final String uriKey = dpPrefix + ".uri";
        String uri = getMandatoryProperty(uriKey);

        DistributionPointName dpName = new DistributionPointName(
                new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, uri)));
        list.add(new DistributionPoint(dpName, null, null));
    }/*from  ww w  .j  av  a  2s.c  om*/
    if (list.isEmpty())
        return null;
    return list.toArray(new DistributionPoint[list.size()]);
}

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

License:Apache License

private AccessDescription[] createAccessDescriptions() {
    List<AccessDescription> list = new ArrayList<>();
    Set<String> keys = getArrayKeys(PROPERTY_PREFIX_AUTHORITY_INFORMATION_ACCESS);
    for (String dpPrefix : keys) {
        final String typeKey = dpPrefix + ".type";
        final String type = getMandatoryProperty(typeKey);

        final String uriKey = dpPrefix + ".uri";
        final String uri = getMandatoryProperty(uriKey);

        ASN1ObjectIdentifier aiaId = null;
        switch (type) {
        case "ocsp":
            aiaId = AccessDescription.id_ad_ocsp;
            break;
        case "issuer":
            aiaId = AccessDescription.id_ad_caIssuers;
            break;
        default://w ww  . j  a  va 2 s.co  m
            throw new IllegalArgumentException(
                    String.format("Value '%s' not supported for '%s'. Supported values are 'ocsp' or 'issuer'.",
                            type, typeKey));
        }

        AccessDescription accessDescription = new AccessDescription(aiaId,
                new GeneralName(GeneralName.uniformResourceIdentifier, uri));

        list.add(accessDescription);
    }

    if (list.isEmpty())
        return null;
    return list.toArray(new AccessDescription[list.size()]);
}

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  w w. j a  v a  2 s. 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 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>/*  w  ww . jav  a 2  s  .  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.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

/**
 * //  w ww.ja  v  a  2 s .co  m
 * @param commonName - Common Name (CN) for generated certificate
 * @param organisation - Organisation (O) for generated certificate
 * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null
 * @param validityTime - the time that the certificate is valid (in days)
 * @return
 * @throws IOException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws CertificateParsingException
 */
public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate(
        String commonName, String organisation, String applicationUri, int validityTime) throws IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException,
        IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException {
    if (applicationUri == null)
        throw new NullPointerException("applicationUri must not be null");
    //Add provider for generator
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    //Initializes generator 
    SecureRandom srForCert = new SecureRandom();
    RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator();

    //Used for generating prime
    Random r = new Random(System.currentTimeMillis());
    int random = -1;

    while (random < 3) {
        random = r.nextInt(32);
    }
    //calculate(generate) possible value for public modulus
    //used method is "monte carlo -algorithm", so we calculate it as long as it generates value.
    BigInteger value = null;
    while (value == null) {
        value = BigInteger.probablePrime(random, new SecureRandom());
    }

    //Generate (Java) keypair
    genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80));
    AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair();

    //Extract the keys from parameters
    logger.debug("Generated keypair, extracting components and creating public structure for certificate");
    RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic();
    RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate();
    // used to get proper encoding for the certificate
    RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(),
            clientPublicKey.getExponent());
    logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent="
            + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus());

    // JCE format needed for the certificate - because getEncoded() is necessary...
    PublicKey certPubKey = KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent()));
    // and this one for the KeyStore
    PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate(
            new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(),
                    clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(),
                    clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv()));

    //The data for the certificate..
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.add(Calendar.DAY_OF_YEAR, validityTime);

    X509Name certificateX509Name = new X509Name(
            "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country"));

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    certGen.setSerialNumber(serial);
    //Issuer and subject must be the same (because this is self signed)
    certGen.setIssuerDN(certificateX509Name);
    certGen.setSubjectDN(certificateX509Name);

    //expiry & start time for this certificate
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks)
    certGen.setNotAfter(expiryTime.getTime());

    certGen.setPublicKey(certPubKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //******* X.509 V3 Extensions *****************

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject());
    SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki);

    /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
    new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey)));
        */
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
    certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation
                            | KeyUsage.dataEncipherment | KeyUsage.keyCertSign));

    BasicConstraints b = new BasicConstraints(false);

    Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage(
                    extendedKeyUsages));

    // create the extension value
    ASN1EncodableVector names = new ASN1EncodableVector();
    names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    //      GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri);
    //      names.add(dnsName);
    final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names));

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

    // AuthorityKeyIdentifier

    final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name));
    AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
    //***** generate certificate ***********/
    X509Certificate cert = certGen.generate(certPrivKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert certificate = new Cert(cert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) certPrivKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey);
}

From source file:org.openqa.selenium.security.CertificateGenerator.java

License:Apache License

public KeyAndCert generateCertificate(String hostname, String certificateRevocationList) {
    X500Principal x500issuer = caCert.getCertificate().getIssuerX500Principal();
    String subject = String.format("CN=%s, OU=Test, O=CyberVillainsCA, L=Seattle, S=Washington, C=US",
            hostname);/*from  w  ww . ja va 2  s .c o m*/
    X500Principal x500subject = new X500Principal(subject);

    Date begin = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
    Date end = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365));

    KeyPair keypair = pairGenerator.generateKeyPair();

    try {
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(keypair.getPublic().getEncoded()))
                        .readObject());

        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(x500issuer,
                BigInteger.valueOf(serialSeed.getAndIncrement()), begin, end, x500subject, keypair.getPublic());
        builder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        builder.addExtension(X509Extension.subjectKeyIdentifier, false, info);

        AuthorityKeyIdentifier caIdentifier = new JcaX509ExtensionUtils()
                .createAuthorityKeyIdentifier(caCert.getCertificate());
        builder.addExtension(X509Extension.authorityKeyIdentifier, false, caIdentifier);

        DERSequence typicalSSLServerExtendedKeyUsages = new DERSequence(new ASN1Encodable[] {
                new DERObjectIdentifier(SERVER_AUTH), new DERObjectIdentifier(CLIENT_AUTH), });

        builder.addExtension(X509Extension.extendedKeyUsage, false, typicalSSLServerExtendedKeyUsages);

        if (certificateRevocationList != null) {
            /* Safari on Windows requires a CRL and validates it */
            DistributionPoint crl = new DistributionPoint(
                    new DistributionPointName(DistributionPointName.FULL_NAME,
                            new GeneralName(GeneralName.uniformResourceIdentifier, certificateRevocationList)),
                    null, null);
            builder.addExtension(X509Extension.cRLDistributionPoints, false,
                    new CRLDistPoint(new DistributionPoint[] { crl }));
        }

        ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE)
                .build(caCert.getPrivateKey());

        X509CertificateHolder holder = builder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE)
                .getCertificate(holder);

        return new KeyAndCert(keypair.getPrivate(), cert);
    } catch (GeneralSecurityException e) {
        throw Throwables.propagate(e);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (OperatorCreationException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.qipki.crypto.x509.X509ExtensionsBuilderImpl.java

License:Open Source License

@Override
public CRLDistPoint buildCRLDistributionPoints(Map<X500Principal, Iterable<String>> crlDistPointsData) {
    List<DistributionPoint> distributionPoints = new ArrayList<DistributionPoint>();
    for (Map.Entry<X500Principal, Iterable<String>> eachIssuerEntry : crlDistPointsData.entrySet()) {

        GeneralName issuerName = new GeneralName(new X509Name(eachIssuerEntry.getKey().getName()));
        ASN1EncodableVector issuerVector = new ASN1EncodableVector();
        issuerVector.add(issuerName);/*from   ww  w  .ja  v  a 2  s  . com*/
        GeneralNames issuerNames = new GeneralNames(new DERSequence(issuerVector));

        for (String eachEndpoint : eachIssuerEntry.getValue()) {

            GeneralName endpointName = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(eachEndpoint));
            ASN1EncodableVector epVector = new ASN1EncodableVector();
            epVector.add(endpointName);
            GeneralNames endpointNames = new GeneralNames(new DERSequence(epVector));
            DistributionPointName dpn = new DistributionPointName(DistributionPointName.FULL_NAME,
                    endpointNames);

            distributionPoints.add(new DistributionPoint(dpn, null, issuerNames));
        }
    }
    return new CRLDistPoint(distributionPoints.toArray(new DistributionPoint[distributionPoints.size()]));
}