Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_friendlyName

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_friendlyName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_friendlyName.

Prototype

ASN1ObjectIdentifier pkcs_9_at_friendlyName

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers pkcs_9_at_friendlyName.

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.20

Usage

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

License:Open Source License

/**
 * Generate the CA's certificate.//from w w w. ja  v  a2 s .co  m
 *
 * @param publicKey
 *            Public key.
 * @param privateKey
 *            Private key.
 * @param distinguishedName
 *            Distinguished Name.
 * @param serialNumber
 *            Unique serial number.
 * @param validDays
 *            valid Days.
 * @param certFriendlyName  Certificate friendly name
 *
 * @throws DigitalSigningException
 *             Customized exception with error message.
 *
 * @return a Certificate.
 */
@SuppressWarnings({ "PMD.AvoidCatchingGenericException", "PMD.ExcessiveParameterList" })
// same handling for multiple exception types, parameters required for generation
Certificate generateRootCert(PublicKey publicKey, PrivateKey privateKey,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays,
        String certFriendlyName) throws DigitalSigningException {

    try {
        X509V1CertificateGenerator v1CertGen = buildX509V1CertificateGenerator(publicKey, distinguishedName,
                serialNumber, validDays);
        X509Certificate cert = v1CertGen.generate(privateKey, BOUNCY_CASTLE_PROVIDER);
        cert.checkValidity(new Date());
        cert.verify(publicKey);
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                new DERBMPString(certFriendlyName));
        return cert;
    } catch (Exception e) {
        throw new DigitalSigningException(ROOT_CA_GENERATION_ERROR_MESSAGE, e);
    }
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

License:Open Source License

/**
 * Generate intermediate certificate signed by CA.
 *
 * @param publicKey//ww  w.j a v a 2 s  . c o m
 *            Public key.
 * @param caPrivateKey
 *            Private key.
 * @param caDistinguishedName
 *            Issuer's Distinguished Name..
 * @param distinguishedName
 *            User's Distinguished Name.
 * @param serialNumber
 *            Unique serial number.
 * @param validDays
 *            valid Days.
 * @param friendName
 *            Set a friendly name for the certificate. Can be null.
 *
 * @throws DigitalSigningException
 *             Customized exception with error message.
 *
 * @return a Certificate.
 */
@SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.AvoidCatchingGenericException" })
// This is minimal parameter list.
// same handling for multiple exception types
Certificate generateUserCert(PublicKey publicKey, PrivateKey caPrivateKey, X509Certificate caCert,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays)
        throws DigitalSigningException {
    try {
        X509V3CertificateGenerator v3CertGen = buildX509V3CertificateGenerator(publicKey, caCert,
                distinguishedName, serialNumber, validDays);
        X509Certificate cert = v3CertGen.generate(caPrivateKey, BOUNCY_CASTLE_PROVIDER);
        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                new DERBMPString("User Certificate"));
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                new SubjectKeyIdentifierStructure(publicKey));

        return cert;
    } catch (Exception e) {
        throw new DigitalSigningException(CERT_GENERATION_ERROR_MESSAGE, e);
    }
}

From source file:org.apache.kerby.pkix.EndEntityGenerator.java

License:Apache License

/**
 * Generate certificate.//w w  w  .  jav  a 2s .  com
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

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

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    // MAY set BasicConstraints=false or not at all.
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(issuerCert));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment));

    ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector();
    keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon);
    //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth );
    DERSequence keyPurposeOids = new DERSequence(keyPurposeVector);

    // If critical, will throw unsupported EKU.
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids);

    ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector();
    pkinitSanVector.add(ID_PKINIT_SAN);
    pkinitSanVector.add(new DERTaggedObject(0, new DERSequence()));
    DERSequence pkinitSan = new DERSequence(pkinitSanVector);

    String dnsName = "localhost";

    GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan);
    GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName);

    GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder();

    genNamesBuilder.addName(name1);
    genNamesBuilder.addName(name2);

    GeneralNames sanGeneralNames = genNamesBuilder.build();

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

    /*
     * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId
     * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's
     * X.509 certificate.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the client's X.509 certificate is restricted with
     * the id-pkinit-KPClientAuth EKU.
     */

    /*
     * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId
     * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as
     * there are a large number of X.509 client certificates deployed for use
     * with PKINIT that have this EKU.
     */

    // KDC
    /*
     * In addition, unless the client can otherwise verify that the public key
     * used to verify the KDC's signature is bound to the KDC of the target realm,
     * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension
     * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined
     * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the
     * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]).
     */

    /*
     * Unless the client knows by some other means that the KDC certificate is
     * intended for a Kerberos KDC, the client MUST require that the KDC certificate
     * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the KDC's X.509 certificate is restricted with the
     * id-pkinit-KPKdc EKU.
     */

    /*
     * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san
     * SAN, this certificate is certified by the issuing CA as a KDC certificate,
     * therefore the id-pkinit-KPKdc EKU is not required.
     */

    /*
     * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth
     * EKU [RFC3280].
     */

    /*
     * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth
     * EKU, and the id-ms-kp-sc-logon EKU.
     */

    /*
     * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC.
     * 
     * MS:  dNSName SAN containing the domain name of the KDC
     *      id-pkinit-KPKdc EKU
     *      id-kp-serverAuth EKU.
     */

    /*
     * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs
     * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and
     * the id-ms-kp-sc-logon EKU.  The id-ms-san-sc-logon-upn SAN contains a
     * UTF8-encoded string whose value is that of the Directory Service attribute
     * UserPrincipalName of the client account object, and the purpose of including
     * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate
     * the client mapping (in other words, the client's public key is bound to
     * the account that has this UserPrincipalName value).
     */

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.apache.kerby.pkix.IntermediateCaGenerator.java

License:Apache License

/**
 * Create certificate./*from  w ww .j  av  a 2  s . c  om*/
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

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

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

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

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(issuerCert));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.apache.kerby.pkix.TrustAnchorGenerator.java

License:Apache License

/**
 * Create CA certificate./*  w  w w  .  jav a  2  s  . c  o  m*/
 *
 * @param publicKey
 * @param privateKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(PublicKey publicKey, PrivateKey privateKey, String dn, int validityDays,
        String friendlyName) throws InvalidKeyException, SecurityException, SignatureException,
        NoSuchAlgorithmException, DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    X509Principal x509Principal = new X509Principal(dn);
    certGen.setIssuerDN(x509Principal);
    certGen.setSubjectDN(x509Principal);

    certGen.setNotBefore(new Date());

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

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

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

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    X509Certificate cert = certGen.generate(privateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.cesecore.keys.util.KeyTools.java

License:Open Source License

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null./*from w ww.  java 2 s  .  c  o m*/
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.ejbca.util.keystore.KeyTools.java

License:Open Source License

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key/*from ww w.jav  a  2 s .c o  m*/
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.objectweb.proactive.core.security.KeyTools.java

License:Open Source License

/**
 * Creates PKCS12-file that can be imported in IE or Netscape. The alias for the private key is
 * set to alias and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key//from  w  ww.ja  v  a2s  . c  om
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(String alias, PrivateKey privKey, X509Certificate cert, Certificate[] cachain)
        throws Exception {
    log.debug(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
            + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));

    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    Certificate[] chain = new Certificate[len];

    // To not get a ClassCastException we need to genereate a real new certificate with BC
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));

            // Set attributes on CA-cert
            PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];

            // We constuct a friendly name for the CA, and try with some parts from the DN if they exist.
            String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");

            // On the ones below we +i to make it unique, O might not be otherwise
            if (cafriendly == null) {
                cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
            }
            if (cafriendly == null) {
                cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
            }
            if (cafriendly == null) {
                cafriendly = "CA_unknown" + i;
            }
            caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                    new DERBMPString(cafriendly));
        }
    }

    // Set attributes on user-cert
    PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
    certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
    // in this case we just set the local key id to that of the public key
    certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            createSubjectKeyId(chain[0].getPublicKey()));
    // "Clean" private key, i.e. remove any old attributes
    KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));

    // Set attributes for private key
    PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;

    // in this case we just set the local key id to that of the public key
    keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
    keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            createSubjectKeyId(chain[0].getPublicKey()));
    // store the key and the certificate chain
    KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    log.debug("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
            + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));

    return store;
}

From source file:org.openconcerto.modules.finance.payment.ebics.crypto.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.
 * /*ww  w  .  j a  va 2s.co  m*/
 * @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)
 * 
 * @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");
    }

    System.out.println("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;

    System.out.println("Creating RSA keypair");
    // generate the keypair for the new certificate

    RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
    // TODO: what are these values??
    gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80));
    AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
    System.out
            .println("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());
    System.out.println("New public key is '" + new String(Hex.encode(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()));

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

    X500Name x509Name = new X500Name("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);

    // TODO GM:
    DERObjectIdentifier sigOID = PKCSObjectIdentifiers.sha1WithRSAEncryption;// DERObjectIdentifier.
                                                                             // 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(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey),
            extOrdering, extensions);
    if (caCert != null) {
        // again: only if we have set CA
        addExtensionHelper(X509Extension.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(X509Extension.basicConstraints, true, new BasicConstraints(0), extOrdering,
                extensions);
    }
    certGen.setExtensions(new X509Extensions(extOrdering, extensions));

    System.out.println("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;

    byte[] certBlock = bOut.toByteArray();
    // first create digest
    System.out.println("Block to sign is '" + new String(Hex.encode(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
        System.out.println("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);

    System.out.println("SHA1/RSA signature of digest is '" + new String(Hex.encode(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)));
    System.out.println("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
    System.out.println("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));
     */

    JDKPKCS12KeyStore store;

    store = new JDKPKCS12KeyStore.BCPKCS12KeyStore();
    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;
    }

    store.engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey,
            exportPassword.toCharArray(), chain);
    store.engineStore(fOut, exportPassword.toCharArray());

    return true;
}

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

License:Open Source License

/**
 * Create a root certificate (version 1).
 * // w w w .j  ava 2s .  c  o  m
 * @param pubKey
 * @param serialNumber
 * @param name
 * @param notBefore
 * @param notAfter
 * @param signatureAlgorithm
 * @param privKey
 * @param friendlyName
 * @return X509Certificate
 * @throws Exception
 */
public static X509Certificate createRootCert(PublicKey pubKey, BigInteger serialNumber, String name,
        Date notBefore, Date notAfter, String signatureAlgorithm, PrivateKey privKey, String friendlyName)
        throws Exception {
    //
    // signers name 
    //
    byte[] nameBytes = new X500Principal(name).getEncoded();

    //
    // create the certificate - version 1
    //

    v1CertGen.setSerialNumber(serialNumber);
    v1CertGen.setIssuerDN(new X509Principal(nameBytes));
    v1CertGen.setNotBefore(notBefore);
    v1CertGen.setNotAfter(notAfter);
    v1CertGen.setSubjectDN(new X509Principal(nameBytes));
    v1CertGen.setPublicKey(pubKey);
    v1CertGen.setSignatureAlgorithm(signatureAlgorithm);

    X509Certificate cert = v1CertGen.generateX509Certificate(privKey);

    cert.checkValidity(new Date());

    cert.verify(pubKey);

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

        //
        // this is actually optional - but if you want to have control
        // over setting the friendly name this is the way to do it...
        //
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    }

    return cert;
}