【问题标题】:python hashlib different hashes for a copied file of the same contentpython hashlib 相同内容的复制文件的不同哈希值
【发布时间】:2018-07-21 03:24:08
【问题描述】:

运行 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()

有什么指点或建议吗?

【问题讨论】:

  • 这是什么sha256_hash?如果您连续调用update(a)update(b),您只需执行update(a+b)docs.python.org/3/library/hashlib.html#hashlib.hash.update。试试hashlib.sha256(byte_block).hexdigest()
  • 对不起 - 当我粘贴我的脚本时错过了一个 var 声明,同时也在执行: sha256_hash = hashlib.sha256() 作为脚本开头的声明 var ...现在阅读你的 hashlib 引用, ty

标签: python python-2.7


【解决方案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)

现在跨多个文件获得良好的可确认哈希。

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多