0

I have the following code in ruby:

hex = Digest::SHA1.hexdigest(str).to_i(16)
hex.to_s(32)

And I tried to implement it in python:

import hashlib
import base64

base64.b32encode(hashlib.sha1(str).digest()) 

When I run the code for the string test in ruby I get l558vpecm6dqc72c11pt74f9guc2veuj While in python I get VFFI7ZOMWGN2MHCMBBZ5HEPJQ6MC7O6T What is wrong with the python code? How to get the same results as for ruby?

  • 1
    What are the conversions supposed to do? Also, did you check that the string results from the digest operation match, in the first place? – Karl Knechtel Jul 08 '20 at 08:32
  • 1
    I don't know Python, but to get the Python result in Ruby, you can use the [base32](https://github.com/stesla/base32) gem: `Base32.encode(Digest::SHA1.digest('test'))`. Maybe that helps to find your problem. – Stefan Jul 08 '20 at 08:57
  • @KarlKnechtel We already have the ruby implementation - we use the results as identifier. Now I need to implement it in new service with python. And yes I did check the digest itself match. – Efrat Zelikovitz Jul 08 '20 at 09:20
  • 1
    One version uses `digest`; the other uses `hexdigest`? – Tom Lord Jul 08 '20 at 11:22

2 Answers2

1

Using gmpy:

import hashlib
import gmpy2

str = 'test'
h = hashlib.sha1(str).hexdigest()
i = int(h, 16)
gmpy2.digits(i, 32)
=> 'l558vpecm6dqc72c11pt74f9guc2veuj'

If you don't want to use gmpy and need a native Python version of digits, then you can find several implementations among the answers here.

Casper
  • 33,403
  • 4
  • 84
  • 79
0

I hope this could help you you will find Hashing examples in different languages: ruby, python, Go,...: https://gist.github.com/jasny/2200f68f8109b22e61863466374a5c1d

Kais Chrif
  • 134
  • 5