12

I'm trying to create an HMAC in Ruby and then verify it in PHP.

Ruby:

require 'openssl'
message = "A522EBF2-5083-484D-99D9-AA97CE49FC6C,1234567890,/api/comic/aWh62,GET"
key     = "3D2143BD-6F86-449F-992C-65ADC97B968B"
hash    = OpenSSL::HMAC.hexdigest('sha256', message, key)
p hash

PHP:

<?php
  $message = "A522EBF2-5083-484D-99D9-AA97CE49FC6C,1234567890,/api/comic/aWh62,GET";
  $key     = "3D2143BD-6F86-449F-992C-65ADC97B968B";
  $hash    = hash_hmac("sha256", $message, $key);
  var_dump($hash);
?>

For the Ruby, I get: 20e3f261b762e8371decdf6f42a5892b530254e666508e885c708c5b0bfc03d3

For the PHP, I get: e5f6995ba1496b2fb144329b2d1b3b23c8fa3211486e57bfaec5d993a1da9d15

I and some colleagues are at a complete loss, any help would be greatly appreciated.

1
  • I suspect that the strings are encoded differently. Aug 26, 2009 at 19:44

2 Answers 2

31

ruby's OpenSSL::HMAC.hexdigest expects first key and then message.

irb(main):002:0> OpenSSL::HMAC.hexdigest('sha256','3D2143BD-6F86-449F-992C-65ADC97B968B','A522EBF2-5083-484D-99D9-AA97CE49FC6C,1234567890,/api/comic/aWh62,GET')
=> "e5f6995ba1496b2fb144329b2d1b3b23c8fa3211486e57bfaec5d993a1da9d15"
1
  • 2
    Well, I'll be damned. Thanks:)
    – Jim Keener
    Aug 26, 2009 at 21:14
0

I noticed that

hash = HMAC::SHA256(key) 
hash << a
hash << b
hash << c

gives different result than PHP's

hash_hmac('sha256',$a.$b.$c, $key)

beware of this caveat. To get correct, just do

hash = HMAC::SHA256(key)
hash << "#{a}#{b}#{c}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.