List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME
String PROVIDER_NAME
To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.
Click Source Link
From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java
License:Apache License
private KeyPair createKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); keyPairGenerator.initialize(4096);//from w w w . j a va 2 s . c om KeyPair keyPair = keyPairGenerator.genKeyPair(); return keyPair; }
From source file:org.apache.zookeeper.server.quorum.UnifiedServerSocketModeDetectionTest.java
License:Apache License
@AfterClass public static void tearDownClass() { try {/*from w w w .ja v a 2 s .c o m*/ FileUtils.deleteDirectory(tempDir); } catch (IOException e) { // ignore } Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.appenders.log4j2.elasticsearch.jest.PEMCertInfo.java
License:Open Source License
@Override public void applyTo(HttpClientConfig.Builder builder) { if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); }/*w w w .j a v a 2 s . c o m*/ try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath)); FileInputStream key = new FileInputStream(new File(keyPath)); FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) { KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase)); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyPassphrase.toCharArray()); KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); // TODO: add support for hostname verification modes builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext)); builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier())); } catch (IOException | GeneralSecurityException e) { throw new ConfigurationException(configExceptionMessage, e); } }
From source file:org.axiom_tools.crypto.Symmetric.java
License:Apache License
private Cipher getCipher() throws Exception { return Cipher.getInstance(Transform, BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCRLGenerator.java
License:Open Source License
/** * If the digestAlgorithm is null, SHA-1 is used. * @return the DER-encoded signed CRL.// w w w . j a v a 2 s . c o m **/ public X509CRL sign(String hashAlgorithm, PrivateKey signingKey, String provider) throws InvalidKeyException, SignatureException, NoSuchProviderException, CRLException, IllegalStateException, NoSuchAlgorithmException { String sigAlgName = OIDLookup.getSignatureAlgorithm( ((null == hashAlgorithm) || (hashAlgorithm.length() == 0)) ? DEFAULT_HASH : hashAlgorithm, signingKey.getAlgorithm()); System.out.println("Signature algorithm: " + sigAlgName + " provider: " + provider); _crlGenerator.setSignatureAlgorithm(sigAlgName); if (null == provider) { provider = BouncyCastleProvider.PROVIDER_NAME; } return _crlGenerator.generate(signingKey, provider); }
From source file:org.ccnx.ccn.KeyManager.java
License:Open Source License
/** * Load the BouncyCastle and other necessary providers, should be called once for initialization. * Currently this is done by CCNHandle./*w ww . jav a2s .com*/ */ private static Provider getBcProvider() { // first try and get it, in case some other code has already created it. Provider p = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); // it's not yet known to the Security class, so create it. if (p == null) { p = new BouncyCastleProvider(); Security.addProvider(p); } return p; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain) throws SignRequestSignatureException { // First verify that we signed this certificate try {/*from ww w . j a v a 2 s.c o m*/ if (cert != null) { final PublicKey verifyKey; final X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } cert.verify(verifyKey); } } catch (CryptoTokenOfflineException e) { throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7", e); } catch (InvalidKeyException e) { throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e); } catch (CertificateException e) { throw new SignRequestSignatureException("An encoding error was encountered.", e); } catch (NoSuchAlgorithmException e) { throw new SignRequestSignatureException( "The certificate provided was signed with an invalid algorithm.", e); } catch (NoSuchProviderException e) { throw new SignRequestSignatureException( "The crypto provider was not found for verification of the certificate.", e); } catch (SignatureException e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?", e); } Collection<Certificate> chain = getCertificateChain(); ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>(); try { if (cert != null) { certList.add(new JcaX509CertificateHolder((X509Certificate) cert)); } if (includeChain) { for (Certificate certificate : chain) { certList.add(new JcaX509CertificateHolder((X509Certificate) certificate)); } } } catch (CertificateEncodingException e) { throw new SignRequestSignatureException("Could not encode certificate", e); } try { CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes()); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final PrivateKey privateKey = cryptoToken .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); if (privateKey == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } String signatureAlgorithmName = AlgorithmTools .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(cryptoToken.getSignProviderName()).build(privateKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate())); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } gen.addCertificates(new CollectionStore(certList)); CMSSignedData s = null; CAToken catoken = getCAToken(); if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) { log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm " + privateKey.getAlgorithm()); s = gen.generate(msg, true); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CryptoTokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { //FIXME: This right here is just nasty throw new RuntimeException(e); } }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] encryptKeys(CryptoToken cryptoToken, String alias, KeyPair keypair) throws IOException, CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(baos); os.writeObject(keypair);/*from www . ja va 2s .co m*/ CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); CMSEnvelopedData ed; // Creating the KeyId may just throw an exception, we will log this but store the cert and ignore the error final PublicKey pk = cryptoToken.getPublicKey(alias); byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier(); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk)); JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); ed = edGen.generate(new CMSProcessableByteArray(baos.toByteArray()), jceCMSContentEncryptorBuilder.build()); log.info("Encrypted keys using key alias '" + alias + "' from Crypto Token " + cryptoToken.getId()); return ed.getEncoded(); }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] encryptData(CryptoToken cryptoToken, byte[] data, int keyPurpose) throws IOException, CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); CMSEnvelopedData ed;//w w w .ja v a 2s . c om final String keyAlias = getCAToken().getAliasFromPurpose(keyPurpose); final PublicKey pk = cryptoToken.getPublicKey(keyAlias); byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier(); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk)); JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); ed = edGen.generate(new CMSProcessableByteArray(data), jceCMSContentEncryptorBuilder.build()); log.info("Encrypted data using key alias '" + keyAlias + "' from Crypto Token " + cryptoToken.getId()); return ed.getEncoded(); }
From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java
License:Open Source License
/** * Tests issuing a CRL from a CA with a SKID that is not generated with SHA1. * The CRL is checked to contain the correct AKID value. *//* w ww .j a v a 2 s . c o m*/ @Test public void testNonSHA1KeyId() throws Exception { final String subcaname = "CrlCSTestSub"; final String subcadn = "CN=" + subcaname; try { // Create an external root ca certificate final KeyPair rootcakp = KeyTools.genKeys("1024", "RSA"); final String rootcadn = "CN=CrlCSTestRoot"; final X509Certificate rootcacert = CertTools.genSelfCert(rootcadn, 3650, null, rootcakp.getPrivate(), rootcakp.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, "BC", false); // Create sub ca final int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(authenticationToken, subcaname, "1024"); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); X509CAInfo subcainfo = new X509CAInfo(subcadn, subcaname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 365, CAInfo.SIGNEDBYEXTERNALCA, null, catoken); X509CA subca = new X509CA(subcainfo); subca.setCAToken(catoken); caSession.addCA(authenticationToken, subca); // Issue sub CA certificate with a non-standard SKID PublicKey subcapubkey = cryptoTokenMgmtSession.getPublicKey(authenticationToken, cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)).getPublicKey(); Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + 365 * 24 * 60 * 60 * 1000); final SubjectPublicKeyInfo subcaspki = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(subcapubkey.getEncoded())); final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(rootcadn, false), new BigInteger(64, new Random(System.nanoTime())), firstDate, lastDate, CertTools.stringToBcX500Name(subcadn, false), subcaspki); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(CertTools.getAuthorityKeyId(rootcacert)); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(TEST_AKID); // Non-standard SKID. It should match the AKID in the CRL certbuilder.addExtension(Extension.authorityKeyIdentifier, true, aki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); BasicConstraints bc = new BasicConstraints(true); certbuilder.addExtension(Extension.basicConstraints, true, bc); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign); certbuilder.addExtension(Extension.keyUsage, true, ku); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(rootcakp.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate subcacert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded(), "BC"); // Replace sub CA certificate with a sub CA cert containing the test AKID subcainfo = (X509CAInfo) caSession.getCAInfo(authenticationToken, subcaname); List<Certificate> certificatechain = new ArrayList<Certificate>(); certificatechain.add(subcacert); certificatechain.add(rootcacert); subcainfo.setCertificateChain(certificatechain); subcainfo.setExpireTime(CertTools.getNotAfter(subcacert)); caSession.editCA(authenticationToken, subcainfo); subca = (X509CA) caTestSessionRemote.getCA(authenticationToken, subcaname); assertArrayEquals("Wrong SKID in test CA.", TEST_AKID, CertTools.getSubjectKeyId(subca.getCACertificate())); // Create a base CRL and check the AKID int baseCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("For a new CA, the next crl number should be 1.", 1, baseCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), -1, baseCrlNumber); final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); checkCrlAkid(subca, crl); // Create a delta CRL and check the AKID int deltaCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("Next CRL number should be 2 at this point.", 2, deltaCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), baseCrlNumber, deltaCrlNumber); final byte[] deltacrl = crlStoreSession.getLastCRL(subcadn, true); // true = get delta CRL checkCrlAkid(subca, deltacrl); } finally { // Remove everything created above to clean the database final Integer cryptoTokenId = cryptoTokenMgmtSession.getIdFromName(subcaname); if (cryptoTokenId != null) { CryptoTokenTestUtils.removeCryptoToken(authenticationToken, cryptoTokenId); } try { int caid = caSession.getCAInfo(authenticationToken, subcaname).getCAId(); // Delete sub CA CRLs while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, true); // delta CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); // base CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } // Delete sub CA caSession.removeCA(authenticationToken, caid); } catch (CADoesntExistsException cade) { // NOPMD ignore } } }