1. 程式人生 > >前端(js)密碼加密後傳輸給後端(python)實現方法

前端(js)密碼加密後傳輸給後端(python)實現方法

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

以上程式碼每個功能可以單獨寫一個函式,具體需求自己定義