List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber
public void setSerialNumber(BigInteger serialNumber)
From source file:org.jmrtd.test.lds.SODFileTest.java
License:Open Source License
public static SODFile createTestObject() { try {/*from w w w . j av a 2s.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/* ww w .ja v a 2 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);// www .j a v a 2 s . 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 v a2s. c o 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 void setSerialNumberAndValidityPeriod(X509V3CertificateGenerator certGen, boolean isRootCA, long validityPeriod) { if (isRootCA) certGen.setSerialNumber(BigInteger.ONE); else/* w w w. j a v a 2 s .co m*/ certGen.setSerialNumber(BigInteger.valueOf(++serial)); long time = System.currentTimeMillis(); time -= time % 86400000L; certGen.setNotBefore(new Date(time)); certGen.setNotAfter(new Date(time + validityPeriod)); }
From source file:org.mitre.jwt.JwtTest.java
License:Apache License
/** * Creates a certificate.//from ww w . ja v a 2 s.com * * @param commonName * @param daysNotValidBefore * @param daysNotValidAfter * @return */ public static X509V3CertificateGenerator createCertificate(String commonName, int daysNotValidBefore, int daysNotValidAfter) { // BC sez X509V3CertificateGenerator is deprecated and the docs say to // use another, but it seemingly isn't included jar... X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * daysNotValidBefore))); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * daysNotValidAfter))); v3CertGen.setSubjectDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None")); return v3CertGen; }
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 a v 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);/*from w w w .j a va 2 s . 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);/* www . ja v a 2s .co 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;//from w w w . j a v a 2 s. co m 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; }