【问题标题】:How to turn items in an array into bytes for hashing?如何将数组中的项目转换为字节以进行散列?
【发布时间】:2020-06-14 01:41:48
【问题描述】:

我正在尝试对通过 easygui 输入的用户输入进行哈希处理。 Easygui 将输入存储到一个数组中(我认为),所以当我尝试对用户输入进行哈希处理时,我不确定如何将其变成一个字节。

这是我的代码:

import hashlib
import easygui


g = hashlib.sha256(b'helloworld').hexdigest()

l = easygui.enterbox('enter password')

f = hashlib.sha256([l]).hexdigest()

print(g)
print(f)

理想情况下,如果我在 easygui 中键入“helloworld”,它应该返回相同的散列输出。

目前的错误是:

"TypeError: object supporting the buffer API required" at the line f = haslib.sha256([l]).hexdigest()

【问题讨论】:

  • 你为什么用 list([l]) 包裹l?我不知道easygui,但你可以试试hashlib.sha256(l) 而不是hashlib.sha256([l])
  • 你可以试试hashlib.sha256('helloworld'.encode())

标签: python python-3.x hash hashlib


【解决方案1】:

easygui.enterbox 返回用户输入的文本,如果取消操作,则返回 None。您必须将返回的文本转换为字节数组。 Docs

if l is not None:
    f = hashlib.sha256(l.encode()).hexdigest()

【讨论】:

  • 谢谢,这个解决方案有效。我也会阅读文档以更好地理解它。
【解决方案2】:

您必须对给定的字符串进行编码,然后才能对其进行哈希处理。最简单的方法是,只使用 for strings 实现的 encode() 方法。

f = hashlib.sha256(l.encode()).hexdigest() print(f)

返回您的 sha256 哈希值。

【讨论】:

    猜你喜欢
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多