我正在遍历一个包含二进制文件的文件夹,并尝试计算每个文件的哈希值,特别是 sha1 和 sha256。在我的运行中,我奇怪地为所有文件获得了相同的 sha256 值,但 sha1 值不同(因此是正确的)。
下面是一个输出文件的屏幕截图,它显示了 sha1 散列已正确完成。但 sha256 不是。(对不起,每个二进制文件的文件名也是它的 sha1)
我的过程有问题吗?这是 Python 中的相关代码。我没有看到任何东西。对不起。
out.write("FILENAME,SHA1,SHA256\n")
for root, dirs, files in os.walk(input_path):
for ffile in files:
myfile = os.path.join(root, ffile)
nice = os.path.join(os.getcwd(), myfile)
fo = open(nice, "rb")
a = hashlib.sha1(fo.read())
b = hashlib.sha256(fo.read())
paylname = os.path.basename(myfile)
mysha1 = str(a.hexdigest())
mysha256 = str(b.hexdigest())
fo.close()
out.write("{0},{1},{2}\n".format(paylname, mysha1, mysha256))
正如我在上面的评论中所说的那样,您正在为第一个散列读取整个文件,但是您需要回到文件的开头以第二次读取它以获取第二个散列。或者,您可以将其存储在一个变量中,并将其传递给每个哈希。
out.write("FILENAME,SHA1,SHA256\n")
for root, dirs, files in os.walk(input_path):
for ffile in files:
myfile = os.path.join(root, ffile)
nice = os.path.join(os.getcwd(), myfile)
fo = open(nice, "rb")
a = hashlib.sha1(fo.read())
fo.seek(0,0) # seek back to start of file
b = hashlib.sha256(fo.read())
paylname = os.path.basename(myfile)
mysha1 = str(a.hexdigest())
mysha256 = str(b.hexdigest())
fo.close()
out.write("{0},{1},{2}\n".format(paylname, mysha1, mysha256))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句