转换哈希甚至ruby像php的hash_hmac()

PHP版本:</ p>

  hash_hmac('sha384',data  ,privateKey,true); 
</ code> </ pre>

我已将上面的PHP代码重写为下面的ruby代码,但未获得类似的结果。</ p>

Ruby版本:</ p>

  OpenSSL :: HMAC.hexdigest(OpenSSL :: Digest.new(“sha384”),privateKey,data)
</ code> < / pre>

PHP是原始二进制数据,Ruby没有这样的选项。</ p>

如何将PHP函数重写为Ruby函数?</ p >
</ div>

展开原文

原文

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?

dtpoius74857
dtpoius74857 “原始数据”是原始二进制数据。(PHP版本的真实情况)
2 年多之前 回复
dongliping003116
dongliping003116 与“原始数据”的关系是什么意思?
2 年多之前 回复
douzai3399
douzai3399 谢谢你的相关链接。但是这个问题有原始数据选项。
2 年多之前 回复
dongshadu2546
dongshadu2546 可能重复的Ruby和PHPHMAC不同意
2 年多之前 回复

1个回答

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问