Is there any way to safely retrieve the password from PasswordField in JavaFX8 so it isn't saved in memory?
Standard option:
String pass = passwordField.getText();
isn't enough for me. I'm expecting something like this:
char[] pass = passwordField.getPassword();
Java program to create a Password field: This program creates a PasswordField indicated by the name b. The PasswordField will be created inside a scene, which in turn will be hosted inside a stage (which is the top level JavaFX container). The function setTitle() is used to provide title to the stage.
Creating a Password Field PasswordField passwordField = new PasswordField(); passwordField. setPromptText("Your password"); For your user interface, you can accompany the password field with a prompt message or you can add a notifying label.
In Java swing, to create a password field you use JPasswordField class. You can assign a different echo character other than the default one (*) using setEchoChar() method. You can get the password using getPassword() method.
As with many things, you can achieve this using reflection. And since you're using reflection, it won't be pretty (just look at all those exceptions), but I think this is the only way for now.
public class SafePasswordField extends PasswordField { public final char[] getPassword() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Content c = getContent(); Field fld = c.getClass().getDeclaredField("characters"); fld.setAccessible(true); StringBuilder sb = (StringBuilder) fld.get(c); char[] result = new char[sb.length()]; sb.getChars(0, sb.length(), result, 0); return result; } }
The Content
returned by getContent()
is always instance of javafx.scene.control.TextField$TextFieldContent
so it's safe to access characters
field.
No matter what the variable type is (String, char[] ...) it will always be stored in memory, until the Garbage Collector picks it up. While I assume it would be a bit difficult, you would have to make a program and read the memory space that contains the variable's data in order to retreive the password. I wouldn't be worried about any eavesdropping if I were you :)
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