Thread safety with RSA Cipher

前端 未结 2 1180
北荒
北荒 2021-02-10 12:41

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:35

    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));
        }
    } 
    

提交回复
热议问题