Java Code Examples for org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder#addExtension()
The following examples show how to use
org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder#addExtension() .
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: SslClientCertificateImplTest.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
private Certificate generateCertWithExtension() throws Exception { final KeyPair keyPair = createKeyPair(); final JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( new X500Name("CN=Test commonName"), BigInteger.valueOf(123456789), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 10000), new X500Name("CN=Test commonName"), keyPair.getPublic() ); certificateBuilder.addExtension(BCStyle.C, false, new DERUTF8String("DE")); certificateBuilder.addExtension(BCStyle.O, false, new DERUTF8String("Test organization")); certificateBuilder.addExtension(BCStyle.OU, false, new DERUTF8String("Test Unit")); certificateBuilder.addExtension(BCStyle.T, false, new DERUTF8String("Test Title")); certificateBuilder.addExtension(BCStyle.L, false, new DERUTF8String("Test locality")); certificateBuilder.addExtension(BCStyle.ST, false, new DERUTF8String("Test state")); return getCertificate(keyPair, certificateBuilder); }
Example 2
Source File: PackedAttestationStatementValidatorTest.java From webauthn4j with Apache License 2.0 | 5 votes |
private static AttestationCertificatePath generateCertPath(KeyPair pair, String signAlg) { try { Provider bcProvider = new BouncyCastleProvider(); //Security.addProvider(bcProvider); long now = System.currentTimeMillis(); Date from = new Date(now); Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(1)); X500Name dnName = new X500Name("C=ORG, O=Dummy Org, OU=Authenticator Attestation, CN=Dummy"); BigInteger certSerialNumber = BigInteger.ZERO; Calendar calendar = Calendar.getInstance(); calendar.setTime(from); calendar.add(Calendar.YEAR, 1); ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).build(pair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, from, to, dnName, pair.getPublic()); BasicConstraints basicConstraints = new BasicConstraints(false); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); return new AttestationCertificatePath(Collections.singletonList(certificate)); } catch (OperatorCreationException | CertificateException | CertIOException e) { throw new UnexpectedCheckedException(e); } }
Example 3
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)); }
Example 4
Source File: CertUtil.java From proxyee with MIT License | 5 votes |
/** * 生成CA服务器证书 */ public static X509Certificate genCACert(String subject, Date caNotBefore, Date caNotAfter, KeyPair keyPair) throws Exception { JcaX509v3CertificateBuilder jv3Builder = new JcaX509v3CertificateBuilder(new X500Name(subject), BigInteger.valueOf(System.currentTimeMillis() + (long) (Math.random() * 10000) + 1000), caNotBefore, caNotAfter, new X500Name(subject), keyPair.getPublic()); jv3Builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); return new JcaX509CertificateConverter().getCertificate(jv3Builder.build(signer)); }
Example 5
Source File: HttpBaseTest.java From calcite-avatica with Apache License 2.0 | 5 votes |
private X509Certificate generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException { Calendar startDate = DateTimeUtils.calendar(); Calendar endDate = DateTimeUtils.calendar(); endDate.add(Calendar.YEAR, 100); BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis()); X500Name issuer = new X500Name( IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE)); JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic()); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); certGen.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(kp.getPublic())); certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority)); certGen.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(signerPublicKey)); if (isCertAuthority) { certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); } X509CertificateHolder certificateHolder = certGen.build( new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey)); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
Example 6
Source File: CertificateServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException, OperatorCreationException { Provider bcProvider = new BouncyCastleProvider(); Security.addProvider(bcProvider); // Use appropriate signature algorithm based on your keyPair algorithm. String signatureAlgorithm = sigAlgName; X500Name dnName = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L); // Using the current timestamp as the certificate serial number BigInteger certSerialNumber = new BigInteger(Long.toString(from.getTime())); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, certSerialNumber, from, to, dnName, keyPair.getPublic()); // true for CA, false for EndEntity BasicConstraints basicConstraints = new BasicConstraints(true); // Basic Constraints is usually marked as critical. certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); }
Example 7
Source File: OxAuthCryptoProvider.java From oxAuth with MIT License | 5 votes |
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // Signers name X500Name issuerName = new X500Name(issuer); // Subjects name - the same as we are self signed. X500Name subjectName = new X500Name(issuer); // Serial BigInteger serial = new BigInteger(256, new SecureRandom()); // Not before Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(expirationTime); // Create the certificate - version 3 JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern(); builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes)); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey); X509CertificateHolder holder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); return cert; }
Example 8
Source File: X509CertUtil.java From portecle with GNU General Public License v2.0 | 4 votes |
/** * Generate a self-signed X509 certificate for the supplied key pair and signature algorithm. * * @return The generated certificate * @param sCommonName Common name certificate attribute * @param sOrganisationUnit Organization Unit certificate attribute * @param sOrganisation Organization certificate attribute * @param sLocality Locality certificate * @param sState State certificate attribute * @param sEmailAddress Email Address certificate attribute * @param sCountryCode Country Code certificate attribute * @param iValidity Validity period of certificate in days * @param sans Subject alternative names certificate extension value * @param publicKey Public part of key pair * @param privateKey Private part of key pair * @param signatureType Signature Type * @throws CryptoException If there was a problem generating the certificate */ public static X509Certificate generateCert(String sCommonName, String sOrganisationUnit, String sOrganisation, String sLocality, String sState, String sCountryCode, String sEmailAddress, int iValidity, Collection<GeneralName> sans, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType) throws CryptoException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); if (sEmailAddress != null) { nameBuilder.addRDN(BCStyle.E, sEmailAddress); } if (sCountryCode != null) { nameBuilder.addRDN(BCStyle.C, sCountryCode); } if (sState != null) { nameBuilder.addRDN(BCStyle.ST, sState); } if (sLocality != null) { nameBuilder.addRDN(BCStyle.L, sLocality); } if (sOrganisation != null) { nameBuilder.addRDN(BCStyle.O, sOrganisation); } if (sOrganisationUnit != null) { nameBuilder.addRDN(BCStyle.OU, sOrganisationUnit); } if (sCommonName != null) { nameBuilder.addRDN(BCStyle.CN, sCommonName); } BigInteger serial = generateX509SerialNumber(); Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(notBefore.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000)); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serial, notBefore, notAfter, nameBuilder.build(), publicKey); try { if (sans != null && !sans.isEmpty()) { certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(sans.toArray(new GeneralName[sans.size()]))); } ContentSigner signer = new JcaContentSignerBuilder(signatureType.name()).build(privateKey); X509CertificateHolder certHolder = certBuilder.build(signer); return new JcaX509CertificateConverter().getCertificate(certHolder); } catch (CertificateException | IOException | OperatorCreationException ex) { throw new CryptoException(RB.getString("CertificateGenFailed.exception.message"), ex); } }
Example 9
Source File: SignedCertificateGeneratorTest.java From credhub with Apache License 2.0 | 4 votes |
@Before public void beforeEach() throws Exception { timeProvider = mock(CurrentTimeProvider.class); now = Instant.ofEpochMilli(1493066824); later = now.plus(Duration.ofDays(expectedDurationInDays)); when(timeProvider.getInstant()).thenReturn(now); serialNumberGenerator = mock(RandomSerialNumberGenerator.class); when(serialNumberGenerator.generate()).thenReturn(BigInteger.valueOf(1337)); jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); generator = KeyPairGenerator .getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME); generator.initialize(1024); // doesn't matter for testing issuerKey = generator.generateKeyPair(); issuerDn = new X500Principal(caName); generatedCertificateKeyPair = generator.generateKeyPair(); certificateGenerationParameters = defaultCertificateParameters(); subject = new SignedCertificateGenerator(timeProvider, serialNumberGenerator, jcaContentSignerBuilder, jcaX509CertificateConverter ); caSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(issuerKey.getPublic()); caSerialNumber = BigInteger.valueOf(42L); final JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder( issuerDn, caSerialNumber, Date.from(now), Date.from(later), issuerDn, issuerKey.getPublic() ); certificateAuthority = createCertificateAuthority(x509v3CertificateBuilder); x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, caSubjectKeyIdentifier); certificateAuthorityWithSubjectKeyId = createCertificateAuthority(x509v3CertificateBuilder); expectedSubjectKeyIdentifier = certificateAuthorityWithSubjectKeyId.getExtensionValue(Extension.subjectKeyIdentifier.getId()); }
Example 10
Source File: CertificateManager.java From Openfire with Apache License 2.0 | 4 votes |
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm, Set<String> sanDnsNames ) throws GeneralSecurityException, IOException { PublicKey pubKey = kp.getPublic(); PrivateKey privKey = kp.getPrivate(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger serial = (new java.math.BigInteger(serno)).abs(); X500Name issuerDN = issuerBuilder.build(); X500Name subjectDN = subjectBuilder.build(); // builder JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( // issuerDN, // serial, // new Date(), // new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), // subjectDN, // pubKey // ); // add subjectAlternativeName extension that includes all relevant names. final GeneralNames subjectAlternativeNames = getSubjectAlternativeNames( sanDnsNames ); final boolean critical = subjectDN.getRDNs().length == 0; certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAlternativeNames); // add keyIdentifiers extensions JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey)); try { // build the certificate ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey); X509CertificateHolder cert = certBuilder.build(signer); // verify the validity if (!cert.isValidOn(new Date())) { throw new GeneralSecurityException("Certificate validity not valid"); } // verify the signature (self-signed) ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey); if (!cert.isSignatureValid(verifierProvider)) { throw new GeneralSecurityException("Certificate signature not valid"); } return new JcaX509CertificateConverter().getCertificate(cert); } catch (OperatorCreationException | CertException e) { throw new GeneralSecurityException(e); } }
Example 11
Source File: AsyncSSLSocketWrapper.java From MediaSDK with Apache License 2.0 | 3 votes |
private static Certificate selfSign(KeyPair keyPair, String subjectDN) throws Exception { Provider bcProvider = new BouncyCastleProvider(); Security.addProvider(bcProvider); long now = System.currentTimeMillis(); Date startDate = new Date(now); X500Name dnName = new X500Name("CN=" + subjectDN); BigInteger certSerialNumber = new BigInteger(Long.toString(now)); // <-- Using the current timestamp as the certificate serial number Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, 1); // <-- 1 Yr validity Date endDate = calendar.getTime(); String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm. ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic()); // Extensions -------------------------- // Basic Constraints BasicConstraints basicConstraints = new BasicConstraints(true); // <-- true for CA, false for EndEntity certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical. // ------------------------------------- return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); }
Example 12
Source File: KeysAndCert.java From verify-service-provider with MIT License | 3 votes |
public static X509Certificate selfSign(KeyPair keyPair, String subjectCn) throws OperatorCreationException, CertificateException, IOException { Provider bcProvider = new BouncyCastleProvider(); long now = System.currentTimeMillis(); Date startDate = new Date(now); X500Name dnName = new X500Name(String.format("cn=%s,o=verify-service-provider,l=gov,c=uk", subjectCn)); BigInteger certSerialNumber = new BigInteger(Long.toString(now)); // <-- Using the current timestamp as the certificate serial number Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, 1); // <-- 1 Yr validity Date endDate = calendar.getTime(); String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm. ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic()); // Extensions -------------------------- // Basic Constraints BasicConstraints basicConstraints = new BasicConstraints(true); // <-- true for CA, false for EndEntity certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical. // ------------------------------------- return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); }