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

text
1
  /**       * 解密       * @param key 解密的密钥       * @param raw 已经加密的数据       * @return 解密后的明文       * @throws Exception       */        public byte[] decrypt(Key key, byte[] raw) throws Exception {           try {              Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());              cipher.init(cipher.DECRYPT_MODE, key);              int blockSize = cipher.getBlockSize();              ByteArrayOutputStream bout = new ByteArrayOutputStream(64);              int j = 0;              while (raw.length - j * blockSize > 0) {                 bout.write(cipher.doFinal(raw, j * blockSize, blockSize));                 j++;              }              return bout.toByteArray();           } catch (Exception e) {              throw new Exception(e.getMessage());           }        }            

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

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

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秒.基本符合公司的要求!具体原因不知道。

原文地址:https://blog.csdn.net/ganjing222/article/details/70230608?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168904449916800185828444%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168904449916800185828444&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-9-70230608-null-null.142^v88^control_2,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96