Created
May 23, 2015 09:57
-
-
Save esamson/f67b94b0033c8677a24b to your computer and use it in GitHub Desktop.
Clearing a Java String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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