简体   繁体   中英

convert hash even ruby like php's hash_hmac ()

PHP version:

hash_hmac('sha384', data, privateKey, true);

I have rewritten the above PHP code to ruby code below, but similar results were not obtained.

Ruby version:

OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha384"), privateKey, data)

PHP is raw binary data, Ruby does not have such an option.

How can I rewrite the PHP function into a Ruby function?

[Edit: I've edited this answer heavily since first writing it, to make it clearer, and to emphasize the use of Array#pack.]

Unfortunately, the way to express raw bytes in Ruby is with a string. You should probably force the encoding to ASCII 8-bit, as opposed to the default UTF-8, so that chars are the same thing as bytes, and no fancy conversions will be done on the input data.

You can explicitly set the encoding of a string:

2.5.0 :008 > my_string = String.new.force_encoding(Encoding::ASCII_8BIT)
 => ""
2.5.0 :009 > my_string.encoding
 => #<Encoding:ASCII-8BIT>

...or use the Array#pack method:

2.5.0 :010 > a123 = [1,2,3].pack('c*')
 => "\x01\x02\x03"
2.5.0 :011 > a123.encoding
 => #<Encoding:ASCII-8BIT>

...or any combination thereof:

2.5.0 :018 > my_string = String.new.force_encoding(Encoding::ASCII_8BIT)
 => ""
2.5.0 :019 > my_string << [4,5,6].pack('c*')
 => "\x04\x05\x06"
2.5.0 :020 > my_string << [7,8,9].pack('c*')
 => "\x04\x05\x06\a\b\t"
2.5.0 :021 > my_string.bytes
 => [4, 5, 6, 7, 8, 9]

The pack method is a great way to insert values into the string, since it's very explicit about the format.

You could of course also use an array of byte values, but that array would not be compatible with most use cases.

I'm not certain that will solve your problem, but it's worth a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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