Compare commits

..

1 Commits
main ... AES

Author SHA1 Message Date
pjbpwnxmf 53bb5e29c5 ADD file via upload
1 year ago

@ -0,0 +1,86 @@
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
import os
# 生成AES密钥
def generate_aes_key():
return get_random_bytes(16) # 16 bytes for AES - 128 bits
# 将AES密钥保存到文件
def save_aes_key_to_file(key, file_path):
with open(file_path, 'wb') as key_file:
key_file.write(key)
# 使用AES加密数据
def aes_encrypt(key, data):
try:
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
return (cipher.nonce, ciphertext, tag)
except ValueError as e:
raise ValueError(f"加密过程出现错误: {str(e)}")
except Exception as ex:
raise Exception(f"加密时发生未知错误: {str(ex)}")
# 使用AES解密数据
def aes_decrypt(key, nonce, ciphertext, tag):
try:
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
return cipher.decrypt_and_verify(ciphertext, tag)
except ValueError as e:
raise ValueError(f"解密过程出现错误: {str(e)}")
except Exception as ex:
raise Exception(f"解密时发生未知错误: {str(ex)}")
#测试部分
if __name__ == "__main__":
# 待加密的原始数据,这里以简单的文本数据为例,实际可以是任意二进制数据
original_data = b"This is a test message for AES encryption and decryption."
# 生成正确的AES密钥
correct_aes_key = generate_aes_key()
# 定义保存密钥的文件路径这里假设在当前目录下创建一个名为aes_key.bin的文件来保存密钥
key_file_path = "aes_key.bin"
try:
# 保存正确的AES密钥到文件
save_aes_key_to_file(correct_aes_key, key_file_path)
print("AES密钥已成功保存到文件。")
# 使用正确的AES密钥加密数据
nonce, ciphertext, tag = aes_encrypt(correct_aes_key, original_data)
print("数据加密成功,加密后的密文数据(十六进制表示):", ciphertext.hex())
print("加密过程生成的随机数(十六进制表示):", nonce.hex())
print("加密过程生成的认证标签(十六进制表示):", tag.hex())
# 模拟从文件中读取密钥(实际应用中可能从更安全的存储位置读取)
with open(key_file_path, 'rb') as key_file:
read_key = key_file.read()
try:
# 使用错误的密钥进行解密,预期会出现解密错误
decrypted_data = aes_decrypt(read_key, nonce, ciphertext, tag)
print("数据解密成功。")
print("原始数据:", original_data)
print("解密后的数据:", decrypted_data)
if decrypted_data == original_data:
print("解密后的数据与原始数据一致,验证通过。")
else:
print("解密后的数据与原始数据不一致,请检查加密和解密过程。")
except ValueError as ve:
print(f"解密出现值错误: {ve}")
except Exception as e:
print(f"解密出现其他错误: {e}")
except ValueError as ve:
print(f"出现值错误: {ve}")
except Exception as e:
print(f"出现其他错误: {e}")
finally:
# 清理生成的密钥文件(实际应用中可能根据情况决定是否保留密钥文件)
if os.path.exists(key_file_path):
os.remove(key_file_path)

Binary file not shown.
Loading…
Cancel
Save