繁体   English   中英

Python hashlib模块产生奇怪的结果

[英]Python hashlib module producing strange results

我正在使用hashlib模块来测试有关哈希算法的假设,但结果hashlib奇怪。 我使用Windows fciv程序检查结果。 我正在使用的工作流程是这样的:

  1. 从用户那里收集文件和算法。
  2. 使用该算法打印出原始文件名和哈希文件。
  3. 在Windows中使用fciv测试结果。
  4. 在文件中添加一些字节或空格字符。
  5. 使用所选算法打印出新的哈希文件。
  6. 使用fciv的更新文件测试结果。

问题是这样的:

当我使用.txt文件时,从程序和fciv获得了与预期不同的结果。 这很完美。

这是输出:

Original Filename: example_docs\testDocument.txt
Original md5 Hash: 62bef8046d4bcbdc46ac81f5e4202fe7
Updated md5 Hash: 78a96b792cf2ea160db5e4823f4bf0c5

但是,当我使用.mp4视频文件时, fciv显示不同的哈希值,但我的程序却没有。

这是输出:

Original Filename: example_docs\testVideo.mp4
Original md5 Hash: 9a7dcb986e2e756dda60e851a0b03916
Updated md5 Hash: 9a7dcb986e2e756dda60e851a0b03916

不管我运行程序多少次,哈希在程序输出中都保持不变,但是fciv显示不同的结果。

这是我的代码段:

def getHash(filename, algorithm):
    h = hashlib.new(algorithm)
    h.update(filename)
    return h.hexdigest()

print "Original Filename: {file}".format(file=args.file)
with open(args.file, "a+") as inFile:
    h = getHash(inFile.read(), args.algorithm)
    print "Original {hashname} Hash: {hashed_file}".format(hashname=args.algorithm, hashed_file=h)              

with open(args.file, "a+") as inFile:               
    inFile.write(b'\x07\x08\x07') # Also worked with inFile.write(" ")

with open(args.file, "a+") as inFile:
    h = getHash(inFile.read(), args.algorithm)
        print "Updated {hashname} Hash: {hashed_file}".format(hashname=args.algorithm, hashed_file=h)

其中args.algorithmmd5args.file是用户提供的文件名。

始终使用ab+以二进制模式打开文件。 否则,Windows上的Python将使用文本模式来处理其认为是文本文件的内容。

但是我确实想知道,如果您打算像使用ab+一样读取整个文件,那么为什么要使用ab+而不是rb+那么文件指针从rb+的结尾处开始,而与rb+它从文件的开头开始。

有关文件模式的详细列表,请参见https://stackoverflow.com/a/23566951

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM