使用Python加密文本文件可以通过多种方法实现,以下是几种常见的方法:
方法一:使用`hashlib`模块进行SHA1加密
import hashlib
def 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 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)
方法四:使用`secrets`库生成随机密钥进行XOR加密
from secrets import token_bytes
def 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加密文本文件。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/15140.html