怎么用python对称加密一个gz压缩文件
时间: 2023-11-26 09:03:54 浏览: 30
可以使用Python的cryptography库进行对称加密。以下是一个使用AES算法对gz压缩文件进行加密的示例代码:
```python
import gzip
from cryptography.fernet import Fernet
# 读取要加密的文件
with open('file.txt.gz', 'rb') as f:
data = f.read()
# 创建加密密钥
key = Fernet.generate_key()
# 创建加密器
cipher = Fernet(key)
# 对文件数据进行加密
encrypted_data = cipher.encrypt(data)
# 将加密后的数据写入文件
with open('file_encrypted.txt', 'wb') as f:
f.write(encrypted_data)
# 将密钥写入文件
with open('key.txt', 'wb') as f:
f.write(key)
# 读取加密后的数据
with open('file_encrypted.txt', 'rb') as f:
encrypted_data = f.read()
# 读取密钥
with open('key.txt', 'rb') as f:
key = f.read()
# 创建解密器
cipher = Fernet(key)
# 对加密数据进行解密
decrypted_data = cipher.decrypt(encrypted_data)
# 将解密后的数据写入文件
with gzip.open('file_decrypted.txt.gz', 'wb') as f:
f.write(decrypted_data)
```
以上代码将文件`file.txt.gz`进行加密,并将加密后的数据写入文件`file_encrypted.txt`。同时,将加密密钥保存在文件`key.txt`中。接着,代码读取加密后的数据和密钥,使用密钥创建解密器并对加密数据进行解密,并将解密后的数据写入文件`file_decrypted.txt.gz`中。