2

我正在尝试编写一些 Perl 来与其他语言的哈希函数进行交互操作,此时也就是 Java。我们找到了可能是正确的来源,RFC 4868,其中包括一些测试键和字符串以及它们的散列值。我正在使用以下代码段,但无法让 Perl 得出相同的结果。我只能假设我使用不正确 - 谁能指出我正确的方向?

use Digest::SHA qw(hmac_sha512_hex);
my $key = '0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b';
my $value = '4869205468657265';
print hmac_sha512_hex($value, $key);

输出是 '4ef7 ... 5d40',虽然 RFC 4868(和我同胞的 Java 实现)返回 '87aa ... 6854'

4

2 回答 2

16
use Digest::SHA qw(hmac_sha512_hex);
my $key = pack('H*','0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b');
my $value = "Hi There";
print hmac_sha512_hex($value, $key);

87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854

引用 RFC:

Key =          0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
               0b0b0b0b                          (20 bytes)

Data =         4869205468657265                  ("Hi There")

PRF-HMAC-SHA-512 = 87aa7cdea5ef619d4ff0b4241a1d6cb0
                   2379f4e2ce4ec2787ad0b30545e17cde
                   daa833b7d6b8a702038b274eaea3f4e4
                   be9d914eeb61f1702e696c203a126854

PS 添加'0x'到字符串不会使其成为二进制文件,而是使其以'0'and开头'x';-)

于 2009-09-23T17:57:27.867 回答
12

The test key needs to be 20 bytes where each byte has the hex value 0x0B, not a string of 40 characters. The test value is the string "Hi There", not the string "4869205468657625". Try this:

use Digest::SHA qw(hmac_sha512_hex);
my $key = "\x0b" x 20;
my $value = 'Hi There';
print hmac_sha512_hex($value, $key) . "\n";
于 2009-09-23T18:00:55.700 回答