简体   繁体   English

Python:使用Hashlib生成文件的MD5哈希

[英]Python: Generating a MD5 Hash of a file using Hashlib

I am trying to generate hashes of files using hashlib inside Tkinter modules. 我正在尝试在Tkinter模块中使用hashlib生成文件的哈希。 My goal: 我的目标:

Step 1:- Button (clicked), opens up a browser (click file you want a hash of). 步骤1:-按钮(单击),打开浏览器(单击您要作为哈希值的文件)。 Step 2:- Once file is chosen, choose output file (.txt) where the hash will be 'printed'. 步骤2:-选择文件后,选择将在其中“打印”哈希的输出文件(.txt)。 Step 3:- Repeat and have no clashes. 步骤3:-重复,没有冲突。

from tkinter.filedialog import askopenfilename
import hashlib

def hashing():
    hash = askopenfilename(title="Select file for Hashing")
    savename = askopenfilename(title="Select output")
    outputhash = open(savename, "w")
    hash1 = open(hash, "r")
    h = hashlib.md5()
    print(h.hexdigest(), file=outputhash)
    love.flush()

It 'works' to some extent, it allows an input file and output file to be selected. 它在某种程度上“起作用”,它允许选择输入文件和输出文件。 It prints the hash into the output file. 它将散列打印到输出文件中。

HOWEVER - If i choose ANY different file, i get the same hash everytime. 但是-如果我选择任何其他文件,则每次都会得到相同的哈希值。

Im new to Python and its really stumping me. 我是Python的新手,它确实让我感到难过。

Thanks in advance. 提前致谢。


Thanks for all your comments. 谢谢你们的评论。

I figured the problem and this is my new code: 我发现了问题,这是我的新代码:

from tkinter.filedialog import askopenfilename
import hashlib

def hashing():
    hash = askopenfilename(title="Select file for Hashing")
    savename = askopenfilename(title="Select output")
    outputhash = open(savename, "w")
    curfile = open(hash, "rb")
    hasher = hashlib.md5()
    buf = curfile.read()
    hasher.update(buf)
    print(hasher.hexdigest(), file=outputhash)
    outputhash.flush()

This code works, You guys rock. 这段代码有效,各位。 :) :)

In your case you do the digest of the empty string and probably you get: d41d8cd98f00b204e9800998ecf8427e 在您的情况下,您将对空字符串进行摘要,并且可能会得到: d41d8cd98f00b204e9800998ecf8427e

I used this method to digest, that is better for big files (see here ). 我用这种方法来消化,这对于大文件来说更好(请参阅此处 )。

   md5 = hashlib.md5()
   with open(File, "rb") as f:
       for block in iter(lambda: f.read(128), ""):
           md5.update(block)
   print(md5.hexdigest())

A very simple way 一个非常简单的方法

from hashlib import md5

f=open("file.txt","r")
data=f.read()
f.close()
Hash=md5(data).hexdigest()
out=open("out.txt","w")
out.write(Hash)
out.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM