RSA解密算法优化(java)

来源:互联网 发布:linux下查看用户权限 编辑:程序博客网 时间:2024/06/05 07:55

公司在开发第三方支付平台的时候,安全模块用的是RSA来解密。结果效果很低。运行100解密线程就用了22秒!这个要求肯定是不符合我们要求的!所以我们到处在网上的找代码。结果还是没办法!还是很慢!最后我们同事找到一个问题,修改了下果然解密速度大幅提高!我特意写这篇文章!已做记录.

   

  1.     /** 
  2.     * 解密 
  3.     * @param key 解密的密钥 
  4.     * @param raw 已经加密的数据 
  5.     * @return 解密后的明文 
  6.     * @throws Exception 
  7.     */  
  8.     public byte[] decrypt(Key key, byte[] raw) throws Exception {  
  9.         try {  
  10.             Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  11.             cipher.init(cipher.DECRYPT_MODE, key);  
  12.             int blockSize = cipher.getBlockSize();  
  13.             ByteArrayOutputStream bout = new ByteArrayOutputStream(64);  
  14.             int j = 0;  
  15.             while (raw.length - j * blockSize > 0) {  
  16.                 bout.write(cipher.doFinal(raw, j * blockSize, blockSize));  
  17.                 j++;  
  18.             }  
  19.             return bout.toByteArray();  
  20.         } catch (Exception e) {  
  21.             throw new Exception(e.getMessage());  
  22.         }  
  23.     }  
  24.       

上面的文章就是以前的代码!在网上到处都可以找到!但是如果你多线程运行的话!结果会很慢很慢!

下面就是修改过后的代码:

  Cipher cipher = Cipher.getInstance("RSA"new org.bouncycastle.jce.provider.BouncyCastleProvider());  

这句替换成

public static synchronized Cipher getCipher()
throws NoSuchAlgorithmException, NoSuchPaddingException {
if (cipher == null) {
cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());
}
return cipher;


}

效果会有比较大的提升!

我测试了运行100解密线程就用了1秒.基本符合公司的要求!具体原因不知道。


0 0