hashlib模块 --用来进行hash或者md5加密(包括md5、sha1、sha224、sha256、sha512等)
基本用法:
#!/usr/bin/python3
# -*- conding:utf-8 -*-
import hashlib
# 字符串计算md5值
test = 'Hello World!'
m = hashlib.md5()
m.update(test.encode('utf-8'))
print(m.hexdigest())
# 文件计算sha1值
filename = 'config.ini'
sha1 = hashlib.sha1()
with open(filename,'rb') as f:
while True:
block = f.read(4096)
if not block:
break
sha1.update(block)
print(sha1.hexdigest())
执行结果:
ed076287532e86365e841e92bfc50d8c
daf82fd4d5cb2c5a8662edf0cbf250bf1041f87c
加密算法中添加自定义key再来做加密(防止撞库)
#!/usr/bin/python3
# -*- conding:utf-8 -*-
import hashlib
test = 'Hello World!'
key = 'X8643'
sha256 = hashlib.sha256(key.encode('utf-8'))
sha256.update(test.encode('utf-8'))
print(sha256.hexdigest())
base64模块 --base64编码解码
#!/usr/bin/python3
# -*- config:utf-8 -*
import base64
test = 'Hello World!'
# 编码
test1 = base64.b64encode(test.encode('utf-8'))
print(test1.decode())
# 解码
test2 = base64.b64decode(test1)
print(test2.decode())
执行结果
SGVsbG8gV29ybGQh
Hello World!