【问题标题】:How to implement ruby int(16).to_s(32) in python如何在python中实现ruby int(16).to_s(32)
【发布时间】:2020-07-08 08:29:16
【问题描述】:

我在 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 中我得到VFFI7ZOMWGN2MHCMBBZ5HEPJQ6MC7O6T python代码有什么问题?如何获得与 ruby​​ 相同的结果?

【问题讨论】:

  • 转换应该做什么?另外,您是否首先检查了摘要操作匹配的字符串结果?
  • 我不懂 Python,但要在 Ruby 中获取 Python 结果,可以使用base32 gem:Base32.encode(Digest::SHA1.digest('test'))。也许这有助于找到您的问题。
  • @KarlKnechtel 我们已经有了 ruby​​ 实现——我们使用结果作为标识符。现在我需要用 python 在新服务中实现它。是的,我确实检查了摘要本身是否匹配。
  • 一个版本使用digest;其他用途hexdigest?

标签: python ruby encode sha1


【解决方案1】:

使用gmpy

import hashlib
import gmpy2

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多