Example usage for org.bouncycastle.x509 X509V3CertificateGenerator setPublicKey

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

Introduction

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

Prototype

public void setPublicKey(PublicKey key) throws IllegalArgumentException 

Source Link

Usage

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

License:Open Source License

public static SODFile createTestObject() {
    try {//w ww .  jav a 2s  .c o  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);

        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  w ww . j a  v  a2  s. c o  m*/
 * @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);/*from w w  w.ja  v  a2s. 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 www .  ja v  a2s .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/* w  w w  .  j av  a  2 s.  co  m*/
        v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    return v3CertGen;
}

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

License:Open Source License

/**
 * Generate a CA Root certificate.//from  www . j  a va2s .c o  m
 */
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  a  v  a  2 s .  c o 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");
}

From source file:org.mitre.jwt.signer.service.impl.KeyStoreTest.java

License:Apache License

/**
 * Create an RSA KeyPair and insert into specified KeyStore
 * //from  w  ww  .  jav  a 2 s .  c om
 * @param location
 * @param domainName
 * @param alias
 * @param keystorePassword
 * @param aliasPassword
 * @param daysNotValidBefore
 * @param daysNotValidAfter
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static java.security.KeyStore generateKeyPair(KeyStore keystore, String keyPairAlgorithm, int keySize,
        String signatureAlgorithm, String domainName, String alias, String aliasPassword,
        int daysNotValidBefore, int daysNotValidAfter) throws GeneralSecurityException, IOException {

    java.security.KeyStore ks;

    if (keystore != null) {
        ks = keystore.getKeystore();
    } else {
        ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
        ks.load(null, null);
    }

    KeyPairGenerator rsaKeyPairGenerator = null;

    rsaKeyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm);

    rsaKeyPairGenerator.initialize(keySize);
    KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();

    // BC sez X509V3CertificateGenerator is deprecated and the docs say to
    // use another, but it seemingly isn't included jar...
    X509V3CertificateGenerator v3CertGen = createCertificate(domainName, daysNotValidBefore, daysNotValidAfter);

    PrivateKey privateKey = rsaKeyPair.getPrivate();

    v3CertGen.setPublicKey(rsaKeyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    // BC docs say to use another, but it seemingly isn't included...
    X509Certificate certificate = v3CertGen.generateX509Certificate(privateKey);

    // if exist, overwrite
    ks.setKeyEntry(alias, privateKey, aliasPassword.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    if (keystore != null) {
        keystore.setKeystore(ks);
    }

    return ks;
}

From source file:org.neo4j.server.security.ssl.SslCertificateFactory.java

License:Open Source License

public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) {
    FileOutputStream fos = null;/*  w w  w . jav a 2s. c o  m*/
    try {

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ENCRYPTION);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator certGenertor = new X509V3CertificateGenerator();

        certGenertor.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        certGenertor.setIssuerDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None"));
        certGenertor.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        certGenertor.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        certGenertor.setSubjectDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None"));

        certGenertor.setPublicKey(keyPair.getPublic());
        certGenertor.setSignatureAlgorithm("MD5WithRSAEncryption");

        Certificate certificate = certGenertor.generate(keyPair.getPrivate(), "BC");

        ensureFolderExists(certificatePath.getParentFile());
        ensureFolderExists(privateKeyPath.getParentFile());

        fos = new FileOutputStream(certificatePath);
        fos.write(certificate.getEncoded());
        fos.close();

        fos = new FileOutputStream(privateKeyPath);
        fos.write(keyPair.getPrivate().getEncoded());
        fos.close();

    } catch (Exception e) {
        throw new RuntimeException("Unable to create self signed SSL certificate, please see nested exception.",
                e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java

License:Apache License

public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey,
        X509Certificate caCert) throws Exception {

    installBouncyCastleProviderIfNecessary();

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD));
    certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate"));
    certGen.setPublicKey(intKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
    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_PROVIDER);
}