Python MD4函数无法生成联机MD4哈希生成器中的哈希代码

2024-06-11 21:48:34 发布

您现在位置:Python中文网/ 问答频道 /正文

从Python生成的MD4哈希代码与在线生成的不同。我知道这一定是因为编码。你能帮忙吗

from Crypto.Hash import MD4

psk = 'The quick brown fox jumps over the lazy dog'

h = MD4.new()
h.update(psk.encode('UTF-16LE'))
print(f'UTF-16LE: {h.hexdigest()}')

h.update(psk.encode('UTF-16'))
print(f'UTF-16:   {h.hexdigest()}')

h.update(psk.encode('UTF-8'))
print(f'UTF8:     {h.hexdigest()}')

h.update(psk)
print(f'UTF8?:    {h.hexdigest()}')

“快速棕色狐狸跳过懒狗”在不同编码中的哈希输出为:

UTF-16LE: 4e6a076ae1b04a815fa6332f69e2e231
UTF-16:   db8ae265b09c6ffa1e2fc163d66f64a4
UTF8:     324563ee68cc8009c82778d70d958723
UTF8?:    1aaf934b705b1d2aab69b0cf2a9cd87b

联机MD4哈希函数(https://emn178.github.io/online-tools/md4.html)将给出

1bee69a46ba811185c194762abaeae90

更新

感谢您的评论,我已经更新了代码:


import getpass
from Crypto.Hash import MD4

psk = 'The quick brown fox jumps over the lazy dog' #getpass.getpass()

h = MD4.new(data=psk.encode('UTF-16LE'))
print(f'UTF-16LE: {h.hexdigest()}')

h = MD4.new(data=psk.encode('UTF-16'))
print(f'UTF-16:   {h.hexdigest()}')

h = MD4.new(data=psk.encode('UTF-8'))
print(f'UTF8:     {h.hexdigest()}')

h = MD4.new(data=psk)
print(f'UTF8?:    {h.hexdigest()}')

新的输出是

UTF-16LE: 4e6a076ae1b04a815fa6332f69e2e231
UTF-16:   c6274a58a30e434503b45d2ce95e6c19
UTF8:     1bee69a46ba811185c194762abaeae90
UTF8?:    1bee69a46ba811185c194762abaeae90

我还发现https://emn178.github.io/online-tools/md4.html使用UTF-16,尽管我给它传递了一个UTF-16LE编码的文件

WPA2 Enterprise要求文本以UTF-16LE编码


Tags: 代码fromimport编码newdataupdateutf8
2条回答

使用update,您显然会更新散列,这意味着您会输入更多的消息片段。因此,实际上,您使用不同的编码多次输入字符串,这最终会给出一个不仅仅是字符串的哈希值

如果只更新一次,将得到预期的结果

from Crypto.Hash import MD4

psk = 'The quick brown fox jumps over the lazy dog'

h = MD4.new()

h.update(psk.encode('UTF-8'))
print(f'UTF8:     {h.hexdigest()}')

摘自digest的文档,其中hexdigest方法是一种衍生方法:

Return the digest of the strings passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes.

我不知道pip是从哪里安装的Crypto模块,所以我无法测试

但只需尝试以下代码:

from Crypto.Hash import MD4

psk = 'The quick brown fox jumps over the lazy dog'

Now that you gave me the information of how

h = MD4.new()
h.update(psk.encode('UTF-16LE'))
print(f'UTF-16LE: {h.hexdigest()}')

h = MD4.new()
h.update(psk.encode('UTF-16'))
print(f'UTF-16:   {h.hexdigest()}')

h = MD4.new()
h.update(psk.encode('UTF-8'))
print(f'UTF8:     {h.hexdigest()}')

h = MD4.new()
h.update(psk)
print(f'UTF8?:    {h.hexdigest()}')

既然您给了我包的pip名称,我可以确认,您的原始代码中的错误是继续更新同一个哈希值,而不是使用新的哈希值(或者重置它)

我得到了正确的结果

相关问题 更多 >