2014-10-18 98 views
1

我正在尝试创建一个名为checksum.dat的文件,其中包含Python中名为index.txt的文件的SHA256哈希。如何从Python中的.txt文件生成checksum.dat哈希文件

我想出迄今:

import hashlib 
with open("index.txt", "rb") as file3: 
    with open("checksum.dat", "wb") as file4: 
     file_checksum = hashlib.sha256() 
     file_checksum.update(file3) 
     file_checksum.digest() 

     print(file_checksum) 
     file4.write(file_checksum) 

我希望它打印散列到控制台,并把它写到文件checksum.dat。

但我得到的是这样的错误:

File "...", line 97, in main 
file_checksum.update(file3) 
TypeError: object supporting the buffer API required 

什么我GOOGLE到目前为止是,你不能让一个哈希出一个字符串,从我的理解,只能从字节对象或东西。不知道如何将我的index.txt放入我可以使用的对象中。

任何人都知道如何解决这个问题?请记住我是一个新手。

+0

其中Python版本是你的工作吗? – 2014-10-18 13:38:16

+0

我关于Python 3.4.2 – LoLei 2014-10-18 14:22:01

回答

0

你必须养活index.txt内容,所以问题就出在这里:

file_checksum.update(file3) 

file3是文件指针index.txt文件并没有文件的内容。要获取内容,请执行read()。所以下面应该修复它:

file_checksum.update(file3.read()) 

所以,你的完整代码如下:

import hashlib 
with open("index.txt", "rb") as file3: 
     file_checksum = hashlib.sha256() 
     for line in file3: 
      file_checksum.update(line) 
      file_checksum.hexdigest() 
     print(file_checksum.hexdigest()) 

with open("checksum.dat", "wb") as file4:   
     file4.write(bytes(file_checksum.hexdigest(), 'UTF-8')) 
+0

现在,我得到以下异常: 'file4.write(file_checksum) 类型错误:“_hashlib.HASH”不支持interface' – LoLei 2014-10-18 14:26:23

+0

缓冲区不读取整个文件一次,否则你的程序将窒息大输入。另外,不要使用'encode()',因为它可能会改变原始表示(以及哈希码)。 – 2014-10-18 14:32:53

+0

@StefanoSanfilippo - 更新了答案,现在它逐行读取并计算校验和。如果您有任何其他建议,请告诉我。 – avi 2014-10-18 14:48:51