2

I'm trying to use the API of a web service provider. They don't have an example in Ruby, but they do have one for PHP, and I'm trying to interpret between the two. The API examples always use "true" on PHP's hash_hmac() call, which produces a binary output. The difference seems to be that Ruby's OpenSSL::HMAC.hexdigest() function always returns text. (If I change the PHP call to "false" they return the same value.) Does anyone know of a way to "encode" the text returned from OpenSSL::HMAC.hexdigest() to get the same thing as returned from a hash_hmac('sha256', $text, $key, true)?

David Krider
  • 886
  • 12
  • 27

2 Answers2

5

Use OpenSSL::HMAC.digest to get the binary output.

aaz
  • 5,136
  • 22
  • 18
  • Of course, I dove straight into the Ruby manual for the first time ever to uncover how to convert from hex characters to bytes, and never thought to actually look at the class in question. Use this one, not mine. :) – Charles Mar 18 '11 at 20:23
  • 2
    @Charles – Me too, but I searched for `digest`, found it, and then stared at it for a couple of minutes wondering why it wasn't working before realizing that OP was using `hexdigest` :) – aaz Mar 18 '11 at 20:30
  • Well, at least I don't feel so bad now for missing it too. ;-) – David Krider Mar 21 '11 at 13:41
1

You'll need to convert each pair of hex digits into a byte with the same value. I don't know any Ruby, but this is similar to how it would be handled in PHP.

First, take your string of hex digits and split them into an array. Each element in the array should be two characters long. Convert each element from a string of two hex bytes to an integer. It looks like you can do this by calling the hex method on each string.

Next, call pack on the converted array using the parameter c*, to convert each integer into a one-byte character. You should get the correct string of bytes as the result.

Charles
  • 50,943
  • 13
  • 104
  • 142