views:

168

answers:

2

I'm trying to write some Perl to inter operate with hash functions in other languages, namely Java at this point. We have found what is presumably a correct source, RFC 4868 which includes some test keys & strings along with their hashed values. I'm using the following snippet, and can't get Perl to come up with the same result. I can only assume that I'm using it incorrectly—can anyone point me in the right direction?

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

The output is '4ef7 ... 5d40', though RFC 4868 (and my compatriot's Java implementation) returns '87aa ... 6854'

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

Gives

87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854

Quoting RFC:

Key =          0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
               0b0b0b0b                          (20 bytes)

Data =         4869205468657265                  ("Hi There")

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

P.S. Adding '0x' to the string doesn't make it binary, it makes it start with '0' and 'x' ;-)

Michael Krelin - hacker
Thanks! I hadn't ever used, nor understood, pack() and hex encodings.
Drew Stephens
+11  A: 

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";
John Kugelman
Very nice, but I am too lazy to type out all those `\x0b`s. I'd do: `my $key = "\x0b" x 20;`
daotoad