Charles Skariah
Charles Skariah

Reputation: 670

Crypto Hmac node.js equivalent for ruby for the following function

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);
}

For the above function hmac encoding is optional, or else it have value 'hex' I checked the OpenSsl library in ruby and found similar functions but not getting the same outputs when running in ruby.

Following link is used as reference to some extend but not exactly.Anyone have came across similar use case.Please let me know

Upvotes: 2

Views: 846

Answers (1)

Eric Dauenhauer
Eric Dauenhauer

Reputation: 759

This is a very old question but I was just trying to do the same thing and figured posting an answer for posterity wouldn't hurt.

The Ruby equivalents I came up with are significantly more verbose because I am not aware of a way to pass the encoding as an argument to any of the methods.

Note: base64 and hex encodings are equivalent between JS and Ruby. It looks like there could be a difference in the output of Node's latin1 encoding depending on how Ruby is configured, but I believe the raw bytes are equivalent.

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

And to test, you can simply run the equivalent in node

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

Upvotes: 5

Related Questions