Crypto Hmac node.js等效于以下函数的ruby

时间:2017-11-27 12:22:14

标签: node.js ruby openssl hmac 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);
}

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

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

1 个答案:

答案 0 :(得分:1)

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

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

注意:base64hex编码在JS和Ruby之间是等效的。看起来Node的latin1编码的输出可能有所不同,具体取决于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

要进行测试,您只需在节点中运行等效项

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