-1

我目前正在构建使用加密原语的应用程序。对于加密和散列,我使用 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(不确定,是否重要)

为什么加密比散列花费更少的时间?哈希函数应该更快。难道我做错了什么?谢谢

4

1 回答 1

0

请在openssl speed sha1 aes-128-cbc下面找到结果:

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
sha1             27821.86k    81142.78k   181461.85k   272193.19k   312980.82k
aes-128 cbc      55984.60k    63748.01k    64728.23k   104889.11k   107399.85k

正如您所看到的,AES 对于少量的速度更快,而对于大量的速度则较慢。为什么会这样?嗯,很简单。AES 使用 128 位的块大小,而 SHA-1 使用 512 位的块大小。因此对于少量数据,SHA-1 必须做更多的工作。请注意,对于 64 字节,SHA-1 必须使用 2 个完整块,因此它仍然处于劣势。由于更大的状态大小,我希望它也不会那么容易优化。

AES 通常也经过大量优化。我不确定 Java 中的 SHA-1 是否引起了同样的兴趣。如今,您宁愿查看 SHA-2。

于 2014-10-21T21:05:58.607 回答