爲何使用字符數組保存密碼比使用String保存密碼更好?(Why character arr...

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

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053


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



原文: http://javarevisited.blogspot.com/2012/03/why-character-array-is-better-than.html#ixzz2guhpuUJO
相關文章
相關標籤/搜索