我已经运行了一个简单的测试,通过在循环中加密字节缓冲区来度量AES-GCM在Java9中的性能。结果有点令人困惑。本机(硬件)加速似乎起作用了--但并非总是如此。更确切地说,
我的测试代码如下所示:
int plen = 1024*1024;
byte[] input = new byte[plen];
for (int i=0; i < input.length; i++) { input[i] = (byte)i;}
byte[] nonce = new byte[12];
...
// Uses SunJCE provider
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] key_code = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
SecretKey key = new SecretKeySpec(key_code, "AES");
SecureRandom random = new SecureRandom();
long total = 0;
while (true) {
random.nextBytes(nonce);
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] cipherText = cipher.doFinal(input);
total += plen;
// print delta_total/delta_time, once in a while
}2019年2月更新: HotSpot已被修改以解决此问题。修复在Java 13中应用,也支持Java 11和12。
id=JDK-8201633,https://hg.openjdk.java.net/jdk/jdk/rev/f35a8aaabcb9
2019年7月16日更新:新发布的版本(Java11.0.4)修复了这个问题。
发布于 2018-02-22 09:55:18
谢谢霍格指出了正确的方向。预先使用多个cipher.doFinal调用的cipher.update将几乎立即触发硬件加速。
基于这个参考,GCM分析,我在每次更新中使用4KB块。现在,1MB和100 MB缓冲区都以1100 MB/秒速度加密(几十毫秒后)。
解决办法是替换
byte[] cipherText = cipher.doFinal(input);使用
int clen = plen + GCM_TAG_LENGTH;
byte[] cipherText = new byte[clen];
int chunkLen = 4 * 1024;
int left = plen;
int inputOffset = 0;
int outputOffset = 0;
while (left > chunkLen) {
int written = cipher.update(input, inputOffset, chunkLen, cipherText, outputOffset);
inputOffset += chunkLen;
outputOffset += written;
left -= chunkLen;
}
cipher.doFinal(input, inputOffset, left, cipherText, outputOffset);发布于 2018-04-12 11:50:33
关于这个问题的几个更新。
我已经向Java平台提交了一个bug报告。它被评价并作为JDK-8201633出版。
发布于 2019-02-14 06:59:37
这个问题在Java 13中得到了解决,修复也被移植到Java 11和12中。
id=JDK-8201633,https://hg.openjdk.java.net/jdk/jdk/rev/f35a8aaabcb9
https://stackoverflow.com/questions/48905291
复制相似问题