Thread safety with RSA Cipher Thread safety with RSA Cipher multithreading multithreading

Thread safety with RSA Cipher


In case somebody else reads this, there shouldn't be need to reinitialize cipher for every call with RSA. Although, pool of ciphers could be used for performance boost.

I have written quick load test to verify this.

It seems that it is enough to synchronize on cipher.doInit() and use single Cipher instance for decryption.

private static Queue<String> results = new ConcurrentLinkedQueue<String>();@Testpublic void test() throws InterruptedException {    String plainText = "some text to verify data integrity";    String encryptedText = Encrypt.encrypt(plainText);    for (int i = 0; i < 5000; i++) {        new Thread( () -> { results.add(Decrypt.decrypt(encryptedText)); })        .start();;              }    Thread.sleep(5000);    assertTrue(results.size() == 5000);    while(!results.isEmpty()) {        assertTrue(results.poll().equals(plainText));    }} 


Encryption (and writing messages) is inherently synchronous. Using multiple threads would not be my approach. Consider a message aabb. With multiple threads that might become abba or baba or abab or bbaa. Note that the internal state of the cipher is also synchronous in that manner ... To get aabb out, you must send aabb in.