Example usage for org.bouncycastle.x509 X509V3CertificateGenerator generate

List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate

Introduction

In this page you can find the example usage for org.bouncycastle.x509 X509V3CertificateGenerator generate.

Prototype

public X509Certificate generate(PrivateKey key) throws CertificateEncodingException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, InvalidKeyException 

Source Link

Document

generate an X509 certificate, based on the current issuer and subject using the default provider.

Usage

From source file:net.jmhertlein.core.crypto.Certs.java

License:Open Source License

/**
 * Generates an X509 certificate//from   w  ww  .j av a  2 s . c o m
 *
 * Valid for 1000 years from 1 second ago, signed with SHA512withECDSA
 * @param authorityPrivateKey private key of the certificate authority
 * @param certPubKey pubkey that the certificate will use
 * @param serialNumber serial number of the certificate
 * @param commonName common name of the subject of this certificate
 * @return a new X509 Certificate
 * @throws SignatureException
 * @throws InvalidKeyException
 */
public static Certificate newCertificate(PrivateKey authorityPrivateKey, PublicKey certPubKey,
        long serialNumber, String commonName) throws SignatureException, InvalidKeyException {
    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();

    gen.setPublicKey(certPubKey); //pubkey of cert we're making
    gen.setSignatureAlgorithm("SHA512withECDSA");
    gen.setSerialNumber(BigInteger.valueOf(Math.abs(serialNumber)));
    gen.setIssuerDN(new X500Principal("CN=" + commonName));
    gen.setNotBefore(new Date(System.currentTimeMillis() - 1000L));
    gen.setNotAfter(new Date(System.currentTimeMillis() + 1000 * 365 * 24 * 60 * 60 * 1000)); //tfw cert valid for 10x longer than I'll be alive
    gen.setSubjectDN(new X500Principal("CN=" + commonName));

    try {
        return gen.generate(authorityPrivateKey); //ca's private key
    } catch (CertificateEncodingException | IllegalStateException | NoSuchAlgorithmException ex) {
        Logger.getLogger(Certs.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

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

License:Apache License

/**
 * Generate certificate./*from  w  w  w . j a  v a2  s.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   ww w. j a v  a  2s. 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./*from   w ww . java  2 s.  co  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.candlepin.controller.CrlGeneratorTest.java

License:Open Source License

private static X509Certificate generateCertificate() {
    X500Principal principal = new X500Principal(generateFakePrincipal());
    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
    gen.setSerialNumber(BigInteger.TEN);
    gen.setNotBefore(Util.yesterday());
    gen.setNotAfter(Util.getFutureDate(2));
    gen.setSubjectDN(principal);/*from ww w .  ja  v  a2s . c  om*/
    gen.setIssuerDN(principal);
    gen.setPublicKey(KP.getPublic());
    gen.setSignatureAlgorithm("SHA1WITHRSA");
    try {
        return gen.generate(KP.getPrivate());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions,
        Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair,
        BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Certificate caCert = reader.getCACert();
    // set cert fields
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(startDate);//from   w  ww . j  a v  a  2  s.co m
    certGen.setNotAfter(endDate);

    X500Principal subjectPrincipal = new X500Principal(dn);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(clientKeyPair.getPublic());
    certGen.setSignatureAlgorithm(SIGNATURE_ALGO);

    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);

    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);

    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType);
    certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    // Add an alternate name if provided
    if (alternateName != null) {
        GeneralName name = new GeneralName(GeneralName.uniformResourceIdentifier, "CN=" + alternateName);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(name));
    }

    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }

    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value));
        }
    }

    // Generate the certificate
    return certGen.generate(reader.getCaKey());
}

From source file:org.conscrypt.java.security.cert.CertificateFactoryTest.java

License:Apache License

@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"));
    cal.set(2100, 0, 1, 0, 0, 0); // Jan 1, 2100 UTC
    Date expiryDate = cal.getTime();

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();

    BigInteger serial;//from w w  w  .  j  a  v a2  s. c om
    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();

    PublicKey pubKey = keyPair.getPublic();
    certGen.setSerialNumber(serial);
    certGen.setIssuerDN(issuerPrincipal);
    certGen.setNotBefore(startDate);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(pubKey);
    certGen.setSignatureAlgorithm("SHA1withRSA");

    if (issuer != null) {
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(issuer.certificate));
    } else {
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(generatePublicKeyDigest(pubKey)));
    }

    certGen.addExtension(Extension.subjectKeyIdentifier, false,
            new SubjectKeyIdentifier(generatePublicKeyDigest(pubKey)));
    certGen.addExtension(Extension.basicConstraints, true, basicConstraints);

    X509Certificate cert = certGen.generate(caKey);

    KeyHolder holder = new KeyHolder();
    holder.certificate = cert;
    holder.privateKey = keyPair.getPrivate();

    return holder;
}

From source file:org.glite.voms.contact.VOMSProxyBuilder.java

License:Open Source License

private static X509Certificate myCreateProxyCertificate(X509Certificate cert, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime, DelegationType delegationMode, CertificateType gtVersion,
        HashMap extensions, String policyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    String cnValue = null;/*from  w  ww.  ja va  2 s  . c  om*/
    ProxyPolicy policy = null;
    BigInteger serialNum = null;

    switch (delegationMode) {
    case LIMITED:
        cnValue = "limited proxy";
        break;
    case FULL:
        cnValue = "proxy";
        break;
    default:
        break;
    }

    switch (gtVersion) {
    case GSI_2_PROXY:
        policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION);
        serialNum = cert.getSerialNumber();
    case GSI_2_LIMITED_PROXY:
        policy = new ProxyPolicy(ProxyPolicy.LIMITED);
        serialNum = cert.getSerialNumber();
        break;
    case GSI_3_IMPERSONATION_PROXY:
    case GSI_3_INDEPENDENT_PROXY:
    case GSI_3_LIMITED_PROXY:
    case GSI_3_RESTRICTED_PROXY:
    case GSI_4_IMPERSONATION_PROXY:
    case GSI_4_INDEPENDENT_PROXY:
    case GSI_4_LIMITED_PROXY:
    case GSI_4_RESTRICTED_PROXY:
        Random rand = new Random();
        int number = Math.abs(rand.nextInt());
        cnValue = String.valueOf(number);
        serialNum = new BigInteger(String.valueOf(number));

        ExtensionData data = (ExtensionData) extensions.get(PROXY_CERT_INFO_V3_OID);
        if (data == null) {
            if (policyType == null) {

                switch (gtVersion) {
                case GSI_3_LIMITED_PROXY:
                case GSI_4_LIMITED_PROXY:
                    policy = new ProxyPolicy(ProxyPolicy.LIMITED);
                    break;
                case GSI_3_IMPERSONATION_PROXY:
                case GSI_4_IMPERSONATION_PROXY:
                    policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION);
                    break;
                case GSI_3_INDEPENDENT_PROXY:
                case GSI_4_INDEPENDENT_PROXY:
                    policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT);
                    break;
                default:
                    throw new IllegalArgumentException("Invalid proxyType " + gtVersion);

                }
            } else {
                try {
                    policy = new ProxyPolicy(new ASN1ObjectIdentifier(policyType));
                } catch (IllegalArgumentException e) {
                    throw new VOMSException("OID required as policyType");
                }
            }

            if (ProxyCertificateUtil.isGsi3Proxy(gtVersion)) {
                extensions.put(PROXY_CERT_INFO_V3_OID, ExtensionData.creator(PROXY_CERT_INFO_V3_OID,
                        new MyProxyCertInfo(policy, gtVersion).toASN1Primitive()));
            } else if (ProxyCertificateUtil.isGsi4Proxy(gtVersion)) {
                extensions.put(PROXY_CERT_INFO_V4_OID, ExtensionData.creator(PROXY_CERT_INFO_V4_OID, true,
                        new MyProxyCertInfo(policy, gtVersion).toASN1Primitive()));
            }

        }
    }

    ExtensionData[] exts = (ExtensionData[]) extensions.values().toArray(new ExtensionData[] {});
    for (int i = 0; i < exts.length; i++) {
        certGen.addExtension(exts[i].getOID(), exts[i].getCritical(), exts[i].getObj());
    }

    X509Name issuerDN = (X509Name) cert.getSubjectDN();

    X509NameHelper issuer = new X509NameHelper(issuerDN);

    X509NameHelper subject = new X509NameHelper(issuerDN);
    subject.add(X509Name.CN, cnValue);

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

    certGen.setSerialNumber(serialNum);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm(cert.getSigAlgName());

    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    /* Allow for a five minute clock skew here. */
    date.add(Calendar.MINUTE, -5);
    certGen.setNotBefore(date.getTime());

    /* If hours = 0, then cert lifetime is set to user cert */
    if (lifetime <= 0) {
        certGen.setNotAfter(cert.getNotAfter());
    } else {
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        certGen.setNotAfter(date.getTime());
    }

    try {
        return certGen.generate(issuerKey);

    } catch (SignatureException e) {
        log.error("Error creating proxy: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }

        throw new VOMSException(e);
    } catch (InvalidKeyException e) {
        log.error("Error creating proxy: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }

        throw new VOMSException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error creating proxy: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }

        throw new VOMSException(e);
    } catch (IllegalStateException e) {
        log.error("Error creating proxy: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }

        throw new VOMSException(e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating proxy: " + e.getMessage());

        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        }

        throw new VOMSException(e);
    }

}

From source file:org.mailster.core.crypto.MailsterKeyStoreFactory.java

License:Open Source License

private void generateSSLServerCertificate(KeyStore store, X500PrivateCredential rootCredential)
        throws Exception {
    LOG.info("Generating SSL server certificate ...");
    KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength());
    String DN = "CN=localhost, " + DN_ROOT;
    X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair,
            rootCredential.getCertificate().getSubjectX500Principal().getName(), DN, false,
            CertificateUtilities.DEFAULT_VALIDITY_PERIOD);

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

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

    // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care.
    // v3CertGen.addExtension(X509Extensions.KeyUsage,
    // true, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.keyAgreement |
    // KeyUsage.keyEncipherment));

    Vector<KeyPurposeId> typicalSSLServerExtendedKeyUsages = new Vector<KeyPurposeId>();

    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(typicalSSLServerExtendedKeyUsages));

    X509Certificate publicKeyCertificate = v3CertGen.generate(pair.getPrivate());
    store.setKeyEntry(MAILSTER_SSL_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD,
            new Certificate[] { publicKeyCertificate, rootCredential.getCertificate() });
    CertificateUtilities.exportCertificate(publicKeyCertificate, SSL_CERT_FULL_PATH, false);
}

From source file:org.mailster.core.crypto.MailsterKeyStoreFactory.java

License:Open Source License

private void generateDummySSLClientCertificate(KeyStore ks) throws Exception {
    LOG.info("Generating a Dummy SSL client certificate ...");
    KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength());
    String DN = "CN=SSL dummy client cert, O=Dummy org., C=FR";
    X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair, DN, DN, true,
            CertificateUtilities.DEFAULT_VALIDITY_PERIOD);

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

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

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    X509Certificate cert = v3CertGen.generate(pair.getPrivate());
    ks.setKeyEntry(DUMMY_SSL_CLIENT_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] { cert });
}