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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献