Why would HMAC SHA-1 return a different digest with the same input?

陌路散爱 提交于 2019-12-03 16:03:53

I find the the main problems I have had with hashes in comparisons are:

  1. ensure the data and key are the same in both comparisons
  2. ensure the data and key are in the same character encoding in both comparisons
  3. ensure the key and text are being passed the same in both scripts, i.e. which one is key and which one is text (this has caught me more than once).

Try using the Digest::SHA module to create the hash for you and compare the results with that.

use Digest::SHA qw(hmac_sha1_hex);
my $hash = hmac_sha1_hex($data, $key);

See docs at http://perldoc.perl.org/Digest/SHA.pdf

The encoding subroutine is virtually identical in both scripts (except for an unused argument passed to the subroutine, which I remove from my custom version).

Since you're not comparing the digests themselves, but Base-64 encoded versions of the digests, I would recommend backing up one step and checking the digests themselves. It may be possible that the Base-64 encoding routines are incorrect.

If you can't compare the digests themselves, then use the same encoding routine in both programs and see what you get.

I'm afraid I can't help much here, but there's definitely something wrong with what you posted. Your example script produces different output for me and the output you posted really cannot be correct.

How could this

secret key hex: abcd...1234

ever be the result of that

_ascii_to_hex("blahblahblah")

Of course, the whole ascii_to_hex thing is completely irrelevant to your problem, but it shows that you should double-check your results.

Divide and conquer?

The test vectors in the RFC are the best place to start. Did they pass in both instances? Which ones did you try? If some work and others don't the most likely problem is that one of the two APIs are improperly marshalling the keys input (Signed vs unsigned arrays, charset conversions..etc)

As an aside its really difficult to help you when your example is nonsense. As others mentioned the hex representation of blah blah is not abc..123. Makes me wonder what else in your example is inaccurate?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!