Does using reflection to scrub a String
make using String
as safe as using char[]
for passwords?
From a security aspect, it is generally considered best practice to use char[]
for storing/passing passwords, because one can zero-out its contents as soon as possible in code, which may be significantly before garbage collection cleans it up and the memory is reused (wiping all trace), limiting the window of time for a memory attack.
However, char[]
is not as convenient as String
, so it would be handy if one could "scrub" a String
if needed, thus making String
as safe as char[]
.
Below is a method that uses reflection to zero-out the fields of String
.
Is this method "OK", and does it achieve the goal of making String
as safe as char[]
for passwords?
public static void scrub(String str) throws NoSuchFieldException, IllegalAccessException {
Field valueField = String.class.getDeclaredField("value");
Field offsetField = String.class.getDeclaredField("offset");
Field countField = String.class.getDeclaredField("count");
Field hashField = String.class.getDeclaredField("hash");
valueField.setAccessible(true);
offsetField.setAccessible(true);
countField.setAccessible(true);
hashField.setAccessible(true);
char[] value = (char[]) valueField.get(str);
// overwrite the relevant array contents with null chars
Arrays.fill(value, offsetField.getInt(str), countField.getInt(str), '\0');
countField.set(str, 0); // scrub password length too
hashField.set(str, 0); // the hash could be used to crack a password
valueField.setAccessible(false);
offsetField.setAccessible(false);
countField.setAccessible(false);
hashField.setAccessible(false);
}
Here's a simple test:
String str = "password";
scrub(str);
System.out.println('"' + str + '"');
Output:
""
Note: You may assume that passwords are not String
constants and thus calling this method will have no adverse effect on interned Strings.
Also, I have left the method is a fairly "raw" state for simplicity's sake. If I were to use it, I would not declare exceptions thrown (try/catch/ignoring them) and refactor repeated code.