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

相关文章

  • 一文带你探寻Python中的迭代器

    一文带你探寻Python中的迭代器

    你知道for...in是底层原理是什么样的么?这篇文章就来和大家详细讲一讲Python中迭代器的的相关知识,文中的示例代码讲解详细,感兴趣的可以了解一下
    2023-04-04
  • Django动态展示Pyecharts图表数据的几种方法

    Django动态展示Pyecharts图表数据的几种方法

    本文主要介绍了Django动态展示Pyecharts图表数据的几种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • 在pycharm中执行 os.makedirs 提示用户名或密码不正确的问题及解决方法

    在pycharm中执行 os.makedirs 提示用户名或密码不正确的问题及解决方法

    这篇文章主要介绍了在pycharm中执行 os.makedirs 提示用户名或密码不正确的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-01-01
  • 在pycharm中实现删除bookmark

    在pycharm中实现删除bookmark

    今天小编就为大家分享一篇在pycharm中实现删除bookmark,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • pandas按行按列遍历Dataframe的几种方式

    pandas按行按列遍历Dataframe的几种方式

    这篇文章主要介绍了pandas按行按列遍历Dataframe的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 纯numpy卷积神经网络实现手写数字识别的实践

    纯numpy卷积神经网络实现手写数字识别的实践

    本文主要介绍了纯numpy卷积神经网络实现手写数字识别的实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Python 变量教程私有变量详解

    Python 变量教程私有变量详解

    这篇文章主要介绍了Python 变量教程私有变量详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • Python+Selenium实现表单自动填充和提交

    Python+Selenium实现表单自动填充和提交

    你是不是也厌倦了每天重复表单填写的工作,是时候让技术来帮助我们解放双手了,下面小编就为大家介绍一下如何使用Selenium和Python来自动填充和提交表单
    2023-09-09
  • Python如何使用Gitlab API实现批量的合并分支

    Python如何使用Gitlab API实现批量的合并分支

    这篇文章主要介绍了Python如何使用Gitlab API实现批量的合并分支,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • NumPy索引与切片的用法示例总结

    NumPy索引与切片的用法示例总结

    numpy 数组索引是一个大话题,有很多种方式可以让你选中数据的子集或某个单个元素,一维数组比较简单,看起来和 python 的列表很类似,这篇文章主要给大家介绍了关于NumPy索引与切片用法的相关资料,需要的朋友可以参考下
    2021-07-07

最新评论