aes加密/解密代码
时间: 2024-10-15 14:19:08 浏览: 22
C++实现AES加密/解密
AES (Advanced Encryption Standard) 是一种常用的对称加密算法,它的全称是高级加密标准,常用于数据的安全传输。在Python中,我们可以使用`cryptography`库来实现AES加密和解密。下面是一个简单的示例:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def encrypt_AES(text, key, iv):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(text.encode('utf-8')) + encryptor.finalize()
return ciphertext, iv
def decrypt_AES(ciphertext, key, iv):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
decryptor = cipher.decryptor()
decrypted_text = decryptor.update(ciphertext) + decryptor.finalize()
return decrypted_text.decode('utf-8')
# 使用示例
key = b'sixteen_byte_key' # 需要16字节长度的秘钥
iv = os.urandom(16) # 需要16字节的初始化向量
plaintext = "Hello, AES!"
ciphertext, iv_used = encrypt_AES(plaintext, key, iv)
decrypted_text = decrypt_AES(ciphertext, key, iv_used)
print(f"Original Text: {plaintext}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Decrypted Text: {decrypted_text}\n")
阅读全文