如何在Python中加密JSON

Red*_*ite 9 python encryption json data-security

我有一个 JSON 文件。我正在 python 中运行一个程序,其中从 JSON 文件中提取数据。有没有什么方法可以用密钥加密 JSON 文件,这样如果有人随机打开该文件,它会是一堆乱七八糟的字符,但是当密钥输入到程序时,它会解密并能够读取它?提前致谢。

小智 12

是的,您可以加密 .json 文件。确保通过键入以下内容安装加密包

pip install cryptography
# or on windows:
python -m pip install cryptography
Run Code Online (Sandbox Code Playgroud)

然后,你可以制作一个类似于我的程序:

#this imports the cryptography package
from cryptography.fernet import Fernet

#this generates a key and opens a file 'key.key' and writes the key there
key = Fernet.generate_key()
with open('key.key','wb') as file:
    file.write(key)

#this just opens your 'key.key' and assings the key stored there as 'key'
with open('key.key','rb') as file:
    key = file.read()

#this opens your json and reads its data into a new variable called 'data'
with open('filename.json','rb') as f:
    data = f.read()

#this encrypts the data read from your json and stores it in 'encrypted'
fernet = Fernet(key)
encrypted = fernet.encrypt(data)

#this writes your new, encrypted data into a new JSON file
with open('filename.json','wb') as f:
    f.write(encrypted)
Run Code Online (Sandbox Code Playgroud)

请注意该块:

with open('key.key','wb') as file:
    file.write(key)

#this just opens your 'key.key' and assigns the key stored there as 'key'
with open('key.key','rb') as file:
    key = file.read()
Run Code Online (Sandbox Code Playgroud)

没有必要。它只是将生成的密钥存储在安全位置并将其读回的一种方法。如果需要,您可以删除该块。

如果您需要进一步帮助,请告诉我:)


Sep*_*Sep 5

您可以使用非对称加密和解密来做到这一点。这是完整的文章文章 请记住这一点,您应该在加密之前对字符串数据进行编码

读取json数据:

data = json.load(open('data.json'))
Run Code Online (Sandbox Code Playgroud)

对于加密:

python -m pip install cryptography
Run Code Online (Sandbox Code Playgroud)

要创建/存储密钥并加密 json 数据,您应该执行以下操作:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

def create_keys():
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = private_key.public_key()

    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    with open('private_key.pem', 'wb') as f:
        f.write(pem)
    pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    with open('public_key.pem', 'wb') as f:
        f.write(pem)


def get_private_key():
    with open("private_key.pem", "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    return private_key

def get_public_key():
    with open("public_key.pem", "rb") as key_file:
        public_key = serialization.load_pem_public_key(
        key_file.read(),
        backend=default_backend()
    )
    return public_key

def encrypt():
    # createKeys()
    public_key = get_public_key()
    massage = str(data).encode('utf-8')
    encrypted = public_key.encrypt(massage, padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None))
    private_key = get_private_key()
    original_message = private_key.decrypt(encrypted, padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None))

    return original_message.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

对于解密你应该这样做:

original_message = private_key.decrypt(
    encrypted,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
Run Code Online (Sandbox Code Playgroud)