How to mask sensitive values ​​in JSON for logging purposes

I have several similar JSON structures that I want to write to an SQL table for logging. However, some of the JSON fields contain sensitive information that I want to partially defer, so the full value is not displayed in the log.

Here is an example of one of the JSON structures:

{
  "Vault": 1,
  "Transaction": {
    "gateway": {
      "Login": "Nick",
      "Password": "Password"
    },
    "credit_card": {
      "number": "4111111111111"
    }
  }
}

In this case, I am trying to change the credit card number 4111so that it looks like 4xxx1111in JSON. I use Newtonsoft and deserialize JSON in JObject, but I am fixated on how to mask the value. I think the key is to something with JToken, but have not yet understood. I would like to make this solution as general as possible so that it works with any JSON structure that I would need to log out of the system.

.

+4
1

, :

  • , , . , - , :

    public static string Obscure(string s)
    {
        if (string.IsNullOrEmpty(s)) return s;
        int len = s.Length;
        int leftLen = len > 4 ? 1 : 0;
        int rightLen = len > 6 ? Math.Min((len - 6) / 2, 4) : 0;
        return s.Substring(0, leftLen) +
               new string('*', len - leftLen - rightLen) +
               s.Substring(len - rightLen);
    }
    
  • , JToken JSONPath. , SelectTokens. .

    public static void ObscureMatchingValues(JToken token, IEnumerable<string> jsonPaths)
    {
        foreach (string path in jsonPaths)
        {
            foreach (JToken match in token.SelectTokens(path))
            {
                match.Replace(new JValue(Obscure(match.ToString())));
            }
        }
    }
    
  • , JSONPath , JSON, . JSON , , Password , , number, credit_card. JSONPath, $..Password $..credit_card.number . ( , JSONPath Json.Net.) , , .

  • , JSON, :

    JToken token = JToken.Parse(json);
    string[] jsonPaths = YourConfigSettings.GetJsonPathsToObscure();
    ObscureMatchingValues(token, jsonPaths);
    YourLogger.Log(token.ToString(Formatting.None));
    

-: https://dotnetfiddle.net/dGPyJF

+5

All Articles