Search code examples
javastringstringbuilder

ensure removal of password at end of string using StringBuilder with java


I need to ensure that always at the end of this string when there is a password, from there it leaves the password masked and does not display.

Remembering that in the end, the value cannot always be cards-app, it can be a different value, I need to mask the end of this string from &password= in order to mask the password.

How can I do this for sure using StringBuilder?

Ex.:

https://hlg-gateway.odsus.com.br/token?grant_type=password&username=cards-app&password=cards-app;

expected output:

https://hlg-gateway.odsus.com.br/token?grant_type=password&username=cards-app&password=######;

This information is displayed in the log, I just want to make sure the end of the string is masked to not display the password.


Solution

  • As a note, StringBuilder is not required here—you could just use basic string concatenation.

    String string = "https://hlg-gateway.odsus.com.br/token?grant_type=password&username=cards-app&password=cards-app;";
    StringBuilder stringBuilder = new StringBuilder(string);
    int indexOfA = string.indexOf("&password=");
    indexOfA = string.indexOf('=', indexOfA);
    int indexOfB = string.indexOf(';', indexOfA);
    String mask = "#".repeat(indexOfB - indexOfA - 1);
    stringBuilder.replace(indexOfA, indexOfB, mask);
    

    Output

    https://hlg-gateway.odsus.com.br/token?grant_type=password&username=cards-app&password=#########;
    

    And, without the StringBuilder, you could use the following concatenation—in place of the replace method call.

    string = string.substring(0, indexOfA + 1) + mask + string.substring(indexOfB);