Java Reference
In-Depth Information
cons.readPassword("Password:")
. This method returns an array of bytes, which can be
used directly in some encryption and security APIs, or can easily be converted into a
String
.
It is generally advised to overwrite the byte array after use to prevent security leaks when
other code can access the stack, although the benefits of this are probably reduced when
Example 10-1. src/main/java/io/ReadPassword.java
public
public class
class
ReadPassword
ReadPassword
{
public
public static
void
main
(
String
[]
args
) {
Console cons
;
iif
((
cons
=
System
.
console
()) !=
null
static
void
null
) {
char
char
[]
passwd
=
null
null
;
try
try
{
passwd
=
cons
.
readPassword
(
"Password:"
);
// In real life you would send the password into authentication code
System
.
out
.
println
(
"Your password was: "
+
new
new
String
(
passwd
));
}
finally
finally
{
// Shred this in-memory copy for security reasons
iif
(
passwd
!=
null
null
) {
java
.
util
.
Arrays
.
fill
(
passwd
,
' '
);
}
}
}
else
else
{
throw
throw new
new
RuntimeException
(
"No console, can't get password"
);
}
}
}
Writing Standard Output or Standard Error
Problem
You want your program to write to the standard output or the standard error stream.
Solution
Use
System.out
or
System.err
as appropriate.