Java Code Examples for org.bouncycastle.operator.OperatorCreationException
The following examples show how to use
org.bouncycastle.operator.OperatorCreationException.
These examples are extracted from open source projects.
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 Project: hadoop-ozone Author: apache File: CertificateSignRequest.java License: Apache License 2.0 | 7 votes |
public PKCS10CertificationRequest build() throws SCMSecurityException { Preconditions.checkNotNull(key, "KeyPair cannot be null"); Preconditions.checkArgument(Strings.isNotBlank(subject), "Subject " + "cannot be blank"); try { CertificateSignRequest csr = new CertificateSignRequest(subject, scmID, clusterID, key, config, createExtensions()); return csr.generateCSR(); } catch (IOException ioe) { throw new CertificateException(String.format("Unable to create " + "extension for certificate sign request for %s.", SecurityUtil .getDistinguishedName(subject, scmID, clusterID)), ioe.getCause()); } catch (OperatorCreationException ex) { throw new CertificateException(String.format("Unable to create " + "certificate sign request for %s.", SecurityUtil .getDistinguishedName(subject, scmID, clusterID)), ex.getCause()); } }
Example #2
Source Project: java-certificate-authority Author: olivierlemasle File: CsrBuilderImpl.java License: Apache License 2.0 | 7 votes |
@Override public CsrWithPrivateKey generateRequest(final DistinguishedName dn) { final KeyPair pair = KeysUtil.generateKeyPair(); try { final PrivateKey privateKey = pair.getPrivate(); final PublicKey publicKey = pair.getPublic(); final X500Name x500Name = dn.getX500Name(); final ContentSigner signGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM) .build(privateKey); final PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder( x500Name, publicKey); final PKCS10CertificationRequest csr = builder.build(signGen); return new CsrWithPrivateKeyImpl(csr, privateKey); } catch (final OperatorCreationException e) { throw new CaException(e); } }
Example #3
Source Project: athenz Author: yahoo File: CryptoExceptionTest.java License: Apache License 2.0 | 6 votes |
@Test public void testCryptoExceptions() { CryptoException ex = new CryptoException(); assertNotNull(ex); assertEquals(ex.getCode(), CryptoException.CRYPTO_ERROR); assertNotNull(new CryptoException(new NoSuchAlgorithmException())); assertNotNull(new CryptoException(new InvalidKeyException())); assertNotNull(new CryptoException(new NoSuchProviderException())); assertNotNull(new CryptoException(new SignatureException())); assertNotNull(new CryptoException(new FileNotFoundException())); assertNotNull(new CryptoException(new IOException())); assertNotNull(new CryptoException(new CertificateException())); assertNotNull(new CryptoException(new InvalidKeySpecException())); assertNotNull(new CryptoException(new OperatorCreationException("unit-test"))); assertNotNull(new CryptoException(new PKCSException("unit-test"))); assertNotNull(new CryptoException(new CMSException("unit-test"))); ex = new CryptoException(CryptoException.CERT_HASH_MISMATCH, "X.509 Certificate hash mismatch"); assertEquals(ex.getCode(), CryptoException.CERT_HASH_MISMATCH); }
Example #4
Source Project: nifi Author: apache File: OcspCertificateValidatorTest.java License: 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 Project: hadoop-ozone Author: apache File: TestCRLCodec.java License: Apache License 2.0 | 6 votes |
@Test public void testGetX509CRLFromCRLHolder() throws IOException, OperatorCreationException, CertificateException, CRLException { X500Name issuer = x509CertificateHolder.getIssuer(); Date now = new Date(); X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now); builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now, CRLReason.cACompromise); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(securityConfig.getSignatureAlgo()); contentSignerBuilder.setProvider(securityConfig.getProvider()); PrivateKey privateKey = keyPair.getPrivate(); X509CRLHolder cRLHolder = builder.build(contentSignerBuilder.build(privateKey)); CRLCodec crlCodec = new CRLCodec(securityConfig); X509CRL crl = crlCodec.getX509CRL(cRLHolder); assertNotNull(crl); }
Example #6
Source Project: hadoop-ozone Author: apache File: TestDefaultProfile.java License: Apache License 2.0 | 6 votes |
/** * Test valid keys are validated correctly. * * @throws SCMSecurityException - on Error. * @throws PKCSException - on Error. * @throws OperatorCreationException - on Error. */ @Test public void testVerifyCertificate() throws SCMSecurityException, PKCSException, OperatorCreationException { PKCS10CertificationRequest csr = new CertificateSignRequest.Builder() .addDnsName("hadoop.apache.org") .addIpAddress("8.8.8.8") .addServiceName("OzoneMarketingCluster001") .setCA(false) .setClusterID("ClusterID") .setScmID("SCMID") .setSubject("Ozone Cluster") .setConfiguration(configuration) .setKey(keyPair) .build(); assertTrue(testApprover.verifyPkcs10Request(csr)); }
Example #7
Source Project: AndroidHttpCapture Author: JZ-Darkal File: BouncyCastleSslEngineSource.java License: MIT License | 6 votes |
private SSLContext createServerContext(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames) throws GeneralSecurityException, IOException, OperatorCreationException { MillisecondsDuration duration = new MillisecondsDuration(); KeyStore ks = CertificateHelper.createServerCertificate(commonName, subjectAlternativeNames, authority, caCert, caPrivKey); KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks, authority); SSLContext result = CertificateHelper.newServerContext(keyManagers); LOG.info("Impersonated {} in {}ms", commonName, duration); return result; }
Example #8
Source Project: NBANDROID-V2 Author: NBANDROIDTEAM File: ApkUtils.java License: Apache License 2.0 | 6 votes |
public static boolean createNewStore(String storeType, File storeFile, char[] storePassword, DN dn) { if (storeType == null) { storeType = "jks"; } try { KeyStore ks = KeyStore.getInstance(storeType); ks.load(null, null); Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", dn.validityYears, encodeDN(dn)); ks.setKeyEntry(dn.alias, generated.getFirst(), dn.password, new Certificate[]{generated.getSecond()}); FileOutputStream fos = new FileOutputStream(storeFile); boolean threw = true; try { ks.store(fos, storePassword); threw = false; } finally { Closeables.close(fos, threw); } } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | OperatorCreationException e) { return false; } return true; }
Example #9
Source Project: Spark Author: igniterealtime File: MutualAuthenticationSettingsPanel.java License: Apache License 2.0 | 6 votes |
private void createSelfSignedCertificate() { idControll.setUpData(commonNameField.getText(), organizationUnitField.getText(), organizationField.getText(), countryField.getText(), cityField.getText()); try { KeyPair keyPair = idControll.createKeyPair(); X509Certificate cert = idControll.createSelfSignedCertificate(keyPair); if (saveCertToFile.isSelected()) { PemBuilder pemBuilder = new PemHelper().new PemBuilder(); pemBuilder.add(keyPair.getPrivate()); pemBuilder.add(cert); pemBuilder.saveToPemFile(IdentityController.CERT_FILE); JOptionPane.showMessageDialog(null, Res.getString("dialog.self.signed.certificate.has.been.created") + IdentityController.SECURITY_DIRECTORY.toString()); } else { try { idControll.addEntryToKeyStore(cert, keyPair.getPrivate()); } catch (HeadlessException | InvalidNameException | KeyStoreException e) { Log.error("Couldn't save entry to IdentityStore", e); } } } catch (NoSuchAlgorithmException | NoSuchProviderException | IOException | OperatorCreationException | CertificateException e1) { Log.error("Couldn't create Self Signed Certificate", e1); } }
Example #10
Source Project: keycloak Author: keycloak File: OcspHandler.java License: Apache License 2.0 | 6 votes |
public OcspHandler(String responderCertPath, String responderKeyPath) throws OperatorCreationException, GeneralSecurityException, IOException { final Certificate certificate = CertificateFactory.getInstance("X509") .generateCertificate(X509OCSPResponderTest.class.getResourceAsStream(responderCertPath)); chain = new X509CertificateHolder[] {new X509CertificateHolder(certificate.getEncoded())}; final AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(certificate.getPublicKey().getEncoded()); subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey); final InputStream keyPairStream = X509OCSPResponderTest.class.getResourceAsStream(responderKeyPath); try (final PEMParser keyPairReader = new PEMParser(new InputStreamReader(keyPairStream))) { final PEMKeyPair keyPairPem = (PEMKeyPair) keyPairReader.readObject(); privateKey = PrivateKeyFactory.createKey(keyPairPem.getPrivateKeyInfo()); } }
Example #11
Source Project: CapturePacket Author: huanglqweiwei File: BouncyCastleSslEngineSource.java License: MIT License | 6 votes |
private SSLContext createServerContext(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames) throws GeneralSecurityException, IOException, OperatorCreationException { MillisecondsDuration duration = new MillisecondsDuration(); KeyStore ks = CertificateHelper.createServerCertificate(commonName, subjectAlternativeNames, authority, caCert, caPrivKey); KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks, authority); SSLContext result = CertificateHelper.newServerContext(keyManagers); LOG.info("Impersonated {} in {}ms", commonName, duration); return result; }
Example #12
Source Project: NetBare Author: MegatronKing File: SSLEngineFactory.java License: MIT License | 6 votes |
/** * Create a client {@link SSLEngine} with the remote server IP and port. * * @param host Remote server host. * @param port Remote server port. * @return A client {@link SSLEngine} instance. * @throws ExecutionException If an execution error has occurred. */ public SSLEngine createClientEngine(@NonNull final String host, int port) throws ExecutionException { SSLContext ctx = CLIENT_SSL_CONTEXTS.get(host, new Callable<SSLContext>() { @Override public SSLContext call() throws GeneralSecurityException, IOException, OperatorCreationException { return createClientContext(host); } }); SSLEngine engine = ctx.createSSLEngine(host, port); List<String> ciphers = new LinkedList<>(); for (String each : engine.getEnabledCipherSuites()) { if (!each.equals("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") && !each.equals("TLS_DHE_RSA_WITH_AES_256_CBC_SHA")) { ciphers.add(each); } } engine.setEnabledCipherSuites(ciphers.toArray(new String[0])); engine.setUseClientMode(true); engine.setNeedClientAuth(false); return engine; }
Example #13
Source Project: zeppelin Author: apache File: PEMImporter.java License: Apache License 2.0 | 6 votes |
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword) throws IOException, GeneralSecurityException { PrivateKey key; try { key = createPrivateKey(privateKeyFile, keyPassword); } catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) { throw new GeneralSecurityException("Private Key issues", e); } List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile); if (certificateChain.isEmpty()) { throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile); } KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new)); return keyStore; }
Example #14
Source Project: keystore-explorer Author: kaikramer File: X509CertificateGenerator.java License: 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 #15
Source Project: athenz Author: yahoo File: Crypto.java License: Apache License 2.0 | 5 votes |
public static String generateX509CSR(PrivateKey privateKey, String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException { final PublicKey publicKey = extractPublicKey(privateKey); ///CLOVER:OFF if (publicKey == null) { throw new CryptoException("Unable to extract public key from private key"); } ///CLOVER:ON return generateX509CSR(privateKey, publicKey, x500Principal, sanArray); }
Example #16
Source Project: isu Author: fgl27 File: ZipUtils.java License: GNU General Public License v3.0 | 5 votes |
/** Sign data and write the digital signature to 'out'. */ private static void writeSignatureBlock( CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey, OutputStream out) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { ArrayList < X509Certificate > certList = new ArrayList < > (1); certList.add(publicKey); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey)) .setProvider(sBouncyCastleProvider) .build(privateKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder() .setProvider(sBouncyCastleProvider) .build()) .setDirectSignature(true) .build(signer, publicKey)); gen.addCertificates(certs); CMSSignedData sigData = gen.generate(data, false); ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject()); }
Example #17
Source Project: chvote-1-0 Author: republique-et-canton-de-geneve File: KeyGenerator.java License: GNU Affero General Public License v3.0 | 5 votes |
private ContentSigner createSigner(KeyPair keyPair) throws PropertyConfigurationException, OperatorCreationException { ContentSigner signer; String hashAlgo = propertyConfigurationService.getConfigValue(CERT_HASH_ALGORITHM); if (keyPair.getPrivate() instanceof RSAPrivateKey) { RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(hashAlgo + "withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build( new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent()) ); } else { throw new KeyGenerationRuntimeException("Unsupported key type"); } return signer; }
Example #18
Source Project: hadoop-ozone Author: apache File: TestCRLCodec.java License: Apache License 2.0 | 5 votes |
@Before public void init() throws NoSuchProviderException, NoSuchAlgorithmException, IOException, CertificateException, OperatorCreationException { conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); securityConfig = new SecurityConfig(conf); writeTempCert(); x509CertificateHolder = readTempCert(); }
Example #19
Source Project: hadoop-ozone Author: apache File: TestCRLCodec.java License: Apache License 2.0 | 5 votes |
@Test public void testGetX509CRL() throws IOException, OperatorCreationException, CertificateException, CRLException { X500Name issuer = x509CertificateHolder.getIssuer(); Date now = new Date(); X509v2CRLBuilder builder = new X509v2CRLBuilder(issuer, now); builder.addCRLEntry(x509CertificateHolder.getSerialNumber(), now, CRLReason.cACompromise); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(securityConfig.getSignatureAlgo()); contentSignerBuilder.setProvider(securityConfig.getProvider()); PrivateKey privateKey = keyPair.getPrivate(); X509CRLHolder cRLHolder = builder.build(contentSignerBuilder.build(privateKey)); CRLCodec crlCodec = new CRLCodec(securityConfig); crlCodec.writeCRL(cRLHolder, this.securityConfig.getCrlName(), true); X509CRLEntryHolder entryHolder = cRLHolder.getRevokedCertificate(BigInteger.ONE); assertNotNull(entryHolder); String pemEncodedString = crlCodec.getPEMEncodedString(cRLHolder); assertNotNull(pemEncodedString); // Verify header and footer of PEM encoded String String header = "-----BEGIN X509 CRL-----"; String footer = "-----END X509 CRL-----"; assertTrue(pemEncodedString.contains(header)); assertTrue(pemEncodedString.contains(footer)); }
Example #20
Source Project: atlas Author: alibaba File: LocalSignedJarBuilder.java License: 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 Project: keystore-explorer Author: kaikramer File: Pkcs10Util.java License: GNU General Public License v3.0 | 5 votes |
/** * Verify a PKCS #10 certificate signing request (CSR). * * @param csr The certificate signing request * @return True if successfully verified * @throws CryptoException * If there was a problem verifying the CSR */ public static boolean verifyCsr(PKCS10CertificationRequest csr) throws CryptoException { try { PublicKey pubKey = new JcaPKCS10CertificationRequest(csr).getPublicKey(); ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey); return csr.isSignatureValid(contentVerifierProvider); } catch (InvalidKeyException | OperatorCreationException | NoSuchAlgorithmException | PKCSException e) { throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e); } }
Example #22
Source Project: SAMLRaider Author: SAMLRaider File: CreateCertificateTest.java License: MIT License | 5 votes |
@Test public void createSelfSignedCertificateShort() throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException, IOException, CertificateEncodingException, InvalidKeyException, IllegalStateException, SignatureException { String subject = "C=CH, ST=St. Gallen, L=Rapperswil, O=Hochschule Rapperswil, OU=IT-Systems, CN=www.hsr.ch"; BurpCertificateBuilder burpCertificateBuilder = new FakeBurpCertificateBuilder(subject); BurpCertificate certificate = burpCertificateBuilder.generateSelfSignedCertificate(); assertEquals(subject, certificate.getIssuer()); }
Example #23
Source Project: hadoop-ozone Author: apache File: TestDefaultProfile.java License: Apache License 2.0 | 5 votes |
/** * Verify that Invalid Extended Key usage works as expected, that is rejected. * @throws IOException - on Error. * @throws OperatorCreationException - on Error. */ @Test public void testInValidExtendedKeyUsage() throws IOException, OperatorCreationException { Extensions extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_clientAuth, true); PKCS10CertificationRequest csr = getInvalidCSR(keyPair, extendedExtension); assertFalse(testApprover.verfiyExtensions(csr)); extendedExtension = getKeyUsageExtension(KeyPurposeId.id_kp_OCSPSigning, false); csr = getInvalidCSR(keyPair, extendedExtension); assertFalse(testApprover.verfiyExtensions(csr)); }
Example #24
Source Project: enmasse Author: EnMasseProject File: DeviceCertificateManager.java License: Apache License 2.0 | 5 votes |
private static AuthorityKeyIdentifier createAuthorityKeyId(final PublicKey publicKey) throws OperatorCreationException { final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); final DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); return new X509ExtensionUtils(digCalc) .createAuthorityKeyIdentifier(publicKeyInfo); }
Example #25
Source Project: nifi Author: apache File: CertificateUtils.java License: 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 #26
Source Project: dss Author: esig File: DSSRevocationUtils.java License: GNU Lesser General Public License v2.1 | 5 votes |
public static DigestCalculator getDigestCalculator(DigestAlgorithm digestAlgorithm) { try { final DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build(); return digestCalculatorProvider.get(new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), DERNull.INSTANCE)); } catch (OperatorCreationException e) { throw new DSSException( String.format("Unable to create a DigestCalculator instance. DigestAlgorithm %s is not supported", digestAlgorithm.name()), e); } }
Example #27
Source Project: xipki Author: xipki File: MyUtil.java License: Apache License 2.0 | 5 votes |
public static PKCS10CertificationRequest generateRequest(PrivateKey privatekey, SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn, String challengePassword, List<Extension> extensions) throws OperatorCreationException { Args.notNull(privatekey, "privatekey"); Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo"); Args.notNull(subjectDn, "subjectDn"); Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<ASN1ObjectIdentifier, ASN1Encodable>(); if (StringUtil.isNotBlank(challengePassword)) { DERPrintableString asn1Pwd = new DERPrintableString(challengePassword); attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, asn1Pwd); } if (CollectionUtil.isNotEmpty(extensions)) { Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0])); attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, asn1Extensions); } PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo); if (attributes != null) { for (ASN1ObjectIdentifier attrType : attributes.keySet()) { csrBuilder.addAttribute(attrType, attributes.get(attrType)); } } ContentSigner contentSigner = new JcaContentSignerBuilder( ScepUtil.getSignatureAlgorithm(privatekey, HashAlgo.SHA1)).build(privatekey); return csrBuilder.build(contentSigner); }
Example #28
Source Project: PowerTunnel Author: krlvm File: BouncyCastleSslEngineSource.java License: MIT License | 5 votes |
public void initializeServerCertificates(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames) throws GeneralSecurityException, OperatorCreationException, IOException { KeyStore ks = CertificateHelper.createServerCertificate(commonName, subjectAlternativeNames, authority, caCert, caPrivKey); PrivateKey key = (PrivateKey) ks.getKey(authority.alias(), authority.password()); exportPem(authority.aliasFile("-" + commonName + "-key.pem"), key); Object[] certs = ks.getCertificateChain(authority.alias()); exportPem(authority.aliasFile("-" + commonName + "-cert.pem"), certs); }
Example #29
Source Project: signer Author: demoiselle File: CertificateHelper.java License: GNU Lesser General Public License v3.0 | 5 votes |
private static X509Certificate signCertificate(X509v3CertificateBuilder certificateBuilder, PrivateKey signedWithPrivateKey) throws OperatorCreationException, CertificateException { ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER_NAME) .build(signedWithPrivateKey); X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME) .getCertificate(certificateBuilder.build(signer)); return cert; }
Example #30
Source Project: besu Author: hyperledger File: SelfSignedP12Certificate.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date. private static Certificate generateSelfSignedCertificate(final KeyPair keyPair) throws CertIOException, GeneralSecurityException, OperatorCreationException { final X500Name issuer = new X500Name(distinguishedName); final X500Name subject = new X500Name(distinguishedName); final BigInteger serialNumber = new BigInteger(String.valueOf(Instant.now().toEpochMilli())); final X509v3CertificateBuilder v3CertificateBuilder = new JcaX509v3CertificateBuilder( issuer, serialNumber, Date.from(Instant.now()), Date.from(Instant.now().plus(Period.ofDays(90))), subject, keyPair.getPublic()); // extensions v3CertificateBuilder.addExtension( Extension.basicConstraints, true, new BasicConstraints(IS_CA)); v3CertificateBuilder.addExtension( Extension.subjectAlternativeName, false, getSubjectAlternativeNames()); final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate()); return new JcaX509CertificateConverter() .setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(v3CertificateBuilder.build(contentSigner)); }