1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password. html
1)因为String在Java中是不可变的,若是你将密码以明文的形式保存成字符串,那么它将一直留在内存中,直到垃圾收集器把它清除。而因为字符串被放在字符串缓冲池中以方便重复使用,因此它就可能在内存中被保留很长时间,而这将致使安全隐患,由于任何可以访问内存(memory dump内存转储)的人都能清晰的看到文本中的密码,这也是为何你应该老是使用加密的形式而不是明文来保存密码。因为字符串是不可变的,因此没有任何方式能够修改字符串的值,由于每次修改都将产生新的字符串,然而若是你使用char[]来保存密码,你仍然能够将其中全部的元素都设置为空或者零。因此将密码保存到字符数组中很明显的下降了密码被窃取的风险。 java
2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it. api
2)Java自己也推荐使用JPasswordField组件的getPassword()方法,该方法将返回一个字符数组,而放弃了原来的getText()方法,这个方法把密码以明文的形式返回而可能会引发安全问题。因此,最好能遵从来自Java团队的建议而且坚持标准,而不是去反对它。 数组
3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense. 安全
3)使用字符串,在将文本输出到日志文件或者控制台的时候会存在风险。可是使用数组你不会把数组的内容打印出来,相反,打印出来的是数组在内存中的位置。尽管这算不上一个真正的缘由,但这仍然颇有意义。 ui
That's all on why character array is better choice than String for storing passwords in Java. Though using char[] is not just enough you need to erase content to be more secure. I also suggest working with hash'd or encrypted password instead of plain text and clearing it from memory as soon as authentication is completed. 加密
这就是所有的关于为何使用字符数组存储密码比字符串更好。只使用字符数组也是不够的,为了更安全你须要将数组内容进行转化。我也建议使用哈希的或者是加密过的密码而不是明文,而后一旦完成验证,就将它从内存中清除掉。 spa