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

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

Introduction

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

Prototype

ASN1ObjectIdentifier ExtendedKeyUsage

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

Click Source Link

Document

Extended Key Usage

Usage

From source file:org.objectweb.proactive.extensions.ssl.CertificateGenerator.java

License:Open Source License

/**
 * Create a random, self signed, one time certificate
 *
 * A such certificate can be used to take advantage of the SSL/TLS encryption
 * feature without requiring any action from the user.
 *
 * A self signed certificate, valid for the next 10 year is issued.
 *
 * @return/*from   w w w  .j  a  va2s  . co m*/
 */
public X509Certificate generateCertificate(String subjectDN, KeyPair pair) throws SslException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Auto-generated certificate, use a default principal
    X500Principal defaultPrincipal;
    defaultPrincipal = new X500Principal(subjectDN);
    certGen.setIssuerDN(defaultPrincipal);
    certGen.setSubjectDN(defaultPrincipal);

    // Valid for the next few years
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + (10 * 365 * 24 * 60)));

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // Not certified by a CA
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // SSL requires signiture & encipherment
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
    certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage);

    // Allow client and server authentication
    Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>();
    extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsageV));

    try {
        X509Certificate cert = certGen.generate(pair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME);
        try {
            cert.checkValidity();
            cert.verify(pair.getPublic());
        } catch (GeneralSecurityException e) {
            throw new SslException("Generated certificate is not valid", e);
        }

        return cert;
    } catch (GeneralSecurityException e) {
        throw new SslException("Failed to generate certificate", e);
    }
}

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

License:Open Source License

/**
 * //from   w w  w  .  j a va2s.c om
 * @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.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

@Deprecated //Use createApplicationInstanceCertificate instead of this...all the x.509 cert fields are not fulfilled in this
public static org.opcfoundation.ua.transport.security.KeyPair generateKeyPair(String CN) throws Exception {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALG, PROV);
    keyGenerator.initialize(KEY_SIZE);// w  w  w .  ja  v  a  2s.c  o m
    KeyPair key = keyGenerator.generateKeyPair();
    PublicKey publicKey = key.getPublic();
    PrivateKey privateKey = key.getPrivate();

    //Keystore not needed in this function (at the moment)
    ///KeyStore keyStore = null;

    ////keyStore = KeyStore.getInstance(STORE_TYPE);
    ///keyStore.load(null,STORE_PASSWD.toCharArray());

    //Use BouncyCastle as Security provider
    new CryptoUtil();
    //////X509Certificate[] chain = new X509Certificate[1];

    //Generates new certificate..add the information needed for the generator
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal("CN=" + CN);
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    //X509Certificate caCert=null;
    certGen.setIssuerDN(subjectName);
    Date notBefore = new Date();
    Date notAfter = new Date();
    notBefore.setTime(notBefore.getTime() - 1000 * 60 * 60);
    notAfter.setTime(notAfter.getTime() + 1000 * 60 * 60 * 24 * 365);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //X.509 V3 Extensions...these are just examples

    //certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,new AuthorityKeyIdentifierStructure(caCert));
    ///7certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
    ////      new SubjectKeyIdentifierStructure(key.getPublic()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new DEROctetString(new SubjectKeyIdentifierStructure(key.getPublic())));

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

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /////chain[0]= certGen.generate(privateKey, "BC"); // note: private key of CA
    //Generate
    X509Certificate caCert = certGen.generate(privateKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert cert = new Cert(caCert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) privateKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(cert, UAkey);
    /*keyStore.setEntry(ALIAS,new KeyStore.PrivateKeyEntry(privateKey, chain),
    new KeyStore.PasswordProtection(KEY_PASSWD.toCharArray())
    );
            
    // Write out the keystore
    FileOutputStream keyStoreOutputStream = new FileOutputStream(keystorePath);
    keyStore.store(keyStoreOutputStream, "123456".toCharArray());
    keyStoreOutputStream.close();*/

}

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

License:Open Source License

/**
 * generates new certificate chain and returns it..
 * first certificate in the returned chain is the issued certificate and the second one is CA certificate
 * //from   ww w  .  j a  va2s  .  co  m
 * @return certificates 
 * @throws Exception
 */
public static X509Certificate[] createCertificateChain() throws Exception {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    // create the keys
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair pair = keyGen.generateKeyPair();

    X509Certificate rootCert = generateRootCertificate(pair);

    //Create certificate request
    PKCS10CertificationRequest request = createCertificateRequest();

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    X509Certificate issuedCert = certGen.generate(pair.getPrivate());
    X509Certificate[] chain = { issuedCert, rootCert };

    //Write certificates to file so we are able to retrieve the also te private key
    /* URL certURL = CertificateUtils.class.getResource( "createdCerts.pem" );
             
     URLConnection connection = certURL.openConnection();
    InputStream is = connection.getInputStream();
     CertificateFactory servercf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) servercf.generateCertificate(is);
            
    PEMWriter        testWriter = new PEMWriter(new OutputStreamWriter(System.out));
    testWriter.writeObject(cert);*/
    return chain;
}

From source file:org.owasp.proxy.util.BouncyCastleCertificateUtils.java

License:Open Source License

private static void addCertificateExtensions(PublicKey pubKey, PublicKey caPubKey,
        X509V3CertificateGenerator certGen) throws IOException, InvalidKeyException {

    // CertificateExtensions ext = new CertificateExtensions();
    ///*from  w  w w.  ja va2  s . c  o  m*/
    // ext.set(SubjectKeyIdentifierExtension.NAME,
    // new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey)
    // .getIdentifier()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey));
    //
    // ext.set(AuthorityKeyIdentifierExtension.NAME,
    // new AuthorityKeyIdentifierExtension(
    // new KeyIdentifier(caPubKey), null, null));
    //
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caPubKey));
    // // Basic Constraints
    // ext.set(BasicConstraintsExtension.NAME, new
    // BasicConstraintsExtension(
    // /* isCritical */true, /* isCA */false, /* pathLen */5));
    //
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // Netscape Cert Type Extension
    // boolean[] ncteOk = new boolean[8];
    // ncteOk[0] = true; // SSL_CLIENT
    // ncteOk[1] = true; // SSL_SERVER
    // NetscapeCertTypeExtension ncte = new
    // NetscapeCertTypeExtension(ncteOk);
    // ncte = new NetscapeCertTypeExtension(false,
    // ncte.getExtensionValue());
    // ext.set(NetscapeCertTypeExtension.NAME, ncte);

    // Key Usage Extension
    // boolean[] kueOk = new boolean[9];
    // kueOk[0] = true;
    // kueOk[2] = true;
    // "digitalSignature", // (0),
    // "nonRepudiation", // (1)
    // "keyEncipherment", // (2),
    // "dataEncipherment", // (3),
    // "keyAgreement", // (4),
    // "keyCertSign", // (5),
    // "cRLSign", // (6),
    // "encipherOnly", // (7),
    // "decipherOnly", // (8)
    // "contentCommitment" // also (1)
    // KeyUsageExtension kue = new KeyUsageExtension(kueOk);
    // ext.set(KeyUsageExtension.NAME, kue);
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new X509KeyUsage(X509KeyUsage.digitalSignature + X509KeyUsage.keyEncipherment));

    // Extended Key Usage Extension
    // int[] serverAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 1 };
    // ObjectIdentifier serverAuthOid = new
    // ObjectIdentifier(serverAuthOidData);
    // int[] clientAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 2 };
    // ObjectIdentifier clientAuthOid = new
    // ObjectIdentifier(clientAuthOidData);
    // Vector<ObjectIdentifier> v = new Vector<ObjectIdentifier>();
    // v.add(serverAuthOid);
    // v.add(clientAuthOid);
    // ExtendedKeyUsageExtension ekue = new ExtendedKeyUsageExtension(false,
    // v);
    // ext.set(ExtendedKeyUsageExtension.NAME, ekue);
    // ExtendedKeyUsage extendedKeyUsage = new
    // ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage);
    Vector<KeyPurposeId> usages = new Vector<KeyPurposeId>();
    usages.add(KeyPurposeId.id_kp_serverAuth);
    usages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(usages));

}

From source file:org.qipki.ca.domain.ca.CAMixin.java

License:Open Source License

@Override
public X509Certificate sign(X509Profile x509profile, PKCS10CertificationRequest pkcs10) {
    LOGGER.debug(//from   w  ww . j  a v a  2 s . com
            "Handling a PKCS#10 Certificate Signing Request using X509Profile " + x509profile.name().get());
    try {

        ensureX509ProfileIsAllowed(x509profile);

        List<X509ExtensionHolder> extensions = x509ExtReader.extractRequestedExtensions(pkcs10);
        ensureNoIllegalRequestedExtensions(extensions);

        // Adding extensions commons to all profiles
        SubjectKeyIdentifier subjectKeyID = x509ExtBuilder.buildSubjectKeyIdentifier(pkcs10.getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.SubjectKeyIdentifier, false, subjectKeyID));
        AuthorityKeyIdentifier authKeyID = x509ExtBuilder
                .buildAuthorityKeyIdentifier(certificate().getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.AuthorityKeyIdentifier, false, authKeyID));

        // Applying X509Profile on issued X509Certificate
        if (x509profile.basicConstraints().get().subjectIsCA().get()) {
            BasicConstraints bc = x509ExtBuilder
                    .buildCABasicConstraints(x509profile.basicConstraints().get().pathLengthConstraint().get());
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        } else {
            BasicConstraints bc = x509ExtBuilder.buildNonCABasicConstraints();
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        }
        KeyUsage keyUsages = x509ExtBuilder.buildKeyUsages(x509profile.keyUsages().get().keyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.KeyUsage,
                x509profile.keyUsages().get().critical().get(), keyUsages));

        ExtendedKeyUsage extendedKeyUsage = x509ExtBuilder
                .buildExtendedKeyUsage(x509profile.extendedKeyUsages().get().extendedKeyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.ExtendedKeyUsage,
                x509profile.extendedKeyUsages().get().critical().get(), extendedKeyUsage));

        NetscapeCertType netscapeCertType = x509ExtBuilder
                .buildNetscapeCertTypes(x509profile.netscapeCertTypes().get().netscapeCertTypes().get());
        extensions.add(new X509ExtensionHolder(MiscObjectIdentifiers.netscapeCertType,
                x509profile.netscapeCertTypes().get().critical().get(), netscapeCertType));

        String[] crlDistPoints = gatherCRLDistributionPoints();
        if (crlDistPoints.length > 0) {
            CRLDistPoint crlDistPointsExt = x509ExtBuilder
                    .buildCRLDistributionPoints(certificate().getSubjectX500Principal(), crlDistPoints);
            extensions.add(
                    new X509ExtensionHolder(X509Extensions.CRLDistributionPoints, false, crlDistPointsExt));
        }

        DistinguishedName issuerDN = new DistinguishedName(certificate().getSubjectX500Principal());
        DistinguishedName subjectDN = new DistinguishedName(pkcs10.getCertificationRequestInfo().getSubject());
        X509Certificate certificate = x509Generator.generateX509Certificate(privateKey(), issuerDN,
                BigInteger.probablePrime(120, new SecureRandom()), subjectDN, pkcs10.getPublicKey(),
                Duration.standardDays(x509profile.validityDays().get()), extensions);

        return certificate;

    } catch (GeneralSecurityException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new QiPkiFailure("Unable to enroll PKCS#10", ex);
    }
}

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

License:Open Source License

@Override
@SuppressWarnings("SetReplaceableByEnumSet")
public Set<ExtendedKeyUsage> getExtendedKeyUsages(X509Certificate cert) {
    try {//from   www .j a v  a  2s . c om
        byte[] value = cert.getExtensionValue(X509Extensions.ExtendedKeyUsage.getId());
        if (value == null) {
            return Collections.emptySet();
        }
        byte[] asn1octets = ((ASN1OctetString) ASN1Object.fromByteArray(value)).getOctets();
        org.bouncycastle.asn1.x509.ExtendedKeyUsage usages = org.bouncycastle.asn1.x509.ExtendedKeyUsage
                .getInstance((ASN1Sequence) ASN1Sequence.fromByteArray(asn1octets));
        Set<ExtendedKeyUsage> keyUsages = new LinkedHashSet<ExtendedKeyUsage>();
        for (ExtendedKeyUsage eachPossible : ExtendedKeyUsage.values()) {
            if (usages.hasKeyPurposeId(eachPossible.getKeyPurposeId())) {
                keyUsages.add(eachPossible);
            }
        }
        return keyUsages;
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to extract ExtendedKeyUsages from X509Certificate extensions", ex);
    }
}

From source file:org.votingsystem.signature.util.CertExtensionCheckerVS.java

License:Open Source License

public CertExtensionCheckerVS() {
    supportedExtensions = new HashSet<String>();
    extensionsVS = new HashSet<ExtensionVS>();
    supportedExtensions.add(X509Extensions.ExtendedKeyUsage.toString());
    supportedExtensions.add(ExtensionVS.VOTE.getOID());
    supportedExtensions.add(ExtensionVS.REPRESENTATIVE_VOTE.getOID());
    supportedExtensions.add(ExtensionVS.ANONYMOUS_REPRESENTATIVE_DELEGATION.getOID());
    supportedExtensions.add(ExtensionVS.CURRENCY.getOID());
    supportedExtensions.add(ExtensionVS.DEVICEVS.getOID());
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 certificate for TimeStamp signing
 */// w  w w.j  av  a 2s  . co  m
public static X509Certificate generateTimeStampingCert(PublicKey entityKey, PrivateKey caKey,
        X509Certificate caCert, long begin, long period, String endEntitySubjectDN) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(begin));
    certGen.setNotAfter(new Date(begin + period));
    certGen.setSubjectDN(new X500Principal(endEntitySubjectDN));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(new DERSequence(KeyPurposeId.id_kp_timeStamping)));
    return certGen.generate(caKey, ContextVS.PROVIDER);
}

From source file:test.integ.be.fedict.trust.util.TestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, X509Certificate issuerCert, DateTime notBefore, DateTime notAfter,
        String signatureAlgorithm, boolean includeAuthorityKeyIdentifier, boolean caCert,
        boolean timeStampingPurpose, String ocspUri, String crlUri, KeyUsage keyUsage, BigInteger serialNumber)
        throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException {

    String finalSignatureAlgorithm = signatureAlgorithm;
    if (null == signatureAlgorithm) {
        finalSignatureAlgorithm = "SHA512WithRSAEncryption";
    }/*from  w  w  w.j a v  a  2 s . co  m*/
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm(finalSignatureAlgorithm);
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());
    X509Principal issuerDN;
    if (null != issuerCert) {
        issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().getName());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(serialNumber);

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    if (null != issuerCert) {
        issuerPublicKey = issuerCert.getPublicKey();
    } else {
        issuerPublicKey = subjectPublicKey;
    }
    if (includeAuthorityKeyIdentifier) {
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));
    }

    certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(caCert));

    if (timeStampingPurpose) {
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false,
                authorityInformationAccess);
    }

    if (null != crlUri) {
        GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlUri));
        GeneralNames gns = new GeneralNames(gn);
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        certificateGenerator.addExtension(X509Extensions.CRLDistributionPoints, false, new DERSequence(distp));
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage);
    }

    return certificateGenerator.generate(issuerPrivateKey);

    // /*
    // * Make sure the default certificate provider is active.
    // */
    // CertificateFactory certificateFactory = CertificateFactory
    // .getInstance("X.509");
    // certificate = (X509Certificate) certificateFactory
    // .generateCertificate(new ByteArrayInputStream(certificate
    // .getEncoded()));
    //
    // return certificate;
}