开发者

Get Ruby's OpenSSL::HMAC.hexdigest() to output the same as PHP's hash_hmac()

开发者 https://www.devze.com 2023-02-18 13:25 出处:网络
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 \"tru

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. Th开发者_如何学Pythone 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)?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消