In Java it is recommended to use char[]
for storing passwords or other sensitive information to be able to clear it manually once the data is no longer needed.
How can such an array be cleared across all threads? If I understand it correctly threads might only perform changes in their cache, but not in the shared memory, so the following would not work reliably:
char[] password = ...
...
Arrays.fill(password, '\0');
volatile
(or other synchronization) to make sure the shared memory is updated?
Edit: The statement that char[]
should be used for passwords was based on Why is char[] preferred over String for passwords?, however after looking at it again, this is also a little bit controversial.
Making the array reference volatile won't guarantee volatile access to it's contents. You could use AtomicIntegerArray
if you want thread safe shared access. Otherwise you might want to wrap your char
array into your custom class with synchronisation around it's methods. Although the latter will be less performant.
Note the using an array of characters instead of a string might not be truly more secure. Dumping the process memory during the time when your char array contains the data is still possible if your attacker has access to your machine, and if he does, you have much more serious concerns than this. Also, garbage collection might move your data elsewhere during it's compaction phase, leaving your password in the freed 'garbage' memory that hasn't been overwritten yet (given you are talking about shared members between threads this is even more likely to happen since your char array would be considered long lived and copied to memory spaces reserved for older generation objects).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With