org.bouncycastle.cert.jcajce.JcaX509CertificateConverter Java Examples
The following examples show how to use
org.bouncycastle.cert.jcajce.JcaX509CertificateConverter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertificateUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 7 votes |
public static X509Certificate generateCert(PublicKey rqPubKey, BigInteger serialNr, Credential cred) throws TechnicalConnectorException { try { X509Certificate cert = cred.getCertificate(); X500Principal principal = cert.getSubjectX500Principal(); Date notBefore = cert.getNotBefore(); Date notAfter = cert.getNotAfter(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, serialNr, notBefore, notAfter, principal, rqPubKey); int keyUsageDetails = 16 + 32; builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails)); ContentSigner signer = (new JcaContentSignerBuilder(cert.getSigAlgName())).build(cred.getPrivateKey()); X509CertificateHolder holder = builder.build(signer); return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder); } catch (OperatorCreationException | IOException | CertificateException ex) { throw new IllegalArgumentException(ex); } }
Example #2
Source File: OcspServerExample.java From netty-4.1.22 with Apache License 2.0 | 7 votes |
private static X509Certificate[] parseCertificates(Reader reader) throws Exception { JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()); List<X509Certificate> dst = new ArrayList<X509Certificate>(); PEMParser parser = new PEMParser(reader); try { X509CertificateHolder holder = null; while ((holder = (X509CertificateHolder) parser.readObject()) != null) { X509Certificate certificate = converter.getCertificate(holder); if (certificate == null) { continue; } dst.add(certificate); } } finally { parser.close(); } return dst.toArray(new X509Certificate[0]); }
Example #3
Source File: KeyStoreDemo.java From Hands-On-Cryptography-with-Java with MIT License | 7 votes |
/** * It's annoying to have to wrap KeyPairs with Certificates, but this is * "easier" for you to know who the key belongs to. * * @param keyPair A KeyPair to wrap * @return A wrapped certificate with constant name * @throws CertificateException * @throws OperatorCreationException */ public static Certificate generateCertificate(KeyPair keyPair) throws CertificateException, OperatorCreationException { X500Name name = new X500Name("cn=Annoying Wrapper"); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); final Date start = new Date(); final Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC)); final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name, new BigInteger(10, new SecureRandom()), //Choose something better for real use start, until, name, subPubKeyInfo ); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()); final X509CertificateHolder holder = builder.build(signer); Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder); return cert; }
Example #4
Source File: TestSslUtils.java From li-apache-kafka-clients with BSD 2-Clause "Simplified" License | 6 votes |
/** * Create a self-signed X.509 Certificate. * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws CertificateException thrown if a security error or an IO error occurred. */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
Example #5
Source File: OcspCertificateValidatorTest.java From localization_nifi with Apache License 2.0 | 6 votes |
/** * Generates a certificate with a specific public key signed by the issuer key. * * @param dn the subject DN * @param publicKey the subject public key * @param issuerDn the issuer DN * @param issuerKey the issuer private key * @return the certificate * @throws IOException if an exception occurs * @throws NoSuchAlgorithmException if an exception occurs * @throws CertificateException if an exception occurs * @throws NoSuchProviderException if an exception occurs * @throws SignatureException if an exception occurs * @throws InvalidKeyException if an exception occurs * @throws OperatorCreationException if an exception occurs */ private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException { ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(YESTERDAY); Date endDate = new Date(ONE_YEAR_FROM_NOW); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #6
Source File: CertUtil.java From littleca with Apache License 2.0 | 6 votes |
/** * 读取x509 证书 * * @param pemPath * @return */ public static X509Certificate readX509Cert(String savePath) throws CertException { try { if (null == savePath) { throw new CertException("save path can't be null"); } PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath))); Object readObject = pemParser.readObject(); if (readObject instanceof X509CertificateHolder) { X509CertificateHolder holder = (X509CertificateHolder) readObject; return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(holder); } pemParser.close(); throw new CertException(savePath + "file read format failed"); } catch (Exception e) { throw new CertException("read x509 cert failed", e); } }
Example #7
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public List<X509Certificate> getAssociatedCertificates() { List<X509Certificate> result = new ArrayList(); X509CertificateHolder[] arr$ = this.ocsp.getCerts(); int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) { X509CertificateHolder certificateHolder = arr$[i$]; try { result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder)); } catch (CertificateException var7) { throw new IllegalArgumentException(var7); } } return result; }
Example #8
Source File: RSAKeyGeneratorUtils.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
public RSAKeyGeneratorUtils() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA"); kpGenerator.initialize(2048); KeyPair keyPair = kpGenerator.generateKeyPair(); X500Name issuerName = new X500Name("OU=spring-cloud-gcp,CN=firebase-auth-integration-test"); this.privateKey = keyPair.getPrivate(); JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( issuerName, BigInteger.valueOf(System.currentTimeMillis()), Date.from(Instant.now()), Date.from(Instant.now().plusMillis(1096 * 24 * 60 * 60)), issuerName, keyPair.getPublic()); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey); X509CertificateHolder certHolder = builder.build(signer); this.certificate = new JcaX509CertificateConverter().getCertificate(certHolder); this.publicKey = this.certificate.getPublicKey(); }
Example #9
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public List<X509Certificate> getAssociatedCertificates() { List<X509Certificate> result = new ArrayList(); X509CertificateHolder[] arr$ = this.ocsp.getCerts(); int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) { X509CertificateHolder certificateHolder = arr$[i$]; try { result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder)); } catch (CertificateException var7) { throw new IllegalArgumentException(var7); } } return result; }
Example #10
Source File: TestSSLUtils.java From ambry with Apache License 2.0 | 6 votes |
/** * Create a self-signed X.509 Certificate. * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN(commonName)=Test, O(organizationName)=Org" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws java.security.cert.CertificateException thrown if a security error or an IO error ocurred. */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
Example #11
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public List<X509Certificate> getAssociatedCertificates() { List<X509Certificate> result = new ArrayList(); X509CertificateHolder[] arr$ = this.ocsp.getCerts(); int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) { X509CertificateHolder certificateHolder = arr$[i$]; try { result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder)); } catch (CertificateException var7) { throw new IllegalArgumentException(var7); } } return result; }
Example #12
Source File: OcspRef.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public List<X509Certificate> getAssociatedCertificates() { List<X509Certificate> result = new ArrayList(); X509CertificateHolder[] arr$ = this.ocsp.getCerts(); int len$ = arr$.length; for(int i$ = 0; i$ < len$; ++i$) { X509CertificateHolder certificateHolder = arr$[i$]; try { result.add((new JcaX509CertificateConverter()).setProvider("BC").getCertificate(certificateHolder)); } catch (CertificateException var7) { throw new IllegalArgumentException(var7); } } return result; }
Example #13
Source File: CertificateUtils.java From docker-java with Apache License 2.0 | 6 votes |
/** * "ca.pem" from Reader */ public static KeyStore createTrustStore(final Reader certReader) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { try (PEMParser pemParser = new PEMParser(certReader)) { KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null); int index = 1; Object pemCert; while ((pemCert = pemParser.readObject()) != null) { Certificate caCertificate = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate((X509CertificateHolder) pemCert); trustStore.setCertificateEntry("ca-" + index, caCertificate); index++; } return trustStore; } }
Example #14
Source File: KeyStoreHelperTest.java From ph-commons with Apache License 2.0 | 6 votes |
@Nonnull private static X509Certificate _createX509V1Certificate (final KeyPair aKeyPair) throws Exception { // generate the certificate final PublicKey aPublicKey = aKeyPair.getPublic (); final PrivateKey aPrivateKey = aKeyPair.getPrivate (); final ContentSigner aContentSigner = new JcaContentSignerBuilder ("SHA256WithRSA").setProvider (PBCProvider.getProvider ()) .build (aPrivateKey); final X509CertificateHolder aCertHolder = new JcaX509v1CertificateBuilder (new X500Principal ("CN=Test Certificate"), BigInteger.valueOf (System.currentTimeMillis ()), new Date (System.currentTimeMillis () - 50000), new Date (System.currentTimeMillis () + 50000), new X500Principal ("CN=Test Certificate"), aPublicKey).build (aContentSigner); // Convert to JCA X509Certificate return new JcaX509CertificateConverter ().getCertificate (aCertHolder); }
Example #15
Source File: CertificateUtils.java From docker-java with Apache License 2.0 | 6 votes |
/** * "cert.pem" from reader */ public static List<Certificate> loadCertificates(final Reader reader) throws IOException, CertificateException { try (PEMParser pemParser = new PEMParser(reader)) { List<Certificate> certificates = new ArrayList<>(); JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME); Object certObj; while ((certObj = pemParser.readObject()) != null) { if (certObj instanceof X509CertificateHolder) { X509CertificateHolder certificateHolder = (X509CertificateHolder) certObj; certificates.add(certificateConverter.getCertificate(certificateHolder)); } } return certificates; } }
Example #16
Source File: CAdESSigner.java From signer with GNU Lesser General Public License v3.0 | 6 votes |
private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) { Collection<X509Certificate> result = new HashSet<X509Certificate>(); Store<?> certStore = previewSignerData.getCertificates(); SignerInformationStore signers = previewSignerData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); try { result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder)); } catch (CertificateException error) { } } return result; }
Example #17
Source File: SSLKeyPairCerts.java From vertx-tcp-eventbus-bridge with Apache License 2.0 | 6 votes |
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception { final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new org.bouncycastle.asn1.x500.X500Name(certSub), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(certSub), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
Example #18
Source File: OcspCertificateValidatorTest.java From nifi with Apache License 2.0 | 6 votes |
/** * Generates a certificate with a specific public key signed by the issuer key. * * @param dn the subject DN * @param publicKey the subject public key * @param issuerDn the issuer DN * @param issuerKey the issuer private key * @return the certificate * @throws IOException if an exception occurs * @throws NoSuchAlgorithmException if an exception occurs * @throws CertificateException if an exception occurs * @throws NoSuchProviderException if an exception occurs * @throws SignatureException if an exception occurs * @throws InvalidKeyException if an exception occurs * @throws OperatorCreationException if an exception occurs */ private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException { ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(YESTERDAY); Date endDate = new Date(ONE_YEAR_FROM_NOW); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #19
Source File: SelfSignedCaCertificate.java From nomulus with Apache License 2.0 | 6 votes |
/** Returns a self-signed Certificate Authority (CA) certificate. */ static X509Certificate createCaCert(KeyPair keyPair, String fqdn, Date from, Date to) throws Exception { X500Name owner = new X500Name("CN=" + fqdn); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate()); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( owner, new BigInteger(64, RANDOM), from, to, owner, keyPair.getPublic()); // Mark cert as CA by adding basicConstraint with cA=true to the builder BasicConstraints basicConstraints = new BasicConstraints(true); builder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); X509CertificateHolder certHolder = builder.build(signer); return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder); }
Example #20
Source File: CertificateUtils.java From keycloak with Apache License 2.0 | 6 votes |
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber) { try { X500Name subjectDN = new X500Name("CN=" + subject); Date validityStartDate = new Date(System.currentTimeMillis() - 100000); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 10); Date validityEndDate = new Date(calendar.getTime().getTime()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate, validityEndDate, subjectDN, subPubKeyInfo); X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate())); return new JcaX509CertificateConverter().getCertificate(holder); } catch (Exception e) { throw new RuntimeException("Error creating X509v1Certificate.", e); } }
Example #21
Source File: CertificateTool.java From peer-os with Apache License 2.0 | 6 votes |
/** * Convert X509 certificate in PEM format to X509Certificate object * * @param x509InPem X509 certificate in PEM format * * @return {@code X509Certificate} */ public X509Certificate convertX509PemToCert( String x509InPem ) { try { PEMParser pemParser = new PEMParser( new StringReader( x509InPem ) ); JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter(); Object o = pemParser.readObject(); return x509CertificateConverter.getCertificate( ( X509CertificateHolder ) o ); } catch ( Exception e ) { throw new ActionFailedException( "Failed to convert PEM to certificate", e ); } }
Example #22
Source File: SslInitializerTestUtils.java From nomulus with Apache License 2.0 | 6 votes |
/** * Signs the given key pair with the given self signed certificate to generate a certificate with * the given validity range. * * @return signed public key (of the key pair) certificate */ public static X509Certificate signKeyPair( SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, Date from, Date to) throws Exception { X500Name subjectDnName = new X500Name("CN=" + hostname); BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); X500Name issuerDnName = new X500Name(ssc.cert().getIssuerDN().getName()); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(ssc.key()); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder( issuerDnName, serialNumber, from, to, subjectDnName, keyPair.getPublic()); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter() .setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #23
Source File: Certificates.java From vertx-config with Apache License 2.0 | 5 votes |
/** * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder * * @param keyPair The RSA keypair with which to generate the certificate * @param issuer The issuer (and subject) to use for the certificate * @return An X509 certificate * @throws IOException * @throws OperatorCreationException * @throws CertificateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException */ private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { final String subject = issuer; final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new X500Name(issuer), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
Example #24
Source File: CertificateGeneratorTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void whenCAExists_andHasATransitionalVersion_aValidChildCertificateIsGenerated() throws Exception { final KeyPair childCertificateKeyPair = setupKeyPair(); setupMocksForRootCA(childCertificateKeyPair); KeyPair transitionalCaKeyPair = fakeKeyPairGenerator.generate(); final X509CertificateHolder caX509CertHolder = makeCert(transitionalCaKeyPair, transitionalCaKeyPair.getPrivate(), rootCaDn, rootCaDn, true); X509Certificate transitionalCaX509Certificate = new JcaX509CertificateConverter() .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME).getCertificate(caX509CertHolder); CertificateCredentialValue transitionalCa = new CertificateCredentialValue( null, CertificateFormatter.pemOf(transitionalCaX509Certificate), CertificateFormatter.pemOf(transitionalCaKeyPair.getPrivate()), null, true, true, false, true); generationParameters.setKeyLength(4096); final CertificateGenerationParameters params = new CertificateGenerationParameters(generationParameters); when( signedCertificateGenerator .getSignedByIssuer(childCertificateKeyPair, params, rootCaX509Certificate, rootCaKeyPair.getPrivate()) ).thenReturn(childX509Certificate); when(certificateAuthorityService.findTransitionalVersion("/my-ca-name")).thenReturn(transitionalCa); final CertificateCredentialValue certificateWithTrustedCa = subject.generateCredential(inputParameters); assertThat(certificateWithTrustedCa.getCa(), equalTo(rootCa.getCertificate())); assertThat(certificateWithTrustedCa.getTrustedCa(), equalTo(transitionalCa.getCertificate())); }
Example #25
Source File: BasicKeyStore.java From env-keystore with MIT License | 5 votes |
protected static X509Certificate parseCert(PEMParser parser) throws IOException, CertificateException { X509CertificateHolder certHolder = (X509CertificateHolder) parser.readObject(); if (certHolder == null) { return null; } return new JcaX509CertificateConverter().getCertificate(certHolder); }
Example #26
Source File: ApkUtils.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(String asymmetric, String sign, int validityYears, String dn) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException { Preconditions.checkArgument(validityYears > 0, "validityYears <= 0"); KeyPair keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair(); Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + validityYears * 31536000000l); X500Name issuer = new X500Name(new X500Principal(dn).getName()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo); ContentSigner signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()); X509Certificate certificate = converter.getCertificate(holder); return Pair.of(keyPair.getPrivate(), certificate); }
Example #27
Source File: AbstractX509CertificateService.java From flashback with BSD 2-Clause "Simplified" License | 5 votes |
protected X509Certificate createCertificate(PrivateKey privateKey, X509v3CertificateBuilder x509v3CertificateBuilder) throws OperatorCreationException, CertificateException { ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(privateKey); X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(x509v3CertificateBuilder.build(contentSigner)); return x509Certificate; }
Example #28
Source File: DeviceCertificateManager.java From enmasse with Apache License 2.0 | 5 votes |
public DeviceCertificateManager(final Mode mode, final X500Principal baseName) throws Exception { this.mode = mode; this.baseName = baseName; this.keyPairGenerator = KeyPairGenerator.getInstance(mode.getGeneratorAlgorithm()); this.keyPairGenerator.initialize(mode.getSpec()); this.keyPair = keyPairGenerator.generateKeyPair(); final Instant now = Instant.now(); final ContentSigner contentSigner = new JcaContentSignerBuilder(mode.getSignatureAlgorithm()) .build(this.keyPair.getPrivate()); final X509CertificateHolder certificate = new JcaX509v3CertificateBuilder( baseName, BigInteger.valueOf(this.serialNumber.getAndIncrement()), Date.from(now), Date.from(now.plus(Duration.ofDays(365))), baseName, this.keyPair.getPublic()) .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(this.keyPair.getPublic())) .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(this.keyPair.getPublic())) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .build(contentSigner); this.certificate = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certificate); }
Example #29
Source File: CertUtil.java From nitmproxy with MIT License | 5 votes |
public static Certificate newCert(String parentCertFile, String keyFile, String host) { try { Date before = Date.from(Instant.now()); Date after = Date.from(Year.now().plus(3, ChronoUnit.YEARS).atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant()); X509CertificateHolder parent = readPemFromFile(parentCertFile); PEMKeyPair pemKeyPair = readPemFromFile(keyFile); KeyPair keyPair = new JcaPEMKeyConverter() .setProvider(PROVIDER) .getKeyPair(pemKeyPair); X509v3CertificateBuilder x509 = new JcaX509v3CertificateBuilder( parent.getSubject(), new BigInteger(64, new SecureRandom()), before, after, new X500Name("CN=" + host), keyPair.getPublic()); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter() .setProvider(PROVIDER); return new Certificate( keyPair, x509CertificateConverter.getCertificate(x509.build(signer)), x509CertificateConverter.getCertificate(parent)); } catch (Exception e) { throw new IllegalStateException(e); } }
Example #30
Source File: CertUtil.java From proxyee with MIT License | 5 votes |
/** * 动态生成服务器证书,并进行CA签授 * * @param issuer 颁发机构 */ public static X509Certificate genCert(String issuer, PrivateKey caPriKey, Date caNotBefore, Date caNotAfter, PublicKey serverPubKey, String... hosts) throws Exception { /* String issuer = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=ProxyeeRoot"; String subject = "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + host;*/ //根据CA证书subject来动态生成目标服务器证书的issuer和subject String subject = Stream.of(issuer.split(", ")).map(item -> { String[] arr = item.split("="); if ("CN".equals(arr[0])) { return "CN=" + hosts[0]; } else { return item; } }).collect(Collectors.joining(", ")); //doc from https://www.cryptoworkshop.com/guide/ JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(issuer), //issue#3 修复ElementaryOS上证书不安全问题(serialNumber为1时证书会提示不安全),避免serialNumber冲突,采用时间戳+4位随机数生成 BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000), caNotBefore, caNotAfter, new X500Name(subject), serverPubKey); //SAN扩展证书支持的域名,否则浏览器提示证书不安全 GeneralName[] generalNames = new GeneralName[hosts.length]; for (int i = 0; i < hosts.length; i++) { generalNames[i] = new GeneralName(GeneralName.dNSName, hosts[i]); } GeneralNames subjectAltName = new GeneralNames(generalNames); jv3Builder.addExtension(Extension.subjectAlternativeName, false, subjectAltName); //SHA256 用SHA1浏览器可能会提示证书不安全 ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPriKey); return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer)); }