python实现常用哈希签名算法
TC3-HMAC-SHA256 算法
from hashlib import sha256
import hmac
def get_sign(data, key):
key = key.encode('utf-8')
message = data.encode('utf-8')
sign = base64.b64encode(hmac.new(key, message, digestmod=sha256).digest())
sign = str(sign, 'utf-8')
print(sign)
return sign
get_sign('helloworld', '123456')
返回值
NizOiZ3X1Ioo+S1Mzo5UKc7aMnUGtkPuca6mWxGQTsA=
MD5算法
# coding:utf-8
import hmac
message = b'Hello, world!'
key = b'secret'
h = hmac.new(key, message, digestmod='MD5')
# 如果消息很长,可以多次调用h.update(msg)
print(h.hexdigest())
返回值
fa4ee7d173f2d97ee79022d1a7355bcf
sha1算法
import hashlib
import hmac
message='hello world'
digest_maker = hmac.new('heloow'.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha1)
print(digest_maker.hexdigest())
返回值
3860be4158e834cf99c33295e0d386ed816d8e10
密码验证应用
#!/usr/bin/python
# coding: utf-8
import hashlib
class User:
def __init__(self, username, password):
self.username = username
md5 = hashlib.md5(password.encode())
print(md5)
print(password.encode('utf-8'))
self.password = md5.hexdigest() # hexdigest是十六进制数据字符串值
def check_password(self, password): # 验证密码是否正确
md5 = hashlib.md5(password.encode())
if md5.hexdigest() == self.password:
return password + ":密码正确"
else:
return password + ":密码错误"
user = User("helloword", "123456789")
print("加密后的密码是:", user.password)
print(user.check_password("12345"))
print(user.check_password("123456789"))