2017-08-24 82 views
-3

我遍历一个包含二进制文件的文件夹,并试图计算每个文件的哈希值,特别是sha1和sha256。在我的跑步中,我奇怪地为所有文件获得相同的sha256值,但sha1值不同(因此是正确的)。不同的SHA1但相同的SHA256

下面是一个输出文件的截图,显示sha1哈希是否正确完成。但sha256不是。 (每个二进制文件的文件名对不起也是它的SHA1)

wat is dis

有什么错我的过程吗?这是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)) 
+2

您认为'fo.read()'在读取文件内容时会读取什么内容? – deceze

+3

当你为sha1哈希执行'fo.read()'时,你已经读取了整个文件,但是你永远不会将光标移回到文件的开头。所以sha256散列的输入总是相同的(没有) –

+1

'hashlib.sha256(b'').hexdigest()=='e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'' –

回答

0

,因为我把我的评论上面,你正在阅读的第一哈希整个文件,但是你需要寻求回文件开始读它第二哈希第二次。或者你可以将它存储在一个变量中,并将其传递给每个散列。

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)) 
相关问题