import json
from cryptography.fernet import Fernet

# 生成密钥，只需生成一次并保存
def generate_key():
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

# 读取密钥
def load_key():
    with open("secret.key", "rb") as key_file:
        return key_file.read()

# 加密 JSON 文件
def encrypt_json(input_file, encrypted_file):
    key = load_key()
    fernet = Fernet(key)

    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    json_str = json.dumps(data)
    encrypted_data = fernet.encrypt(json_str.encode('utf-8'))

    with open(encrypted_file, 'wb') as f:
        f.write(encrypted_data)

# 解密 JSON 文件
def decrypt_json(encrypted_file, output_file):
    key = load_key()
    fernet = Fernet(key)

    with open(encrypted_file, 'rb') as f:
        encrypted_data = f.read()

    decrypted_data = fernet.decrypt(encrypted_data)
    data = json.loads(decrypted_data.decode('utf-8'))

    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4, ensure_ascii=False)

# 示例用法
if __name__ == "__main__":
    # 只需生成一次密钥
    # generate_key()

    # 加密
    encrypt_json("siwei_config.json", "siwei_config.json.enc")

    # 解密
    # decrypt_json("siwei_config_encry.json", "data_decrypted.json")
