Frage

I have observed that the output of HMAC SHA512 for a given data and a key varies each time I execute the script.

first, I take an example of a script where the output does not vary:

#! /usr/bin/perl

use Digest::SHA qw(hmac_sha512_hex);
use warnings;

$data="test";
$key="20202020";

print hmac_sha512_hex($data,$key),"\n";

I run this script two times and get the same output:

perl test.pl
457a1ff378f11880defaa91675de4633d1f1e69712b5dccd2f86612224b825b4461a9215a37cce53
8e7f5de43a6900867667b9361af38df32fc58e54d7ce9a02

perl test.pl
457a1ff378f11880defaa91675de4633d1f1e69712b5dccd2f86612224b825b4461a9215a37cce53
8e7f5de43a6900867667b9361af38df32fc58e54d7ce9a02

now I modify the data variable in the script as follows:

#! /usr/bin/perl

use Digest::SHA qw(hmac_sha512_hex);
use warnings;

$data={'method' => 'test', 'value' => 21};
$key="20202020";

print hmac_sha512_hex($data,$key),"\n";

now the output is different each time I run the script:

perl test.pl
cb1a40ba7a7f52da39dc0a3f130399dfbecb5249946057fd19887b72a58701f28452f6e663153bb6
85a4b86f9d427de4af5904801e11cb6fcbc272344605c2a9

perl test.pl
73dd1678a4e7f29f8032a65cbe979248b3e41cd6ed7aa81e5b214b8b6232af1e7a6683412b8532b7
187313d2c2a96c7e5009a9362690f355028b56ca319825e4

how do I correct this?

War es hilfreich?

Lösung

The data that you pass into hmac_sha512_hex is interpreted as a string. You are passing it as a reference to a hash. You can verify this by printing the value of $data before passing it into the function.

Your reference is just a unique identifier for your hash. Perl doesn't guarantee that you'll get the same hash reference for the same data in different runs of your program. You are therefore passing different values into hmac_sha512_hex which will obviously give you different output.

If you want your output to be the same, then you need to find a way to pass the same string into the function each time. One simple approach might be to use the string that you get back from Data::Dumper's Dumper function.

Update: If you use Data::Dumper, then you'll need to set $Data::Dumper::Sortkeys to a true value.

Andere Tipps

When you pass $data to the hmac_sha512_hex function you are passing the address of the variable which will change every time you run the program. You will have to look into serializing your hash into a string in a consistent way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top