我目前正在构建使用加密原语的应用程序。对于加密和散列,我使用 javax.crypto 和 java.security 包。我做了一些基准测试,结果证明 ECB-AES-128 比 SHA1 快。我用于 AES 测试的代码:
byte[] key = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
byte[] data = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
SecretKeySpec encryptionKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
long start = System.currentTimeMillis();
for (int i=0; i<10000000; i++)
{
cipher.doFinal(data);
}
long end = System.currentTimeMillis();
System.out.println("took: "+ (end-start));
用于散列
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] data = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
long start = System.currentTimeMillis();
for (int i=0; i<10000000; i++)
{
md.digest(data);
}
long end = System.currentTimeMillis();
System.out.println("took:" + (end-start));
加密时间:~4sec。散列时间需要:~10 秒。配置:Core i5 3570-3.4Ghz,8Gb RAM(不确定,是否重要)
为什么加密比散列花费更少的时间?哈希函数应该更快。难道我做错了什么?谢谢