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.nifi.web.server.JettyServerTest.java
License:Apache License
@Test public void testConfigureSslContextFactoryWithPkcsTrustStore() { // Expect that we will set Bouncy Castle provider for pkcs12 truststore final Map<String, String> addProps = new HashMap<>(); String trustStoreType = KeystoreType.PKCS12.toString(); addProps.put(NiFiProperties.SECURITY_TRUSTSTORE_TYPE, trustStoreType); NiFiProperties nifiProperties = NiFiProperties.createBasicNiFiProperties(null, addProps); SslContextFactory contextFactory = mock(SslContextFactory.class); JettyServer.configureSslContextFactory(contextFactory, nifiProperties); verify(contextFactory).setTrustStoreType(trustStoreType); verify(contextFactory).setTrustStoreProvider(BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
public MessageCrypto(String logCtx, boolean keyGenNeeded) { this.logCtx = logCtx; encryptedDataKeyMap = new ConcurrentHashMap<String, EncryptionKeyInfo>(); dataKeyCache = CacheBuilder.newBuilder().expireAfterAccess(4, TimeUnit.HOURS) .build(new CacheLoader<ByteBuffer, SecretKey>() { @Override/*w w w . ja v a 2 s . c o m*/ public SecretKey load(ByteBuffer key) { return null; } }); try { cipher = Cipher.getInstance(AESGCM, BouncyCastleProvider.PROVIDER_NAME); // If keygen is not needed(e.g: consumer), data key will be decrypted from the message if (!keyGenNeeded) { digest = MessageDigest.getInstance("MD5"); dataKey = null; return; } keyGenerator = KeyGenerator.getInstance("AES"); int aesKeyLength = Cipher.getMaxAllowedKeyLength("AES"); if (aesKeyLength <= 128) { log.warn( "{} AES Cryptographic strength is limited to {} bits. Consider installing JCE Unlimited Strength Jurisdiction Policy Files.", logCtx, aesKeyLength); keyGenerator.init(aesKeyLength, secureRandom); } else { keyGenerator.init(256, secureRandom); } } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { cipher = null; log.error("{} MessageCrypto initialization Failed {}", logCtx, e.getMessage()); } // Generate data key to encrypt messages dataKey = keyGenerator.generateKey(); iv = new byte[ivLen]; }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
private PublicKey loadPublicKey(byte[] keyBytes) throws Exception { Reader keyReader = new StringReader(new String(keyBytes)); PublicKey publicKey = null;/*from ww w . j a v a 2 s .c o m*/ try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(keyReader)) { Object pemObj = pemReader.readObject(); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); SubjectPublicKeyInfo keyInfo = null; X9ECParameters ecParam = null; if (pemObj instanceof ASN1ObjectIdentifier) { // make sure this is EC Parameter we're handling. In which case // we'll store it and read the next object which should be our // EC Public Key ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj; ecParam = ECNamedCurveTable.getByOID(ecOID); if (ecParam == null) { throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId()); } pemObj = pemReader.readObject(); } else if (pemObj instanceof X9ECParameters) { ecParam = (X9ECParameters) pemObj; pemObj = pemReader.readObject(); } if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) { keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo(); } else { keyInfo = (SubjectPublicKeyInfo) pemObj; } publicKey = pemConverter.getPublicKey(keyInfo); if (ecParam != null && ECDSA.equals(publicKey.getAlgorithm())) { ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed()); KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME); ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) publicKey).getQ(), ecSpec); publicKey = (PublicKey) keyFactory.generatePublic(keySpec); } } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) { throw new Exception(e); } return publicKey; }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
private PrivateKey loadPrivateKey(byte[] keyBytes) throws Exception { Reader keyReader = new StringReader(new String(keyBytes)); PrivateKey privateKey = null; try (PEMParser pemReader = new PEMParser(keyReader)) { X9ECParameters ecParam = null;/* ww w .ja v a 2 s . c o m*/ Object pemObj = pemReader.readObject(); if (pemObj instanceof ASN1ObjectIdentifier) { // make sure this is EC Parameter we're handling. In which case // we'll store it and read the next object which should be our // EC Private Key ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj; ecParam = ECNamedCurveTable.getByOID(ecOID); if (ecParam == null) { throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ecOID.getId()); } pemObj = pemReader.readObject(); } else if (pemObj instanceof X9ECParameters) { ecParam = (X9ECParameters) pemObj; pemObj = pemReader.readObject(); } if (pemObj instanceof PEMKeyPair) { PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo(); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); privateKey = pemConverter.getPrivateKey(pKeyInfo); } // if our private key is EC type and we have parameters specified // then we need to set it accordingly if (ecParam != null && ECDSA.equals(privateKey.getAlgorithm())) { ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed()); KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME); ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privateKey).getS(), ecSpec); privateKey = (PrivateKey) keyFactory.generatePrivate(keySpec); } } catch (IOException e) { throw new Exception(e); } return privateKey; }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
private void addPublicKeyCipher(String keyName, CryptoKeyReader keyReader) throws CryptoException { if (keyName == null || keyReader == null) { throw new PulsarClientException.CryptoException("Keyname or KeyReader is null"); }/*from w w w . j a v a2 s .c om*/ // Read the public key and its info using callback EncryptionKeyInfo keyInfo = keyReader.getPublicKey(keyName, null); PublicKey pubKey; try { pubKey = loadPublicKey(keyInfo.getKey()); } catch (Exception e) { String msg = logCtx + "Failed to load public key " + keyName + ". " + e.getMessage(); log.error(msg); throw new PulsarClientException.CryptoException(msg); } Cipher dataKeyCipher = null; byte[] encryptedKey; try { // Encrypt data key using public key if (RSA.equals(pubKey.getAlgorithm())) { dataKeyCipher = Cipher.getInstance(RSA_TRANS, BouncyCastleProvider.PROVIDER_NAME); } else if (ECDSA.equals(pubKey.getAlgorithm())) { dataKeyCipher = Cipher.getInstance(ECIES, BouncyCastleProvider.PROVIDER_NAME); } else { String msg = logCtx + "Unsupported key type " + pubKey.getAlgorithm() + " for key " + keyName; log.error(msg); throw new PulsarClientException.CryptoException(msg); } dataKeyCipher.init(Cipher.ENCRYPT_MODE, pubKey); encryptedKey = dataKeyCipher.doFinal(dataKey.getEncoded()); } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException e) { log.error("{} Failed to encrypt data key {}. {}", logCtx, keyName, e.getMessage()); throw new PulsarClientException.CryptoException(e.getMessage()); } EncryptionKeyInfo eki = new EncryptionKeyInfo(encryptedKey, keyInfo.getMetadata()); encryptedDataKeyMap.put(keyName, eki); }
From source file:org.apache.pulsar.client.impl.MessageCrypto.java
License:Apache License
private boolean decryptDataKey(String keyName, byte[] encryptedDataKey, List<KeyValue> encKeyMeta, CryptoKeyReader keyReader) {// ww w. java2 s .c o m Map<String, String> keyMeta = new HashMap<String, String>(); encKeyMeta.forEach(kv -> { keyMeta.put(kv.getKey(), kv.getValue()); }); // Read the private key info using callback EncryptionKeyInfo keyInfo = keyReader.getPrivateKey(keyName, keyMeta); // Convert key from byte to PivateKey PrivateKey privateKey; try { privateKey = loadPrivateKey(keyInfo.getKey()); if (privateKey == null) { log.error("{} Failed to load private key {}.", logCtx, keyName); return false; } } catch (Exception e) { log.error("{} Failed to decrypt data key {} to decrypt messages {}", logCtx, keyName, e.getMessage()); return false; } // Decrypt data key to decrypt messages Cipher dataKeyCipher = null; byte[] dataKeyValue = null; byte[] keyDigest = null; try { // Decrypt data key using private key if (RSA.equals(privateKey.getAlgorithm())) { dataKeyCipher = Cipher.getInstance(RSA_TRANS, BouncyCastleProvider.PROVIDER_NAME); } else if (ECDSA.equals(privateKey.getAlgorithm())) { dataKeyCipher = Cipher.getInstance(ECIES, BouncyCastleProvider.PROVIDER_NAME); } else { log.error("Unsupported key type {} for key {}.", privateKey.getAlgorithm(), keyName); return false; } dataKeyCipher.init(Cipher.DECRYPT_MODE, privateKey); dataKeyValue = dataKeyCipher.doFinal(encryptedDataKey); keyDigest = digest.digest(encryptedDataKey); } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException e) { log.error("{} Failed to decrypt data key {} to decrypt messages {}", logCtx, keyName, e.getMessage()); return false; } dataKey = new SecretKeySpec(dataKeyValue, "AES"); dataKeyCache.put(ByteBuffer.wrap(keyDigest), dataKey); return true; }
From source file:org.apache.zookeeper.common.X509TestContext.java
License:Apache License
/** * Constructor is intentionally private, use the Builder class instead. * @param tempDir the directory in which key store and trust store temp files will be written. * @param trustStoreKeyPair the key pair for the trust store. * @param trustStoreCertExpirationMillis the expiration of the trust store cert, in milliseconds from now. * @param trustStorePassword the password to protect a JKS trust store (ignored for PEM trust stores). * @param keyStoreKeyPair the key pair for the key store. * @param keyStoreCertExpirationMillis the expiration of the key store cert, in milliseconds from now. * @param keyStorePassword the password to protect the key store private key. * @throws IOException// w w w . j a v a 2 s. co m * @throws GeneralSecurityException * @throws OperatorCreationException */ private X509TestContext(File tempDir, KeyPair trustStoreKeyPair, long trustStoreCertExpirationMillis, String trustStorePassword, KeyPair keyStoreKeyPair, long keyStoreCertExpirationMillis, String keyStorePassword, Boolean hostnameVerification) throws IOException, GeneralSecurityException, OperatorCreationException { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { throw new IllegalStateException("BC Security provider was not found"); } this.tempDir = requireNonNull(tempDir); if (!tempDir.isDirectory()) { throw new IllegalArgumentException("Not a directory: " + tempDir); } this.trustStoreKeyPair = requireNonNull(trustStoreKeyPair); this.trustStoreKeyType = keyPairToType(trustStoreKeyPair); this.trustStoreCertExpirationMillis = trustStoreCertExpirationMillis; this.trustStorePassword = requireNonNull(trustStorePassword); this.keyStoreKeyPair = requireNonNull(keyStoreKeyPair); this.keyStoreKeyType = keyPairToType(keyStoreKeyPair); this.keyStoreCertExpirationMillis = keyStoreCertExpirationMillis; this.keyStorePassword = requireNonNull(keyStorePassword); X500NameBuilder caNameBuilder = new X500NameBuilder(BCStyle.INSTANCE); caNameBuilder.addRDN(BCStyle.CN, MethodHandles.lookup().lookupClass().getCanonicalName() + " Root CA"); trustStoreCertificate = X509TestHelpers.newSelfSignedCACert(caNameBuilder.build(), trustStoreKeyPair, trustStoreCertExpirationMillis); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, MethodHandles.lookup().lookupClass().getCanonicalName() + " Zookeeper Test"); keyStoreCertificate = X509TestHelpers.newCert(trustStoreCertificate, trustStoreKeyPair, nameBuilder.build(), keyStoreKeyPair.getPublic(), keyStoreCertExpirationMillis); trustStorePemFile = trustStoreJksFile = keyStorePemFile = keyStoreJksFile = null; this.hostnameVerification = hostnameVerification; }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * PEM-encodes the given private key (compatible with OpenSSL), optionally protecting it with a password, and * returns the result as a String./*from www . j a v a2 s . c o m*/ * @param key the private key. * @param password an optional key password. If empty or null, the private key will not be encrypted. * @return a String containing the PEM encoding of the private key. * @throws IOException if converting the key to PEM format fails. * @throws OperatorCreationException if constructing the encryptor from the given password fails. */ public static String pemEncodePrivateKey(PrivateKey key, String password) throws IOException, OperatorCreationException { StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter); OutputEncryptor encryptor = null; if (password != null && password.length() > 0) { encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC) .setProvider(BouncyCastleProvider.PROVIDER_NAME).setRandom(PRNG) .setPasssword(password.toCharArray()).build(); } pemWriter.writeObject(new JcaPKCS8Generator(key, encryptor)); pemWriter.close(); return stringWriter.toString(); }
From source file:org.apache.zookeeper.common.X509TestHelpers.java
License:Apache License
/** * Convenience method to convert a bouncycastle X509CertificateHolder to a java X509Certificate. * @param certHolder a bouncycastle X509CertificateHolder. * @return a java X509Certificate/*from w ww. j a v a2 s . co m*/ * @throws CertificateException if the conversion fails. */ public static X509Certificate toX509Cert(X509CertificateHolder certHolder) throws CertificateException { return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certHolder); }
From source file:org.apache.zookeeper.common.ZKTrustManagerTest.java
License:Apache License
@BeforeClass public static void createKeyPair() throws Exception { Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); keyPairGenerator.initialize(4096);//from w w w. j a v a 2 s .c o m keyPair = keyPairGenerator.genKeyPair(); }