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

I'm trying to take this hex number "A10000009296F2" and do a SHA1 hash and make it come out as "2d0e6efea8f8082c9703cf6636c4a2195c75b7ed". You can see here that it does generate as "2d0e6efea8f8082c9703cf6636c4a2195c75b7ed".

I see other on-line calculators where this works as well. But I can't reproduce the results with Perl. My SHA-1 keeps coming out as 'cc73e65e0f3282e01a6de37446df45bbdd46ba02' or '4cf522d69e6334472377eed5959dbfaa422005dc'.

What is wrong with my code that I can't make a proper SHA-1 of my hex number? Any ideas? After the Perl code, I put in some Python that calc's it correctly.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Modern::Perl; use Digest::SHA qw( sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex + hmac_sha1_base64 ); my $var = 'A10000009296F2'; say "hmac_sha1: " . hmac_sha1($var); say "hmac_sha1_hex: " . hmac_sha1_hex($var); say "hmac_sha1_bae_64: " . hmac_sha1_base64($var); say "sha1: " . sha1($var); say "sha1_hex: " . sha1_hex($var); say "sha1_base64: " . sha1_base64($var); say "orig var: " . $var;
Here is the Python code that calcs the SHA1 properly
import hashlib mid = 'A10000009296F2'.upper() s = hashlib.sha1(mid.decode('hex')) print s.hexdigest()

Replies are listed 'Best First'.
Re: SHA1 Not Generating Properly
by daxim (Curate) on Jul 05, 2012 at 07:14 UTC
    You forgot to convert the hex representation of your input data into octets. Use pack:
    use Digest qw(); Digest->new('SHA-1')->add(pack 'H*', 'A10000009296F2')->hexdigest # expression returns '2d0e6efea8f8082c9703cf6636c4a2195c75b7ed'
Re: SHA1 Not Generating Properly ( hex string is not hex encoded number )
by Anonymous Monk on Jul 05, 2012 at 07:08 UTC

    What is mid.decode in s = hashlib.sha1(mid.decode('hex'))?

    What you got in $var is a STRING not a hex number

    Use $var = pack 'H*', $var ;

Re: SHA1 Not Generating Properly
by awohld (Hermit) on Jul 05, 2012 at 13:27 UTC
    Using pack worked! Thanks! I see where I went wrong.