js 实现
<script src="js/jsencrypt.min.js"></script>
var encrypt = new JSEncrypt();
encrypt.setPublicKey(pubKey);
# 加密
return encrypt.encrypt(pwd);
# pubKey 后端传入的密码
# pwd 是用户输入的密码
python 后端实现
安装模块: pip3 install pycryptodome
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5, PKCS1_OAEP
import base64
生成密钥:
key = RSA.generate(1024)
exportKey = key.publickey().exportKey()
encrypted_key = key.exportKey()
# 秘钥
request.session['encrypted_key'] = bytes.decode(encrypted_key)
# 公钥
request.session['exportKey'] = bytes.decode(exportKey)
解密:
def decrypt_password(request, password):
confirmpassword = base64.b64decode(password)
encrypted_key = request.session['encrypted_key']
encrypted_key = RSA.import_key(encrypted_key)
cipher_rsa2 = PKCS1_v1_5.new(encrypted_key)
data = cipher_rsa2.decrypt(confirmpassword, None)
password = bytes.decode(data)
return password
以上代码每个功能可以单独写一个函数,具体需求自己定义