简体   繁体   中英

How to mask a value in java?

I have a pinNumber value. How to mask it (ie) say if my pinNumber is 1234 and mask it with four asteriks symbol instead of showing the numbers. This masked value will be shown in a webpage using a jsp.

<input type="PASSWORD" name="password">

如果要在标签上显示密码,只需显示5或6个星号字符,因为您不希望通过使标签的长度与密码的长度相同来提供线索。

At some point in your code, you will convert the number to a string for display. At this point, you can simply call String's replaceAll method to replace all the characters from 0-9 with * character :

s.replaceAll("[0-9]", "*")

well - this is how you do it directly in Java. In JSP it is taken care of for you, as other posters show, if you select 'password' type on your input.

You create form like that

<form action="something" method="post">
pinNumber:<input type="password" name="pass"/>
<input type="submit" value="OK"/>
</form>

then it will change the into *

This code might help you.

    class Password {
        final String password; // the string to mask

      Password(String password) { this.password = password; } // needs null protection

         // allow this to be equal to any string
        // reconsider this approach if adding it to a map or something?

      public boolean equals(Object o) {
            return password.equals(o);
        }
        // we don't need anything special that the string doesnt

      public int hashCode() { return password.hashCode(); }

        // send stars if anyone asks to see the string - consider sending just
        // "******" instead of the length, that way you don't reveal the password's length
        // which might be protected information

      public String toString() {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; < password.length(); i++) 
                sb.append("*");
            return sb.toString();
        }
    }

I use following code in my many application and it works nicely.

public class Test {
    public static void main(String[] args) {
        String number = "1234";
        StringBuffer maskValue = new StringBuffer();
        if(number != null && number.length() >0){
            for (int i = 0; i < number.length(); i++) {
                maskValue.append("*");
            }
        }
        System.out.println("Masked Value of 1234 is "+maskValue);
    }
}
Ans - Masked Value of 1234 is ****

Two ways (this will mask all charecters not only numbers) :

private String mask(String value) {
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < value.length(); sb.append("*"), i++); 
    return sb.toString();
}

or:

private String mask(String value) {
    return value.replaceAll(".", "*");
}

I use the second one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM