在Python中加密文件可以通过多种方法实现,以下是使用`cryptography`库进行AES加密的示例代码:
```python
from cryptography.fernet import Fernet
def encrypt_file(file_path, key):
读取文件内容
with open(file_path, 'rb') as file:
file_content = file.read()
创建加密器
cipher = Fernet(key)
加密文件内容
encrypted_content = cipher.encrypt(file_content)
将加密后的内容写入新文件
encrypted_file_path = file_path + '.enc'
with open(encrypted_file_path, 'wb') as encrypted_file:
encrypted_file.write(encrypted_content)
示例用法
file_path = 'path/to/file.txt'
key = Fernet.generate_key() 生成密钥
encrypt_file(file_path, key)
如果你需要加密整个目录,可以使用以下代码:
```python
import os
import hashlib
def encrypt_directory(directory, password):
for root, dirs, files in os.walk(directory):
for file in files:
path = os.path.join(root, file)
with open(path, 'rb') as f:
data = f.read()
key = hashlib.sha256(password.encode()).hexdigest()
encrypted_data = bytearray(x ^ ord(key[i % len(key)]) for i, x in enumerate(data))
with open(path, 'wb') as f:
f.write(encrypted_data)
示例用法
directory_path = 'path/to/directory'
password = input('Enter a password: ')
encrypt_directory(directory_path, password)
请注意,上述代码示例使用了`cryptography`库,该库需要安装。你可以使用`pip`来安装:
```
pip install cryptography
如果你需要更高级的加密方法,比如非对称加密,可以使用`cryptography`库中的其他函数,例如RSA加密。
请根据你的具体需求选择合适的加密算法和库,并确保密钥的安全管理