Question

How do i convert

import base64
import hashlib
import hmac
key = ''
text = 'GET\n\n\nSat, 22 Mar 2014 13:49:42 +0000\n'
base64.b64encode(hmac.new(key, text, hashlib.sha1).hexdigest())
#=> 'ZmUxN2YxMDQxMTdlODg3MDljMTRjYjY0ZGU1NDk1MjgwNzI2Yjk1Zg=='

into Ruby 1.9.3?

This way it returns different string:

require 'base64'
require 'digest'
require 'digest/hmac'
require 'cgi'
require 'openssl'
key = ''
text = 'GET\n\n\nSat, 22 Mar 2014 13:49:42 +0000\n'
hex = Digest::HMAC.hexdigest(key, text, Digest::SHA1)
Base64.urlsafe_encode64(hex)
#=> "YjdlNzBhMjFkZmRmZDFlMjM2Mzg5ZjYxYWE3NWEyZTJhN2I3MWNhMA=="

How should I generate hash to make it equal to Python's result?

Was it helpful?

Solution

First, '\n' in Ruby means literally \ and n. To represent newline, you need to use double-quoted string: "\n".

The order of parameter of Digest::HMAC.hexdigest is different from python version. And according to the Digest::HMAC documetation, its usage is discouraged. Use OpenSSL:HMAC instead.

So the ruby script should be read as:

require 'base64'
require 'openssl'
key = ''
text = "GET\n\n\nSat, 22 Mar 2014 13:49:42 +0000\n"
# hex = Digest::HMAC.hexdigest(text, key, Digest::SHA1) # <-- discouraged
hex = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), key, text)
p Base64.urlsafe_encode64(hex)
# => "ZmUxN2YxMDQxMTdlODg3MDljMTRjYjY0ZGU1NDk1MjgwNzI2Yjk1Zg=="
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top