Example usage for org.bouncycastle.x509 X509V3CertificateGenerator X509V3CertificateGenerator

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

Introduction

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

Prototype

public X509V3CertificateGenerator() 

Source Link

Usage

From source file:org.jcryptool.visual.ssl.protocol.Crypto.java

License:Open Source License

/**
 * Generates a default certificate with the given key pair {@link pubKey}
 * The certificate will be singed with the {@link sigKey} and uses the
 * {@link strHash} with and the {@link strSignature} algorithm.
 *
 * @param key/*from   w w  w. ja v a2 s .c  o  m*/
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 */
public X509Certificate generateX509(KeyPair pubKey, KeyPair sigKey, String strHash, String strSignature)
        throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException {

    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.set(Calendar.YEAR, notBefore.get(Calendar.YEAR) + 1);
    notAfter.set(Calendar.HOUR, 23);
    notAfter.set(Calendar.MINUTE, 59);
    notAfter.set(Calendar.SECOND, 59);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal certName = new X500Principal("CN=Test Server Certificate");
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(certName);
    certGen.setNotAfter(notAfter.getTime());
    certGen.setNotBefore(notBefore.getTime());
    certGen.setSubjectDN(certName);
    certGen.setPublicKey(pubKey.getPublic());
    certGen.setSignatureAlgorithm(strHash + "With" + strSignature);

    X509Certificate cert = certGen.generate(sigKey.getPrivate(), "BC");

    return cert;
}

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   ww w.  j  a  v  a  2 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;
}

From source file:org.jmrtd.test.api.lds.SODFileTest.java

License:Open Source License

public static SODFile createTestObject() {
    try {//from   w ww .  ja va2s  . co m
        Security.insertProviderAt(BC_PROVIDER, 4);

        Date today = Calendar.getInstance().getTime();
        DG1File dg1File = DG1FileTest.createTestObject();
        byte[] dg1Bytes = dg1File.getEncoded();
        DG2File dg2File = DG2FileTest.getDefaultTestObject();
        byte[] dg2Bytes = dg2File.getEncoded();
        //         DG15File dg15File = DG15FileTest.createTestObject();
        //         byte[] dg15Bytes = dg15File.getEncoded();

        KeyPair keyPair = createTestKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        Date dateOfIssuing = today;
        Date dateOfExpiry = today;
        String digestAlgorithm = "SHA-256";
        String signatureAlgorithm = "SHA256withRSA";
        X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
        certGenerator.setSerialNumber(BigInteger.ONE);
        certGenerator.setIssuerDN(new X509Name(
                "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=CSCA NL"));
        certGenerator.setSubjectDN(new X509Name(
                "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=DS-01 NL, OID.2.5.4.5=1"));
        certGenerator.setNotBefore(dateOfIssuing);
        certGenerator.setNotAfter(dateOfExpiry);
        certGenerator.setPublicKey(publicKey);
        certGenerator.setSignatureAlgorithm(signatureAlgorithm);
        X509Certificate docSigningCert = (X509Certificate) certGenerator.generate(privateKey, BC_PROVIDER_NAME);
        Map<Integer, byte[]> hashes = new HashMap<Integer, byte[]>();
        MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
        hashes.put(1, digest.digest(dg1Bytes));
        hashes.put(2, digest.digest(dg2Bytes));
        //         hashes.put(15, digest.digest(dg15Bytes));
        //         byte[] encryptedDigest = new byte[128]; // Arbitrary value. Use a private key to generate a real signature?

        SODFile sod = new SODFile(digestAlgorithm, signatureAlgorithm, hashes, privateKey, docSigningCert);

        File outputDir = new File("tmp");
        if (!outputDir.exists()) {
            if (!outputDir.mkdirs()) {
                fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\"");
            }
        }
        if (!outputDir.isDirectory()) {
            fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\"");
        }

        int[] dgPresenceList = { LDSFile.EF_DG1_TAG, LDSFile.EF_DG2_TAG };
        COMFile com = new COMFile("1.7", "4.0.0", dgPresenceList);
        FileOutputStream comOut = new FileOutputStream(new File(outputDir, "EF_COM.bin"));
        comOut.write(com.getEncoded());
        comOut.flush();
        comOut.close();

        FileOutputStream dg1Out = new FileOutputStream(new File(outputDir, "DataGroup1.bin"));
        dg1Out.write(dg1File.getEncoded());
        dg1Out.flush();
        dg1Out.close();

        FileOutputStream dg2Out = new FileOutputStream(new File(outputDir, "DataGroup2.bin"));
        dg2Out.write(dg2File.getEncoded());
        dg2Out.flush();
        dg2Out.close();

        FileOutputStream sodOut = new FileOutputStream(new File(outputDir, "EF_SOD.bin"));
        sodOut.write(sod.getEncoded());
        sodOut.flush();
        sodOut.close();

        return sod;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.jmrtd.test.lds.SODFileTest.java

License:Open Source License

public static SODFile createTestObject() {
    try {/*w  w w .  j a  v a 2  s.c  om*/
        Security.insertProviderAt(BC_PROVIDER, 4);

        Date today = Calendar.getInstance().getTime();
        DG1File dg1File = DG1FileTest.createTestObject();
        byte[] dg1Bytes = dg1File.getEncoded();
        DG2File dg2File = DG2FileTest.getDefaultTestObject();
        byte[] dg2Bytes = dg2File.getEncoded();
        //         DG15File dg15File = DG15FileTest.createTestObject();
        //         byte[] dg15Bytes = dg15File.getEncoded();

        KeyPair keyPair = createTestKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        Date dateOfIssuing = today;
        Date dateOfExpiry = today;
        String digestAlgorithm = "SHA-256";
        String signatureAlgorithm = "SHA256withRSA";
        X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
        certGenerator.setSerialNumber(BigInteger.ONE);
        certGenerator.setIssuerDN(new X509Name(
                "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=CSCA NL"));
        certGenerator.setSubjectDN(new X509Name(
                "C=NL, O=State of the Netherlands, OU=Ministry of the Interior and Kingdom Relations, CN=DS-01 NL, OID.2.5.4.5=1"));
        certGenerator.setNotBefore(dateOfIssuing);
        certGenerator.setNotAfter(dateOfExpiry);
        certGenerator.setPublicKey(publicKey);
        certGenerator.setSignatureAlgorithm(signatureAlgorithm);
        X509Certificate docSigningCert = (X509Certificate) certGenerator.generate(privateKey, BC_PROVIDER_NAME);
        Map<Integer, byte[]> hashes = new HashMap<Integer, byte[]>();
        MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
        hashes.put(1, digest.digest(dg1Bytes));
        hashes.put(2, digest.digest(dg2Bytes));
        //         hashes.put(15, digest.digest(dg15Bytes));
        //         byte[] encryptedDigest = new byte[128]; // Arbitrary value. Use a private key to generate a real signature?

        SODFile sod = new SODFile(digestAlgorithm, signatureAlgorithm, hashes, privateKey, docSigningCert);

        int[] dgPresenceList = { LDSFile.EF_DG1_TAG, LDSFile.EF_DG2_TAG };
        COMFile com = new COMFile("1.7", "4.0.0", dgPresenceList);

        //         File outputDir = new File("tmp");
        //         if (!outputDir.exists()) {
        //            if (!outputDir.mkdirs()) {
        //               fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\"");
        //            }
        //         }
        //         if (!outputDir.isDirectory()) {
        //            fail("Could not make output dir \"" + outputDir.getAbsolutePath() + "\"");
        //         }
        //         
        //
        //         FileOutputStream comOut = new FileOutputStream(new File(outputDir, "EF_COM.bin"));
        //         comOut.write(com.getEncoded());
        //         comOut.flush();
        //         comOut.close();

        //         FileOutputStream dg1Out = new FileOutputStream(new File(outputDir, "DataGroup1.bin"));
        //         dg1Out.write(dg1File.getEncoded());
        //         dg1Out.flush();
        //         dg1Out.close();
        //
        //         FileOutputStream dg2Out = new FileOutputStream(new File(outputDir, "DataGroup2.bin"));
        //         dg2Out.write(dg2File.getEncoded());
        //         dg2Out.flush();
        //         dg2Out.close();
        //
        //         FileOutputStream sodOut = new FileOutputStream(new File(outputDir, "EF_SOD.bin"));
        //         sodOut.write(sod.getEncoded());
        //         sodOut.flush();
        //         sodOut.close();

        return sod;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns an <code>X509Certificate</code> from a given
 * <code>KeyPair</code> and limit dates validations
 * @param keypair the given key pair//from  ww w  .j  a  va2 s.c om
 * @param issuer the certificate issuer
 * @param notBefore the begin validity date
 * @param notAfter the end validity date
 * @param keyusage the certificate key usage
 * @return the X509 certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage)
        throws GeneralSecurityException, IOException {
    X509V3CertificateGenerator generator;
    BigInteger serial;
    X509Certificate certificate;
    ASN1EncodableVector vector;

    serial = BigInteger.valueOf(generateSerial());
    generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serial);
    generator.setIssuerDN(new X509Principal(issuer));
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setSubjectDN(new X509Principal(issuer));
    generator.setPublicKey(keypair.getPublic());
    generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
    generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
    generator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            getSubjectKeyIdentifier(keypair.getPublic()));
    generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
    vector = new ASN1EncodableVector();
    vector.add(KeyPurposeId.id_kp_emailProtection);

    generator.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(new DERSequence(vector)));

    switch (keyusage) {
    case X509Constants.SIGNATURE_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
        break;
    case X509Constants.AUTHENTICATION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
        break;
    case X509Constants.ENCRYPTION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
        break;
    default:
        generator.addExtension(X509Extensions.KeyUsage, false,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        break;
    }

    certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
    certificate.checkValidity(new Date());
    certificate.verify(keypair.getPublic());

    return certificate;
}

From source file:org.krakenapps.ca.util.CertificateBuilder.java

License:Apache License

public static X509Certificate createCertificate(CertificateRequest req) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    X509Principal subject = parseDn(req.getSubjectDn());
    X509Principal issuer = parseDn(req.getIssuerDn());

    certGen.setSerialNumber(req.getSerial());
    certGen.setIssuerDN(issuer);/*  www  .  ja  v  a2 s.c  om*/
    certGen.setSubjectDN(subject);
    certGen.setNotBefore(req.getNotBefore());
    certGen.setNotAfter(req.getNotAfter());
    certGen.setPublicKey(req.getKeyPair().getPublic());
    certGen.setSignatureAlgorithm(req.getSignatureAlgorithm());

    if (req.getCrlUrl() != null) {
        GeneralName gn = new GeneralName(6, new DERIA5String(req.getCrlUrl().toString()));

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);

        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);

        List<DistributionPoint> l = new ArrayList<DistributionPoint>();
        l.add(new DistributionPoint(dpn, null, null));

        CRLDistPoint crlDp = new CRLDistPoint(l.toArray(new DistributionPoint[0]));

        certGen.addExtension(new DERObjectIdentifier("2.5.29.31"), false, crlDp);
    }

    return certGen.generate(req.getIssuerKey(), "BC");
}

From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

License:Educational Community License

protected Certificate generateCertificate(KeyPair keyPair, String alias) throws GeneralSecurityException {

    //test that Bouncy Castle provider is present and add it if it's not
    if (Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }/*from   w ww. j a v a  2  s.co  m*/
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    //      X509Name nameInfo = new X509Name(false,"CN=" + alias);
    certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
    certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
    X509Principal nameInfo = new X509Principal("CN=" + alias);
    certificateGenerator.setIssuerDN(nameInfo);
    certificateGenerator.setSubjectDN(nameInfo); // note: same as issuer for self signed
    certificateGenerator.setNotBefore(new Date());
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
    certificateGenerator.setNotAfter(c.getTime());
    certificateGenerator.setPublicKey(keyPair.getPublic());
    return certificateGenerator.generate(keyPair.getPrivate(),
            org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME);
}

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

License:Open Source License

public static X509V3CertificateGenerator initCertificateGenerator(KeyPair pair, String issuerDN,
        String subjectDN, boolean isCA, long validityPeriod, String signatureAlgorithm) throws Exception {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    setSerialNumberAndValidityPeriod(v3CertGen, isCA, validityPeriod);

    v3CertGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, issuerDN));
    v3CertGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, subjectDN));
    v3CertGen.setPublicKey(pair.getPublic());
    if (signatureAlgorithm != null)
        v3CertGen.setSignatureAlgorithm(signatureAlgorithm);
    else//from   w w w .ja  va2s  .  c o m
        v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    return v3CertGen;
}

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

License:Open Source License

/**
 * Generate a CA Root certificate.//w w  w.  ja va2s . c om
 */
private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN));
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(
            new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation));
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning));

    return certGen.generate(pair.getPrivate(), "BC");
}

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

License:Open Source License

/**
 * Generate a sample V3 certificate to use as an intermediate or end entity 
 * certificate depending on the <code>isEndEntity</code> argument.
 *//*from   w  w  w.  j ava 2s.co  m*/
private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey,
        PrivateKey caKey, X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD);

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

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(caCert.getEncoded(),
                    new GeneralNames(new GeneralName(
                            new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))),
                    caCert.getSerialNumber()));

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

    if (isEndEntity) {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    } else {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    }
    return certGen.generate(caKey, "BC");
}