As the titles says, i would like to know how to best use Cipher instance in multi threaded environment given the RSA algorithm.
I have read a couple of questions on the topic, and from what i gathered:
Cipher is not thread safe as it maintains internal state while encrypting/decrypting
if AES is used, then
doFinal()
will reset Initialization vector to last known value and therefore new Cipher instance should be generated each time
My Questions
Is it alright to invoke
cipher.init()
only once if chosen algorithm is RSA ? This is contrary to second bullet as shown in the code bellow. I believe so as there is no initialization vector. Also, the cipher will only be used to decrypt data.Should i synchronize only on
cipher.doFinal()
invocation ?- What is the common way to handle multiple threads requesting cryptography services, should i have pool of ciphers as a blocking queue behind some proxy?
Code sample:
public class RsaPrototype {
private static PrivateKey privKey;
private static Cipher cipher;
private static final String PRIVATE_KEY_PATH ="./privK.pem";
/*
* ALGORITHM/BLOCKING_MODE/PADDING_SCHEMA
*/
private static final String CIPHER_SPECIFICATION = "RSA/None/NoPadding";
private static final String RSA_PROVIDER ="BC";
static {
Security.addProvider(new BouncyCastleProvider());
importPrivateKey();
cipher = getCipher();
}
/**
* Initializes cipher with RSA algorithm, without blocking mode and padding.
* Implementation provider is bouncy castle.
*
* @return cipher instance.
*/
private static Cipher getCipher() {
try
{
Cipher cipher = Cipher.getInstance(CIPHER_SPECIFICATION, RSA_PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, privKey);
return cipher;
} catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Imports public key from the given .PEM file into application cache.
*/
private static void importPrivateKey() {
try (BufferedReader reader =
new BufferedReader(new FileReader(PRIVATE_KEY_PATH));
PEMParser pemParser =
new PEMParser(reader);) {
privKey = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pemParser.readObject());
}
catch (IOException ignorable) {
// not handled
}
}
public static String decrypt(byte[] encryptedText) {
byte[] plainText;
synchronized (cipher) {
plainText = cipher.doFinal(encryptedText);
}
return new String(plainText, StandardCharsets.UTF_8);
}
}