使用pycryptodome库实现AES加密解密的完整代码
时间: 2024-10-09 15:06:41 浏览: 97
在Python中,使用pycryptodome库可以方便地实现AES(高级加密标准)的加密和解密。首先,你需要安装pycryptodome库,如果尚未安装,可以使用pip install pycryptodome命令。以下是使用AES的基本示例:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
# 设置密钥(16字节,也可以是32或256字节)
key = b'Sixteen byte key'
# 初始化AES cipher
cipher = AES.new(key, AES.MODE_CBC) # CBC模式是一种常用的加密模式
def encrypt(plaintext):
# 添加前缀,用于后续解密
iv = cipher.iv
ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
return b64encode(iv + ciphertext)
def decrypt(ciphertext):
decoded_ciphertext = b64decode(ciphertext)
iv = decoded_ciphertext[:AES.block_size]
ciphertext = decoded_ciphertext[AES.block_size:]
plain_text = unpad(cipher.decrypt(ciphertext), AES.block_size).decode('utf-8')
return plain_text
# 示例
plaintext = 'Hello, world!'
encrypted_text = encrypt(plaintext)
print("Encrypted text:", encrypted_text)
decrypted_text = decrypt(encrypted_text)
print("Decrypted text:", decrypted_text)
```
注意,这个例子使用了CBC模式(Cipher Block Chaining),并且对明文进行了PKCS7填充,确保块大小一致。实际应用中,需要考虑如何安全地存储IV(初始向量)。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)