List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java
License:Open Source License
private static X509Certificate generateCertificate(KeyPair keyPair, String dn) throws Exception { ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn), new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn), keyPair.getPublic());//ww w .j av a 2 s . c om v3CertGen.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.otherName, new DERSequence(new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.4.1.311.20.2.3"), new DERTaggedObject(true, 0, new DERUTF8String(upn)) })))); X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
License:Open Source License
/** * Returns a signed certificate.// w w w .j a v a2 s . c o m * * @param builder * builder to create the certificate * @param key * private key for the certificate * @return a signed certificate * @throws OperatorCreationException * if there was a problem creation a bouncy castle operator * @throws CertificateException * if any of the certificates in the keystore could not be * loaded */ private final X509Certificate getSignedCertificate(final X509v3CertificateBuilder builder, final PrivateKey key) throws OperatorCreationException, CertificateException { final ContentSigner signer; // Content signer final String provider; // Provider final X509Certificate signed; // Signed certificate provider = BouncyCastleProvider.PROVIDER_NAME; signer = new JcaContentSignerBuilder(getSignatureAlgorithm()).setProvider(provider).build(key); signed = new JcaX509CertificateConverter().setProvider(provider).getCertificate(builder.build(signer)); LOGGER.debug("Signed certificate with {} private key {}, using algorithm {}", key.getAlgorithm(), Arrays.asList(key.getEncoded()), key.getFormat()); return signed; }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static X509Certificate loadX509Certificate(Reader reader) throws CryptoException { try (PEMParser pemParser = new PEMParser(reader)) { Object pemObj = pemParser.readObject(); if (pemObj instanceof X509Certificate) { return (X509Certificate) pemObj; } else if (pemObj instanceof X509CertificateHolder) { try { return new JcaX509CertificateConverter().setProvider(BC_PROVIDER) .getCertificate((X509CertificateHolder) pemObj); } catch (CertificateException ex) { LOG.error("loadX509Certificate: Caught CertificateException, unable to parse X509 certficate: " + ex.getMessage()); throw new CryptoException(ex); }// w w w . j a v a 2 s . c o m } } catch (IOException ex) { LOG.error( "loadX509Certificate: Caught IOException, unable to parse X509 certficate: " + ex.getMessage()); throw new CryptoException(ex); } return null; }
From source file:com.yahoo.athenz.auth.util.Crypto.java
License:Apache License
public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) { // set validity for the given number of minutes from now Date notBefore = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(notBefore);//from w w w .j a v a 2 s .c om cal.add(Calendar.MINUTE, validityTimeout); Date notAfter = cal.getTime(); // Generate self-signed certificate X509Certificate cert = null; try { JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest( certReq); PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey(); X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey) .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)) .addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)) .addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // see if we have the dns/rfc822/ip address extensions specified in the csr ArrayList<GeneralName> altNames = new ArrayList<>(); Attribute[] certAttributes = jcaPKCS10CertificationRequest .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (certAttributes != null && certAttributes.length > 0) { for (Attribute attribute : certAttributes) { Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); if (gns == null) { continue; } GeneralName[] names = gns.getNames(); for (int i = 0; i < names.length; i++) { switch (names[i].getTagNo()) { case GeneralName.dNSName: case GeneralName.iPAddress: case GeneralName.rfc822Name: altNames.add(names[i]); break; } } } if (!altNames.isEmpty()) { caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]))); } } String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256); ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER) .build(caPrivateKey); JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER); cert = converter.getCertificate(caBuilder.build(caSigner)); } catch (CertificateException ex) { LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage()); throw new CryptoException(ex); } catch (OperatorCreationException ex) { LOG.error( "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage()); throw new CryptoException(ex); } catch (InvalidKeyException ex) { LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage()); throw new CryptoException(ex); } catch (NoSuchAlgorithmException ex) { LOG.error( "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage()); throw new CryptoException(ex); } catch (Exception ex) { LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage()); throw new CryptoException("Unable to generate X509 Certificate"); } return cert; }
From source file:com.zotoh.crypto.Crypto.java
License:Open Source License
private Tuple createSSV1Cert(Provider pv, KeyPair keyPair, Date start, Date end, String dnStr, int keyLength, String algo) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, GeneralSecurityException { // generate self-signed cert X500Principal dnName = new X500Principal(dnStr); PrivateKey prv = keyPair.getPrivate(); PublicKey pub = keyPair.getPublic(); X509Certificate cert;/*from w ww.j a va2 s. c o m*/ // self signed-> issuer is self JcaX509v1CertificateBuilder bdr = new JcaX509v1CertificateBuilder(dnName, getNextSerialNumber(), start, end, dnName, pub); ContentSigner cs; try { cs = new JcaContentSignerBuilder(algo).setProvider(pv).build(prv); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } cert = new JcaX509CertificateConverter().setProvider(pv).getCertificate(bdr.build(cs)); cert.checkValidity(new Date()); cert.verify(pub); return new Tuple(cert, prv); }
From source file:com.zotoh.crypto.Crypto.java
License:Open Source License
private Tuple createSSV3Cert(Provider pv, KeyPair keyPair, Date start, Date end, String dnStr, Certificate issuer, PrivateKey issuerKey, int keyLength, String algo) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, GeneralSecurityException { X500Principal subject = new X500Principal(dnStr); PrivateKey prv = keyPair.getPrivate(); PublicKey pub = keyPair.getPublic(); X509Certificate cert, top = (X509Certificate) issuer; JcaX509v3CertificateBuilder bdr = new JcaX509v3CertificateBuilder(top, getNextSerialNumber(), start, end, subject, pub);/*from w w w . j ava 2 s . c om*/ ContentSigner cs; try { cs = new JcaContentSignerBuilder(algo).setProvider(pv).build(issuerKey); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } bdr.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(top)); bdr.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pub)); cert = new JcaX509CertificateConverter().setProvider(pv).getCertificate(bdr.build(cs)); cert.checkValidity(new Date()); cert.verify(top.getPublicKey()); return new Tuple(cert, prv); }
From source file:craterdog.security.RsaCertificateManager.java
License:Open Source License
@Override public X509Certificate createCertificateAuthority(PrivateKey privateKey, PublicKey publicKey, String subjectString, BigInteger serialNumber, long lifetime) { try {/* w ww . j a v a 2 s . com*/ logger.entry(); logger.debug("Initializing the certificate generator..."); Date startDate = new Date(); Date expiryDate = new Date(startDate.getTime() + lifetime); X500Principal issuer = new X500Principal(subjectString); X500Principal subject = new X500Principal(subjectString); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate, expiryDate, subject, publicKey); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); builder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(publicKey)); builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); // adds CA:TRUE extension builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); ContentSigner signer = new JcaContentSignerBuilder(ASYMMETRIC_SIGNATURE_ALGORITHM) .setProvider(PROVIDER_NAME).build(privateKey); X509Certificate result = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME) .getCertificate(builder.build(signer)); result.checkValidity(new Date()); result.verify(result.getPublicKey()); logger.exit(); return result; } catch (CertIOException | CertificateException | InvalidKeyException | OperatorCreationException | NoSuchProviderException | NoSuchAlgorithmException | SignatureException e) { RuntimeException exception = new RuntimeException( "An unexpected exception occurred while attempting to generate a new certificate authority.", e); throw logger.throwing(exception); } }
From source file:craterdog.security.RsaCertificateManager.java
License:Open Source License
@Override public X509Certificate createCertificate(PrivateKey caPrivateKey, X509Certificate caCertificate, PublicKey publicKey, String subjectString, BigInteger serialNumber, long lifetime) { try {/*w ww .jav a2 s.c om*/ logger.entry(); logger.debug("Initializing the certificate generator..."); Date startDate = new Date(); Date expiryDate = new Date(startDate.getTime() + lifetime); X509Certificate issuer = caCertificate; X500Principal subject = new X500Principal(subjectString); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate, expiryDate, subject, publicKey); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); builder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCertificate)); builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); ContentSigner signer = new JcaContentSignerBuilder(ASYMMETRIC_SIGNATURE_ALGORITHM) .setProvider(PROVIDER_NAME).build(caPrivateKey); X509Certificate result = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME) .getCertificate(builder.build(signer)); result.checkValidity(new Date()); result.verify(caCertificate.getPublicKey()); logger.exit(); return result; } catch (CertIOException | OperatorCreationException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { RuntimeException exception = new RuntimeException( "An unexpected exception occurred while attempting to generate a new certificate.", e); throw logger.throwing(exception); } }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java
License:Open Source License
@Override public X509Certificate generateAndSignCRT(KeyPair key, X509CertificateParams certificateParams, CertificateValidity certificateValidity, KeyPair issuerKey, X509Certificate issuerCRT, BigInteger serial) throws IOException, GeneralSecurityException { X500Principal issuerSubjectDN = (issuerCRT != null ? issuerCRT.getSubjectX500Principal() : certificateParams.getSubjectDN()); Date validFrom = Date/*from w w w . ja v a2 s .c o m*/ .from(certificateValidity.getValidFrom().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); Date validTo = Date .from(certificateValidity.getValidTo().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); X500Principal subjectDN = certificateParams.getSubjectDN(); X509v3CertificateBuilder crtBuilder = new JcaX509v3CertificateBuilder(issuerSubjectDN, serial, validFrom, validTo, subjectDN, key.getPublic()); addKeyIdentifierExtensions(crtBuilder, key.getPublic(), (issuerKey != null ? issuerKey.getPublic() : key.getPublic())); addCustomExtensions(crtBuilder, certificateParams); LOG.notice(I18N.BUNDLE, I18N.STR_GENERATE_CRT, subjectDN); ContentSigner crtSigner; try { crtSigner = new JcaContentSignerBuilder(certificateParams.getSigAlg()) .build((issuerKey != null ? issuerKey.getPrivate() : key.getPrivate())); } catch (OperatorCreationException e) { throw new StoreProviderException(e.getMessage(), e); } return new JcaX509CertificateConverter().getCertificate(crtBuilder.build(crtSigner)); }
From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java
License:Open Source License
@Override public X509Certificate generateAndSignCRT(X509Certificate crt, X509CertificateParams certificateParams, CertificateValidity certificateValidity, KeyPair issuerKey) throws IOException, GeneralSecurityException { X500Principal issuerSubjectDN = crt.getIssuerX500Principal(); BigInteger serial = crt.getSerialNumber(); Date validFrom = Date/*w ww.j a v a 2 s . c om*/ .from(certificateValidity.getValidFrom().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); Date validTo = Date .from(certificateValidity.getValidTo().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()); X500Principal subjectDN = crt.getSubjectX500Principal(); X509v3CertificateBuilder crtBuilder = new JcaX509v3CertificateBuilder(issuerSubjectDN, serial, validFrom, validTo, subjectDN, crt.getPublicKey()); addKeyIdentifierExtensions(crtBuilder, crt.getPublicKey(), issuerKey.getPublic()); addCustomExtensions(crtBuilder, certificateParams); LOG.notice(I18N.BUNDLE, I18N.STR_GENERATE_CRT, subjectDN); ContentSigner crtSigner; try { crtSigner = new JcaContentSignerBuilder(certificateParams.getSigAlg()).build(issuerKey.getPrivate()); } catch (OperatorCreationException e) { throw new StoreProviderException(e.getMessage(), e); } return new JcaX509CertificateConverter().getCertificate(crtBuilder.build(crtSigner)); }