第十章、hashlib模块和hmac模块

第十章、hashlib模块和hmac模块

一、hashlib模块

hash是一种算法,接收传入的内容,经过运算得到的一串hash值

hash的特点:

  1. 具有唯一性
  2. 安全性,可以用于保存非明文密码
  3. 无论传入的什么内容,返回的hash值长度都是固定的
import hashlib
m=hashlib.md5() #创建了hash对象
print(type(m)) #<class '_hashlib.HASH'>
m.update("hello".encode('utf8'))#必须写编码格式否则报错
print(m.hexdigest())    #得到hash值
#5d41402abc4b2a76b9719d911017c592
m.update("hel".encode('utf8'))
m.update("lo".encode('utf8'))
print(m.hexdigest()) 
#5d41402abc4b2a76b9719d911017c592
#唯一性

二、hash模块

hmac模块内部对我们创建key和内容做过某种处理后再加密。

和hashlib模块类似,hash模块具有加盐的功能,保证hmac最终结果一致,必须要hmac.new括号内指定的初始key一样

也具有唯一性

import hmac
h1=hmac.new(b"hash")#创建了hmac对象h1,加盐(”hash“这个字符串)
#注意hmac模块只接受二进制数据的加密
print(type(h1)) #<class 'hmac.HMAC'>

h1.update(b"hello")
print(h1.hexdigest())
#bea9d9de0f3dc7706393020b00404324
h1.update(b"hel")
h1.update(b"lo")
print(h1.hexdigest())
#bea9d9de0f3dc7706393020b00404324
原文地址:https://www.cnblogs.com/demiao/p/11378263.html