In Swing, the password field has a getPassword()
(returns char[]
) method instead of the usual getText()
(returns String
)
While other suggestions here seem valid, there is one other good reason. With plain String
you have much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[]
is less vulnerable.
Consider this:
public static void main(String[] args) {
Object pw = "Password";
System.out.println("String: " + pw);
pw = "Password".toCharArray();
System.out.println("Array: " + pw);
}
Prints:
String: Password
Array: [C@5829428e