Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby sha 256 hexidigest values are different from what python generates

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 ?

like image 311
Hound Avatar asked Dec 24 '22 12:12

Hound


1 Answers

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

like image 130
Frederick Cheung Avatar answered May 03 '23 13:05

Frederick Cheung