use of org.apache.pulsar.client.api.PulsarClientException.CryptoException in project incubator-pulsar by apache.
the class MessageCrypto method addPublicKeyCipher.
private void addPublicKeyCipher(String keyName, CryptoKeyReader keyReader) throws CryptoException {
if (keyName == null || keyReader == null) {
throw new PulsarClientException.CryptoException("Keyname or KeyReader is null");
}
// 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);
}
Aggregations