前端和Python API接口加解密
安装包 https://www.npmjs.com/package/crypto-js
一、前端加解密
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script>
var key='Ow2Qd11KeZS_ahNOMicpWUr3nu3RjOUYa0_GEuMDlOc='//后端提供的加密规则
//加密
var ciphertext = CryptoJS.AES.encrypt('待加密数据', key).toString();
console.log('加密后的数据',ciphertext)
//解密:
var originalText = CryptoJS.AES.decrypt(ciphertext,key).toString(CryptoJS.enc.Utf8);
console.log('解密的数据',originalText);
</script>
二、后端加解密
from Crypto import Random
from Crypto.Cipher import AES
import base64
from hashlib import md5
KEY = 'Ow2Qd11KeZS_ahNOMicpWUr3nu3RjOUYa0_GEuMDlOc='
class EncDecAES(object):
def pad(self, data):
length = 16 - (len(data) % 16)
return data.encode() + (chr(length) * length).encode()
def unpad(self, data):
return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
def bytes_to_key(self, data, salt, output=48):
"""
字节转换为key
:param data:秘钥
:param salt:
:param output:
:return:
"""
assert len(salt) == 8, len(salt)
data = data.encode() + salt
key = md5(data).digest()
final_key = key
while len(final_key) < output:
key = md5(key + data).digest()
final_key += key
return final_key[:output]
def encrypt(self, message, passphrase):
"""
加密
:param message:
:param passphrase: 秘钥
:return:
"""
salt = Random.new().read(8)
key_iv = self.bytes_to_key(passphrase, salt, 32 + 16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(b"Salted__" + salt + aes.encrypt(self.pad(message))).decode()
def decrypt(self, encrypted, passphrase):
"""
解密
:param encrypted:内容
:param passphrase:秘钥
:return:
"""
encrypted = base64.b64decode(encrypted)
assert encrypted[0:8] == b"Salted__"
salt = encrypted[8:16]
key_iv = self.bytes_to_key(passphrase, salt, 32 + 16)
key = key_iv[:32]
iv = key_iv[32:]
aes = AES.new(key, AES.MODE_CBC, iv)
return self.unpad(aes.decrypt(encrypted[16:])).decode()
if __name__ == '__main__':
Crypto=EncDecAES()
data=Crypto.encrypt('123',KEY)
print('加密数据:'+data)
print('解密数据:'+Crypto.decrypt('U2FsdGVkX1+vUhg6N+xA9aLqe6xCLuCbD94sHDSGPY0=', KEY))