hashlib模块
- 用于加密相关的操作,代替md5模块和sha模块,主要提供SHA1,SHA224,SSHA256,SHA384,SHA512,MD5算法
- 直接看代码案例:
---------md5-----------
hash = hashlib.md5()
hash.update(bytes('admin',encoding='utf-8'))
hash.update(bytes('123',encoding='utf-8'))
print(hash.hexdigest()) print(hash.digest())
----------sha1---------
hash = hashlib.sha1()
hash.update(bytes('admin',encoding='utf-8'))
print(hash.hexdigest())
----------sha256-------
hash = hashlib.sha256()
hash.update(bytes('admin',encoding='utf-8'))
print(hash.hexdigest())
---------sha384--------
hash = hashlib.sha384()
hash.update(bytes("admin",encoding='utf-8'))
print(hash.hexdigest())
------------sha512--------
hash = hashlib.sha512()
hash.update(bytes('admin',encoding='utf-8'))
print(hash.hexdigest())
注意
以上加密算法虽然非常厉害,但有时存在缺陷,即:通过撞库可以反解。
所以,有必要对加密算法中添加自定义key再来加密
hash = hashlib.md5(bytes('790dfhdfe3',encoding='utf-8'))
hash.update(bytes('admin',encoding='utf-8'))
print(hash.hexdigest())
-------------------------------
python 内置还有一个hmac模块,它内部对我们创建key和内容进行进一步的处理然后再加密
import hmac
h = hmac.new(bytes('dfew3',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())
计算得到文件md5值
def MD5(file):
import hashlib
md5_value = hashlib.md5()
with open(file, 'rb') as file:
while True:
data = file.read()
if not data:
break
md5_value.update(data)
return md5_value.hexdigest() ret = MD5(r"C:\Users\Administrator\Desktop\aaaa\cgss2008append.dta")
print(ret)
Base64加密解密方法
base64代码博文链接:http://www.cnblogs.com/txw1958/archive/2012/07/19/python3-base64.html
import base64 copyright = 'Copyright (c) 2012 Doucube Inc. All rights reserved.' def main():
#转成bytes string
bytesString = copyright.encode(encoding="utf-8")
print(bytesString) #base64 编码
encodestr = base64.b64encode(bytesString)
print(encodestr)
print(encodestr.decode()) #解码
decodestr = base64.b64decode(encodestr)
print(decodestr.decode()) if __name__ == '__main__':
main()