python hashlib不同哈希值用于相同内容的复制文件

时间:2018-07-19 14:29:45

标签: python python-2.7

运行python 2.7并尝试将两个不同文件的哈希计算为变量,以便我可以在布尔循环中进行比较和使用。首先,我在file1中生成内容,然后将file1复制到file2并针对file1和file2运行,我使用python hashlib获得了不同的哈希值,但是针对两个不同的文件名运行了powershell get-filehash,我得到了相同的哈希值(因为我预期)。

file1和file2之间没有内容差异,只需创建包含内容的file1并复制到file2。

import sys
import hashlib

goldresulthashVar = None
testresulthashVar = None


def sha256hashcheck1():
    with open( 'goldresult.txt' ,"rb") as f:
        # Read and update hash string value in blocks of 4K
        for byte_block in iter(lambda: f.read(4096),b""):
            sha256_hash.update(byte_block)
        goldresulthashVar = sha256_hash.hexdigest()
        print goldresulthashVar

def sha256hashcheck2():
    with open( 'test.txt' ,"rb") as f2:
        # Read and update hash string value in blocks of 4K
        for byte_block in iter(lambda: f2.read(4096),b""):
            sha256_hash.update(byte_block)
        testresulthashVar = sha256_hash.hexdigest()
        print testresulthashVar     

sha256hashcheck1()
sha256hashcheck2()

有什么建议或建议吗?

1 个答案:

答案 0 :(得分:1)

验证了我的脚本打算散列的文本文件的大小,并切换为一个小的单个文件,并且根据Andrej对文档的指示没有更新。

def sha256hashcheck1():
    with open( 'goldresult.txt' ,"rb") as f:
        bytes = f.read() # read entire file as bytes
        goldresulthashVar = hashlib.sha256(bytes).hexdigest();
        print(goldresulthashVar)

现在可以很好地确认多个文件之间的哈希值。