第 0021 题: 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。
解答:常见的几种加密方式有MD5,AES加密,RSA加密
#encoding:utf-8
import hashlib
from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
import rsa
# MD5加密
def encrypt_password_MD5(pwd):
h1 = hashlib.md5()
h1.update(pwd.encode(encoding='utf8'))
return h1.hexdigest()
# AES加解密
class AESCrypto():
def __init__(self,key,model,encoding='utf8'):
self.encode_ = encoding
self.model = {'ECB':AES.MODE_ECB,'CBC':AES.MODE_CBC}[model]
self.key = self.add_16(key)
if model == 'ECB':
self.aes = AES.new(self.key,self.model) #创建一个aes对象
elif model == 'CBC':
self.aes = AES.new(self.key,self.model,self.key) #创建一个aes对象
#这里的密钥长度必须是16、24或32,目前16位的就够用了
def add_16(self,par):
par = par.encode(self.encode_)
while len(par) % 16 != 0:
par += b'\x00'
return par
def encrypt(self,text):
text = self.add_16(text)
self.encrypt_text = self.aes.encrypt(text)
return b2a_hex(self.encrypt_text)
def decrypt(self,text):
if self.model == 2:
# 如果为CBC模式,不能直接直接加密后进行解密,需要重新创建aes对象
self.aes = AES.new(self.key, self.model, self.key) # 创建一个aes对象
self.decrypt_text = self.aes.decrypt(a2b_hex(text))
return bytes.decode(self.decrypt_text).rstrip('\0')
# RSA加解密
class RSAEncrypt():
def __init__(self):
# 生成密钥
(pubkey, privkey) = rsa.newkeys(1024)
# 保存密钥
with open('public.pem', 'w+') as f:
f.write(pubkey.save_pkcs1().decode())
with open('private.pem', 'w+') as f:
f.write(privkey.save_pkcs1().decode())
# 导入密钥
with open('public.pem', 'r') as f:
self.pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private.pem', 'r') as f:
self.privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
# rsa加密,通常对加密结果进行base64编码
def encrypt(self,message):
return rsa.encrypt(message.encode(), self.pubkey)
# rsa解密
def decrypt(self,encrypt_text):
message = rsa.decrypt(encrypt_text, self.privkey).decode()
return message
if __name__ == '__main__':
pwd = "12345678"
md5_pwd = encrypt_password_MD5(pwd)
print("MD5加密前:%s,MD5加密后密码为:%s"%(pwd,md5_pwd))
# AES加密解密
pc = AESCrypto('keyskeyskeyskeys','CBC')
e = pc.encrypt(pwd)
d = pc.decrypt(b'221a30a43fd464b1ee173afeabef46ce')
print("AES加密后:%s,AES解密后:%s"%(e,d))
# RSA加密解密
rsae = RSAEncrypt()
e = rsae.encrypt(pwd)
d = rsae.decrypt(e)
print("RSA加密后:%s,RSA解密后:%s" % (e, d))