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:at.ac.tuwien.ifs.tita.business.security.TiTASecurity.java
License:Apache License
/** * Generates a fresh Certificate for a Users KeyPair. * /*from w w w. j a v a 2 s . co m*/ * @param pair the KeyPair to create a Certificate for. * @param userName the Issuer of the Certificate * @return a 10 Year valid Certificate for the User. * @throws TiTASecurityException If an error occurs during the generation Process. */ private static X509Certificate generateV3Certificate(KeyPair pair, String userName) throws TiTASecurityException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE)); certGen.setSubjectDN(new X500Principal("CN=" + userName + " Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); X509Certificate targetCertificate = null; try { targetCertificate = certGen.generate(pair.getPrivate(), "BC"); } catch (NoSuchProviderException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified provider was not found.\n" + e.getMessage()); } catch (NoSuchAlgorithmException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified algorithm was not found.\n" + e.getMessage()); } catch (SignatureException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Signature is not valid.\n" + e.getMessage()); } catch (CertificateEncodingException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Wrong encoding for Signature.\n" + e.getMessage()); } catch (InvalidKeyException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". The Key is not valid.\n" + e.getMessage()); } return targetCertificate; }
From source file:brooklyn.util.crypto.FluentKeySigner.java
License:Apache License
public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) { try {/* ww w. j a va 2s . c om*/ X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(serialNumber != null ? serialNumber : // must be positive BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE)); v3CertGen.setIssuerDN(issuerPrincipal); v3CertGen.setNotBefore(validityStartDate); v3CertGen.setNotAfter(validityEndDate); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); v3CertGen.setSubjectDN(subject); v3CertGen.setPublicKey(keyToCertify); v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyToCertify)); if (authorityKeyIdentifier != null) v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC"); return pkCertificate; } catch (Exception e) { throw Exceptions.propagate(e); } }
From source file:ca.nrc.cadc.cred.CertUtil.java
License:Open Source License
/** * Method that generates an X509 proxy certificate * //w w w. j a va 2 s . c om * @param csr CSR for the certificate * @param lifetime lifetime of the certificate in SECONDS * @param chain certificate used to sign the proxy certificate * @return generated proxy certificate * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CertificateParsingException * @throws CertificateEncodingException * @throws SignatureException * @throws CertificateNotYetValidException * @throws CertificateExpiredException */ public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime, X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException, CertificateExpiredException, CertificateNotYetValidException { X509Certificate issuerCert = chain.getChain()[0]; PrivateKey issuerKey = chain.getPrivateKey(); Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(issuerCert.getSubjectX500Principal()); // generate the proxy DN as the issuerDN + CN=random number Random rand = new Random(); String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253); String delegDN = String.valueOf(Math.abs(rand.nextInt())); String proxyDn = "CN=" + delegDN + "," + issuerDN; certGen.setSubjectDN(new X500Principal(proxyDn)); // set validity GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Start date. Allow for a sixty five minute clock skew here. date.add(Calendar.MINUTE, -65); Date beforeDate = date.getTime(); for (X509Certificate currentCert : chain.getChain()) { if (beforeDate.before(currentCert.getNotBefore())) { beforeDate = currentCert.getNotBefore(); } } certGen.setNotBefore(beforeDate); // End date. // If hours = 0, then cert lifetime is set to that of user cert if (lifetime <= 0) { // set the validity of certificates as the minimum // of the certificates in the chain Date afterDate = issuerCert.getNotAfter(); for (X509Certificate currentCert : chain.getChain()) { if (afterDate.after(currentCert.getNotAfter())) { afterDate = currentCert.getNotAfter(); } } certGen.setNotAfter(afterDate); } else { // check the validity of the signing certificate date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); for (X509Certificate currentCert : chain.getChain()) { currentCert.checkValidity(date.getTime()); } certGen.setNotAfter(date.getTime()); } certGen.setPublicKey(csr.getPublicKey()); // TODO: should be able to get signature algorithm from the csr, but... obtuse certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM); // extensions // add ProxyCertInfo extension to the new cert certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // add the Proxy Certificate Information // I expect this code to be removed once support to proxy // certificates is provided in Bouncy Castle. // create a proxy policy // types of proxy certificate policies - see RFC3820 // impersonates the user final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1"); // independent // final DERObjectIdentifier INDEPENDENT = new // DERObjectIdentifier( // "1.3.6.1.5.5.7.21.2"); // defined by a policy language // final DERObjectIdentifier LIMITED = new DERObjectIdentifier( // "1.3.6.1.4.1.3536.1.1.1.9"); ASN1EncodableVector policy = new ASN1EncodableVector(); policy.add(IMPERSONATION); // pathLengthConstr (RFC3820) // The pCPathLenConstraint field, if present, specifies the // maximum // depth of the path of Proxy Certificates that can be signed by // this // Proxy Certificate. A pCPathLenConstraint of 0 means that this // certificate MUST NOT be used to sign a Proxy Certificate. If // the // pCPathLenConstraint field is not present then the maximum proxy // path // length is unlimited. End entity certificates have unlimited // maximum // proxy path lengths. // DERInteger pathLengthConstr = new DERInteger(100); // create the proxy certificate information ASN1EncodableVector vec = new ASN1EncodableVector(); // policy.add(pathLengthConstr); vec.add(new DERSequence(policy)); // OID final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14"); certGen.addExtension(OID, true, new DERSequence(vec)); return certGen.generate(issuerKey, "BC"); }
From source file:com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest.java
License:Open Source License
private void addEntry(final String alias) throws GeneralSecurityException { final KeyPair pair = KG.generateKeyPair(); // build a certificate generator final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); final X500Principal dnName = new X500Principal("cn=" + alias); certGen.setSerialNumber(new BigInteger(256, RND)); certGen.setSubjectDN(new X509Name("dc=" + alias)); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC"); ks.setEntry(alias, new KeyStore.PrivateKeyEntry(pair.getPrivate(), new X509Certificate[] { cert }), PP); }
From source file:com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest.java
License:Open Source License
private void addPublicEntry(final String alias) throws GeneralSecurityException { final KeyPair pair = KG.generateKeyPair(); // build a certificate generator final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); final X500Principal dnName = new X500Principal("cn=" + alias); certGen.setSerialNumber(new BigInteger(256, RND)); certGen.setSubjectDN(new X509Name("dc=" + alias)); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000)); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); final X509Certificate cert = certGen.generate(pair.getPrivate(), "BC"); ks.setEntry(alias, new KeyStore.TrustedCertificateEntry(cert), null); }
From source file:com.eucalyptus.auth.crypto.DefaultCryptoProvider.java
License:Open Source License
@Override public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey) {/*from w ww. j a v a 2 s.c o m*/ signer = (signingKey == null ? signer : subjectDn); signingKey = (signingKey == null ? keys.getPrivate() : signingKey); EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.getPublic())); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); cal.add(Calendar.YEAR, 5); certGen.setNotAfter(cal.getTime()); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(keys.getPublic()); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:com.eucalyptus.auth.util.KeyTool.java
License:Open Source License
public X509Certificate getCertificate(KeyPair keyPair, String certDn) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal dnName = new X500Principal(certDn); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(dnName);//w ww.ja va 2s . c o m certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); cal.add(Calendar.YEAR, 5); certGen.setNotAfter(cal.getTime()); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(this.keySigningAlgorithm); try { X509Certificate cert = certGen.generate(keyPair.getPrivate(), PROVIDER); return cert; } catch (Exception e) { LOG.fatal(e, e); System.exit(-3); return null; } }
From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java
License:Open Source License
@Override public X509Certificate generateCertificate(PublicKey key, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey, Date notAfter) { if (signingKey == null) { LOG.error("No signing key is provided"); return null; }// w w w .ja va 2 s. c o m if (signer == null) { LOG.error("No signiner principal is specified"); return null; } if (subjectDn == null) { LOG.error("No subject principal is specified"); return null; } if (key == null) { LOG.error("No requesting key is specified"); return null; } EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(key)); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); certGen.setNotAfter(notAfter); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(key); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java
License:Open Source License
@Override public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey, Date notAfter) { signer = (signingKey == null ? signer : subjectDn); signingKey = (signingKey == null ? keys.getPrivate() : signingKey); EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer);/* w ww .j ava 2s . c o m*/ certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.getPublic())); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); certGen.setNotAfter(notAfter); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(keys.getPublic()); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java
License:Open Source License
private X509Certificate generateCertificateToEntity(EntityAuthentication entity, DataMoverSessionID sessionID) throws SSLPeerUnverifiedException, CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, KeyStoreException, UnrecoverableKeyException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal dnName = new X500Principal("CN=" + entity.getEntityID().toString()); certGen.setSerialNumber(sessionID.toBigInteger()); X509Certificate rootCertificate = null; for (X509Certificate checkCertificate : trustedServerCertificates.values()) { try {/*from ww w. j a v a 2s.c om*/ entity.getCertificate().verify(checkCertificate.getPublicKey(), "BC"); rootCertificate = checkCertificate; break; } catch (GeneralSecurityException e) { Logger.getLogger(getClass()).debug(new ErrorLogMessage("Skipping certificate {0}", (Serializable) checkCertificate.getSubjectDN().getName())); } } if (rootCertificate == null) throw new SSLPeerUnverifiedException("No certificates authenticated"); certGen.setIssuerDN(rootCertificate.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis() - 60L * 60L * 1000L)); certGen.setNotAfter(new Date(System.currentTimeMillis() + (365L * 24L * 60L * 1000L))); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setPublicKey(entity.getCertificate().getPublicKey()); certGen.setSignatureAlgorithm(EntityAuthenticationServer.kCertificateSignatureAlg); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCertificate)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entity.getCertificate().getPublicKey())); byte[] sessionIDBytes = new byte[DataMoverSessionID.kTotalBytes]; sessionID.getBytes(sessionIDBytes, 0); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, sessionIDBytes); byte[] issuerIDBytes = new byte[EntityID.kTotalBytes]; clientIdentity.getBytes(issuerIDBytes, 0); certGen.addExtension(X509Extensions.IssuerAlternativeName, false, issuerIDBytes); X509Certificate cert = certGen.generate((PrivateKey) persistentKeyStore .getKey(kPrivateKeyAliasPrefix + id.toString(), kDefaultKeyStorePassword.toCharArray()), "BC"); return cert; }