String or char[] for password when using JDBC?

2019-07-03 15:58发布

问题:

This comes from a security point of view.Best practice says not to use a String to store a password, but a char[]. Does this apply to using a password at any time? For example, it is acceptable to use a String to hold a password when using JDBC?

public final void Login(String username, String password){
...
conn = DriverManager.getConnection(url, username, password);
...
}

Or could a char[] be used here in place of the String?

回答1:

I don't know that I accept your premise that a char [] is more secure than a String in the context of a system(s) resource (e.g. JDBC database connection). Regardless, you can use a connection manager (or connection pool, whichever is appropriate to your container) and then the connection manager (and only the connection manager) has visibility to the underlying databse username / password.



回答2:

String in java is immutable, once you create it, it can't be changed and thus whenever we say String s="abc"; s="def"; they do not refer to same string, instead it creates "abc" string object, s refers to it and when we say s="def", another string object "def" is created referred by s, and thus abandoning "abc".

So "abc" is left in the heap, and now suppose this is some highly secure password floating in heap just waiting to be accessed by some wrong party.

that is why it is encouraged to use char[] for password.

there are other alternatives like StringBuffer too.