Thread safety with RSA Cipher

前端 未结 2 1752
伪装坚强ぢ
伪装坚强ぢ 2021-02-10 13:01

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

相关标签:
2条回答
  • 2021-02-10 13:19

    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>();
    
    @Test
    public 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));
        }
    } 
    
    0 讨论(0)
  • 2021-02-10 13:30

    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.

    0 讨论(0)
提交回复
热议问题