一、前端公鑰加密
在main.js中引入 jsencrypt.js文件
import JSEncrypt from './common/js/jsencrypt'
然后在main.js中定義全局的前端加密方法
//JSEncrypt加密方法(參數(shù)1:數(shù)據(jù)栽渴,參數(shù)2:公鑰)
Vue.prototype.$jsEncrypt = function(data,pub_key){
let encrypt = new JSEncrypt()
encrypt.setPublicKey(pub_key)
let en_data = encrypt.encrypt(data.toString())
return en_data
}
使用舉例:
this.$jsEncrypt(password,pub_key),
二、后端私鑰解密
Linux上安裝:
pip install pycryptodome
Windows上安裝:
pip install pycryptodomex
在項(xiàng)目根目錄下新建一個(gè)工具文件夾:utils
新建文件:rsa_crypt.py
import base64
from Cryptodome import Random
from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.PublicKey import RSA
def creat_key():
"""
生成密鑰對(duì)
:return:
"""
# 偽隨機(jī)數(shù)的方式生成RSA公私鑰對(duì)
random_generator = Random.new().read
rsa = RSA.generate(1024, random_generator)
# 私鑰
pri_key = rsa.exportKey().decode('utf-8')
# 公鑰
pub_key = rsa.publickey().exportKey().decode('utf-8')
# 以列表形式返回密鑰對(duì)
return [pri_key, pub_key]
def decrypt_data(input_data, key):
"""
解密數(shù)據(jù)
:param input_data:
:param key:
:return:
"""
try:
# 分組解密默認(rèn)長度128
default_length = 128
# 創(chuàng)建私鑰對(duì)象
pri_key = RSA.importKey(key.encode('utf-8'))
cipher = PKCS1_v1_5.new(pri_key)
# 現(xiàn)將base64編碼格式的數(shù)據(jù)解碼蚂且,然后解密纹安,并用decode轉(zhuǎn)成str
input_data_b64 = base64.b64decode(input_data.encode('utf-8'))
# 獲取密文長度
length = len(input_data_b64)
# 直接解密
if length < default_length:
output_data = cipher.decrypt(input_data_b64, sentinel='error').decode('utf-8')
# 分組解密
else:
offset = 0
res = []
while length - offset > 0:
if length - offset > default_length:
res.append(cipher.decrypt(input_data_b64[offset: offset + default_length], sentinel='error'))
else:
res.append(cipher.decrypt(input_data_b64[offset:], 'error'))
offset += default_length
output_data = b''.join(res)
output_data = output_data.decode('utf-8')
return output_data
except Exception as e:
return e
使用舉例:
# 引入方法
from utils.rsa_crypt import creat_key, decrypt_data,
# 私鑰解密
password = decrypt_data(request.POST.get('password'), PRI_KEY)