Tuesday 9 January 2018

java - Why is char[] preferred over String for passwords?

itemprop="text">

In Swing, the password field has a
getPassword() (returns char[]) method
instead of the usual getText() (returns
String) method. Similarly, I have come across a suggestion not
to use String to handle
passwords.



Why does
String pose a threat to security when it comes to
passwords?
It feels inconvenient to use
char[].



class="post-text" itemprop="text">
class="normal">Answer




Strings are
immutable
. That means once you've created the
String, if another process can dump memory, there's no way
(aside from href="https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29"
rel="noreferrer">reflection) you can get rid of the data before href="https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29"
rel="noreferrer">garbage collection kicks
in.



With an array, you can explicitly wipe the
data after you're done with it. You can overwrite the array with anything you like, and
the password won't be present anywhere in the system, even before garbage
collection.



So yes, this is
a security concern - but even using char[] only reduces the
window of opportunity for an attacker, and it's only for this specific type of
attack.



As noted in the comments, it's possible
that arrays being moved by the garbage collector will leave stray copies of the data in
memory. I believe this is implementation-specific - the garbage collector
may clear all memory as it goes, to avoid this sort of thing. Even
if it does, there's still the time during which the char[]
contains the actual characters as an attack window.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...