python AES加密解密
时间: 2025-02-06 22:09:42 浏览: 45
AES(Advanced Encryption Standard)是高级加密标准的缩写,它是对称加密算法中的一种。Python中有多个库能够实现AES加密和解密操作,其中`pycryptodome`是一个常用的选择。
### 安装 pycryptodome
如果你还没有安装这个库的话,请先用pip安装:
```bash
pip install pycryptodome
```
### Python AES 加密解密示例代码
以下是一段简单的例子展示如何在Python中使用AES来进行字符串的加密与解密:
#### 导入必要的模块
首先导入所需的类和方法:
```python
from Crypto.Cipher import AES
import base64
# 用于处理填充
from Crypto.Util.Padding import pad, unpad
```
#### 设置加解密使用的函数
接下来定义两个辅助函数用来执行实际的加密和解密逻辑:
```python
def encrypt(plain_text, key):
# 创建一个基于给定key的新AES Cipher实例
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC)
# 对明文进行PKCS7填充并编码为bytes类型后再加密
padded_plaintext = plain_text.encode('utf-8')
ct_bytes = cipher.encrypt(pad(padded_plaintext, AES.block_size))
# 将IV(初始化向量)附加上去以便后续正确解码;这里我们简单地把它base64转成string连在一起返回。
iv_base64 = base64.b64encode(cipher.iv).decode('utf-8')
ct_base64 = base64.b64encode(ct_bytes).decode('utf-8')
return f"{iv_base64}:{ct_base64}"
def decrypt(encryption_str, key):
try:
# 解析出IV部分以及真实的cipher text部分.
iv_base64, ct_base64 = encryption_str.split(':')
# 分别将两部分内容从base64恢复回来得到原本的数据形式。
iv = base64.b64decode(iv_base64)
ct = base64.b64decode(ct_base64)
# 使用相同的key创建一个新的AES Cipher对象,并传入之前保存下来的IV作为参数之一重新构造Cipher instance。
cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, iv=iv)
decrypted_data = unpad(cipher.decrypt(ct), AES.block_size)
return decrypted_data.decode('utf-8')
except Exception as e:
print(f"Error occurred during decryption - {str(e)}")
raise ValueError("Failed to Decrypt Data")
```
请注意,在上面的例子中,我们需要确保提供的`key`长度符合AES的要求——即必须为16字节、24字节或32字节长(对应于AES-128, AES-192 和 AES-256)。如果您的键不符合这些尺寸,则需要对其进行适当的截断或者扩展以满足需求。
#### 测试功能
现在我们可以尝试一下这两个新构建的方法了!
```python
if __name__ == "__main__":
secret_key = "thisisaverysecret"
message_to_encrypt = "Hello World!"
encrypted_message = encrypt(message_to_encrypt, secret_key)
print("Encrypted:", encrypted_message)
decrypted_message = decrypt(encrypted_message, secret_key)
print("Decrypted:", decrypted_message)
```
以上就是关于Python中的AES加密/解密的基本介绍啦~希望这对您有所帮助!如果您还有其他疑问或其他方面的需求,请随时告诉我哦。
阅读全文
相关推荐





