使用Python对字符串进行加密

本文整理一下Python的几种对字符串加密的方式。

hashlib模块

Python提供了hashlib模块,该模块中提供了几种常用的加密算法,比如MD5、SHA1、SHA256等

MD5

md5 = hashlib.md5()
md5.update(oldStr.encode('utf-8'))
print("MD5加密:", md5.hexdigest())

请输入要加密的字符串:晓天的BigWorld
MD5加密: a3eaf3b1f2b122fbec46bf42cec6273d

SHA-1

sha1 = hashlib.sha1()
sha1.update(oldStr.encode('utf-8'))
print("SHA1加密:", sha1.hexdigest())

请输入要加密的字符串:晓天的BigWorld
SHA1加密: bcb3990c5cba4a030a663f8fb9e0cac00fa2667d

hmac模块

hmac提供了一种hmac算法,在计算哈希码的过程中,将key值和字符串一起加密

pwd = oldStr.encode('utf-8')
key = 'id'.encode('utf-8')
h = hmac.new(key, pwd, digestmod='MD5')
print("Hmac算法加密:", h.hexdigest())

请输入要加密的字符串:晓天的BigWorld
Hmac算法加密: 7ba52fe62d3759d815f33046061735d2

posted @ 2020-09-06 15:33  晓天的BigWorld  阅读(3356)  评论(0编辑  收藏  举报