List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate
public X509Certificate generate(PrivateKey key, String provider) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
From source file:org.jmrtd.test.api.lds.SODFileTest.java
License:Open Source License
public static SODFile createTestObject() { try {//from w w w. j a v a 2 s . 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); 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 . com 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.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 .j a v a 2s . com 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 w w. j a va2s .c om 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
/** * Generate a CA Root certificate.//from w w w .j a v a 2s . 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. *///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.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.j av a 2 s . co 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);/*from w w w . j av a 2s.c om*/ 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); }
From source file:org.neociclo.odetteftp.util.OnTheFlyHelper.java
License:Apache License
public static X509Certificate generateEndEntityCert(PublicKey entityKey, 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 End Certificate")); certGen.setPublicKey(entityKey);//from w ww . j a v a 2 s. c o m certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generate(caKey, BC_PROVIDER); }
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException { X509Certificate cert;//w ww. j a va 2 s . c om try { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal()); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setNotBefore(getCertStartDate()); certGen.setNotAfter(getCertEndDate()); certGen.setPublicKey(csr.getPublicKey("BC")); certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(getRootCertificate())); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); @SuppressWarnings("rawtypes") Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(), rootService.getRootCertificateAlias(), rootService.getRootKeyPassword()); cert = certGen.generate(rootKeyPair.getPrivate(), "BC"); } catch (CertificateParsingException e) { throw new CertException(e); } catch (CertificateEncodingException e) { throw new CertException(e); } catch (InvalidKeyException e) { throw new CertException(e); } catch (IllegalStateException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } LOG.debug("Certificate generated for subject: " + cert.getSubjectDN()); return cert; }