一、加密代码

import base64
import zlib
from Crypto.Cipher import AES
from Crypto import Random


BLOCK_SIZE = 16


def pad(s): return s + ((BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)).encode("utf-8")


class AESCipher:
    def __init__(self, key):

        self.key = key

    def encrypt(self, raw):

        """
        加密
        """

        raw = pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return iv + cipher.encrypt(raw)


def encode(data, key) -> bytes:

    """
    :param data: 序列化后的数据
    :param key: 加密的 key
    :return: 
    """

    # 压缩
    compress_data = zlib.compress(data)

    # 加密
    aes = AESCipher(key)
    encrypt_data = aes.encrypt(compress_data)

    # 转成Base64编码
    encode_data = base64.b64encode(encrypt_data)
    return encode_data


if __name__ == '__main__':
    key = hashlib.md5(str(time.time()).encode('utf-8')).hexdigest()
    json_data = json.dumps({'data': 'test'})
    encode_data = encode(json_data, key)
View Code

相关文章:

  • 2021-12-07
  • 2021-12-12
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2021-10-04
  • 2021-12-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-04-04
  • 2021-05-26
  • 2022-01-19
  • 2021-07-28
相关资源
相似解决方案