dqnqpqv3841 2018-01-22 08:33
浏览 99

转换哈希甚至ruby像php的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?

  • 写回答

1条回答 默认 最新

  • duanhua9398 2018-01-22 16:35
    关注

    [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.

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题