Python实现AES的加解密
时间: 2023-11-19 11:54:30 浏览: 123
Python可以使用Crypto库来实现AES的加解密。具体实现方法如下:
1. 导入所需的库:
```
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from Crypto.Util.Padding import pad, unpad
```
2. 创建AES对象:
```
password = b'1234567812345678' #秘钥,b就是表示为bytes类型
aes = AES.new(password,AES.MODE_ECB) #创建一个aes对象
```
3. 加密明文:
```
text = b'abcdefghijklmnhi' #需要加密的内容,bytes类型
en_text = aes.encrypt(text) #加密明文,bytes类型
```
4. 解密密文:
```
den_text = aes.decrypt(en_text) # 解密密文,bytes类型
```
另外,如果需要加密的数据较长,可以使用padding来填充数据,以保证数据长度为16的倍数。解密时需要先去除padding。
如果需要加密文件,可以使用类似以下代码:
```
from Crypto.Cipher import AES
import os
secret_key = b'xxxxxx' # Convert the secret key to bytes
input_file = 'xxx.zip.enc'
output_file = 'xxx.zip'
# Initialize the AES cipher with the secret key and ECB mode
cipher = AES.new(secret_key, AES.MODE_ECB)
# Get the size of the input file
file_size = os.path.getsize(input_file)
# Open the input and output files
with open(input_file, 'rb') as in_file, open(output_file, 'wb') as out_file:
# Read and decrypt the input file in chunks
while True:
chunk = in_file.read(AES.block_size)
if len(chunk) == 0:
break
out_chunk = cipher.decrypt(chunk)
out_file.write(out_chunk)
# Remove any padding from the output file
out_file.truncate(file_size - AES.block_size + len(out_chunk))
```
阅读全文