Json 嵌套加密值 - Python

Json nested encryption value - Python

我有一个 json 输出文件,我正在尝试使用 sha256 加密方法加密其中的 key(name) 值。在字典列表中出现两次名称,但每次我写的时候,变化都会反映一次。谁能告诉我我哪里不见了?

Json structure:
Output.json
{
    "site": [
        {
            "name": "google", 
            "description": "Hi I am google"
        }, 
        {
            "name": "microsoft", 
            "description": "Hi, I am microsoft"
        }
    ],
    "veg": [
        {
            "status": "ok",
            "slot": null
        },
        {
            "status": "ok"
        }
    ]
}

代码:

import hashlib
import json

class test():
    def __init__(self):
    
    def encrypt(self):
        with open("Output.json", "r+") as json_file:
            res = json.load(json_file)
            for i in res['site']:
                for key,val in i.iteritems():
                    if 'name' in key:
                        hs = hashlib.sha256(val.encode('utf-8')).hexdigest()
                        res['site'][0]['name'] = hs
                        json_file.seek(0)
                        json_file.write(json.dumps(res,indent=4))
                        json_file.truncate()
                        

当前Output.json

{
    "site": [
        {
            "name": "bbdefa2950f49882f295b1285d4fa9dec45fc4144bfb07ee6acc68762d12c2e3", 
            "description": "Hi I am google"
        }, 
        {
            "name": "microsoft", 
            "description": "Hi, I am microsoft"
        }
    ],
    "veg": [
        {
            "status": "ok",
            "slot": null
        },
        {
            "status": "ok"
        }
    ]
}

我认为你的问题出在这一行:

res['site'][0]['name'] = hs

您总是在更改 site 列表中第一张地图的 name 字段。我想你希望它是:

i['name'] = hs

以便您更新当前正在处理的地图(由 i 指向)。

您可以利用字典是用来按键查找值的事实,而不是遍历字典中的每个项目,然后这样做:

if 'name' in i:
    val = i['name']
    hs = hashlib.sha256(val.encode('utf-8')).hexdigest()
    i['name'] = hs
    json_file.seek(0)
    json_file.write(json.dumps(res, indent=4))
    json_file.truncate()

而不是这个:

for key,val in i.iteritems():
    if 'name' in key:
        ...

另外,iteritems()应该是items()if 'name' in key应该是if key == 'name',因为key是一个字符串。实际上,您将匹配任何条目与包含子字符串 'name'.

的键名

更新:我注意到您多次写入整个文件,每个加密的 name 条目一次。即使没有这个,我也建议您打开文件两次......一次用于阅读,一次用于写入。这优于打开文件进行读取和写入,并且必须查找和截断。因此,在您的代码的完整版本中,这是我建议的所有更改以及其他一些调整:

import hashlib
import json

class Test:

    def encrypt(self, infile, outfile=None):
        if outfile is None:
            outfile = infile
        with open(infile) as json_file:
            res = json.load(json_file)
        for i in res['site']:
            if 'name' in i:
                i['name'] = hashlib.sha256(i['name'].encode('utf-8')).hexdigest()
        with open(outfile, "w") as json_file:
            json.dump(res, json_file, indent=4)

Test().encrypt("/tmp/input.json", "/tmp/output.json")

# Test().encrypt("/tmp/Output.json")  # <- this form will read and write to the same file

生成的文件内容:

{
    "site": [
        {
            "name": "bbdefa2950f49882f295b1285d4fa9dec45fc4144bfb07ee6acc68762d12c2e3",
            "description": "Hi I am google"
        },
        {
            "name": "9fbf261b62c1d7c00db73afb81dd97fdf20b3442e36e338cb9359b856a03bdc8",
            "description": "Hi, I am microsoft"
        }
    ],
    "veg": [
        {
            "status": "ok",
            "slot": null
        },
        {
            "status": "ok"
        }
    ]
}