List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator X509V3CertificateGenerator
public X509V3CertificateGenerator()
From source file:org.mitre.jwt.JwtTest.java
License:Apache License
/** * Creates a certificate.//from ww w. j a va2 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;//from www . j av a 2 s.c om 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 v a 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);//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(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;/* www .j a va2 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; }
From source file:org.obiba.opal.core.unit.UnitKeyStore.java
License:Open Source License
public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey, PublicKey subjectPublicKey, String certificateInfo, String signatureAlgorithm) throws SignatureException, InvalidKeyException, CertificateEncodingException, NoSuchAlgorithmException { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); X509Name issuerDN = new X509Name(certificateInfo); X509Name subjectDN = new X509Name(certificateInfo); int daysTillExpiry = 30 * 365; Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, daysTillExpiry); certificateGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(subjectDN); certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setNotBefore(new Date()); certificateGenerator.setNotAfter(expiry.getTime()); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); return certificateGenerator.generate(issuerPrivateKey); }
From source file:org.obiba.security.KeyStoreManager.java
License:Open Source License
public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey, PublicKey subjectPublicKey, String certificateInfo, String signatureAlgorithm) throws SignatureException, InvalidKeyException, CertificateEncodingException, NoSuchAlgorithmException { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); X509Name issuerDN = new X509Name(certificateInfo); X509Name subjectDN = new X509Name(certificateInfo); int daysTillExpiry = 30 * 365; Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, daysTillExpiry); certificateGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(subjectDN); certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setNotBefore(new Date()); certificateGenerator.setNotAfter(expiry.getTime()); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); return certificateGenerator.generate(issuerPrivateKey); }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * DOCUMENT ME!/* w ww .j a v a2 s .c o m*/ * * @param dn DOCUMENT ME! * @param validity DOCUMENT ME! * @param policyId DOCUMENT ME! * @param privKey DOCUMENT ME! * @param pubKey DOCUMENT ME! * @param isCA DOCUMENT ME! * * @return DOCUMENT ME! * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException { // Create self signed certificate String sigAlg = "SHA1WithRSA"; Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(pubKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla. try { if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey); return selfcert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {//from www . j av a 2 s.c o m // Create self signed certificate String sigAlg = "SHA1WithRSA"; Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(caDn)); certgen.setPublicKey(pubKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (false) { //if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla. try { if (false) { //if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate cert = certgen.generate(caPrivateKey); return cert; }
From source file:org.objectweb.proactive.extensions.ssl.CertificateGenerator.java
License:Open Source License
/** * Create a random, self signed, one time certificate * * A such certificate can be used to take advantage of the SSL/TLS encryption * feature without requiring any action from the user. * * A self signed certificate, valid for the next 10 year is issued. * * @return/* w w w . j av a2 s . c om*/ */ public X509Certificate generateCertificate(String subjectDN, KeyPair pair) throws SslException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Auto-generated certificate, use a default principal X500Principal defaultPrincipal; defaultPrincipal = new X500Principal(subjectDN); certGen.setIssuerDN(defaultPrincipal); certGen.setSubjectDN(defaultPrincipal); // Valid for the next few years certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + (10 * 365 * 24 * 60))); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // Not certified by a CA certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // SSL requires signiture & encipherment KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment); certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage); // Allow client and server authentication Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>(); extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(extendedKeyUsageV)); try { X509Certificate cert = certGen.generate(pair.getPrivate(), BouncyCastleProvider.PROVIDER_NAME); try { cert.checkValidity(); cert.verify(pair.getPublic()); } catch (GeneralSecurityException e) { throw new SslException("Generated certificate is not valid", e); } return cert; } catch (GeneralSecurityException e) { throw new SslException("Failed to generate certificate", e); } }