如何纠正 TypeError:Unicode 对象在散列之前必须进行编码?

2025-02-20 09:23:00
admin
原创
27
摘要:问题描述:我有这个错误:Traceback (most recent call last): File "python_md5_cracker.py", line 27, in <module> m.update(line) TypeError: Unicode-obj...

问题描述:

我有这个错误:

Traceback (most recent call last):
  File "python_md5_cracker.py", line 27, in <module>
  m.update(line)
TypeError: Unicode-objects must be encoded before hashing

当我尝试在Python 3.2.2中执行此代码时:

import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides?  ")
wordlist = input("What is your wordlist?  (Enter the file name)  ")
try:
  hashdocument = open(hash_file, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  hash = hashdocument.readline()
  hash = hash.replace("
", "")

try:
  wordlistfile = open(wordlist, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  pass
for line in wordlistfile:
  # Flush the buffer (this caused a massive problem when placed 
  # at the beginning of the script, because the buffer kept getting
  # overwritten, thus comparing incorrect hashes)
  m = hashlib.md5()
  line = line.replace("
", "")
  m.update(line)
  word_hash = m.hexdigest()
  if word_hash == hash:
    print("Collision! The word corresponding to the given hash is", line)
    input()
    sys.exit()

print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()

解决方案 1:

它可能正在寻找来自的字符编码wordlistfile

wordlistfile = open(wordlist,"r",encoding='utf-8')

或者,如果您逐行进行操作:

line.encode('utf-8')

编辑

根据以下评论和这个答案。

我上面的回答假设所需的输出是str来自wordlist文件的。如果您习惯于使用bytes,那么最好使用。open(wordlist, "rb")但重要的是要记住,如果您将其与的输出进行比较,则hashfile不应使用。输出 a并且不能直接与字节对象进行比较:。(这个话题还有很多内容,但我没有时间)。rb`hexdigesthashlib.md5(value).hashdigest()str`'abc' != b'abc'

还应该注意这一行:

line.replace("
", "")

应该

line.strip()

这对字节和字符串都有效。但如果您决定只转换为bytes,则可以将行更改为:

line.replace(b"
", b"")

解决方案 2:

你必须定义encoding formatutf-8,试试这种简单的方法,

此示例使用 SHA256 算法生成一个随机数:

>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'

解决方案 3:

import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())

解决方案 4:

错误已经说明了你必须做什么。MD5 对字节进行操作,因此你必须将 Unicode 字符串编码为bytes,例如使用line.encode('utf-8')

解决方案 5:

存储密码(PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()

解决方案 6:

对这一行进行编码帮我修复了这个问题。

m.update(line.encode('utf-8'))

解决方案 7:

请先看一下那个答案。

现在,错误消息很清楚:您只能使用字节,而不能使用 Python 字符串(以前unicode在 Python <3 中),因此您必须使用您喜欢的编码对字符串进行编码:utf-32,,utf-16甚至utf-8是受限制的 8 位编码之一(有些人可能称之为代码页)。

当你从文件中读取时,Python 3 会自动将单词列表文件中的字节解码为 Unicode。我建议你这样做:

m.update(line.encode(wordlistfile.encoding))

这样推送到 md5 算法的编码数据就与底层文件完全一样编码。

解决方案 8:

您可以以二进制模式打开该文件:

import hashlib

with open(hash_file) as file:
    control_hash = file.readline().rstrip("
")

wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
    if hashlib.md5(line.rstrip(b'

')).hexdigest() == control_hash:
       # collision

解决方案 9:

如果它是单行字符串,则用 b 或 B 包装它。例如:

variable = b"This is a variable"

或者

variable2 = B"This is also a variable"

解决方案 10:

此程序是上述 MD5 破解程序的无错误增强版,可读取包含散列密码列表的文件,并将其与英语词典单词列表中的散列单词进行核对。希望对您有所帮助。

我从以下链接下载了英语词典
https://github.com/dwyl/english-words

# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words 

import hashlib, sys

hash_file = 'exercisehashed.txt'
wordlist = 'data_setsenglish_dictionarywords.txt'

try:
    hashdocument = open(hash_file,'r')
except IOError:
    print('Invalid file.')
    sys.exit()
else:
    count = 0
    for hash in hashdocument:
        hash = hash.rstrip('
')
        print(hash)
        i = 0
        with open(wordlist,'r') as wordlistfile:
            for word in wordlistfile:
                m = hashlib.md5()
                word = word.rstrip('
')            
                m.update(word.encode('utf-8'))
                word_hash = m.hexdigest()
                if word_hash==hash:
                    print('The word, hash combination is ' + word + ',' + hash)
                    count += 1
                    break
                i += 1
        print('Itiration is ' + str(i))
    if count == 0:
        print('The hash given does not correspond to any supplied word in the wordlist.')
    else:
        print('Total passwords identified is: ' + str(count))
sys.exit()
相关推荐
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1325  
  IPD(Integrated Product Development)流程作为一种先进的产品开发管理模式,在众多企业中得到了广泛应用。它涵盖了从产品概念产生到产品退市的整个生命周期,通过整合跨部门团队、优化流程等方式,显著提升产品开发的效率和质量,进而为项目的成功奠定坚实基础。深入探究IPD流程的五个阶段与项目成功之间...
IPD流程分为几个阶段   4  
  华为作为全球知名的科技企业,其成功背后的管理体系备受关注。IPD(集成产品开发)流程作为华为核心的产品开发管理模式,其中的创新管理与实践更是蕴含着丰富的经验和深刻的智慧,对众多企业具有重要的借鉴意义。IPD流程的核心架构IPD流程旨在打破部门墙,实现跨部门的高效协作,将产品开发视为一个整体的流程。它涵盖了从市场需求分析...
华为IPD是什么   3  
  IPD(Integrated Product Development)研发管理体系作为一种先进的产品开发模式,在众多企业的发展历程中发挥了至关重要的作用。它不仅仅是一套流程,更是一种理念,一种能够全方位提升企业竞争力,推动企业持续发展的有效工具。深入探究IPD研发管理体系如何助力企业持续发展,对于众多渴望在市场中立足并...
IPD管理流程   3  
  IPD(Integrated Product Development)流程管理旨在通过整合产品开发流程、团队和资源,实现产品的快速、高质量交付。在这一过程中,有效降低成本是企业提升竞争力的关键。通过优化IPD流程管理中的各个环节,可以在不牺牲产品质量和性能的前提下,实现成本的显著降低,为企业创造更大的价值。优化产品规划...
IPD流程分为几个阶段   4  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用