suggested method of encrypting via python

Viewed 66

thanks for your time and effort but I think I probably misdeliver what I wanted, my fault.

Long story short, is there any way you can encrypt the certain string or the whole array?

{
    "gender": "male",
    "phone-number": "1234567890",
    "job": "student",
    "location": {
        "county": "LA-county",
        "town": "sunvalley",
        "country": "USA",
        "apartment-number": "13579abcdefg"
    },
    "item": {
        "item-type": "cloth",
        "item-size": "large",
        "item-number": "xyz24680abc",
        "item-material": "cotton"
    },
    "hairstyle": "long",
    "alive": "true",
}

let's say that apartment-number: 13579abcdefg needs to be encrypted. Can I use fernet as below?

from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
encrypt_value = f.encrypt(b"YourString")
f.decrypt(encrypt_value)

I heard some people mention about the base64... which method would you recommend when it comes for encrypting certain values?

5 Answers

Just get the first three characters, three dots, then the last three characters.

def censor(string):
    return string[:3] + "..." + string[-3:]

data["phone-number"] = censor(data["phone-number"])
data["apartment-number"] = censor(data["item-number"])
data["location"]["apartment-number"] = censor(data["location"]["apartment-number"])

This code will run over the JSON and will parse the names from the keys in the JSON that in values_to_change list with the format that specified in the question

import json

with open('filename.json') as f:
    data = json.load(f)

values_to_change = ["phone-number", "apartment-number", "item-number"]
for k, v in data.items():
    if isinstance(v, str):
        if k in values_to_change:
            data[k] = "{}...{}".format(v[:3], v[-3:])
    elif isinstance(v, dict):
        for kv, vv in v.items():
            if kv in values_to_change:
                data[k][kv] = "{}...{}".format(vv[:3], vv[-3:])


with open('newfilename.json', 'w') as f:
    json.dump(data, f, indent=2)

Output

{'gender': 'male',
 'phone-number': '123...890',
 'job': 'student',
 'location': {'county': 'LA-county',
  'town': 'sunvalley',
  'country': 'USA',
  'apartment-number': '135...efg'},
 'item': {'item-type': 'cloth',
  'item-size': 'large',
  'item-number': 'xyz...abc',
  'item-material': 'cotton'},
 'hairstyle': 'long',
 'alive': 'true'}

Here is a solution that will account for nested JSON:


def mask_sensitive(payload, fields, n_front=3, n_back=3):
    out = {}
    for k, v in payload.items():

        # if it's a dict, recurse
        if isinstance(v, dict):
            out[k] = mask_sensitive(v, fields, n_front, n_back)

        # this assumes the field is a string, and not an iterable
        # but you can always add logic to allow ints, lists, etc.
        elif k in fields:
            out[k] = v[:n_front] + "..." + v[-n_back:]

        else:
            out[k] = v
    return out

There are some things you may want to write logic for, like, if the field is less than 3 characters long, how do you want to pad the sensitive information? But this gives you a good jumping off point. Example:

>>> import pprint
>>> pprint.pprint(mask_sensitive(x, ["phone-number", "apartment-number"]))
{'alive': 'true',
 'gender': 'male',
 'hairstyle': 'long',
 'item': {'item-material': 'cotton',
          'item-number': 'xyz24680abc',
          'item-size': 'large',
          'item-type': 'cloth'},
 'job': 'student',
 'location': {'apartment-number': '135...efg',
              'country': 'USA',
              'county': 'LA-county',
              'town': 'sunvalley'},
 'phone-number': '123...890'}

Using @Clinton Graham, plus some edits as you will get TypeError: unhashable type: 'slice' otherwise - something like this should work.

import json
import pandas as pd

with open('filename.json') as f:
    data = json.load(f)


def reformat(data):
    return data.values[:, 3] + "..." + data.valies[-3:]


data["phone-number"] = reformat(data["phone-number"])
data["item"]["item-number"] = reformat(data["item"]["item-number"])
data["location"]["apartment-number"] = reformat(data["location"]["apartment-number"])



print(reformat(data))

Parsing dict is very important in this code. parse_dict method will parse all elements in dict. If any type of any element in data is dict, then we will use recursion, to call parse_dict again, to parse inner dict. After this we check if key is one of ["phone-number", "apartment-number", "item-number"], if yes, then we change its value, to required format.

In this way, if in future, we want to change any other key, apart from ["phone-number", "apartment-number", "item-number"], then we simply need to append new key, in our list and this code will work.

import json
def parse_dict(data):
    for key, value in data.items():
        if type(value) == dict:
            parse_dict(value)
        if key in ["phone-number", "apartment-number", "item-number"]: 
            data[key] = value[:3] + "..." + value[-3:]

def main():
    with open('sample.json') as f: 
        data = json.load(f)
    parse_dict(data)
    print("*****: ", data)
    with open('newfilename.json', 'w') as f:
        json.dump(data, f, indent=2)
main()
Related