Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe way to get password from PasswordField in JavaFX

Tags:

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(); 
like image 482
Krzysiek Avatar asked Mar 31 '15 12:03

Krzysiek


People also ask

How to use password field in JavaFX?

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.

How to make a password textfield in JavaFX?

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.

Which method is used to set password character for a textfield?

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.


2 Answers

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.

like image 177
3ph3r Avatar answered Oct 20 '22 06:10

3ph3r


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 :)

like image 37
Adam Martinu Avatar answered Oct 20 '22 06:10

Adam Martinu