Java将敏感的”密钥”存储为string或char[]?

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

本问题已经有最佳答案,请猛点这里访问。

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

我在某个地方读到,将敏感键存储为char[]而不是字符串更好,因为后者可以在内存中找到。它也有点道理,因为jpaswordField的getText()方法已被弃用。

这是真的吗?


一旦在char[]中使用完密码,就可以用0或随机值覆盖它。但是,你不能用EDCOX1的1个对象来实现这一点,因为它们是Java中不可变的对象,并且字符串将保持生命,直到垃圾收集器进入并清除它。

下面是一个有趣的注释,位于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.