纯python实现aes加解密算法
时间: 2024-10-10 13:01:03 浏览: 41
纯Python实现AES(高级加密标准)加解密算法通常会依赖于第三方库,如`pycryptodome`或`cryptography`。以下是使用`pycryptodome`库的一个简单示例:
首先,确保安装了`pycryptodome`,可以使用pip进行安装:
```bash
pip install pycryptodome
```
然后,你可以通过以下代码来实现AES的加解密:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
def aes_encrypt(plaintext, key):
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
iv = cipher.iv
return b64encode(iv + ciphertext)
def aes_decrypt(ciphertext, key):
ciphertext = b64decode(ciphertext)
iv = ciphertext[:16]
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv=iv)
plaintext = unpad(cipher.decrypt(ciphertext[16:]), AES.block_size)
return plaintext.decode('utf-8')
# 示例
key = 'your_secret_key_1234567890'
plaintext = 'Hello, world!'
encrypted_text = aes_encrypt(plaintext, key)
decrypted_text = aes_decrypt(encrypted_text, key)
print(f"Encrypted text: {encrypted_text}")
print(f"Decrypted text: {decrypted_text}")
阅读全文