Python 获取md5值(hashlib)常用方法

 更新时间:2023年07月18日 11:34:37   作者:墨痕诉清风  
这篇文章主要介绍了Python获取md5值(hashlib)常用方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

常用方法 

import hashlib
# 创建MD5对象,可以直接传入要加密的数据
m = hashlib.md5('123456'.encode(encoding='utf-8'))
# m = hashlib.md5(b'123456') 与上面等价
print(hashlib.md5('123456'.encode(encoding='utf-8')).hexdigest())
print(m) 
print(m.hexdigest()) # 转化为16进制打印md5值

结果

<md5 HASH object @ 0x000001C67C71C8A0>
e10adc3949ba59abbe56e057f20f883e

如果要被加密的数据太长,可以分段update, 结果是一样的

import hashlib
str = 'This is a string.'
m = hashlib.md5()
m.update('This i'.encode('utf-8'))
m.update('s a string.'.encode('utf-8'))
print(m.hexdigest())

结果

13562b471182311b6eea8d241103e8f0

封装成常用库md5.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
def get_file_md5(file_name):
    """
    计算文件的md5
    :param file_name:
    :return:
    """
    m = hashlib.md5()   #创建md5对象
    with open(file_name,'rb') as fobj:
        while True:
            data = fobj.read(4096)
            if not data:
                break
            m.update(data)  #更新md5对象
    return m.hexdigest()    #返回md5对象
def get_str_md5(content):
    """
    计算字符串md5
    :param content:
    :return:
    """
    m = hashlib.md5(content) #创建md5对象
    return m.hexdigest()

某源码封装

class Files(Storage):
    @staticmethod
    def temp_put(content, path=None):
        """Store a temporary file or files.
        @param content: the content of this file
        @param path: directory path to store the file
        """
        fd, filepath = tempfile.mkstemp(
            prefix="upload_", dir=path or temppath()
        )
        if hasattr(content, "read"):
            chunk = content.read(1024)
            while chunk:
                os.write(fd, chunk)
                chunk = content.read(1024)
        else:
            os.write(fd, content)
        os.close(fd)
        return filepath
    @staticmethod
    def temp_named_put(content, filename, path=None):
        """Store a named temporary file.
        @param content: the content of this file
        @param filename: filename that the file should have
        @param path: directory path to store the file
        @return: full path to the temporary file
        """
        filename = Storage.get_filename_from_path(filename)
        #dirpath = tempfile.mkdtemp(dir=path or temppath())
        dirpath = temppath()
        Files.create(dirpath, filename, content)
        return os.path.join(dirpath, filename)
    @staticmethod
    def create(root, filename, content):
        if isinstance(root, (tuple, list)):
            root = os.path.join(*root)
        filepath = os.path.join(root, filename)
        with open(filepath, "wb") as f:
            if hasattr(content, "read"):
                chunk = content.read(1024 * 1024)
                while chunk:
                    f.write(chunk)
                    chunk = content.read(1024 * 1024)
            else:
                f.write(content)
        return filepath
    @staticmethod
    def copy(path_target, path_dest):
        """Copy a file. The destination may be a directory.
        @param path_target: The
        @param path_dest: path_dest
        @return: path to the file or directory
        """
        shutil.copy(src=path_target, dst=path_dest)
        return os.path.join(path_dest, os.path.basename(path_target))
    @staticmethod
    def hash_file(method, filepath):
        """Calculate a hash on a file by path.
        @param method: callable hashing method
        @param path: file path
        @return: computed hash string
        """
        f = open(filepath, "rb")
        h = method()
        while True:
            buf = f.read(1024 * 1024)
            if not buf:
                break
            h.update(buf)
        return h.hexdigest()
    @staticmethod
    def md5_file(filepath):
        return Files.hash_file(hashlib.md5, filepath)
    @staticmethod
    def sha1_file(filepath):
        return Files.hash_file(hashlib.sha1, filepath)
    @staticmethod
    def sha256_file(filepath):
        return Files.hash_file(hashlib.sha256, filepath)

到此这篇关于Python 获取md5值(hashlib)的文章就介绍到这了,更多相关Python 获取md5值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python3.10接入ChatGPT实现逐句回答流式返回

    Python3.10接入ChatGPT实现逐句回答流式返回

    这篇文章主为大家要介绍了Python3.10接入ChatGPT实现逐句回答流式返回示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • python中将\\uxxxx转换为Unicode字符串的方法

    python中将\\uxxxx转换为Unicode字符串的方法

    这篇文章主要介绍了python中将\\uxxxx转换为Unicode字符串的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • .dcm格式文件软件读取及python处理详解

    .dcm格式文件软件读取及python处理详解

    今天小编就为大家分享一篇.dcm格式文件软件读取及python处理详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Python数据处理的三个实用技巧分享

    Python数据处理的三个实用技巧分享

    数据处理无所不在,掌握常用技巧,事半功倍。这篇文章将使用Pandas开展数据处理分析,总结其中常用、好用的数据分析技巧,感兴趣的可以学习一下
    2022-04-04
  • Python中如何将一个类方法变为多个方法

    Python中如何将一个类方法变为多个方法

    这篇文章主要介绍了Python中如何将一个类方法变为多个方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • hmac模块生成加入了密钥的消息摘要详解

    hmac模块生成加入了密钥的消息摘要详解

    这篇文章主要介绍了hmac模块生成加入了密钥的消息摘要详解,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • Python实现人机中国象棋游戏

    Python实现人机中国象棋游戏

    中国象棋是一种古老的棋类游戏,大约有两千年的历史。本文将介绍如何通过Python中的Pygame模块实现人机中国象棋游戏,感兴趣的可以学习一下
    2022-01-01
  • 详解Python3中的迭代器和生成器及其区别

    详解Python3中的迭代器和生成器及其区别

    本篇将介绍Python3中的迭代器与生成器,描述可迭代与迭代器关系,并实现自定义类的迭代器模式。非常具有实用价值,需要的朋友可以参考下
    2018-10-10
  • Python将图片转为漫画风格的示例

    Python将图片转为漫画风格的示例

    本文主要介绍了Python将图片转为漫画风格的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Python对列表排序的方法实例分析

    Python对列表排序的方法实例分析

    这篇文章主要介绍了Python对列表排序的方法,实例分析了Python列表排序函数的相关使用技巧,非常简单实用,需要的朋友可以参考下
    2015-05-05

最新评论