
Python对文档加密的方法有多种:使用内置的库如cryptography、PyCrypto、Fernet,以及第三方库如PyPDF2、python-docx。其中,推荐使用cryptography库因为其功能强大、安全性高、文档丰富。
一、使用cryptography库进行对称加密
cryptography库是Python中功能非常强大且广泛使用的加密库。它支持多种加密方式,包括对称加密、非对称加密、哈希函数等。下面我们将详细介绍如何使用cryptography进行对称加密。
1. 安装cryptography库
首先,我们需要安装cryptography库。可以使用以下命令进行安装:
pip install cryptography
2. 生成密钥并加密文档
在使用对称加密时,我们需要生成一个密钥,并使用该密钥对文档进行加密。下面是一个简单的示例代码:
from cryptography.fernet import Fernet
生成密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)
加密文档
with open('sample.txt', 'rb') as file:
file_data = file.read()
encrypted_data = cipher_suite.encrypt(file_data)
保存加密后的文件
with open('encrypted_sample.txt', 'wb') as file:
file.write(encrypted_data)
保存密钥
with open('key.key', 'wb') as key_file:
key_file.write(key)
3. 解密文档
加密后的文档需要使用相同的密钥进行解密。下面是解密的示例代码:
from cryptography.fernet import Fernet
读取密钥
with open('key.key', 'rb') as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
读取加密的文件
with open('encrypted_sample.txt', 'rb') as file:
encrypted_data = file.read()
解密数据
decrypted_data = cipher_suite.decrypt(encrypted_data)
保存解密后的文件
with open('decrypted_sample.txt', 'wb') as file:
file.write(decrypted_data)
二、使用PyCrypto库进行加密
PyCrypto库也是一个非常流行的加密库,但由于其已不再维护,建议使用pycryptodome库作为替代品。下面是如何使用pycryptodome进行文档加密的示例。
1. 安装pycryptodome库
pip install pycryptodome
2. 对文档进行加密
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os
def pad(data):
return data + b"