From 35fea93de123edd3fa119a456d4301bf97612846 Mon Sep 17 00:00:00 2001 From: plri7qhng <1501976682@qq.com> Date: Sat, 19 Apr 2025 16:25:18 +0800 Subject: [PATCH] ADD file via upload --- AES.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 AES.py diff --git a/AES.py b/AES.py new file mode 100644 index 0000000..0ebde41 --- /dev/null +++ b/AES.py @@ -0,0 +1,54 @@ +from Crypto.Cipher import AES +from Crypto.Util.Padding import pad, unpad +from Crypto.Random import get_random_bytes +import binascii + + +def aes_encrypt(plaintext, key): + try: + if len(key) != 16: + raise ValueError("密钥必须为16字节") + plaintext_bytes = plaintext.encode('utf-8') + key_bytes = key.encode('utf-8') + padded_plaintext = pad(plaintext_bytes, AES.block_size) + iv = get_random_bytes(AES.block_size) + cipher = AES.new(key_bytes, AES.MODE_CBC, iv) + ciphertext = cipher.encrypt(padded_plaintext) + return iv, ciphertext + except Exception as e: + return None, str(e) + + +def aes_decrypt(iv, ciphertext, key): + try: + if len(key) != 16: + raise ValueError("密钥必须为16字节") + key_bytes = key.encode('utf-8') + cipher = AES.new(key_bytes, AES.MODE_CBC, iv) + padded_plaintext = cipher.decrypt(ciphertext) + plaintext_bytes = unpad(padded_plaintext, AES.block_size) + return plaintext_bytes.decode('utf-8') + except Exception as e: + return str(e) + + +def main(): + plaintext = "陈跨国方式点卡" + key = "1234567890abcdef" + + print(f"明文: {plaintext}") + print(f"密钥: {key}") + + iv, ciphertext = aes_encrypt(plaintext, key) + if ciphertext: + print(f"IV (hex): {binascii.hexlify(iv).decode()}") + print(f"密文 (hex): {binascii.hexlify(ciphertext).decode()}") + + decrypted_text = aes_decrypt(iv, ciphertext, key) + print(f"解密后的明文: {decrypted_text}") + else: + print(f"加密失败: {ciphertext}") + + +if __name__ == "__main__": + main() \ No newline at end of file