Skip to main content
  1. blog/

Use Character Arrays to Store Sensitive Text Data in Java

·1 min

Strings objects in Java are immutable which means they cannot be modified once created. The only way for their contents to be removed from memory is during garbage collection.

The issue with garbage collection is that it doesn’t happen at any kind of guaranteed interval. Invoking System.gc() is a hint to the garbage collector to run — it’s under no obligation to do so. The strings may persist in memory for a long time and will be vulnerable to disclosure via a memory dump.

With a character array, you can fetch a password, do something with it, and then immediately zero out the array.

// password data 
char[] password = {'s', 'e', 'c', 'r', 'e', 't'}; 
// do something useful with password (e.g. hash it) 
// empty the password array 
Arrays.fill(password, '\0');