用python实现aes加解密
时间: 2023-06-10 18:07:39 浏览: 67
可以使用PyCryptodome模块来实现AES的加解密。以下是一个基本的示例:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
# 加密函数
def encrypt_AES(key, plaintext):
cipher = AES.new(key, AES.MODE_ECB)
padded_plaintext = pad(plaintext.encode('utf-8'), AES.block_size)
ciphertext = cipher.encrypt(padded_plaintext)
return base64.b64encode(ciphertext).decode('utf-8')
# 解密函数
def decrypt_AES(key, ciphertext):
cipher = AES.new(key, AES.MODE_ECB)
padded_plaintext = cipher.decrypt(base64.b64decode(ciphertext))
plaintext = unpad(padded_plaintext, AES.block_size).decode('utf-8')
return plaintext
# 测试
key = b'0123456789abcdef' # 16字节的密钥
plaintext = 'hello world'
ciphertext = encrypt_AES(key, plaintext)
print(ciphertext) # 输出加密后的密文
decrypted_text = decrypt_AES(key, ciphertext)
print(decrypted_text) # 输出解密后的明文
```
注意,以上示例使用了ECB模式,这种模式不安全,因为相同的明文会得到相同的密文,容易被攻击者破解。在实际应用中,应该使用更安全的CBC或CTR模式。