@Override
public char[] readPassword(Mode mode) throws PreferencesException
{
char[] password;
Console console = System.console();
if (console == null)
{
if (isEchoAllowed())
{
//Since we are echoing the password anyway no need to make the user validate by typing second time
if (!StringUtils.isEmpty(getEchoWarningText()))
System.err.println(getEchoWarningText());
if (!StringUtils.isEmpty(getPasswordPrompt()))
System.err.print(getPasswordPrompt() + ": ");
@SuppressWarnings("resource") //Don't want to close System.in
Scanner sc = new Scanner(System.in);
try
{
password = sc.nextLine().toCharArray();
}
catch (NoSuchElementException e)
{
//End of System.in stream possible I guess, regard as a cancel
password = null;
}
}
else
throw new PreferencesException("Console not available, cannot read password from user securely.");
}
else
{
if (mode == Mode.ENCRYPTION)
{
boolean passwordsAreTheSame;
do
{
if (!StringUtils.isEmpty(getPasswordPrompt()))
System.err.print(getPasswordPrompt() + ": ");
password = console.readPassword();
//User cancelled
if (password.length == 0)
return(null);
if (!StringUtils.isEmpty(getVerifyPrompt()))
System.err.print(getVerifyPrompt() + ": ");
char[] verifyPassword = console.readPassword();
passwordsAreTheSame = Arrays.equals(password, verifyPassword);
if (!passwordsAreTheSame && !StringUtils.isEmpty(getVerifyErrorMessage()))
System.err.println(getVerifyErrorMessage());
}
while (!passwordsAreTheSame);
}
else
{
if (!StringUtils.isEmpty(getPasswordPrompt()))
System.err.print(getPasswordPrompt() + ": ");
password = console.readPassword();
}
}
//If the user just presses ENTER regard as a cancel
if (password != null && password.length == 0)