In a discussion one of our senior told that we should not use String for storing password in a Java project because it's a security risk. But it can be acceptable in C project. I did not get why he said that. Can anyone tell me why so?
Asked
Active
Viewed 2,772 times
3
-
2http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords?rq=1 – Sotirios Delimanolis Jun 15 '15 at 19:00
-
4Your question doesn't make sense. How would someone tell why a person you talked to said something? – xxbbcc Jun 15 '15 at 19:00
-
2The best person to ask would be the person making the statement. – T.J. Crowder Jun 15 '15 at 19:02
1 Answers
9
In Java, Strings are immutable, so once you use String to store a password, there is no way that content can be changed because any change will produce new String. And the String which contains the password, will be available in memory until it got garbage collected. So it will be remain in memory for long duration which might be a security risk.
But, in C language, String is a null terminated character array and you can set all the array elements as blank or zero, therefore the password will not be remain in memory.
-
Perhaps it is the reason the guy had in mind, but it is not convincing at all. – Eugene Sh. Jun 15 '15 at 19:03
-
@EugeneSh.: This is a fairly well-known reason for using `char[]`, rather than `String`, for password data in Java. – T.J. Crowder Jun 15 '15 at 19:04
-
Why can't a developer force the garbage collection in Java in the same pace he would nullify the memory in C? – Eugene Sh. Jun 15 '15 at 19:08
-
5@EugeneSh. because there is no actual way to force the garbage collection to do anything. The contract of `System.gc()` is that it *suggests* to the garbage collector that it should collect. Furthermore, even if the space is garbage-collected, there is absolutely no guarantee it will be zeroed out. So the data will still be floating there until the same memory location is allocated to something else. – RealSkeptic Jun 15 '15 at 19:12
-
-
System.gc() can be used as a hint, but there is no way to force it immediately. – Bacteria Jun 15 '15 at 19:13
-
@EugeneSh.: What RealSkeptic said, plus: Not only is there no guarantee it will be zeroed out, but there are really good reasons it probably *won't* be (performance, for instance). – T.J. Crowder Jun 15 '15 at 19:14
-
@UUIIUI could you perhaps augment your answer with your comment above? It is a good addition. `System.gc() can be used as a hint, but there is no way to force it immediately. ` – EkcenierK Nov 16 '15 at 12:13