使用Python加密文本文件可以通过多种方法实现,以下是几种常见的方法:
方法一:使用`hashlib`模块进行SHA1加密
import hashlibdef sha1_encrypt_file(input_file, output_file):with open(input_file, 'rb') as file:content = file.read()sha1 = hashlib.sha1()sha1.update(content)encrypted_content = sha1.hexdigest()with open(output_file, 'w') as file:file.write(encrypted_content)
方法二:使用XOR加密算法
def xor_encrypt_decrypt(input_string, key):return ''.join(chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(input_string))def encrypt_file(input_file, output_file, key):with open(input_file, 'r', encoding='utf-8') as file:content = file.read()encrypted_content = xor_encrypt_decrypt(content, key)with open(output_file, 'w', encoding='utf-8') as file:file.write(encrypted_content)def decrypt_file(input_file, output_file, key):with open(input_file, 'r', encoding='utf-8') as file:encrypted_content = file.read()decrypted_content = xor_encrypt_decrypt(encrypted_content, key)with open(output_file, 'w', encoding='utf-8') as file:file.write(decrypted_content)
方法三:使用`cryptography`库进行AES加密
from cryptography.fernet import Fernetdef 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)

方法四:使用`secrets`库生成随机密钥进行XOR加密
from secrets import token_bytesdef random_key(length):return token_bytes(nbytes=length)def xor_encrypt_decrypt(input_string, key):key_int = int.from_bytes(key, 'big')return ''.join(chr(ord(c) ^ key_int[i % len(key_int)]) for i, c in enumerate(input_string))def encrypt_file(input_file, output_file):with open(input_file, 'rb') as file:content = file.read()encrypted_content = xor_encrypt_decrypt(content, key)with open(output_file, 'wb') as file:file.write(encrypted_content)
注意事项
加密和解密时,请确保密钥的安全存储和传输。
对于不同的用途,可以选择不同的加密算法,例如AES通常比XOR更安全。
加密后的文件通常以`.enc`或其他扩展名标识。
解密时需要使用相同的密钥。
以上方法可以帮助你用Python加密文本文件。
