python模拟Java使用AES对称加密算法CBC对消息体进行参数加解密(模拟Java的SHA1PRNG算法)

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
import hashlib
import json


class AESUtils:
    # 填充向量,长度为16位
    FILL_VECTOR = "abcsadadaaEW"

    @staticmethod
    def base64_encode(bytes_data):
        return b64encode(bytes_data).decode('utf-8')

    @staticmethod
    def base64_decode(base64_code):
        return b64decode(base64_code)

    @staticmethod
    def encrypt(content, key):
        key_bytes = AESUtils.get_secret_key(key)
        iv = AESUtils.FILL_VECTOR.encode('utf-8')
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
        content_bytes = content.encode('utf-8')
        ct_bytes = cipher.encrypt(pad(content_bytes, AES.block_size))
        return AESUtils.base64_encode(ct_bytes)

    @staticmethod
    def decrypt(content, key):
        key_bytes = AESUtils.get_secret_key(key)
        iv = AESUtils.FILL_VECTOR.encode('utf-8')
        cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
        ct_bytes = AESUtils.base64_decode(content)
        pt_bytes = unpad(cipher.decrypt(ct_bytes), AES.block_size)
        return pt_bytes.decode('utf-8')

    @staticmethod
    def get_secret_key(key):
        # 模拟Java的 SHA1PRNG算法的行为
        # 这里使用SSHA-1 哈希计算使用
        # 然后返回最终哈希的前16个字节。其目的是使用 SHA-1 哈希算法生成一个128位(16字节)的加密密钥。
        # 这行代码首先将输入的 key 字符串编码为字节序列,然后使用 SHA-1 哈希算法对其进行哈希计算,并通过 digest() 方法获取计算后的原始二进制哈希值
        signature = hashlib.sha1(key.encode()).digest()
        # 接着,将第一步得到的原始二进制哈希值再次使用 SHA-1 哈希算法进行哈希计算,得到一个新的原始二进制哈希值。
        signature = hashlib.sha1(signature).digest()
        # 最后,从第二步得到的新的原始二进制哈希值中取前16个字节,作为最终的密钥 key_bytes。
        key_bytes = signature[:16]
        return key_bytes


if __name__ == "__main__":
    data = {
            "user_name": "SSHAJSJ",
            "user_phone": "1524151470247"
            }
    original_content = json.dumps(data, separators=(',', ':'))
    secret_key = "47cc736d8cfb134542425461514712175414"

    encrypted_content = AESUtils.encrypt(original_content, secret_key)
    print(f"Encrypted Content: ", encrypted_content)

    decrypted_content = AESUtils.decrypt(encrypted_content, secret_key)
    print(f"Decrypted Content: ", decrypted_content)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值