aes加密解密 python实现函数
时间: 2024-08-15 09:09:47 浏览: 55
python实现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
# 密钥(16字节,即128位)
key = b'sixteen_byte_key'
def encrypt(plaintext, key):
backend = default_backend()
cipher_algorithm = algorithms.AES(key)
cipher_mode = modes.CBC(b'some_random_iv') # 使用随机初始化向量(IV)
# 创建一个Cipher实例并设置操作模式
cipher = Cipher(cipher_algorithm, cipher_mode, backend=backend)
# 对象用于进行加密
encryptor = cipher.encryptor()
# 将明文分成块(这里我们假设每个块大小为16字节)
ciphertext = b''
for i in range(0, len(plaintext), 16):
ciphertext += encryptor.update(plaintext[i:i+16])
# 添加填充后的最终块
ciphertext += encryptor.finalize()
return ciphertext, cipher_mode.iv
def decrypt(ciphertext, key, iv):
backend = default_backend()
cipher_algorithm = algorithms.AES(key)
cipher_mode = modes.CBC(iv)
cipher = Cipher(cipher_algorithm, cipher_mode, backend=backend)
decryptor = cipher.decryptor()
decrypted_text = b''
while True:
try:
decrypted_text += decryptor.update(ciphertext)
except ValueError: # 如果到达了数据的结束
break
# 移除填充
padding_length = decrypted_text[-1]
if not 0 < padding_length <= 16:
raise ValueError("Invalid padding")
decrypted_text = decrypted_text[:-padding_length]
return decrypted_text.decode() # 返回明文字符串
# 示例用法
plaintext = "Hello, world!"
ciphertext, iv = encrypt(plaintext.encode(), key)
decrypted_text = decrypt(ciphertext, key, iv)
print(f"原文: {plaintext}")
print(f"密文: {ciphertext.hex()}")
print(f"解密后: {decrypted_text}")
```
阅读全文