应用AES算法对“明天中午吃什么”这段文本进行加密解密代码显示以及结果显示
时间: 2024-10-16 22:05:10 浏览: 38
C#代码实现对AES加密解密
AES (Advanced Encryption Standard) 是一种常用的块加密算法,用于保护数据的安全传输。在Python中,我们可以使用`cryptography`库来实现AES加密解密。下面是一个简单的例子展示了如何对字符串"明天中午吃什么"进行AES加密和解密:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# 密钥和密码
password = b'supersecretkey123'
salt = b'some_salt'
kdf_iterations = 100000
# 使用PBKDF2获取密钥
kdf = PBKDF2HMAC(algorithm=hashlib.sha256(), length=32, salt=salt, iterations=kdf_iterations, backend=default_backend())
key = kdf.derive(password)
# 创建AES实例并设置模式和填充
cipher_algorithm = algorithms.AES(key)
cipher_mode = modes.CBC(key[:16]) # CBC模式需要一个初始化向量,这里使用密钥的一部分
iv = cipher_mode.iv
# 加密函数
def encrypt(plaintext):
encryptor = Cipher(cipher_algorithm, cipher_mode, backend=default_backend()).encryptor()
ct_bytes = encryptor.update(plaintext.encode('utf-8')) + encryptor.finalize()
return iv + ct_bytes
# 解密函数
def decrypt(ciphertext):
cipher_text = ciphertext
iv = cipher_text[:16]
cipher_text = cipher_text[16:]
decryptor = Cipher(cipher_algorithm, cipher_mode, backend=default_backend()).decryptor()
pt_bytes = decryptor.update(cipher_text) + decryptor.finalize()
return pt_bytes.decode('utf-8')
# 加密示例
ciphertext = encrypt("明天中午吃什么")
print(f"Ciphertext: {ciphertext.hex()}")
# 解密示例
decrypted_text = decrypt(bytes.fromhex(ciphertext.hex()))
print(f"Decrypted text: {decrypted_text}")
阅读全文