0

I am building SMS gateway where I want to mask any credential info (e.g. password) if the SMS message has any before persisting it into the database.

Here is the code:

String message = "Your password is [MASK:1234]!";

boolean bMasked = message.matches("(\\[MASK:)*(\\])");
String plainText = message.replaceAll(..., "");
String withStars = message.replaceAll("...", "*");

System.out.println("bMasked: " + bMasked);
System.out.println("plainText: " + plainText);
System.out.println("withStars:  " + withStar);

My knowledge in the regular expression is poor, so I need your help if possible to get the following output:

bMasked: true
plainText: Your password is 1234!
withStars: Your password is ****!
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 2
    Do you really want to store as many stars as characters the password has? This is not security wise. It gives too much hints to whatever gets this info to crack the password. – m0skit0 Feb 17 '13 at 10:23
  • @m0skit0 +1 You are right, it shouldn't be with the same length. – Eng.Fouad Feb 17 '13 at 10:24
  • Why include that line about the password in the SMS if it's going to be masked anyway (thankfully)? – kjetilh Feb 17 '13 at 10:25
  • @kjetilh the plain text will be sent to the client as SMS message, and after that the SMS message will be persisted into the database where other tools check the status of SMS messages via database. – Eng.Fouad Feb 17 '13 at 11:32

1 Answers1

1
String message = "Your password is [MASK:1234]!";

boolean bMasked = message.matches(".*\\[MASK:[^\\]]*\\].*");
String plainText = message.replaceAll("\\[MASK:([^\\]]*)\\]", "$1");
String withStars = message.replaceAll("\\[MASK:[^\\]]*\\]", "******");

System.out.println("bMasked: " + bMasked);
System.out.println("plainText: " + plainText);
System.out.println("withStars:  " + withStars);

gives you:

bMasked: true
plainText: Your password is 1234!
withStars:  Your password is ******!
Kent
  • 189,393
  • 32
  • 233
  • 301
  • Hmmm, `!` is not a part of the mask, if I remove it `bMasked` will be `false`. – Eng.Fouad Feb 17 '13 at 10:39
  • @Eng.Fouad match means "Returns: true if, and only if, this string matches the given regular expression" `!` is part of your string too. what do you want? – Kent Feb 17 '13 at 10:42
  • `bMasked` would be `true`, if only and only if `[MASK:blah]` is present. `blah` can be anything and can contain spaces. – Eng.Fouad Feb 17 '13 at 10:44