Java: convert a char[] to a CharSequence
Context:
One of the most common usage of char[] instead of String, is to "temporary" store secrets/passwords. To pass it to initialization of some service/clients ... The sercrets are not needed after such initialization. But in java string is not possible to clear it from memory (manualy nor by garbage collection)... So, it is basically forbiden to store secrets in Strings.
Recommended way: Load secrets to char[], pass it to init proces, and clear it manually (set forEach char[i] = '0';). Read about this problem on specialized blogs...
Question/Answer:
- if service/cliets API accepts only pass/secret as a string - don't use it (and report bug)
- if service/cliets API accept char array, use it and clear it
- if service/cliets API accept CharSequence, java.nio.CharBuffer.wrap(array) could be used and cleared after
NOTE: unfortunately, one has to check even 3rd party service/client init source code, it happens that they convert char array to string somewhere deep in their code... )-: Choose your dependencies wisely.
A String
is a CharSequence
. So you can just create a new String
given your char[]
.
CharSequence seq = new String(arr);
Without the copy:
CharSequence seq = java.nio.CharBuffer.wrap(array);
However, the new String(array)
approach is likely to be easier to write, easier to read and faster.