kboss/kgadget/src/KaiYyEnDecryptUtil.py
2025-07-16 14:27:17 +08:00

70 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
# @Time: 2025/6/17 11:33
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
class KaiYyEnDecryptUtil:
# 注意需要将Java中的密钥补充完整PEM头实际使用时请替换为完整密钥
# 读取本地私钥文件
# with open('public_key.pem', 'r', encoding='utf-8') as f:
# RSA_PUBLIC_KEY = f.read()
RSA_PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3LWvOQCufDQpf9PsOrBF
SsjPqIg/x1YZpQ4MksZs4BwHWjHT9PHoJ88OZl2cXmyaY6Hde2KXG1v873lI70/2
oUizX8Fyl0TTliAQ/p/kSsmgHfzhY+KOZUQ5HwXwnjFKv1q+Y0PpseNPFFHGiB1H
/6p8kJeV61GN00etwvAvDdfZKm9W6t1ByD9Bsr3/VSHJtv1DqVdgmVMxnI7W4mx6
UmseGmywngLvBHXI0+MWRK1RszCMISA6SsKTlT9IdT/r64vLht+NImEY6KPwODpu
6vBUSyRqbGVitZ6PPIPwzLkB8LZ69eTjK5SMXP6RD7kHio+vb4ljHWXzDfRH9HXq
FQIDAQAB
-----END PUBLIC KEY-----
"""
# with open('private_key.pem', 'r', encoding='utf-8') as f:
# RSA_PRIVATE_KEY = f.read()
@staticmethod
async def encrypt_by_digital_envelope(to_encrypt_data: str) -> dict:
# 加载RSA公钥
public_key = RSA.import_key(KaiYyEnDecryptUtil.RSA_PUBLIC_KEY)
rsa_cipher = PKCS1_v1_5.new(public_key)
# 1.1 生成AES-128密钥16字节
aes_key = get_random_bytes(16) # 等同于Java的AES-128
# 1.2 使用AES-ECB-PKCS7加密数据匹配Java默认模式
aes_cipher = AES.new(aes_key, AES.MODE_ECB)
encrypted_data = aes_cipher.encrypt(pad(to_encrypt_data.encode(), AES.block_size))
data = base64.b64encode(encrypted_data).decode()
# 1.3 使用RSA公钥加密AES密钥
encrypted_aes_key = rsa_cipher.encrypt(aes_key)
encoded_key = base64.b64encode(encrypted_aes_key).decode()
return {"AESKey": encoded_key, "data": data}
# @staticmethod
# def decrypt_by_digital_envelope(encoded_key: str, data: str) -> str:
# # 加载RSA私钥
# private_key = RSA.import_key(KaiYyEnDecryptUtil.RSA_PRIVATE_KEY)
# rsa_cipher = PKCS1_v1_5.new(private_key)
#
# # 1.1 使用RSA私钥解密AES密钥
# decrypted_aes_key = rsa_cipher.decrypt(base64.b64decode(encoded_key), None)
#
# # 1.2 使用AES-ECB-PKCS7解密数据
# aes_cipher = AES.new(decrypted_aes_key, AES.MODE_ECB)
# decrypted_data = unpad(aes_cipher.decrypt(base64.b64decode(data)), AES.block_size)
#
# return decrypted_data.decode()
# if __name__ == '__main__':
# res = KaiYyEnDecryptUtil.encrypt_by_digital_envelope('1230')
# print(res)
# res = {}
# des_res = KaiYyEnDecryptUtil.decrypt_by_digital_envelope(res['AESKey'], res['data'])
# print(des_res)