Skip to content

Instantly share code, notes, and snippets.

@esamson
Created May 23, 2015 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esamson/f67b94b0033c8677a24b to your computer and use it in GitHub Desktop.
Save esamson/f67b94b0033c8677a24b to your computer and use it in GitHub Desktop.
Clearing a Java String
import java.lang.reflect.Field;
import java.io.Console;
public class Secret {
public static void main(String[] args) throws Exception {
Console console = System.console();
String secret = console.readLine("secret: ");
System.out.println("Capture secret in heap");
System.in.read();
clearString(secret);
System.out.println("Removed from heap: " + secret);
System.in.read();
}
static void clearString(String s) throws Exception {
Field stringValue = String.class.getDeclaredField("value");
stringValue.setAccessible(true);
char[] mem = (char[]) stringValue.get(s);
for (int i=0; i < mem.length; i++) {
mem[i] = 'h';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment