agnome has asked for the wisdom of the Perl Monks concerning the following question:

I'm having problems with hash encoding in Perl. I've narrowed it down to the following code which seems to be giving me the wrong result

#!/usr/bin/perl use warnings; use strict; use Digest::SHA qw(sha256 sha256_hex); my $digest=sha256_hex("138539083512345apiKeyDEMO","apiSecretDEMO" ); print "Digest=$digest\n"; # correct answer is: #696E087F4B1902AA58D35E75B4600580D70A92ED68B23379373117FB3FE3064A # my code generates: #ea645ae07e04289f3fe14c81af54f7da9cae1114fe2bb9efbb6b383ef276434b

I've included what the answer should be at the bottom. I've checked the answer at http://hash.online-convert.com/sha256-generator and it confirms the correct figure. Why is my code generating the wrong answer?

Replies are listed 'Best First'.
Re: Problems with HMAC SHA-256
by marto (Cardinal) on Mar 07, 2014 at 16:25 UTC

    The documentation is pretty clear about how to calculate using the hmac algorithms:

    #!/usr/bin/perl use warnings; use strict; use Digest::SHA qw(hmac_sha256_hex); my $digest=hmac_sha256_hex("138539083512345apiKeyDEMO","apiSecretDEMO" +); print "Digest=$digest\n";

    Update: output:

    Digest=696e087f4b1902aa58d35e75b4600580d70a92ed68b23379373117fb3fe3064 +a

      Thanks very much to everyone for the prompt replies. You are of course correct, I should have used hmac_sha256_hex instead of just sha256_hex if I want to include my own encryption key as the last argument. Otherwise, as pointed out, it just combines all the arguments into one string and then uses its own key.

      Thanks once again.

Re: Problems with HMAC SHA-256
by hazylife (Monk) on Mar 07, 2014 at 16:26 UTC

    Quoting Digest::SHA:

    sha256_hex($data, ...)
    Logically joins the arguments into a single string, and returns its SHA-1/224/256/384/512 digest encoded as a hexadecimal string.
    $ { echo -n 138539083512345apiKeyDEMO ; echo -n apiSecretDEMO; } | sha +256sum ea645ae07e04289f3fe14c81af54f7da9cae1114fe2bb9efbb6b383ef276434b -
Re: Problems with HMAC SHA-256
by hippo (Archbishop) on Mar 07, 2014 at 16:31 UTC

    Using your online calculator at http://hash.online-convert.com/sha256-generator I get ea645ae07e04289f3fe14c81af54f7da9cae1114fe2bb9efbb6b383ef276434b which is the same as the output from your script. Perhaps you are not using the online generator correctly? Or at least not in the same way as sha256_hex?

Re: Problems with HMAC SHA-256
by 2teez (Vicar) on Mar 07, 2014 at 16:28 UTC

    Hi agnome,
    If I may ask, is hmac_sha256_hex($data,$key) the same with sha256_hex($data,$key) like you used it?

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me