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值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Opencv求取连通区域重心实例

    Opencv求取连通区域重心实例

    这篇文章主要介绍了Opencv求取连通区域重心实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Python+PyQT5实现手绘图片生成器

    Python+PyQT5实现手绘图片生成器

    这篇文章主要介绍了利用Python PyQT5制作一个手绘图片生成器,可以将导入的彩色图片通过python分析光源、灰度等操作生成手绘图片。感兴趣的可以跟随小编一起了解一下
    2022-02-02
  • python之当你发现QTimer不能用时的解决方法

    python之当你发现QTimer不能用时的解决方法

    今天小编就为大家分享一篇python之当你发现QTimer不能用时的解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • python实现员工管理系统

    python实现员工管理系统

    这篇文章主要介绍了python实现员工管理系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • Python中tqdm的使用和例子

    Python中tqdm的使用和例子

    Tqdm是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器tqdm(iterator),下面这篇文章主要给大家介绍了关于Python中tqdm的使用和例子的相关资料,需要的朋友可以参考下
    2022-09-09
  • python库h5py入门详解

    python库h5py入门详解

    本文只是简单的对h5py库的基本创建文件,数据集和读取数据的方式进行介绍,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Python告诉你木马程序的键盘记录原理

    Python告诉你木马程序的键盘记录原理

    今天小编就为大家分享一篇关于Python告诉你木马程序的键盘记录原理,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Python文件操作之合并文本文件内容示例代码

    Python文件操作之合并文本文件内容示例代码

    众所周知Python文件处理操作方便快捷,下面这篇文章主要给大家介绍了关于Python文件操作之合并文本文件内容的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧。
    2017-09-09
  • 基于Python的socket库实现通信功能的示例代码

    基于Python的socket库实现通信功能的示例代码

    本文主要给大家介绍了如何使用python的socket库实现通信功能,这里简单的给每个客户端增加一个不重复的uid,客户端之间可以根据这个uid选择进行广播通信,感兴趣的小伙伴快来看看吧
    2023-08-08
  • OpenCV图像缩放之cv.resize()函数详解

    OpenCV图像缩放之cv.resize()函数详解

    resize函数opencv中专门用来调整图像大小的函数,下面这篇文章主要给大家介绍了关于OpenCV图像缩放之cv.resize()函数的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-09-09

最新评论