Crypto Hmac node.js 相当于 ruby​​ 的以下功能

Cha*_*iah 2 ruby openssl hmac node.js cryptojs

function hmac(key, string, encoding) {
  return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding);
}
function hash(string, encoding) {
    return crypto.createHash('sha256').update(string, 'utf8').digest(encoding);
}
Run Code Online (Sandbox Code Playgroud)

对于上面的函数,hmac 编码是可选的,否则它的值是“hex”,我检查了 ruby​​ 中的 OpenSsl 库,发现了类似的函数,但在 ruby​​ 中运行时没有得到相同的输出。

以下链接用作某些扩展的参考,但不完全是。任何人都遇到过类似的用例。请告诉我

Eri*_*uer 5

这是一个非常古老的问题,但我只是想做同样的事情,并认为为后代发布答案不会有什么坏处。

我想出的 Ruby 等价物明显更加冗长,因为我不知道如何将编码作为参数传递给任何方法。

注意: base64 JS 和 Ruby 之间的编码hex是等效的。看起来 Nodelatin1编码的输出可能会有所不同,具体取决于 Ruby 的配置方式,但我相信原始字节是等效的。

require 'openssl'
require 'base64'

def hmac(key, string, encoding = 'hex')
  hmac = OpenSSL::HMAC.new(key, 'sha256')
  hmac << string
  case encoding
    when 'base64'
      Base64.encode64(hmac.digest)
    when 'hex'
      hmac.hexdigest
    else
      hmac.digest
  end
end

def hash(string, encoding = 'hex')
  sha256 = OpenSSL::Digest::SHA256.new
  sha256 << string
  case encoding
    when 'base64'
      Base64.encode64(sha256.digest)
    when 'hex'
      sha256.hexdigest
    else
      sha256.digest
  end
end

key = "NjNsSSpyaE83NyZGaGdpYXhLQmFjVUJhZ3UyMENqZWY="
string = "this is a test"
encoding = "hex";
puts hmac(key, string, encoding) # => adb2946c2815047327d51459b401836cebb1a31644604303b4886b028bb98e69
puts hash(string, encoding) # => 2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c
Run Code Online (Sandbox Code Playgroud)

要进行测试,您可以简单地在节点中运行等效的命令

var key = "NjNsSSpyaE83NyZGaGdpYXhLQmFjVUJhZ3UyMENqZWY="
var string = "this is a test"
var encoding = "hex";
console.log(hmac(key, string, encoding)) // => adb2946c2815047327d51459b401836cebb1a31644604303b4886b028bb98e69
console.log(hash(string, encoding)) // => 2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c
Run Code Online (Sandbox Code Playgroud)