Java Code Examples for org.bouncycastle.cert.X509v3CertificateBuilder#addExtension()
The following examples show how to use
org.bouncycastle.cert.X509v3CertificateBuilder#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: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private static X509Certificate createRootCACertificate(final KeyPair keyPair, final String dn, final ValidityPeriod validityPeriod) throws CertificateException { try { final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( new X500Name(RFC4519Style.INSTANCE, dn), generateSerialNumber(), new Date(validityPeriod.getFrom().toEpochMilli()), new Date(validityPeriod.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic()); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); builder.addExtension(createSubjectKeyExtension(keyPair.getPublic())); builder.addExtension(createAuthorityKeyExtension(keyPair.getPublic())); return buildX509Certificate(builder, keyPair.getPrivate()); } catch (OperatorException | IOException e) { throw new CertificateException(e); } }
Example 2
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 3
Source File: KeyGenerator.java From chvote-1-0 with GNU Affero General Public License v3.0 | 6 votes |
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY)); nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY)); nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY)); nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY)); X500Name x500Name = nameBuilder.build(); BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS)); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo); String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY); certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName)); return certificateBuilder; }
Example 4
Source File: RsaSsaPss.java From testarea-itext5 with GNU Affero General Public License v3.0 | 6 votes |
/** * create a basic X509 certificate from the given keys */ static X509Certificate makeCertificate( KeyPair subKP, String subDN, KeyPair issKP, String issDN) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name(issDN), BigInteger.valueOf(serialNo++), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(subDN), subPub); v3CertGen.addExtension( X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub)); v3CertGen.addExtension( X509Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub)); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(issPriv))); }
Example 5
Source File: SubjectAlternativeNameHolder.java From PowerTunnel with MIT License | 5 votes |
public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans .size()]); certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example 6
Source File: CertificateHelper.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static KeyStore createServerCertificate(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames, Authority authority, Certificate caCert, PrivateKey caPrivKey) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException, CertificateException, InvalidKeyException, SignatureException, KeyStoreException { KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE); X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE); name.addRDN(BCStyle.CN, commonName); name.addRDN(BCStyle.O, authority.certOrganisation()); name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName()); X500Name subject = name.build(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, keyPair.getPublic()); builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(keyPair.getPublic())); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); subjectAlternativeNames.fillInto(builder); X509Certificate cert = signCertificate(builder, caPrivKey); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); KeyStore result = KeyStore.getInstance("PKCS12" /* , PROVIDER_NAME */); result.load(null, null); Certificate[] chain = { cert, caCert }; result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), chain); return result; }
Example 7
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair, final KeyCertificatePair rootCA, final String dn, final ValidityPeriod validityPeriod, final String crlUri) throws CertificateException { try { final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( rootCA.getCertificate(), generateSerialNumber(), new Date(validityPeriod.getFrom().toEpochMilli()), new Date(validityPeriod.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic()); //builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign)); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); builder.addExtension(createSubjectKeyExtension(keyPair.getPublic())); builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey())); if (crlUri != null) { builder.addExtension(createDistributionPointExtension(crlUri)); } return buildX509Certificate(builder, rootCA.getPrivateKey()); } catch (OperatorException | IOException e) { throw new CertificateException(e); } }
Example 8
Source File: CertificateAutogenTask.java From Launcher with GNU General Public License v3.0 | 5 votes |
@Override public Path process(Path inputFile) throws IOException { if (signedDataGenerator != null) return inputFile; try { LogHelper.warning("You are using an auto-generated certificate (sign.enabled false). It is not good"); LogHelper.warning("It is highly recommended that you use the correct certificate (sign.enabled true)"); LogHelper.warning("You can use GenerateCertificateModule or your own certificate."); X500NameBuilder subject = new X500NameBuilder(); subject.addRDN(BCStyle.CN, server.config.projectName.concat(" Autogenerated")); subject.addRDN(BCStyle.O, server.config.projectName); LocalDateTime startDate = LocalDate.now().atStartOfDay(); X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject.build(), new BigInteger("0"), Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()), Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()), new X500Name("CN=ca"), SubjectPublicKeyInfo.getInstance(server.publicKey.getEncoded())); builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning)); //builder.addExtension(Extension.keyUsage, false, new KeyUsage(1)); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA"); ContentSigner signer = csBuilder.build(server.privateKey); bcCertificate = builder.build(signer); certificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(bcCertificate); ArrayList<Certificate> chain = new ArrayList<>(); chain.add(certificate); signedDataGenerator = SignHelper.createSignedDataGenerator(server.privateKey, certificate, chain, "SHA256WITHECDSA"); } catch (OperatorCreationException | CMSException | CertificateException e) { LogHelper.error(e); } return inputFile; }
Example 9
Source File: CertificateHelper.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static KeyStore createRootCertificate(Authority authority, String keyStoreType) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException, OperatorCreationException, CertificateException, KeyStoreException { KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, authority.commonName()); nameBuilder.addRDN(BCStyle.O, authority.organization()); nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName()); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */); result.load(null, null); result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert }); return result; }
Example 10
Source File: CertificateGeneratorTest.java From credhub with Apache License 2.0 | 5 votes |
private X509CertificateHolder makeCert(final KeyPair certKeyPair, final PrivateKey caPrivateKey, final X500Name caDn, final X500Name subjectDn, final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException { final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic() .getEncoded()); final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA") .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME) .build(caPrivateKey); final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider(); final Instant now = Instant.from(currentTimeProvider.getInstant()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( caDn, BigInteger.TEN, Date.from(now), Date.from(now.plus(Duration.ofDays(365))), subjectDn, publicKeyInfo ); x509v3CertificateBuilder .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa)); return x509v3CertificateBuilder.build(contentSigner); }
Example 11
Source File: CertificateUtils.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate */ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // (3) subjectAlternativeName if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example 12
Source File: CertificateUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
public static X509Certificate generateCert(KeyPair pair) { try { X500Principal principal = new X500Principal(RaPropertiesLoader.getProperty("dummycert.subject")); Date notBefore = (new DateTime()).minusDays(1).toDate(); Date notAfter = (new DateTime()).minusDays(1).plusMinutes(1).toDate(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, BigInteger.ZERO, notBefore, notAfter, principal, pair.getPublic()); int keyUsageDetails = 16 + 32; builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails)); ContentSigner signer = (new JcaContentSignerBuilder(RaPropertiesLoader.getProperty("dummycert.signature.algorithm"))).build(pair.getPrivate()); X509CertificateHolder holder = builder.build(signer); return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder); } catch (OperatorCreationException | IOException | CertificateException ex) { throw new IllegalArgumentException(ex); } }
Example 13
Source File: CertificateUtils.java From nifi-registry with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example 14
Source File: TlsUtils.java From tessera with Apache License 2.0 | 4 votes |
default void generateKeyStoreWithSelfSignedCertificate(String address, Path privateKeyFile, char[] password) throws NoSuchAlgorithmException, IOException, OperatorCreationException, CertificateException, InvalidKeyException, NoSuchProviderException, SignatureException, KeyStoreException { final SecureRandom secureRandom = new SecureRandom(); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ENCRYPTION); keyGen.initialize(2048, secureRandom); KeyPair keypair = keyGen.generateKeyPair(); final PublicKey publicKey = keypair.getPublic(); final PrivateKey privateKey = keypair.getPrivate(); final String cnString = address.replaceFirst("^(http[s]?://www\\.|http[s]?://|www\\.)", ""); final X500Name commonName = new X500Name(COMMON_NAME_STRING + cnString); Date startDate = new Date(System.currentTimeMillis()); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, 1); Date endDate = calendar.getTime(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( commonName, new BigInteger(64, secureRandom), startDate, endDate, commonName, publicKey); GeneralName[] subjectAlternativeNames = new GeneralName[] { new GeneralName(GeneralName.dNSName, LOCALHOST), new GeneralName(GeneralName.dNSName, HostnameUtil.create().getHostName()), new GeneralName(GeneralName.iPAddress, LOCALHOST_IP), new GeneralName(GeneralName.iPAddress, LOCALHOST_IP_2), new GeneralName(GeneralName.iPAddress, HostnameUtil.create().getHostIpAddress()) }; builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(subjectAlternativeNames)); ContentSigner contentSigner = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(privateKey); X509CertificateHolder certHolder = builder.build(contentSigner); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(provider).getCertificate(certHolder); certificate.verify(publicKey); KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); keyStore.load(null, null); keyStore.setKeyEntry("tessera", privateKey, password, new X509Certificate[] {certificate}); try (OutputStream keyStoreFile = Files.newOutputStream(privateKeyFile)) { keyStore.store(keyStoreFile, password); } }
Example 15
Source File: CertGen.java From snowblossom with Apache License 2.0 | 4 votes |
/** * @param key_pair Key pair to use to sign the cert inner signed message, the node key * @param tls_wkp The temporary key to use just for this cert and TLS sessions * @param spec Address for 'key_pair' */ public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec) throws Exception { AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec); String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash); byte[] encoded_pub= tls_wkp.getPublicKey().toByteArray(); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(encoded_pub)); String dn=String.format("CN=%s, O=Snowblossom", address); X500Name issuer = new X500Name(dn); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L); X500Name subject = issuer; X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder( issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo); //System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName); ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134"); //System.out.println(spec); SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build(); SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload); byte[] sm_data = sm.toByteString().toByteArray(); cert_builder.addExtension(snow_claim_oid, true, sm_data); String algorithm = "SHA256withRSA"; AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); //ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X509CertificateHolder certificateHolder = cert_builder.build(sigGen); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); return cert; }
Example 16
Source File: IdentityCertificateService.java From flashback with BSD 2-Clause "Simplified" License | 4 votes |
@Override protected void buildExtensions(X509v3CertificateBuilder x509v3CertificateBuilder, PublicKey publicKey) throws IOException { x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey)); x509v3CertificateBuilder.addExtension(Extension.basicConstraints, false, BASIC_CONSTRAINTS); }
Example 17
Source File: Certificates.java From icure-backend with GNU General Public License v2.0 | 4 votes |
/** * Creates a certificate for a healthcare party. */ public static X509Certificate createCertificateV3(PublicKey hcpartyPublicKey, HealthcareParty hcparty, String hcPartyEmail, PublicKey icurePublicKey, PrivateKey icurePrivateKey) throws Exception { // // Signers // Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> sAttrs = new Hashtable<>(); Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> sOrder = new Vector<>(); sAttrs.put(X509Principal.C, "BE"); sAttrs.put(X509Principal.O, "Taktik"); sAttrs.put(X509Principal.OU, "ICureCloud"); sAttrs.put(X509Principal.EmailAddress, "[email protected]"); sOrder.addElement(X509Principal.C); sOrder.addElement(X509Principal.O); sOrder.addElement(X509Principal.OU); sOrder.addElement(X509Principal.EmailAddress); X509Principal issuerX509Principal = new X509Principal(sOrder, sAttrs); X500Name issuer = new X500Name(issuerX509Principal.getName()); // // Subjects // Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> attrs = new Hashtable<>(); Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> order = new Vector<>(); attrs.put(X509Principal.C, "BE"); attrs.put(X509Principal.O, "organization-" + hcparty.getCompanyName()); attrs.put(X509Principal.L, "location-" + hcparty.getId()); attrs.put(X509Principal.CN, "cn-" + hcparty.getId()); attrs.put(X509Principal.EmailAddress, hcPartyEmail); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.L); order.addElement(X509Principal.CN); order.addElement(X509Principal.EmailAddress); X509Principal subjectX509Principal = new X509Principal(order, attrs); X500Name subject = new X500Name(subjectX509Principal.getName()); // // Other attrs // BigInteger serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong()); Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000); SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(hcpartyPublicKey.getEncoded()); X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki); x509v3CertBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // hcparty is not CA x509v3CertBuilder.addExtension(Extension.subjectKeyIdentifier, true, new SubjectKeyIdentifier(hcpartyPublicKey.getEncoded())); x509v3CertBuilder.addExtension(Extension.authorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(icurePublicKey)); // // Create a content signer // AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId); AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(icurePrivateKey.getEncoded()); ContentSigner contentSigner = new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp); // // Build the certificate // X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner); Certificate certificateStructure = holder.toASN1Structure(); X509Certificate certificate = convertToJavaCertificate(certificateStructure); certificate.verify(icurePublicKey); return certificate; }
Example 18
Source File: PacketProxyCAPerUser.java From PacketProxy with Apache License 2.0 | 4 votes |
private void generateKeyStore(String ksPath) throws Exception { KeyStore ks; KeyPair CAKeyPair = super.genRSAKeyPair(); // 各ユーザ用のキーストアを作るためのテンプレートを取得 try (InputStream input = this.getClass().getResourceAsStream("/certificates/user.ks")) { ks = KeyStore.getInstance("JKS"); ks.load(input, password); } int serialNumber = 0; do { serialNumber = SecureRandom.getInstance("SHA1PRNG").nextInt(); } while (serialNumber <= 0); String x500Name = String.format("C=PacketProxy, ST=PacketProxy, L=PacketProxy, O=PacketProxy, OU=PacketProxy CA, CN=PacketProxy per-user CA (%x)", serialNumber); Date from = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(from); cal.add(Calendar.YEAR, 30); Date to = cal.getTime(); X509v3CertificateBuilder caRootBuilder = new X509v3CertificateBuilder( new X500Name(x500Name), BigInteger.valueOf(serialNumber), from, to, new X500Name(x500Name), SubjectPublicKeyInfo.getInstance(CAKeyPair.getPublic().getEncoded())); /* CA: X509 Extensionsの設定(CA:true, pathlen:0) */ caRootBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(CAKeyPair.getPrivate().getEncoded())); X509CertificateHolder signedRoot = caRootBuilder.build(signer); // 新しいKeyStoreの生成 KeyStore newks = KeyStore.getInstance("JKS"); newks.load(null, password); // 証明書と秘密鍵の登録 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); newks.setKeyEntry( "root", CAKeyPair.getPrivate(), password, new Certificate[]{ certFactory.generateCertificate(new ByteArrayInputStream(signedRoot.getEncoded())) }); File newksfile = new File(ksPath); newksfile.getParentFile().mkdirs(); newksfile.createNewFile(); newksfile.setWritable(false, false); newksfile.setWritable(true); newksfile.setReadable(false, false); newksfile.setReadable(true); try (FileOutputStream fos = new FileOutputStream(ksPath)) { newks.store(fos, password); } }
Example 19
Source File: TLSCertificateBuilder.java From fabric-sdk-java with Apache License 2.0 | 4 votes |
private void addSAN(X509v3CertificateBuilder certBuilder, String san) throws CertIOException { ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[]{new GeneralName(GeneralName.dNSName, san)}; certBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(subjectAlternativeNames)); }
Example 20
Source File: CACertificateService.java From flashback with BSD 2-Clause "Simplified" License | 3 votes |
protected void buildExtensions(X509v3CertificateBuilder x509v3CertificateBuilder, PublicKey publicKey) throws IOException { x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey)); // The Key Usage, Extended Key Usage, and Basic Constraints extensions act together to define the purposes for // which the certificate is intended to be used x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, BASIC_CONSTRAINTS); x509v3CertificateBuilder.addExtension(Extension.keyUsage, false, KEY_USAGE); x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, false, EXTERNAL_KEY_USAGE); }