Python实现Rsa非对称加密
非对称加密时公钥和私钥成对,使用公钥加密的密码 再用私钥进行解密
使用场景:
密码登录加密:前端获取后台给定公钥进行加密,后端拿到密码后再进行解密 然后将密码md5转换后存入数据库。
后台密钥具有时效性 这样传输中被截取也无法仿造
import base64
import rsa
# 秘钥的位数, 可以自定义指定, 例如: 128、256、512、1024、2048等
(pubkey, privkey) = rsa.newkeys(256)
# 生成公钥
pub = pubkey.save_pkcs1()
with open('public.pem', 'wb') as f:
f.write(pub)
# # 生成私钥
pri = privkey.save_pkcs1()
with open('private.pem', 'wb') as f:
f.write(pri)
pub_str = '''-----BEGIN RSA PUBLIC KEY-----
MCgCIQCR8RiQaYZ8AwSt/EVMVs0Y88qqWGW0pYFdCgfi8G0z1QIDAQAB
-----END RSA PUBLIC KEY-----
'''
``
priv_str = '''-----BEGIN RSA PRIVATE KEY-----
MIGqAgEAAiEAkfEYkGmGfAMErfxFTFbNGPPKqlhltKWBXQoH4vBtM9UCAwEAAQIg
WP1kdxqBkLjeb6D2OJhsqUtU9+E+KkG3+4/DHH6mJYECEgDi1MtnvlIeYE2YX2Rr
1/HiJQIQAKS1cuWHyxZ/PTFR50dj8QIRWnsDgCh83T0Q9rzmc9Y52DkCDzw0QroZ
Z6difOiRKnuS0QIRX2j3UMIeTiom54alccbRQ4Y=
-----END RSA PRIVATE KEY-----
'''
class Rsa():
def __init__(self):
self.pub_key = rsa.PublicKey.load_pkcs1(pub_str)
self.priv_key = rsa.PrivateKey.load_pkcs1(priv_str)
def encrypt(self,text):
# rsa加密 最后把加密字符串转为base64
text = text.encode("utf-8")
cryto_info = rsa.encrypt(text, self.pub_key)
cipher_base64 = base64.b64encode(cryto_info)
cipher_base64 = cipher_base64.decode()
return cipher_base64
def decrypt(self,text):
# rsa解密 返回解密结果
cryto_info = base64.b64decode(text)
talk_real = rsa.decrypt(cryto_info, self.priv_key)
res = talk_real.decode("utf-8")
return res
if __name__=="__main__":
rsaer = Rsa()
info = rsaer.encrypt('哈哈哈哈牛逼')
print('加密:',info)
print('解密:',rsaer.decrypt(info))
#加密: c1s4H392ngYbwfL7S4vJS8VuspQQrNEeKT73DqSZEQ4=
#解密: 哈哈哈哈牛逼