在Python中,使用json庫進行數據加密和解密可以通過多種方式實現。以下是一些常見的方法:
import json
from cryptography.fernet import Fernet
# 生成密鑰
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 待加密的數據
data = {"name": "John", "age": 30}
# 將數據轉換為JSON字符串
data_json = json.dumps(data)
# 加密JSON字符串
encrypted_data = cipher_suite.encrypt(data_json.encode())
print("加密后的數據:", encrypted_data)
# 解密JSON字符串
decrypted_data = cipher_suite.decrypt(encrypted_data).decode()
# 將解密后的JSON字符串轉換回字典
decrypted_dict = json.loads(decrypted_data)
print("解密后的數據:", decrypted_dict)
import json
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# 待加密的數據
data = {"name": "John", "age": 30}
# 將數據轉換為JSON字符串
data_json = json.dumps(data)
# 生成隨機密鑰
key = get_random_bytes(16)
# 創建AES加密器
cipher = AES.new(key, AES.MODE_CBC)
# 加密JSON字符串
encrypted_data = cipher.encrypt(pad(data_json.encode(), AES.block_size))
print("加密后的數據:", encrypted_data)
# 解密JSON字符串
cipher = AES.new(key, AES.MODE_CBC, cipher.iv)
decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)
print("解密后的數據:", decrypted_data.decode())
# 將解密后的JSON字符串轉換回字典
decrypted_dict = json.loads(decrypted_data.decode())
print("解密后的數據:", decrypted_dict)
請注意,加密和解密數據時,應確保密鑰的安全存儲和管理,因為密鑰的安全性對于保護數據至關重要。