如何在Python中计算文件内容的MD5校验和?

问题描述

情况是:我使用以下代码为存储在服务器上的pdf文件生成了md5校验和:

 def createMd5Hash(self,file_path,pdf_title,pdf_author):
    md5_returned = None
    try:
        md5 = hashlib.md5()
        with open(file_path,'rb') as file_to_check:
            for chunk in file_to_check:
                md5.update(chunk)
            md5_file = md5.hexdigest()
            custom_key = 'xyzkey-{}'.format(md5_file)
            md5.update(custom_key.encode())
            md5_returned = md5.hexdigest()
    except Exception as e:
        print("Error while calculate md5: {}".format(e))
  
    # code to add Hash value in Metadata
    try:
        file = open(file_path,'rb+')
        reader = PdfFileReader(file)
        writer = PdfFileWriter()
        writer.appendPagesFromreader(reader)
        Metadata = reader.getDocumentInfo()
        writer.addMetadata(Metadata)
        writer.addMetadata({
            '/Author': pdf_author,'/Title': pdf_title,'/HashKey': md5_returned,})
        writer.write(file)
        file.close()
    except Exception:
        print("Error while editing Metadata")

示例:HashKey = 02c85672c041c8c762474799690ad1a5

在第二部分中,我添加了元数据,包括pdf中的哈希值。 现在,客户可以从我的服务器下载此文件(可以修改,也可以不修改)。 当我从任何客户那里收到文件时,我想检查该文件的完整性。天气文件数据是否被修改。因此,我编写了一个实用程序,可以上传文件提取pdf文件的元数据,从中可以获取HashKey值,该值是文件生成时的原始哈希值。 当我尝试使用以下功能文件进行解码时,如果只是从服务器下载而不是由客户端修改,我想获得相同的哈希值。

def validateMd5Hash(file_path,current_md5):
md5_returned = None
try:
    md5 = hashlib.md5()
    with open(file_path,'rb') as file_to_check:
        # read contents of the file
        for chunk in file_to_check:
            md5.update(chunk)
        # pipe contents of the file through
        md5_file = md5.hexdigest()
        private_key = 'xyzkey-{}'.format(md5_file)
        md5.update(private_key.encode())
        md5_returned = md5.hexdigest()

    if md5_returned != current_md5:
        return True

    return False
except Exception as e:
    print("Error while calculate md5: {}".format(e))

,但结果不同。 md5_returned = fbf79424a68892887379108a05968437 current_md5 = 02c85672c041c8c762474799690ad1a5

当我使用上面的函数时,它生成的哈希值不同于创建时的哈希值。 我想原因是客户端下载文件,创建日期和修改日期更改时,这就是我得到新的md5校验和而不是HashKey内部内容的原因。 我正在寻找仅为文件内容生成哈希值,而不包含元数据。 有人可以帮我吗? 对不起,英语不好

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)