python - 逐行阅读 .txt 单词列表时如何获得正确的哈希值?

标签 python python-3.x hash md5 argparse

我正在尝试构建一个 Python3.x 脚本,该脚本读取 .txt 单词列表并将每一行中的单词转换为其散列等效项,但是当我执行此脚本时,它会生成错误的散列。

希望你们能帮我弄清楚我在这里做错了什么..

输出

Arguments passed to the program:
Namespace(inputHashType=['md5'], verbose=True, 
    wordlist=_io.TextIOWrapper name='C:\\Users\\Mikael\\Desktop\\wordlist.txt' mode='rt' encoding='utf-8')
Verbose is set to: True

correct hash:  b61a6d542f9036550ba9c401c80f00ef
Line 1:  PT: tests      As hash: a58c6e40436bbb090294218b7d758a15

输入文件示例:

tests
tests1
tests2

源代码

import argparse
import sys
from Crypto.Hash import MD5, SHA1, SHA224, SHA256, SHA384, SHA512


parser = argparse.ArgumentParser(description='Hash production')
parser.add_argument('-v', action='store_true', dest='verbose', default=False, help='Print attempts')
parser.add_argument('-t', nargs=1, dest='inputHashType', help='Hash type')
parser.add_argument('-d', nargs='?', dest='wordlist', type=argparse.FileType('rt', encoding='utf-8'), default=sys.stdin, help='Dictionary (as file)')
args =  parser.parse_args()

inputHashType = ''.join(map(str, args.inputHashType)) # Formats args list as string
inputHashType.lower()

if inputHashType == 'md5':
    htype = MD5.new()

try:
    if args.verbose:
        with args.wordlist as file:
            line = file.readline()
            cnt = 1
            while line:
                word = line.encode('utf-8').rstrip()
                hashed = htype.update(word)
                hashed = htype.hexdigest()
                print("Line {}:  PT: {}      As hash: {}".format(cnt, line.strip(), hashed))
                line = file.readline()
                cnt += 1
    else:
        break
except:
    print('Error')

最佳答案

问题在于,在代码的 try block 中,您通过 update( ) 方法。这不会计算该输入字符串的哈希值,但会累积输入并评估截至该点的累积字符串的哈希值。

使用 md5sum 很容易看出这是发生了什么:

$ echo -n 'tests' | md5sum
b61a6d542f9036550ba9c401c80f00ef  -    # Identical to your 1st output line
$ echo -n 'teststests' | md5sum         # This is what you're calculating
a58c6e40436bbb090294218b7d758a15  -    # Identical to your 2nd output line.

要评估每个新输入的哈希值,您需要通过调用 new() 方法重新初始化一个新的 MD5 实例。

关于python - 逐行阅读 .txt 单词列表时如何获得正确的哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824301/

相关文章:

ruby - CSV 处理 with1.9.2 - 使用选项哈希时,多行作为单个数组返回

python - Selenium 检查元素是否无一异常(exception)地存在

Python:从派生类获取基类值

python正则表达式去除重复的单词

python - 删除重音符号并保留在 Python 中的点下

python-3.x - python中变量的聚类

python - 属性错误: 'WebElement' object has no attribute 'copy' error when moved the function Select to a common file using Selenium Python through Django

python - 查看函数是否被调用

java - 内部对象更改时 HashSet 的哈希解决方法

c# - 如何挑选质数来计算哈希码?