Example usage for org.bouncycastle.x509 X509V3CertificateGenerator generateX509Certificate

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

Introduction

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

Prototype

public X509Certificate generateX509Certificate(PrivateKey key, String provider, SecureRandom random)
        throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException 

Source Link

Document

generate an X509 certificate, based on the current issuer and subject, using the passed in provider for the signing and the supplied source of randomness, if required.

Usage

From source file:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Generate a X509 certificate for the given keypair.
 * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode
 * use backslash to escape a comma/*w w w .j av a  2  s . c  om*/
 * @param keypair the keypair
 * @param months the validity length in months
 * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param domain domain of the server to store in the subject alternative name extension
 * @param signAlgorithm the signing algorithm to use
 * @return the generated X509 certificate
 */
public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN,
        String domain, String signAlgorithm) {
    try {
        // calendar for date calculations
        GregorianCalendar cal = new GregorianCalendar();

        // extract keypair components
        PublicKey pubKey = keypair.getPublic();
        PrivateKey privKey = keypair.getPrivate();

        // generate a random serial number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte[] serialNo = new byte[8];
        random.nextBytes(serialNo);
        BigInteger serial = new BigInteger(serialNo).abs();

        // create the certificate generator
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.reset();

        // set certificate attributes
        certGen.setSerialNumber(serial);
        cal.setTimeInMillis(System.currentTimeMillis());
        certGen.setNotBefore(cal.getTime());
        cal.add(GregorianCalendar.MONTH, months);
        certGen.setNotAfter(cal.getTime());
        certGen.setPublicKey(pubKey);
        certGen.setSignatureAlgorithm(signAlgorithm);
        certGen.setIssuerDN(new X509Name(issuerDN));
        certGen.setSubjectDN(new X509Name(subjectDN));

        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));

        // create subject alternative name
        boolean isCritical = subjectDN == null || "".equals(subjectDN.trim());
        DERSequence othernameSeq = new DERSequence(
                new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                        new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
        GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq);
        GeneralNames subjectAlternatives = new GeneralNames(othernameGen);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives);

        // finally generate the certificate
        X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(),
                new SecureRandom());
        cert.checkValidity(new Date());
        cert.verify(pubKey);

        return cert;
    } catch (NoSuchAlgorithmException ex) {
        throw new KeystoreFault(ex);
    } catch (CertificateException ex) {
        throw new KeystoreFault(ex);
    } catch (SignatureException ex) {
        throw new KeystoreFault(ex);
    } catch (NoSuchProviderException ex) {
        throw new KeystoreFault(ex);
    } catch (InvalidKeyException ex) {
        throw new KeystoreFault(ex);
    }
}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Creates an X509 version3 certificate.
 *
 * @param kp           KeyPair that keeps the public and private keys for the new certificate.
 * @param months       time to live/*from  w ww  .  j  a  v  a2  s  .  c  o  m*/
 * @param issuerDN     Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
 * @param subjectDN    Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
 * @param domain       Domain of the server.
 * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
 * @return X509 V3 Certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN,
        String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(serial);
    certGenerator.setIssuerDN(new X509Name(issuerDN));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    // Generate the subject alternative name
    boolean critical = subjectDN == null || "".equals(subjectDN.trim());
    ASN1Sequence othernameSequence = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                    new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    // Add subject alternative name extension
    certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames);

    X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom());
    cert.checkValidity(new Date());
    cert.verify(pubKey);

    return cert;
}