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)