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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算