0

I have Ruby 2.5.3 code that create hmac with sha256

require 'openssl'

key = '4629de5def93d6a2abea6afa9bd5476d9c6cbc04223f9a2f7e517b535dde3e25'
message = 'lucas'
hash = OpenSSL::HMAC.hexdigest('sha256', key, message)

hash => ba2e2505c6f302fb3c40bea4491d95bacd96c3d12e8fbe50197ca431165fcee2

But the result is different from Python & JavaScript code. What should I do in Ruby code to have the same result as from the others?

Python

import hmac
import hashlib
import binascii

message = "lucas"
key = "4629de5def93d6a2abea6afa9bd5476d9c6cbc04223f9a2f7e517b535dde3e25"
hash = hmac.new(
    binascii.unhexlify(bytearray(key, "utf-8")),
    msg=message.encode('utf-8'),
    digestmod=hashlib.sha256
).hexdigest()

hash => 99427c7bba36a6902c5fd6383f2fb0214d19b81023296b4bd6b9e024836afea2

JavaScript

const crypto = require('crypto');

const message = 'lucas';
const key = '4629de5def93d6a2abea6afa9bd5476d9c6cbc04223f9a2f7e517b535dde3e25';

const hash = crypto.createHmac('sha256', Buffer.from(key, 'hex'))
                .update(message)
                .digest('hex');

hash => 99427c7bba36a6902c5fd6383f2fb0214d19b81023296b4bd6b9e024836afea2
3
  • Comparing it to an online tool (devglan.com/online-tools/hmac-sha256-online) it looks to me that the ruby version is correct and python and js are wrong. Not the other way around. Commented Jun 30, 2021 at 7:44
  • 2
    In Python and JS you are using the "key" as hexstring, means that the hexstring is converted to a binary format. In Ruby the key is used without conversion. Commented Jun 30, 2021 at 8:33
  • @MichaelFehr Oh! You're certainly right! Commented Jun 30, 2021 at 10:08

1 Answer 1

1

In Python and JS you are using the "key" as hexstring, means that the hexstring is converted to a binary format. In Ruby the key is used without conversion. – Michael Fehr

This gave me the solution.

key = '4629de5def93d6a2abea6afa9bd5476d9c6cbc04223f9a2f7e517b535dde3e25'
message = 'lucas'
puts OpenSSL::HMAC.hexdigest('sha256', [key].pack('H*') , message)

hash => 99427c7bba36a6902c5fd6383f2fb0214d19b81023296b4bd6b9e024836afea2

thank you!

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.