2

In making password handling more secure by eliminating storage in Strings (which end up on the heap). I have the following existing code:

String pw = new String(buffer, 0, len, "UTF-32LE");

I came up with:

Charset charSet = Charset.forName("UTF-32LE");
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, len);
CharBuffer charBuffer = charSet.decode(byteBuffer);
charArray = new char[charBuffer.length()];
for (int i = 0; i < charBuffer.length(); ++i)
{
    charArray[i] = charBuffer.charAt(i);
}

Note that we support many different languages, so I'm not quite sure how best to thoroughly test this approach.

  1. Is this correct? Are there caveats to this approach?
  2. Is this the best approach or am I missing something simpler?

Thanks for any feedback or advice.

3
  • 1
    Isn't your data still on the heap? What threat are you trying to counter? Commented Oct 14, 2013 at 20:37
  • 2
    char arrays can be zeroed out after use, but Strings are immutable and persist on the heap until they are garbage collected. Commented Oct 14, 2013 at 20:52
  • Recommendation is to store password as charArray instead of string, if you have to store it in heap. Commented Oct 14, 2013 at 21:17

1 Answer 1

1

I am not sure what are you trying to achieve. At first I had thought you want to get rid of data being stored on the heap but then I saw array of chars. In java every array is an object and every object is stored on the heap. Reference variables can land on the stack but they are only handlers not the object itself.

Sign up to request clarification or add additional context in comments.

3 Comments

When you use an array, it is allocated off the heap, but you can zero out the array as soon as you've done what you need to do with it. When you use a String, you cannot update it -- that immutable String sits on the heap, potentially for a very long time, until it is garbage collected.
So if your biggest concern is that someone might get password from String object that was not GC'ed then your approach is safer but the tricky part is the interface which user of your app will use to provide password. It gets more tricky when there is more third party libraries which are used in the process of getting a password.
JPasswordField -- seems to behave properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.