简体   繁体   English

获取Ruby的OpenSSL :: HMAC.hexdigest()输出与PHP的hash_hmac()相同

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

I'm trying to use the API of a web service provider. 我正在尝试使用Web服务提供商的API。 They don't have an example in Ruby, but they do have one for PHP, and I'm trying to interpret between the two. 他们在Ruby中没有示例,但是他们有一个PHP示例,我正在尝试在两者之间进行解释。 The API examples always use "true" on PHP's hash_hmac() call, which produces a binary output. API示例始终在PHP的hash_hmac()调用上使用“ true”,这会产生二进制输出。 The difference seems to be that Ruby's OpenSSL::HMAC.hexdigest() function always returns text. 区别似乎在于Ruby的OpenSSL :: HMAC.hexdigest()函数始终返回文本。 (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)? (如果我将PHP调用更改为“ false”,它们将返回相同的值。)是否有人知道对从OpenSSL :: HMAC.hexdigest()返回的文本进行“编码”的方法,以获得与从hash_hmac返回的相同的东西(“ sha256”,$ text,$ key,true)?

使用OpenSSL::HMAC.digest获取二进制输出。

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. 我不知道任何Ruby,但这类似于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. 看起来您可以通过在每个字符串上调用hex方法来做到这一点。

Next, call pack on the converted array using the parameter c* , to convert each integer into a one-byte character. 接下来,使用参数c*调用转换后的数组上的pack ,以将每个整数转换为一个字节的字符。 You should get the correct string of bytes as the result. 您应该获得正确的字节字符串作为结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM