13

Possible Duplicate:
Why is char[] preferred over string for passwords?

I read somewhere that storing a sensitive key as a char[] rather than a String is better because the latter can be found in the memory. It also makes a little sense because of JPasswordField's getText() method being Deprecated.

Is this true?

Community
  • 1
  • 1
LanguagesNamedAfterCofee
  • 5,782
  • 7
  • 45
  • 72
  • 2
    FYI: `String` stores its contents as `char[]`. – Radu Murzea Aug 17 '12 at 21:32
  • 2
    @SoboLAN Yes, a String is basically a char[] inside, but we can tamper with the individual characters held in a variable declared char[] whereas we cannot do anything to modify the characters held inside a String object, and simply nulling a variable which points to a String does not guarantee that it will be deleted by the garbage collector. And even deletion does not guarantee that the memory used by the String will be overwritten any time soon. – Bobulous Aug 17 '12 at 21:52
  • @user1515834 What I meant to imply by saying that was: if you look inside the RAM, then both `String` and `char[]` will look the same. Because they are basically the same. To a hacker it won't make much difference. As to the immediate change of the contents of `char[]` vs. garbage collecting a `String`: yes, you're right. – Radu Murzea Aug 17 '12 at 22:07

1 Answers1

14

Once you are done using the password in a char[] you can always overwrite it with 0's or random values. However, you can't do that with String objects because they are immutable objects in Java and the strings will remain alive until the garbage collector kicks in and clears it.

Here is an interesting note at http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

In this example, we prompt the user for a password from which we derive an encryption key.

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.

Community
  • 1
  • 1
Susam Pal
  • 32,765
  • 12
  • 81
  • 103