目前系统的登录接口,在传密码时,前端做了RSA加密处理,只有加密后的密文才可以登录成功,现将RSA加密解密代码总结如下: 1、导入第三方库
pip install pycryptodome
注意:这里需要处理下,避免导入时报错:进入python安装目录,修改一个文件夹的名称,博主路径为 D:\Users\AppData\Local\Programs\Python\Python39\Lib\site-packages,将文件夹crypto修改为Crypto即可! 2、RSA公钥加密:需要从开发处获取到加密的公钥
import base64
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA
def encrpt(password, public_key):
public_key = '-----BEGIN PUBLIC KEY-----\n' + public_key + '\n-----END PUBLIC KEY-----'
rsakey = RSA.importKey(public_key)
cipher = Cipher_pksc1_v1_5.new(rsakey)
password = str(password)
cipher_text = base64.b64encode(cipher.encrypt(password.encode()))
return cipher_text.decode()
if __name__ == '__main__':
pub_key = "公钥"
pwd = "123456"
pwd_key = encrpt(pwd, pub_key)
print(pwd_key)
以上就是公钥加密代码~~
3、RSA私钥解密:需要从开发处获取到解密的私钥
def decrpt(password, private_key):
encrypt_text = password.encode('utf-8')
private_key = '-----BEGIN RSA PRIVATE KEY-----\n' + private_key + '\n-----END RSA PRIVATE KEY-----'
print(private_key)
rsakey = RSA.importKey(private_key)
cipher = Cipher_pksc1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(encrypt_text), 1024)
print(text.decode('utf-8'))
return text.decode('utf-8')
|