String secret="foo";
WhatILookFor.securelyWipe(secret);
And I need to know that it will not be removed by java optimizer.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A String cannot be "wiped". It is immutable, and short of some really dirty and dangerous tricks (using reflection, for example) you cannot alter that.
So the safest solution is to not put the data into a
Stringin the first place. Use aStringBuilderor an array of characters instead, or some other representation that is not immutable. (And then clear it when you are done. And don’t usetoString()etc on theStringBuilderor you have created theStringyou were trying to avoid.)Of course, the "safest" solution is rather impractical. Many Java SE and 3rd party APIs require or return text data to be provided as
Stringobjects.For the record, there are a couple of ways that you can change the contents of a String’s backing array. For example, you can use reflection to fish out a reference to the
Stringobject’s backing array, and overwrite its contents. However, this involves doing things that the JLS states have unspecified behavior so you cannot guarantee that the optimizer won’t do something unexpected. And the code to do this will be non-portable, since it depends on internal details ofStringthat have changed over time and may change again.My personal take on this is that you are better off locking down your application platform so that unauthorized people can’t gain access to the memory / memory dump in the first place. After all, if the platform is not properly secured, the "bad guys" may be able to get hold of the string contents before you erase it. Steps like this might be warranted for small amounts of security critical state, but if you’ve got a lot of "confidential" information to process, it is going to be a major hassle to not be able to use normal strings and string handling.