Search in sources :

Example 1 with SubjectKeyIdentifierStructure

use of org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure in project nhin-d by DirectProject.

the class CertGenerator method createLeafCertificate.

private static CertCreateFields createLeafCertificate(CertCreateFields fields, KeyPair keyPair) throws Exception {
    StringBuilder dnBuilder = new StringBuilder();
    // create the DN
    if (fields.getAttributes().containsKey("EMAILADDRESS"))
        dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
    if (fields.getAttributes().containsKey("CN"))
        dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
    if (fields.getAttributes().containsKey("C"))
        dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
    if (fields.getAttributes().containsKey("ST"))
        dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
    if (fields.getAttributes().containsKey("L"))
        dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
    if (fields.getAttributes().containsKey("O"))
        dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
    String DN = dnBuilder.toString().trim();
    if (DN.endsWith(","))
        ;
    DN = DN.substring(0, DN.length() - 1);
    X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
    // not the best way to do this... generally done with a db file
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(fields.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(DN));
    v1CertGen.setPublicKey(keyPair.getPublic());
    v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
    // pointer to the parent CA
    v1CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(fields.getSignerCert()));
    v1CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
    v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    // use the CA's private key to sign the certificate
    X509Certificate newCACert = v1CertGen.generate((PrivateKey) fields.getSignerKey(), "BC");
    // validate the certificate 
    newCACert.verify(fields.getSignerCert().getPublicKey());
    // write the certificate the file system
    writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
    return fields;
}
Also used : X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) X509Principal(org.bouncycastle.jce.X509Principal) SubjectKeyIdentifierStructure(org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) Calendar(java.util.Calendar) AuthorityKeyIdentifierStructure(org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate)

Example 2 with SubjectKeyIdentifierStructure

use of org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure in project robovm by robovm.

the class CertificateFactoryTest method generateCertificate.

@SuppressWarnings("deprecation")
private static KeyHolder generateCertificate(boolean isCa, KeyHolder issuer) throws Exception {
    Date startDate = new Date();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    // Jan 1, 2100 UTC
    cal.set(2100, 0, 1, 0, 0, 0);
    Date expiryDate = cal.getTime();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();
    BigInteger serial;
    X500Principal issuerPrincipal;
    X500Principal subjectPrincipal;
    PrivateKey caKey;
    if (issuer != null) {
        serial = issuer.certificate.getSerialNumber().add(BigInteger.ONE);
        subjectPrincipal = new X500Principal("CN=Test Certificate Serial #" + serial.toString());
        issuerPrincipal = issuer.certificate.getSubjectX500Principal();
        caKey = issuer.privateKey;
    } else {
        serial = BigInteger.ONE;
        subjectPrincipal = new X500Principal("CN=Test CA, O=Tests, C=US");
        issuerPrincipal = subjectPrincipal;
        caKey = keyPair.getPrivate();
    }
    BasicConstraints basicConstraints;
    if (isCa) {
        basicConstraints = new BasicConstraints(10 - serial.intValue());
    } else {
        basicConstraints = new BasicConstraints(false);
    }
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(serial);
    certGen.setIssuerDN(issuerPrincipal);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA1withRSA");
    if (issuer != null) {
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuer.certificate));
    } else {
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    }
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
    certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints);
    X509Certificate cert = certGen.generate(caKey);
    KeyHolder holder = new KeyHolder();
    holder.certificate = cert;
    holder.privateKey = keyPair.getPrivate();
    return holder;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) SubjectKeyIdentifierStructure(com.android.org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) GregorianCalendar(java.util.GregorianCalendar) KeyPairGenerator(java.security.KeyPairGenerator) AuthorityKeyIdentifierStructure(com.android.org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints)

Example 3 with SubjectKeyIdentifierStructure

use of org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure in project OpenAttestation by OpenAttestation.

the class TpmUtils method createCaP12.

/**
	 * Creates a key pair and associated certificate for a certificate authority. An RSA key pair
	 * of specified size is stored with the self-signed certificate in an encrypted PKCS 12 key
	 * store file. The format of the certificate and PKCS 12 file are a replica of what is created
	 * by OpenSSL.
	 *
	 * @param keySize The size (in bits) of the RSA key to create
	 * @param caName The subject name for the new Certificate Authority (do not include "CN=")
	 * @param newP12Pass The password for encrypting the PKCS 12 file
	 * @param p12FileName The name for the PKCS 12 key store file (should end with .p12)
	 * @param validityDays The number of days the certificate should be valid before expiring
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws IllegalStateException
	 * @throws SignatureException
	 * @throws KeyStoreException
	 * @throws java.security.cert.CertificateException
	 * @throws IOException
	 */
public static void createCaP12(int keySize, String caName, String newP12Pass, String p12FileName, int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, SignatureException, KeyStoreException, java.security.cert.CertificateException, IOException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(keySize);
    KeyPair keyPair = keyGen.generateKeyPair();
    RSAPrivateKey privKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=" + caName));
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setSubjectDN(new X500Principal("CN=" + caName));
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("SHA1withRSA");
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.subjectKeyIdentifier, /*X509Extensions.SubjectKeyIdentifier*/
    false, new SubjectKeyIdentifierStructure(pubKey));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.basicConstraints, /*X509Extensions.BasicConstraints*/
    true, new BasicConstraints(true));
    X509Certificate caCert = certGen.generate(privKey);
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.authorityKeyIdentifier, /*X509Extensions.AuthorityKeyIdentifier*/
    false, new AuthorityKeyIdentifierStructure(caCert));
    caCert = certGen.generate(privKey);
    FileOutputStream newp12 = new FileOutputStream(p12FileName);
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(null, newP12Pass.toCharArray());
        Certificate[] chain = { caCert };
        keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain);
        keystore.store(newp12, newP12Pass.toCharArray());
    //		} catch (Exception e) {
    //			e.printStackTrace();
    } finally {
        newp12.close();
    }
}
Also used : SubjectKeyIdentifierStructure(org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) AuthorityKeyIdentifierStructure(org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) X500Principal(javax.security.auth.x500.X500Principal) Certificate(java.security.cert.Certificate)

Example 4 with SubjectKeyIdentifierStructure

use of org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure in project OpenAttestation by OpenAttestation.

the class TpmUtils method createClientP12.

/**
	 * This function creates a p12 file for a client, creating a new RSA key pair of specified size. A certificate generated, signed by a the CA using the specified private key and CA certificate file. Both the client and CA certificates are stored as a chain in the p12 file. The client certificate's serial number is a system time in miliseconds.
	 *
	 * @param keySize Size of the key to generate
	 * @param subjectName Subject name for the client certificate
	 * @param newP12Pass Password to use for encrypting the p12 file
	 * @param p12FileName name for the generated file
	 * @param validityDays number of days the client certificate should be valid
	 * @param caCert The CA's certificate
	 * @param caPrivKey The CA's private key, for signing the client certificate
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws IllegalStateException
	 * @throws SignatureException
	 * @throws KeyStoreException
	 * @throws java.security.cert.CertificateException
	 * @throws IOException
	 */
public static void createClientP12(int keySize, String subjectName, String newP12Pass, String p12FileName, int validityDays, X509Certificate caCert, RSAPrivateKey caPrivKey) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, SignatureException, KeyStoreException, java.security.cert.CertificateException, IOException {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(keySize);
    KeyPair keyPair = keyGen.generateKeyPair();
    RSAPrivateKey privKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis()));
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);
    certGen.setNotAfter(expiry.getTime());
    certGen.setSubjectDN(new X500Principal("CN=" + subjectName));
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("SHA1withRSA");
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.subjectKeyIdentifier, /*X509Extensions.SubjectKeyIdentifier*/
    false, new SubjectKeyIdentifierStructure(pubKey));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.authorityKeyIdentifier, /* X509Extensions.AuthorityKeyIdentifier*/
    false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extension.basicConstraints, /* X509Extensions.BasicConstraints*/
    true, new BasicConstraints(false));
    X509Certificate clientCert = certGen.generate(caPrivKey);
    FileOutputStream newp12 = new FileOutputStream(p12FileName);
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(null, newP12Pass.toCharArray());
        System.out.println(clientCert.toString());
        System.out.println(caCert.toString());
        Certificate[] chain = { clientCert, caCert };
        keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain);
        keystore.store(newp12, newP12Pass.toCharArray());
    //		} catch (Exception e) {
    //			e.printStackTrace();
    } finally {
        newp12.close();
    }
}
Also used : SubjectKeyIdentifierStructure(org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) AuthorityKeyIdentifierStructure(org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) X500Principal(javax.security.auth.x500.X500Principal) Certificate(java.security.cert.Certificate)

Example 5 with SubjectKeyIdentifierStructure

use of org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure in project nhin-d by DirectProject.

the class CertGenerator method createLeafCertificate.

private static CertCreateFields createLeafCertificate(CertCreateFields fields, KeyPair keyPair, boolean addAltNames) throws Exception {
    String altName = "";
    StringBuilder dnBuilder = new StringBuilder();
    // create the DN
    if (fields.getAttributes().containsKey("EMAILADDRESS")) {
        dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
        altName = fields.getAttributes().get("EMAILADDRESS").toString();
    }
    if (fields.getAttributes().containsKey("CN"))
        dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
    if (fields.getAttributes().containsKey("C"))
        dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
    if (fields.getAttributes().containsKey("ST"))
        dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
    if (fields.getAttributes().containsKey("L"))
        dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
    if (fields.getAttributes().containsKey("O"))
        dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
    String DN = dnBuilder.toString().trim();
    if (DN.endsWith(","))
        DN = DN.substring(0, DN.length() - 1);
    X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
    // not the best way to do this... generally done with a db file
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(fields.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(DN));
    v1CertGen.setPublicKey(keyPair.getPublic());
    v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
    // pointer to the parent CA
    v1CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(fields.getSignerCert()));
    v1CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));
    boolean allowToSign = (fields.getAttributes().get("ALLOWTOSIGN") != null && fields.getAttributes().get("ALLOWTOSIGN").toString().equalsIgnoreCase("true"));
    v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(allowToSign));
    int keyUsage = 0;
    if (fields.getAttributes().get("KEYENC") != null && fields.getAttributes().get("KEYENC").toString().equalsIgnoreCase("true"))
        keyUsage = keyUsage | KeyUsage.keyEncipherment;
    if (fields.getAttributes().get("DIGSIG") != null && fields.getAttributes().get("DIGSIG").toString().equalsIgnoreCase("true"))
        keyUsage = keyUsage | KeyUsage.digitalSignature;
    if (keyUsage > 0)
        v1CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(keyUsage));
    if (fields.getSignerCert().getSubjectAlternativeNames() != null) {
        for (List<?> names : fields.getSignerCert().getSubjectAlternativeNames()) {
            GeneralNames issuerAltName = new GeneralNames(new GeneralName((Integer) names.get(0), names.get(1).toString()));
            v1CertGen.addExtension(X509Extensions.IssuerAlternativeName, false, issuerAltName);
        }
    }
    if (addAltNames && !altName.isEmpty()) {
        int nameType = altName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        GeneralNames subjectAltName = new GeneralNames(new GeneralName(nameType, altName));
        v1CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
    }
    // use the CA's private key to sign the certificate
    X509Certificate newCACert = v1CertGen.generate((PrivateKey) fields.getSignerKey(), CryptoExtensions.getJCEProviderName());
    // validate the certificate 
    newCACert.verify(fields.getSignerCert().getPublicKey());
    // write the certificate the file system
    writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
    return fields;
}
Also used : SubjectKeyIdentifierStructure(org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure) Calendar(java.util.Calendar) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifierStructure(org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Principal(org.bouncycastle.jce.X509Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Aggregations

AuthorityKeyIdentifierStructure (org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure)4 SubjectKeyIdentifierStructure (org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure)4 X509Certificate (java.security.cert.X509Certificate)3 X500Principal (javax.security.auth.x500.X500Principal)3 BigInteger (java.math.BigInteger)2 Certificate (java.security.cert.Certificate)2 Calendar (java.util.Calendar)2 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)2 X509Principal (org.bouncycastle.jce.X509Principal)2 X509V3CertificateGenerator (org.bouncycastle.x509.X509V3CertificateGenerator)2 BasicConstraints (com.android.org.bouncycastle.asn1.x509.BasicConstraints)1 X509V3CertificateGenerator (com.android.org.bouncycastle.x509.X509V3CertificateGenerator)1 AuthorityKeyIdentifierStructure (com.android.org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure)1 SubjectKeyIdentifierStructure (com.android.org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure)1 KeyPair (java.security.KeyPair)1 KeyPairGenerator (java.security.KeyPairGenerator)1 PrivateKey (java.security.PrivateKey)1 Date (java.util.Date)1 GregorianCalendar (java.util.GregorianCalendar)1 GeneralName (org.bouncycastle.asn1.x509.GeneralName)1