2

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?

Joe Devilla
  • 227
  • 4
  • 16
  • 6
    Don't bother creating your own "security encryption", just use one of the built in cryptography APIs such as `javax.crypto.Cipher`. See [this question](http://stackoverflow.com/questions/1132567/encrypt-password-in-configuration-files-java). – 0x6C38 Jun 09 '13 at 22:48
  • Not only is that a bad idea, but it is also a bad idea to use regexes to modify JSON. There are JSON libraries for this (Jackson in particular is fantastic at "JSON edition"). – fge Jun 09 '13 at 22:56
  • ok, I did not get your question, to be clear: you want to replace whatever full text password is showing by a string containing only XXXX. – zmo Jun 09 '13 at 22:58
  • 1
    please, use the verb "obfuscate" instead of "encrypt", so that there can't be any confusion in your question :-) – zmo Jun 09 '13 at 23:07

3 Answers3

2

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

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

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.

zmo
  • 24,463
  • 4
  • 54
  • 90
-1

You can also do something like this in PHP-land:

// Obfuscate / mask password in JSON string
$json = preg_replace('/"(pass|password)":"(.*?)"/i', '"$1":"****"', $json);
David Thomas
  • 4,027
  • 3
  • 28
  • 22