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

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

Introduction

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

Prototype

ASN1ObjectIdentifier BasicConstraints

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

Click Source Link

Document

Basic Constraints

Usage

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

License:Open Source License

/**
 * //from  w w w  .j av a  2  s . c  o 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.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.j ava 2 s.  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 w w  w  . ja va2  s .  c  om*/
 * @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.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Creates a lower level certificate, adding authority key-id and subject
  * key-id extensions to the resulting certificate (version 3).
 * /* w  ww .j  av a2 s . co  m*/
 * @param pubKey
 * @param serialNumber
 * @param name
 * @param notBefore
 * @param notAfter
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @param friendlyName
 * @return X509Certificate
 * @throws Exception
 */
public static X509Certificate createCert(PublicKey pubKey, BigInteger serialNumber, String name, Date notBefore,
        Date notAfter, String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert,
        String friendlyName) throws Exception {
    byte[] nameBytes = new X500Principal(name).getEncoded();

    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(notBefore);
    v3CertGen.setNotAfter(notAfter);
    v3CertGen.setSubjectDN(new X509Principal(nameBytes));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(pubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient
                    | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    if (friendlyName != null) {
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(pubKey));
    }

    return cert;
}

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Generate a certificate which is a "copy" of another certificate, but 
* resigned by a different issuer./*from  ww w.j  a v  a2 s.  c  o m*/
 *
 * @param initialCert
 * @param serialNumber
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @return X509Certificate
 */
public static X509Certificate resignCert(X509Certificate initialCert, BigInteger serialNumber,
        String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert) throws Exception {
    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(initialCert.getNotBefore());
    v3CertGen.setNotAfter(initialCert.getNotAfter());
    v3CertGen.setSubjectDN(new X509Principal(initialCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setPublicKey(initialCert.getPublicKey());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(initialCert.getPublicKey()));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.sslClient | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    return cert;
}

From source file:org.opensc.test.pkcs11.SaveCertificateTest.java

License:Open Source License

public void testX509CertificateGeneration() throws KeyStoreException, NoSuchProviderException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException,
        InvalidKeyException, IllegalStateException, SignatureException, InvalidKeySpecException {
    KeyStore ks = KeyStore.getInstance("PKCS11", "OpenSC-PKCS11");

    PKCS11LoadStoreParameter params = new PKCS11LoadStoreParameter();

    PINEntry pe = new PINEntry();

    params.setWaitForSlot(true);// w  ww .ja v  a  2s  .  com
    params.setProtectionCallback(pe);
    params.setSOProtectionCallback(pe);
    params.setWriteEnabled(true);
    params.setEventHandler(pe);

    ks.load(params);

    // well, find a private key.
    Enumeration<String> aliases = ks.aliases();

    String alias = null;

    while (aliases.hasMoreElements()) {
        String s = aliases.nextElement();
        if (ks.isKeyEntry(s)) {
            alias = s;
            break;
        }
    }

    assertNotNull(alias);

    PKCS11PrivateKey privKey = (PKCS11PrivateKey) ks.getKey(alias, null);
    PKCS11PublicKey pubKey = privKey.getPublicKey();

    KeyFactory kf = KeyFactory.getInstance(pubKey.getAlgorithm());

    PublicKey dup = (PublicKey) kf.translateKey(pubKey);

    PKCS11Id enc1 = new PKCS11Id(pubKey.getEncoded());
    PKCS11Id enc2 = new PKCS11Id(dup.getEncoded());

    System.out.println("enc1=" + enc1);
    System.out.println("enc2=" + enc2);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    long now = System.currentTimeMillis();

    certGen.setSerialNumber(BigInteger.valueOf(now));

    X509Principal subject = new X509Principal("CN=PKCS11 Test CA,DC=opensc-project,DC=org");

    certGen.setIssuerDN(subject);
    certGen.setSubjectDN(subject);

    Date from_date = new Date(now);
    certGen.setNotBefore(from_date);
    Calendar cal = new GregorianCalendar();
    cal.setTime(from_date);
    cal.add(Calendar.YEAR, 4);
    Date to_date = cal.getTime();
    certGen.setNotAfter(to_date);

    certGen.setPublicKey(dup);
    certGen.setSignatureAlgorithm("SHA256withRSA");
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    X509Certificate x509 = certGen.generate(privKey, "OpenSC-PKCS11");

    ks.setCertificateEntry(alias, x509);
}

From source file:org.openuat.channel.X509CertificateGenerator.java

License:Open Source License

/** This method implements the public one, but offers an additional parameter which is only used when
 * creating a new CA, namely the export alias to use.
 * @param commonName @see #createCertificate(String, int, String, String)
 * @param validityDays @see #createCertificate(String, int, String, String)
 * @param exportFile @see #createCertificate(String, int, String, String)
 * @param exportPassword @see #createCertificate(String, int, String, String)
 * @param exportAlias If this additional parameter is null, a default value will be used as the "friendly name" in the PKCS12 file.
 * @return @see #createCertificate(String, int, String, String)
 * //  w ww  .ja  v  a 2 s .c  om
 * @see #X509CertificateGenerator(boolean)
 */
protected boolean createCertificate(String commonName, int validityDays, String exportFile,
        String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException,
        SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException,
        CertificateException, InvalidKeySpecException {
    if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) {
        throw new IllegalArgumentException("Can not work with null parameter");
    }

    logger.info("Generating certificate for distinguished common subject name '" + commonName + "', valid for "
            + validityDays + " days");
    SecureRandom sr = new SecureRandom();

    // the JCE representation
    PublicKey pubKey;
    PrivateKey privKey;

    // the BCAPI representation
    RSAPrivateCrtKeyParameters privateKey = null;

    logger.debug("Creating RSA keypair");
    // generate the keypair for the new certificate
    if (useBCAPI) {
        RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
        // TODO: what are these values??
        gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80));
        AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
        logger.debug("Generated keypair, extracting components and creating public structure for certificate");
        RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
        privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();
        // used to get proper encoding for the certificate
        RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(),
                publicKey.getExponent());
        logger.debug("New public key is '" + new String(Hex.encodeHex(pkStruct.getEncoded())) + ", exponent="
                + publicKey.getExponent() + ", modulus=" + publicKey.getModulus());
        // TODO: these two lines should go away
        // JCE format needed for the certificate - because getEncoded() is necessary...
        pubKey = KeyFactory.getInstance("RSA")
                .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
        // and this one for the KeyStore
        privKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                        privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(),
                        privateKey.getDQ(), privateKey.getQInv()));
    } else {
        // this is the JSSE way of key generation
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, sr);
        KeyPair keypair = keyGen.generateKeyPair();
        privKey = keypair.getPrivate();
        pubKey = keypair.getPublic();
    }

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    X509Name x509Name = new X509Name("CN=" + commonName);

    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
    if (caCert != null) {
        // Attention: this is a catch! Just using "new X509Name(caCert.getSubjectDN().getName())" will not work!
        // I don't know why, because the issuerDN strings look similar with both versions.
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
    } else {
        // aha, no CA set, which means that we should create a self-signed certificate (called from createCA)
        certGen.setIssuer(x509Name);
    }
    certGen.setSubject(x509Name);
    DERObjectIdentifier sigOID = X509Util.getAlgorithmOID(CertificateSignatureAlgorithm);
    AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
    certGen.setSignature(sigAlgId);
    //certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId, pkStruct.toASN1Object()));
    // TODO: why does the coding above not work? - make me work without PublicKey class
    certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject()));
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
    certGen.setEndDate(new Time(expiry.getTime()));

    // These X509v3 extensions are not strictly necessary, but be nice and provide them...
    Hashtable extensions = new Hashtable();
    Vector extOrdering = new Vector();
    addExtensionHelper(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey),
            extOrdering, extensions);
    if (caCert != null) {
        // again: only if we have set CA
        addExtensionHelper(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions);
    } else {
        // but if we create a new self-signed cert, set its capability to be a CA
        // this is a critical extension (true)!
        addExtensionHelper(X509Extensions.BasicConstraints, true, new BasicConstraints(0), extOrdering,
                extensions);
    }
    certGen.setExtensions(new X509Extensions(extOrdering, extensions));

    logger.debug("Certificate structure generated, creating SHA1 digest");
    // attention: hard coded to be SHA1+RSA!
    SHA1Digest digester = new SHA1Digest();
    AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
    TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(tbsCert);

    // and now sign
    byte[] signature;
    if (useBCAPI) {
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        logger.debug("Block to sign is '" + new String(Hex.encodeHex(certBlock)) + "'");
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // and sign that
        if (caCert != null) {
            rsa.init(true, caPrivateKey);
        } else {
            // no CA - self sign
            logger.info("No CA has been set, creating self-signed certificate as a new CA");
            rsa.init(true, privateKey);
        }
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);
    } else {
        // or the JCE way
        Signature sig = Signature.getInstance(sigOID.getId());
        if (caCert != null) {
            PrivateKey caPrivKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateCrtKeySpec(caPrivateKey.getModulus(),
                            caPrivateKey.getPublicExponent(), caPrivateKey.getExponent(), caPrivateKey.getP(),
                            caPrivateKey.getQ(), caPrivateKey.getDP(), caPrivateKey.getDQ(),
                            caPrivateKey.getQInv()));
            sig.initSign(caPrivKey, sr);
        } else {
            logger.info("No CA has been set, creating self-signed certificate as a new CA");
            sig.initSign(privKey, sr);
        }
        sig.update(bOut.toByteArray());
        signature = sig.sign();
    }
    logger.debug("SHA1/RSA signature of digest is '" + new String(Hex.encodeHex(signature)) + "'");

    // and finally construct the certificate structure
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));

    X509CertificateObject clientCert = new X509CertificateObject(
            new X509CertificateStructure(new DERSequence(v)));
    logger.debug("Verifying certificate for correct signature with CA public key");
    /*        if (caCert != null) {
               clientCert.verify(caCert.getPublicKey());
            }
            else {
               clientCert.verify(pubKey);
            }*/

    // and export as PKCS12 formatted file along with the private key and the CA certificate 
    logger.debug("Exporting certificate in PKCS12 format");

    PKCS12BagAttributeCarrier bagCert = clientCert;
    // if exportAlias is set, use that, otherwise a default name
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias));
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(pubKey));

    // this does not work as in the example
    /*PKCS12BagAttributeCarrier   bagKey = (PKCS12BagAttributeCarrier)privKey;
    bagKey.setBagAttribute(
    PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
    new SubjectKeyIdentifierStructure(tmpKey));*/

    Object store;
    if (!useBCAPI) {
        store = java.security.KeyStore.getInstance("PKCS12");
        ((java.security.KeyStore) store).load(null, null);
    } else {
        store = new JDKPKCS12KeyStore(null, sigOID, sigOID);
        ((JDKPKCS12KeyStore) store).engineLoad(null, null);
    }

    FileOutputStream fOut = new FileOutputStream(exportFile);
    X509Certificate[] chain;

    if (caCert != null) {
        chain = new X509Certificate[2];
        // first the client, then the CA certificate - this is the expected order for a certificate chain
        chain[0] = clientCert;
        chain[1] = caCert;
    } else {
        // for a self-signed certificate, there is no chain...
        chain = new X509Certificate[1];
        chain[0] = clientCert;
    }

    if (!useBCAPI) {
        ((java.security.KeyStore) store).setKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias,
                privKey, exportPassword.toCharArray(), chain);
        ((java.security.KeyStore) store).store(fOut, exportPassword.toCharArray());
    } else {
        ((JDKPKCS12KeyStore) store).engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias,
                privKey, exportPassword.toCharArray(), chain);
        ((JDKPKCS12KeyStore) store).engineStore(fOut, exportPassword.toCharArray());
    }

    return true;
}

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

License:Open Source License

private static void addCACertificateExtensions(X509V3CertificateGenerator certGen) throws IOException {
    // Basic Constraints
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
}

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();
    ///* w  w w .j  av  a  2 s .  co 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(/* ww  w. jav a  2  s . co  m*/
            "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);
    }
}