前端和Python API接口加解密

前端和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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值