Manipulate a Password
My Java application manipulates a password that is eventually used to encrypt a file. I load it in a structure
public char[] password;
because I saw it in swing JPasswordField
.
I suppose 开发者_JAVA技巧that this adds some level of protection against the memory scanning for passwords. I think that it is just a little "obscurity" level, not a real protection. It seems to me that this is useful because it is effective against many trivial scanners. Do things stand like this, or am I missing something?
The reason why using char[]
instead of String
is preferred by some people is that the char[]
can be cleared after use narrowing the window when the password appearing in core dumps or exposed through failure of bound checking reads from buffers.
However, it doesn't work so well for JPasswordField
for a number of reasons:
- GC can move the object without necessarily immediately blanking the original copy.
JPasswordField
is often used with anActionListener
, which receives the password as the command string in theActionEvent
.- The
Document
implementation may make copies. - People forget to blank the
JPasswordField
after extracting thechar[]
. - There's probably more important security things that you could be expending effort on (like airport screeners keeping an eye out for bottle of water and letting bomb parts through).
On the pro side, you get a tick list feature and don't have to explain yourself because you are doing Best Practice.
As others have said, char[]
offers no real security benefits over String
. However, char[]
does offer these benefits over String
objects:
- It's harder to accidentally reveal the password (an array's
toString()
method doesn't reveal its content) - The contents can be cleared when they are no longer needed
Do you mean that you think that a char[] is more secure from someone scanning memory than a String? Umm, no. Internally a String holds its text in a char[]. They'd look exactly the same.
I suppose you could encrypt the password in memory to protect against that sort of thing. But presumably you have to read it in as plain text before encrypting it, so it would still be there in plain text for some period of time. I suppose if you expect whatever your manipulations are doing to take a long amount of time, there might be some value in encrypting the password internally to reduce the exposure.
精彩评论