Java storing sensitive 'key' as String or char[]?

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?


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, ie, 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.

链接地址: http://www.djcxy.com/p/17884.html

上一篇: 在java中取消String是否是一个好习惯

下一篇: Java将敏感的'key'存储为String或char []?