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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With