2. Why char array is more suitable for storing passwords than String in Java

Another tricky Java problem based on String, I believe that only a few Java programmers can answer this question correctly. This is a really tough core Java interview question, and a solid knowledge of String is required to answer this question.

This is a question I asked a friend of mine in a Java interview recently. He is being interviewed for the position of technical director and has more than 6 years of experience. If you have not encountered this situation, character arrays and strings can be used to store text data, but it is difficult to choose one over the other. But as my friend said, any String-related question must have some clues about the special properties of the string, such as immutability, and he uses it to convince the questioner. Here, we will explore some of the reasons why you should use char[] to store passwords instead of String.

String:

1) Since strings are immutable in Java, if you store the password as plain text, it will be available in memory until the garbage collector clears it. And for reusability, there will be String in the string pool , It is likely to remain in the memory for a long time, thus posing a security threat.

Since anyone with access to the memory dump can find the password in clear text, this is another reason, you should always use encrypted passwords instead of plain text. Since the string is immutable, the content of the string cannot be changed, because any change will produce a new string, and if you use char[], you can set all elements to blanks or zeros. Therefore, storing passwords in character arrays can significantly reduce the security risk of password stealing.

2) Java itself recommends using the getPassword() method of JPasswordField, which returns a char[] and the deprecated getTex() method, which returns the password in plain text, due to security reasons. Follow the recommendations of the Java team and stick to the standard instead of opposing it.

3) When using String, there is always the risk of printing plain text in the log file or console, but if using Array, the content of the array will not be printed but its memory location. Although not a real reason, it still makes sense.

String strPassword =“Unknown”; 
char [] charPassword = new char [] {'U','n','k','w','o','n'}; 
System.out.println(“字符密码:”+ strPassword);
System.out.println(“字符密码:”+ charPassword);

Output

String password: Unknown
character password: [C @110b053
I also recommend using a hashed or encrypted password instead of plain text, and clear it from memory immediately after verification is complete. Therefore, in Java, using character arrays to store passwords is a better choice than character strings. Although only using char[] is not enough, you also need to erase the content to be more secure

Guess you like

Origin blog.csdn.net/weixin_45627031/article/details/112852627