import jwt
import os
# 密钥用于HS256加密,必须保密
SECRET_KEY = "your-secret-key-1234567890" # 请在实际使用中更换为安全的密钥
def encrypt_file(input_file, output_file):
"""
使用HS256加密文本文件
"""
try:
# 读取输入文件内容
with open(input_file, 'r', encoding='utf-8') as f:
plaintext = f.read()
# 使用HS256算法加密
encoded_jwt = jwt.encode({"data": plaintext}, SECRET_KEY, algorithm="HS256")
# 将加密后的内容写入输出文件
with open(output_file, 'w', encoding='utf-8') as f:
f.write(encoded_jwt)
print(f"文件已加密并保存到 {output_file}")
except FileNotFoundError:
print(f"错误:找不到文件 {input_file}")
except Exception as e:
print(f"加密时发生错误:{str(e)}")
def decrypt_file(encrypted_file, output_file):
"""
使用HS256解密文本文件
"""
try:
# 读取加密文件内容
with open(encrypted_file, 'r', encoding='utf-8') as f:
encoded_jwt = f.read()
# 使用HS256算法解密
decoded = jwt.decode(encoded_jwt, SECRET_KEY, algorithms=["HS256"])
plaintext = decoded["data"]
# 将解密后的内容写入输出文件
with open(output_file, 'w', encoding='utf-8') as f:
f.write(plaintext)
print(f"文件已解密并保存到 {output_file}")
except FileNotFoundError:
print(f"错误:找不到文件 {encrypted_file}")
except jwt.InvalidTokenError:
print("错误:无效的加密文件或密钥不匹配")
except Exception as e:
print(f"解密时发生错误:{str(e)}")
if __name__ == "__main__":
# 示例用法
input_file = "input.txt" # 待加密的原始文本文件
encrypted_file = "encrypted.txt" # 加密后的文件
decrypted_file = "decrypted.txt" # 解密后的文件
# 确保输入文件存在
if not os.path.exists(input_file):
with open(input_file, 'w', encoding='utf-8') as f:
f.write("这是一个测试文本文件。\nHello, World!")
print(f"已创建示例输入文件 {input_file}")
# 加密文件
encrypt_file(input_file, encrypted_file)
# 解密文件
decrypt_file(encrypted_file, decrypted_file)