5

I am using hashlib library in python and Digest::SHA256.hexdigest library in ruby

With python I tried,

import hashlib
hasher = hashlib.sha256()
hasher.update("xyz")
hasher.digest()
hash = hasher.hexdigest()
print hash

output : 3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282

With Ruby I tried,

require 'digest'
hasher   = Digest::SHA256.digest "xyz"
hash   = Digest::SHA256.hexdigest(hasher)

output : "18cefdae0f25ad7bb5f3934634513e54e5ac56d9891eb13ce456d3eb1f3e72e8"

Can anyone help me to understand why there is a difference? how can I get the same value as python ?

Hound
  • 837
  • 17
  • 31

2 Answers2

11

The ruby code you want is just

require 'digest'
hash   = Digest::SHA256.hexdigest("xyz")

hexdigest takes as argument the string to digest, so what your previous code was doing was digesting the string (returning as a raw array of 32 bytes), and then computing the SHA256 of that & formatting as 64 hex characters.

The ruby digest library does also have an api similar to your python example:

hash = Digest::SHA256.new
hash.update 'xyz'
hash.hexdigest

For when you want to compute a hash incrementally

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
4

I get the same results using the following code:

Python 3.5.0:

import hashlib
>>> hashlib.sha256("xyz".encode()).hexdigest()
'3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282'

Ruby 2.2.3

require 'digest'

Digest::SHA256.hexdigest("xyz")
# => "3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282"

OR

H = Digest::SHA256.new
# => #<Digest::SHA256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855>
H << "xyz"
# => #<Digest::SHA256: 3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282>
H.hexdigest
# => "3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282"

The issue lied within (in my opinion), that:

hasher = Digest::SHA256.digest("xyz")
# => "6\b\xBC\xA1\xE4N\xA6\xC4\xD2h\xEBm\xB0\"`&\x98\x92\xC0\xB4+\x86\xBB\xF1\xE7zo\xA1l<\x92\x82"`

which is not "xyz:". (disclaimer: I had barely used Ruby in the past).

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
jermenkoo
  • 643
  • 5
  • 20