Python hashlib常见摘要算法详解

yipeiwu_com6年前Python基础

这篇文章主要介绍了Python hashlib常见摘要算法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等

计算出一个字符串的MD5值:

import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode("utf8")) #需要指定转码 否则报错 update()必须指定要加密的字符串的字符编码
print( md5.hexdigest())#返回十六进制
print( md5.digest()) #二进制

# 如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的:
md5 = hashlib.md5()
md5.update('how to use md5 in '.encode("utf8"))
md5.update('python hashlib?'.encode("utf8"))
print( md5.hexdigest())#返回十六进制

上述结果:

d26a53750bc40b38b65a520292f69306
b'\xd2jSu\x0b\xc4\x0b8\xb6ZR\x02\x92\xf6\x93\x06'
d26a53750bc40b38b65a520292f69306

计算出一个字符串SHA1值:

import hashlib
sha_1 = hashlib.sha1()
sha_1.update('how to use sha1 in '.encode("utf8"))  #需要指定转码 否则报错 update()必须指定要加密的字符串的字符编码
sha_1.update('python hashlib?'.encode("utf8"))
print (sha_1.hexdigest())

# 如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的:
sha2 = hashlib.sha1()
sha2.update('how to use sha1 in python hashlib?'.encode("utf8"))
print (sha2.hexdigest())

打印结果:

2c76b57293ce30acef38d98f6046927161b46a44

2c76b57293ce30acef38d98f6046927161b46a44

读取文件获取MD5值:

import os
import hashlib
#文件md5
def file_md5(pathandname):
  if os.path.isfile(pathandname):
    hashmd5 = hashlib.md5()
    file = open(pathandname, 'rb')
    while True:
      b = file.read(1024)
      if not b:
        break
      hashmd5.update(b)
    file.close()
    return hashmd5.hexdigest()
  else:
    return None

print(file_md5("C:\\Users\\Administrator\\Desktop\\V2.6.1_B511\\hvr_dec"))   #aef87d1d673ca52412b4a950a06b9557

读取文件base64

import base64
import os
# base64,参数为文件路径名
def file_base64(filepath):
  if os.path.isfile(filepath):
    with open(filepath, 'rb') as file:
      file_base64_str = base64.b64encode(file.read())
    return file_base64_str
  else:
    return None

读取sha256

import hmac
import hashlib
def get_hmacsha256(key, message):
  key_bytes = bytes(key, 'utf-8')
  message_bytes = bytes(message, 'utf-8')
  hmacsha256_str = hmac.new(key_bytes, message_bytes, digestmod=hashlib.sha256).hexdigest()
  return hmacsha256_str

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

itchat-python搭建微信机器人(附示例)

itchat是python开源第三方库,用于搭建微信机器人,几十行代码就能帮你实现自动的处理所有信息。比如,添加好友,搭建自动回复机器人,还原撤销信息,分析好友男女比例,地理分布情况,爬...

python实现模拟按键,自动翻页看u17漫画

python 适用于windows平台 使用 win32gui,win32api,win32con 包 simu_read.py 复制代码 代码如下: #-*- coding=utf-...

python os用法总结

python os用法总结

前言:在自动化测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告(从而发送测试报告邮件),经常要对大量文件和大量路径进行操作,这就依赖于os模块,所...

python利用跳板机ssh远程连接redis的方法

公司服务器的mysql和redis连接都需要有跳板机,网上有很多python ssh远程连接mysql的,那天我研究了下,利用sshtunnel模块连接上了redis,具体如下: f...

python3利用venv配置虚拟环境及过程中的小问题小结

python3利用venv配置虚拟环境及过程中的小问题小结

在利用python进行flask等开发过程中经常需要配置虚拟环境以方便针对不同的项目需求配置不同的生产环境。在python3.3之前,需要利用virtualenv等工具来实现python...