Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obfuscating password parameters inside a JSON using Java Regular Expressions

Tags:

java

json

regex

I would like to obscure certain password type words within a json string, such that the following:

"password":"foobar1"

would be replaced with

"password":"XXXXX"

or

"pwd":"foobar1"

would be replaced with

"pwd":"XXXXX"

I was able to do it using the following Pattern and replaceAll method

REGEX_JSON_PASSWORD = 
    Pattern.compile("\"(?i)(password|pwd)\":\"[\\w\\p{Punct}&&[^&]]*?\"");
replacementString = 
    REGEX_JSON_PASSWORD.matcher(returnMe).replaceAll("\"$1\":\"XXXXXXXXXXXXXXXX\"");

I don't like having to add the double quotes in the replacement string, but if I don't add them, all I get is

pwd:foobar1 

(no quotes)

Is there a more efficient way of implementing the replaceAll than what is show above?

like image 957
Joe Devilla Avatar asked Sep 24 '26 08:09

Joe Devilla


2 Answers

First, a good way is to use a json parser to make change into your JSON.

With your method:

change your pattern and your replacement to:

pattern: (?<=\"(?i)p(?>assword|wd)\":\")[^\"]++ 
replacement: XXXXXXXXXXXXXXXX

With this you avoid quotes question and backreference in the replacement, cause you have matched only what you need: foobar1

like image 167
Casimir et Hippolyte Avatar answered Sep 27 '26 00:09

Casimir et Hippolyte


afaict, string replacement are better done using regular expressions, as ugly as they may look like.

I think with the following you nailed it:

REGEX_JSON_PASSWORD = Pattern.compile("\"(?i)(password|pwd)\":\"[\\w\\p{Punct}&&[^&]]*?\"");
replacementString =  REGEX_JSON_PASSWORD.matcher(returnMe).replaceAll("\"$1\":\"XXXXXXXXXXXXXXXX\"");

If you keep the REGEX_JSON_PASSWORD instanciated once, and apply the replacementString on each string.

But if you feed your data to a JSON parser, like gson, you may want to replace the password string just before it gets serialized to JSON, and thus just make a plain stupid replace of the value of your string. But that will all depend on the context of your code.

like image 36
zmo Avatar answered Sep 26 '26 23:09

zmo