org.bouncycastle.operator.jcajce.JcaContentSignerBuilder Java Examples
The following examples show how to use
org.bouncycastle.operator.jcajce.JcaContentSignerBuilder.
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: 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 #2
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 #3
Source File: X509Util.java From logback-gelf with GNU Lesser General Public License v2.1 | 6 votes |
private X509Certificate build() throws NoSuchAlgorithmException, CertIOException, OperatorCreationException, CertificateException { final X500Principal issuer = new X500Principal("CN=MyCA"); final BigInteger sn = new BigInteger(64, new SecureRandom()); final Date from = Date.valueOf(LocalDate.now()); final Date to = Date.valueOf(LocalDate.now().plusYears(1)); final X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic()); final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(keyPair.getPublic())); v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keyPair.getPublic())); v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM) .build(keyPair.getPrivate()); return new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(v3CertGen.build(signer)); }
Example #4
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 #5
Source File: TestDefaultProfile.java From hadoop-ozone with Apache License 2.0 | 6 votes |
/** * Generates an CSR with the extension specified. * This function is used to get an Invalid CSR and test that PKI profile * rejects these invalid extensions, Hence the function name, by itself it * is a well formed CSR, but our PKI profile will treat it as invalid CSR. * * @param kPair - Key Pair. * @return CSR - PKCS10CertificationRequest * @throws OperatorCreationException - on Error. */ private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair, Extensions extensions) throws OperatorCreationException { X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle()); namebuilder.addRDN(BCStyle.CN, "invalidCert"); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keyPair.getPublic()); p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo()); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); return p10Builder.build(signer); }
Example #6
Source File: CAImpl.java From littleca with Apache License 2.0 | 6 votes |
@Override public PKCS10CertificationRequest makeUserCertReq(PublicKey publicKey, String userDN, String signAlg) throws CertException { try { PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(new X500Name(userDN) ,SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); if(null==signAlg) { signAlg=DEFAULT_SIGN_ALG; } JcaContentSignerBuilder jcaBuilder = new JcaContentSignerBuilder(signAlg); jcaBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); ContentSigner contentSigner = jcaBuilder.build(privateKey); PKCS10CertificationRequest certificationRequest = builder.build(contentSigner); return certificationRequest; } catch (Exception e) { throw new CertException("makeUserCertReq failed",e); } }
Example #7
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 6 votes |
/** * Creates the beast that can actually sign the data (for JKS, for other make it). */ public static CMSSignedDataGenerator createSignedDataGenerator(KeyStore keyStore, String keyAlias, String signAlgo, String keyPassword) throws KeyStoreException, OperatorCreationException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, CMSException { List<Certificate> certChain = new ArrayList<>(Arrays.asList(keyStore.getCertificateChain(keyAlias))); @SuppressWarnings("rawtypes") Store certStore = new JcaCertStore(certChain); Certificate cert = keyStore.getCertificate(keyAlias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword != null ? keyPassword.toCharArray() : null); ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert); generator.addSignerInfoGenerator(sig); generator.addCertificates(certStore); return generator; }
Example #8
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 #9
Source File: JCEUtils.java From java-11-examples with Apache License 2.0 | 6 votes |
public static X509Certificate createSignedCertificate(String issuerName, String subjectName, Date notBefore, Long duration, TimeUnit timeUnit, PublicKey publicKey, PrivateKey privateKey) throws PKIException { try { X500Name issuer = new X500Name(CN_NAME + issuerName); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); Date notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(duration)); X500Name subject = new X500Name(CN_NAME + subjectName); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo); JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(SHA256_RSA); ContentSigner signer = jcaContentSignerBuilder.build(privateKey); CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, BC_PROVIDER); byte[] certBytes = certBuilder.build(signer).getEncoded(); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes)); } catch (Exception e) { throw new PKIException(e); } }
Example #10
Source File: X509CertificateGenerator.java From keystore-explorer with GNU General Public License v3.0 | 6 votes |
private X509Certificate generateVersion1(X500Name subject, X500Name issuer, Date validityStart, Date validityEnd, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType, BigInteger serialNumber) throws CryptoException { Date notBefore = validityStart == null ? new Date() : validityStart; Date notAfter = validityEnd == null ? new Date(notBefore.getTime() + TimeUnit.DAYS.toMillis(365)) : validityEnd; JcaX509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(issuer, serialNumber, notBefore, notAfter, subject, publicKey); try { ContentSigner certSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider("BC").build( privateKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBuilder.build(certSigner)); } catch (CertificateException | IllegalStateException | OperatorCreationException ex) { throw new CryptoException(res.getString("CertificateGenFailed.exception.message"), ex); } }
Example #11
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 #12
Source File: BouncyCastleSecurityProviderTool.java From AndroidHttpCapture with MIT License | 5 votes |
/** * Creates a ContentSigner that can be used to sign certificates with the given private key and signature algorithm. * * @param certAuthorityPrivateKey the private key to use to sign certificates * @param signatureAlgorithm the algorithm to use to sign certificates * @return a ContentSigner */ private static ContentSigner getCertificateSigner(PrivateKey certAuthorityPrivateKey, String signatureAlgorithm) { try { return new JcaContentSignerBuilder(signatureAlgorithm) .build(certAuthorityPrivateKey); } catch (OperatorCreationException e) { throw new CertificateCreationException("Unable to create ContentSigner using signature algorithm: " + signatureAlgorithm, e); } }
Example #13
Source File: TestUtil.java From fabric-chaincode-java with Apache License 2.0 | 5 votes |
/** * Function to create a certificate with dummy attributes * * @param attributeValue {String} value to be written to the identity attributes * section of the certificate * @return encodedCert {String} encoded certificate with re-written attributes */ public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception { // Use existing certificate with attributes final byte[] decodedCert = Base64.getDecoder().decode(CERT_MULTIPLE_ATTRIBUTES); // Create a certificate holder and builder final X509CertificateHolder certHolder = new X509CertificateHolder(decodedCert); final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(certHolder); // special OID used by Fabric to save attributes in x.509 certificates final String fabricCertOid = "1.2.3.4.5.6.7.8.1"; // Write the new attribute value final byte[] extDataToWrite = attributeValue.getBytes(); certBuilder.replaceExtension(new ASN1ObjectIdentifier(fabricCertOid), true, extDataToWrite); // Create a privateKey final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); generator.initialize(384); final KeyPair keyPair = generator.generateKeyPair(); // Create and build the Content Signer final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withECDSA"); final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate()); // Build the Certificate from the certificate builder final X509CertificateHolder builtCert = certBuilder.build(contentSigner); final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509") .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded())); final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded()); return encodedCert; }
Example #14
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 #15
Source File: CertificateProvider.java From bouncr with Eclipse Public License 1.0 | 5 votes |
public X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder) throws OperatorCreationException, CertificateException { ContentSigner signer = new JcaContentSignerBuilder(config.getCertConfiguration().getSignAlgorithm()) .setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(ca.getPrivateKey()); return new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateBuilder.build(signer)); }
Example #16
Source File: TLSCertificateBuilder.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san) throws Exception { X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair); // Basic constraints BasicConstraints constraints = new BasicConstraints(false); certBuilder.addExtension( Extension.basicConstraints, true, constraints.getEncoded()); // Key usage KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature); certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded()); // Extended key usage certBuilder.addExtension( Extension.extendedKeyUsage, false, certType.keyUsage().getEncoded()); if (san != null) { addSAN(certBuilder, san); } ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm) .build(keyPair.getPrivate()); X509CertificateHolder holder = certBuilder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); converter.setProvider(new BouncyCastleProvider()); return converter.getCertificate(holder); }
Example #17
Source File: CertificateUtils.java From nifi-registry 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 #18
Source File: RootKeyStoreGenerator.java From cute-proxy with BSD 2-Clause "Simplified" License | 5 votes |
private static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder, PrivateKey signedWithPrivateKey) throws OperatorCreationException, CertificateException { ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(signedWithPrivateKey); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateBuilder.build(signer)); }
Example #19
Source File: CreateCA.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static void main(String[] args) throws IOException, OperatorCreationException, NoSuchAlgorithmException { // ---------------------- CA Creation ---------------------- // System.out.println("Generating Keys"); KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(1024); KeyPair kp = rsa.generateKeyPair(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 100); // System.out.println("Getting data"); byte[] pk = kp.getPublic().getEncoded(); SubjectPublicKeyInfo bcPk = SubjectPublicKeyInfo.getInstance(pk); // System.out.println("Creating cert"); X509v1CertificateBuilder certGen = new X509v1CertificateBuilder(new X500Name("CN=CA Cert"), BigInteger.ONE, new Date(), cal.getTime(), new X500Name("CN=CA Cert"), bcPk); X509CertificateHolder certHolder = certGen .build(new JcaContentSignerBuilder("SHA1withRSA").build(kp.getPrivate())); StringBuffer s = new StringBuffer(); s.append(X509Factory.BEGIN_CERT + "\n"); s.append(Base64Utils.base64Encode(certHolder.getEncoded()) + "\n"); s.append(X509Factory.END_CERT); saveFile(s.toString().getBytes()); // ---------------------- ISSUER Creation ---------------------- }
Example #20
Source File: LocalSignedJarBuilder.java From atlas with Apache License 2.0 | 5 votes |
/** * Write the certificate file with a digital signature. */ private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm()).build( privateKey); gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder() .build()).setDirectSignature( true).build(sha1Signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(mOutputJar); dos.writeObject(asn1.readObject()); dos.flush(); dos.close(); asn1.close(); }
Example #21
Source File: CertificateValidatorTest.java From keycloak with Apache License 2.0 | 5 votes |
/** * will create a self-signed certificate * * @param dn the DN of the subject and issuer * @param startDate startdate of the validity of the created certificate * @param expiryDate expiration date of the created certificate * @param keyPair the keypair that is used to create the certificate * @return a X509-Certificate in version 3 */ public X509Certificate createCertificate(String dn, Date startDate, Date expiryDate, KeyPair keyPair) { X500Name subjectDN = new X500Name(dn); X500Name issuerDN = new X500Name(dn); // @formatter:off SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance( ASN1Sequence.getInstance(keyPair.getPublic().getEncoded())); // @formatter:on BigInteger serialNumber = new BigInteger(130, new SecureRandom()); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(issuerDN, serialNumber, startDate, expiryDate, subjectDN, subjPubKeyInfo); ContentSigner contentSigner = null; try { // @formatter:off contentSigner = new JcaContentSignerBuilder("SHA256withRSA") .setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); X509Certificate x509Certificate = new JcaX509CertificateConverter() .setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(contentSigner)); // @formatter:on return x509Certificate; } catch (CertificateException | OperatorCreationException e) { throw new IllegalStateException(e); } }
Example #22
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 #23
Source File: JwtSecurityProviderIntegrationTest.java From cruise-control with BSD 2-Clause "Simplified" License | 5 votes |
private File createCertificate(TokenGenerator.TokenAndKeys tokenAndKeys) throws Exception { String subjectDN = "C=US, ST=California, L=Santa Clara, O=LinkedIn, CN=localhost"; Provider bcProvider = new BouncyCastleProvider(); Security.addProvider(bcProvider); long now = System.currentTimeMillis(); Date startDate = new Date(now); X500Name dnName = new X500Name(subjectDN); BigInteger certSerialNumber = new BigInteger(Long.toString(now)); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); calendar.add(Calendar.YEAR, 100); Date endDate = calendar.getTime(); String signatureAlgorithm = "SHA256WithRSA"; ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(tokenAndKeys.privateKey()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, certSerialNumber, startDate, endDate, dnName, tokenAndKeys.publicKey()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); File certificate = File.createTempFile("test-certificate", ".pub"); try (OutputStream os = new FileOutputStream(certificate)) { Base64.Encoder encoder = Base64.getEncoder(); os.write("-----BEGIN CERTIFICATE-----\n".getBytes(StandardCharsets.UTF_8)); os.write(encoder.encodeToString(cert.getEncoded()).getBytes(StandardCharsets.UTF_8)); os.write("\n-----END CERTIFICATE-----\n".getBytes(StandardCharsets.UTF_8)); } return certificate; }
Example #24
Source File: IdentityController.java From Spark with Apache License 2.0 | 5 votes |
/** * Creates Certificate Signing Request. * * @throws IOException * @throws OperatorCreationException */ public PKCS10CertificationRequest createCSR(KeyPair keyPair) throws IOException, OperatorCreationException { X500Principal principal = new X500Principal(createX500NameString()); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(principal, keyPair.getPublic()); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); PKCS10CertificationRequest csr = p10Builder.build(signer); return csr; }
Example #25
Source File: PkiUtil.java From cloudbreak with Apache License 2.0 | 5 votes |
private static PKCS10CertificationRequest generateCsrWithName(KeyPair identity, String name, List<String> sanList) throws Exception { X500Principal principal = new X500Principal(name); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(principal, identity.getPublic()); if (!CollectionUtils.isEmpty(sanList)) { p10Builder = addSubjectAlternativeNames(p10Builder, sanList); } JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(identity.getPrivate()); return p10Builder.build(signer); }
Example #26
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 #27
Source File: SignHelper.java From Launcher with GNU General Public License v3.0 | 5 votes |
public static CMSSignedDataGenerator createSignedDataGenerator(PrivateKey privateKey, Certificate cert, List<Certificate> certChain, String signAlgo) throws OperatorCreationException, CertificateEncodingException, CMSException { @SuppressWarnings("rawtypes") Store certStore = new JcaCertStore(certChain); ContentSigner signer = new JcaContentSignerBuilder(signAlgo).setProvider("BC").build(privateKey); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); DigestCalculatorProvider dcp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator sig = new JcaSignerInfoGeneratorBuilder(dcp).build(signer, (X509Certificate) cert); generator.addSignerInfoGenerator(sig); generator.addCertificates(certStore); return generator; }
Example #28
Source File: OcspCertificateValidatorTest.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Generates a signed certificate with a specific keypair. * * @param dn the DN * @param keyPair the public key will be included in the certificate and the the private key is used to sign the certificate * @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 generateCertificate(String dn, KeyPair keyPair) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException { PrivateKey privateKey = keyPair.getPrivate(); ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(privateKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(YESTERDAY); Date endDate = new Date(ONE_YEAR_FROM_NOW); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name(dn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement)); // (2) extendedKeyUsage extension Vector<KeyPurposeId> ekUsages = new Vector<>(); ekUsages.add(KeyPurposeId.id_kp_clientAuth); ekUsages.add(KeyPurposeId.id_kp_serverAuth); certBuilder.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(ekUsages)); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #29
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 #30
Source File: CertificateUtils.java From localization_nifi 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); } }