如何在python中实现ruby int(16).to_s(32)



我在ruby中有以下代码:

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

我尝试在python中实现它:

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

当我在ruby中运行字符串test的代码时,我得到了l558vpecm6dqc72c11pt74f9guc2veuj在python中,我得到VFFI7ZOMWGN2MHCMBBZ5HEPJQ6MC7O6Tpython代码出了什么问题?如何获得与ruby相同的结果?

使用gmpy:

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

如果您不想使用gmpy,并且需要digits的原生Python版本,那么您可以在这里找到几个实现。

我希望这能帮助您找到不同语言中的哈希示例:ruby、python、Go…:https://gist.github.com/jasny/2200f68f8109b22e61863466374a5c1d

最新更新