[英]Python hashlib module producing strange results
我正在使用hashlib
模块来测试有关哈希算法的假设,但结果hashlib
奇怪。 我使用Windows fciv
程序检查结果。 我正在使用的工作流程是这样的:
fciv
测试结果。 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.algorithm
是md5
而args.file
是用户提供的文件名。
始终使用ab+
以二进制模式打开文件。 否则,Windows上的Python将使用文本模式来处理其认为是文本文件的内容。
但是我确实想知道,如果您打算像使用ab+
一样读取整个文件,那么为什么要使用ab+
而不是rb+
那么文件指针从rb+
的结尾处开始,而与rb+
它从文件的开头开始。
有关文件模式的详细列表,请参见https://stackoverflow.com/a/23566951 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.