Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

hashlib - Json nested encryption value - Python

I have a json output file and I am trying to encrypt a value of key(name) in it using sha256 encryption method. Have two occurence of name in a list of dict but everytime when I write, the changes reflecting once. Can anybody tell me where I am missing?

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"
        }
    ]
}

Code:

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()
                        

Current Output.json

{
    "site": [
        {
            "name": "bbdefa2950f49882f295b1285d4fa9dec45fc4144bfb07ee6acc68762d12c2e3", 
            "description": "Hi I am google"
        }, 
        {
            "name": "microsoft", 
            "description": "Hi, I am microsoft"
        }
    ],
    "veg": [
        {
            "status": "ok",
            "slot": null
        },
        {
            "status": "ok"
        }
    ]
}
question from:https://stackoverflow.com/questions/65829083/json-nested-encryption-value-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think your problem is in this line:

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

you are always changing the name field of the first map in the site list. I think you want this to be:

i['name'] = hs

so that you are updating the map you are currently working on (pointed to by i).

Instead of iterating over each item in the dictionary, you could make use of the fact that dictionaries are made for looking up values by key, and do this:

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()

instead of this:

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

Also, iteritems() should be items(), and if 'name' in key should be if key == 'name', as key is a string. As it is, you'd be matching any entry with a key name containing the substring 'name'.

UPDATE: I noticed that you are writing the entire file multiple times, once for each name entry that you encrypt. Even without this I would recommend that you open the file twice...once for reading and once for writing. This is preferred over opening a file for both reading and writing, and having to seek and truncate. So, here are all of my suggested changes, along with a few other tweaks, in a full version of your code:

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

Resulting file contents:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...