encry.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import json
  2. from cryptography.fernet import Fernet
  3. # 生成密钥,只需生成一次并保存
  4. def generate_key():
  5. key = Fernet.generate_key()
  6. with open("secret.key", "wb") as key_file:
  7. key_file.write(key)
  8. # 读取密钥
  9. def load_key():
  10. with open("secret.key", "rb") as key_file:
  11. return key_file.read()
  12. # 加密 JSON 文件
  13. def encrypt_json(input_file, encrypted_file):
  14. key = load_key()
  15. fernet = Fernet(key)
  16. with open(input_file, 'r', encoding='utf-8') as f:
  17. data = json.load(f)
  18. json_str = json.dumps(data)
  19. encrypted_data = fernet.encrypt(json_str.encode('utf-8'))
  20. with open(encrypted_file, 'wb') as f:
  21. f.write(encrypted_data)
  22. # 解密 JSON 文件
  23. def decrypt_json(encrypted_file, output_file):
  24. key = load_key()
  25. fernet = Fernet(key)
  26. with open(encrypted_file, 'rb') as f:
  27. encrypted_data = f.read()
  28. decrypted_data = fernet.decrypt(encrypted_data)
  29. data = json.loads(decrypted_data.decode('utf-8'))
  30. with open(output_file, 'w', encoding='utf-8') as f:
  31. json.dump(data, f, indent=4, ensure_ascii=False)
  32. # 示例用法
  33. if __name__ == "__main__":
  34. # 只需生成一次密钥
  35. # generate_key()
  36. # 加密
  37. encrypt_json("siwei_config.json", "siwei_config.json.enc")
  38. # 解密
  39. # decrypt_json("siwei_config_encry.json", "data_decrypted.json")