Thread safety with RSA Cipher

前端 未结 2 1753
伪装坚强ぢ
伪装坚强ぢ 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 results = new ConcurrentLinkedQueue();
    
    @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));
        }
    } 
    

提交回复
热议问题