List of usage examples for java.io Console readPassword
public char[] readPassword()
From source file:pa55.java.core.PA55.java
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException { System.out.println("**** This is a reference implementation version " + APP_VERSION + " of pa55. Please see the project page (http://anirbanbasu.github.io/pa55/) for details. ****\r\n"); Console inputConsole = System.console(); //If it is available, we need Console for masking passwords. Scanner inputConsoleScanner;//from w ww . ja va2 s. com Scanner echoOptionScanner = new Scanner(System.in); boolean disableEcho = false; if (inputConsole != null) { //We can hide the input, but should we? Ask the user. System.out.println( "Do you want to hide the master secret and the password hint as you type them? Enter 1 to hide or 0 to not hide."); disableEcho = echoOptionScanner.nextInt() == 0 ? false : true; } String echoNotice; if (disableEcho) { inputConsoleScanner = new Scanner(inputConsole.reader()); echoNotice = " (your input will NOT be visible as you type)"; } else { inputConsoleScanner = new Scanner(System.in); echoNotice = " (your input will be visible as you type)"; } PA55 core = new PA55(); String lineInput = ""; System.out.println("Enter master secret" + echoNotice); lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); while (lineInput.length() == 0) { System.out.println("Please enter a non-empty string" + echoNotice); lineInput = (inputConsole != null ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); } core.setMasterSecret(lineInput); System.out.println("Enter password hint" + echoNotice); lineInput = (disableEcho ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); while (lineInput.length() == 0) { System.out.println("Please enter a non-empty string" + echoNotice); lineInput = (inputConsole != null ? new String(inputConsole.readPassword()) : inputConsoleScanner.nextLine().trim()); } core.setPasswordHint(lineInput); int choiceInput = 0; System.out.println( "Choose desired length in characters:\r\n (0) default: 12 characters\r\n (1) 8 characters\r\n (2) 12 characters\r\n (3) 16 characters\r\n (4) 20 characters\r\n (5) 24 characters\r\n (6) 28 characters\r\n (7) 32 characters"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 7) { System.out.println("Please enter a choice between 0 and 7."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 2; } core.setPbkdfLength((choiceInput + 1) * 3); System.out.println( "Choose the password iterations:\r\n (0) default: 500K\r\n (1) Low (10K)\r\n (2) 250K\r\n (3) 500K\r\n (4) 750K\r\n (5) 1M\r\n (6) 1.25M\r\n (7) 1.5M"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 7) { System.out.println("Please enter a choice between 0 and 7."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 3; } if (choiceInput != 1) { core.setPbkdfRounds((choiceInput - 1) * 250000); } else { core.setPbkdfRounds(10000); } System.out.println( "Choose the HMAC algorithm:\r\n (0) default: SHA256\r\n (1) SHA1\r\n (2) SHA256\r\n (3) SHA512"); choiceInput = inputConsoleScanner.nextInt(); while (choiceInput < 0 || choiceInput > 3) { System.out.println("Please enter a choice between 0 and 3."); choiceInput = inputConsoleScanner.nextInt(); } if (choiceInput == 0) { choiceInput = 2; } core.setPbkdfAlgorithm(HMACHashFunction.values()[choiceInput - 1]); inputConsoleScanner.close(); echoOptionScanner.close(); System.out.print("Generating password...\r"); core.generatePBKDF2Password(); System.out.println("Your password is: " + core.getPbkdfGeneratedPassword()); }
From source file:org.ow2.proactive.authentication.crypto.CreateCredentials.java
/** * Entry point/* ww w.j a v a 2s .c o m*/ * * @see org.ow2.proactive.authentication.crypto.Credentials * @param args arguments, try '-h' for help * @throws IOException * @throws ParseException * */ public static void main(String[] args) throws IOException, ParseException { SecurityManagerConfigurator.configureSecurityManager( CreateCredentials.class.getResource("/all-permissions.security.policy").toString()); Console console = System.console(); /** * default values */ boolean interactive = true; String pubKeyPath = null; PublicKey pubKey = null; String login = null; String pass = null; String keyfile = null; String cipher = "RSA/ECB/PKCS1Padding"; String path = Credentials.getCredentialsPath(); String rm = null; String scheduler = null; String url = null; Options options = new Options(); Option opt = new Option("h", "help", false, "Display this help"); opt.setRequired(false); options.addOption(opt); OptionGroup group = new OptionGroup(); group.setRequired(false); opt = new Option("F", "file", true, "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]"); opt.setArgName("PATH"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL"); opt.setArgName("URL"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL"); opt.setArgName("URL"); opt.setArgs(1); opt.setRequired(false); group.addOption(opt); options.addOptionGroup(group); opt = new Option("l", "login", true, "Generate credentials for this specific user, will be asked interactively if not specified"); opt.setArgName("LOGIN"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified"); opt.setArgName("PWD"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("k", "keyfile", true, "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise."); opt.setArgName("PATH"); opt.setOptionalArg(true); opt.setRequired(false); options.addOption(opt); opt = new Option("o", "output", true, "Output the resulting credentials to the specified file [default:" + path + "]"); opt.setArgName("PATH"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); opt = new Option("c", "cipher", true, "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher + "]"); opt.setArgName("PARAMS"); opt.setArgs(1); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println(newline + "ERROR : " + e.getMessage() + newline); System.out.println("type -h or --help to display help screen"); System.exit(1); } if (cmd.hasOption("help")) { displayHelp(options); } if (cmd.hasOption("file")) { pubKeyPath = cmd.getOptionValue("file"); } if (cmd.hasOption("rm")) { rm = cmd.getOptionValue("rm"); } if (cmd.hasOption("scheduler")) { scheduler = cmd.getOptionValue("scheduler"); } if (cmd.hasOption("login")) { login = cmd.getOptionValue("login"); } if (cmd.hasOption("password")) { pass = cmd.getOptionValue("password"); } if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) { keyfile = cmd.getOptionValue("keyfile"); } if (cmd.hasOption("output")) { path = cmd.getOptionValue("output"); } if (cmd.hasOption("cipher")) { cipher = cmd.getOptionValue("cipher"); } int acc = 0; if (pubKeyPath != null) { acc++; } if (scheduler != null) { url = Connection.normalize(scheduler) + "SCHEDULER"; acc++; } if (rm != null) { url = Connection.normalize(rm) + "RMAUTHENTICATION"; acc++; } if (acc > 1) { System.out.println("--rm, --scheduler and --file arguments cannot be combined."); System.out.println("try -h for help."); System.exit(1); } if (url != null) { try { Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) { public Logger getLogger() { return Logger.getLogger("pa.scheduler.credentials"); } }; AuthenticationImpl auth = conn.connect(url); pubKey = auth.getPublicKey(); } catch (Exception e) { System.err.println("ERROR : Could not retrieve public key from '" + url + "'"); e.printStackTrace(); System.exit(3); } System.out.println("Successfully obtained public key from " + url + newline); } else if (pubKeyPath != null) { try { pubKey = Credentials.getPublicKey(pubKeyPath); } catch (KeyException e) { System.err .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)"); System.exit(4); } } else { System.out.println("No public key specified, attempting to retrieve it from default location."); pubKeyPath = Credentials.getPubKeyPath(); try { pubKey = Credentials.getPublicKey(pubKeyPath); } catch (KeyException e) { System.err .println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)"); System.exit(5); } } if (login != null && pass != null && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) { System.out.println("Running in non-interactive mode." + newline); interactive = false; } else { System.out.println("Running in interactive mode."); } if (interactive) { System.out.println("Please enter Scheduler credentials,"); System.out.println("they will be stored encrypted on disk for future logins." + newline); System.out.print("login: "); if (login == null) { login = console.readLine(); } else { System.out.println(login); } System.out.print("password: "); if (pass == null) { pass = new String(console.readPassword()); } else { System.out.println("*******"); } System.out.print("keyfile: "); if (!cmd.hasOption("keyfile")) { System.out.println("no key file specified"); } else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) { System.out.println(keyfile); } else { keyfile = console.readLine(); } } try { CredData credData; if (keyfile != null && keyfile.length() > 0) { byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile)); credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass, keyfileContent); } else { System.out.println("--> Ignoring keyfile, credential does not contain SSH key"); credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass); } Credentials cred = Credentials.createCredentials(credData, pubKey, cipher); cred.writeToDisk(path); } catch (FileNotFoundException e) { System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)"); System.exit(6); } catch (Throwable t) { t.printStackTrace(); System.exit(7); } System.out.println("Successfully stored encrypted credentials on disk at :"); System.out.println("\t" + path); System.exit(0); }
From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java
private static void loadConfig() { boolean read = false; File f = CONFIG_FILE;/*from ww w .j a v a 2 s.c o m*/ if (!f.exists()) { read = true; try { f.getParentFile().mkdirs(); f.createNewFile(); java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()), PosixFilePermissions.fromString("rw-------")); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error writing empty config.yml!"); } } Map<String, Object> config; if (read) { Console console = System.console(); console.printf("Nick: \n->"); nick = console.readLine(); console.printf("\nPassword: \n-|"); pass = new String(console.readPassword()); console.printf("\nServer: \n->"); server = console.readLine(); console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->"); channels = Arrays.asList(console.readLine().split(",")); System.out.println("Fetching max XKCD..."); maxXKCD = fetchMaxXKCD(); System.out.println("Fetched."); cachedUTC = System.currentTimeMillis(); dadLeaveTimes = new HashMap<>(); noVoiceNicks = new HashSet<>(); writeConfig(); System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath()); } else { try (FileInputStream fis = new FileInputStream(f)) { Yaml y = new Yaml(); config = y.loadAs(fis, Map.class); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error parsing config!"); return; } nick = (String) config.get("nick"); pass = (String) config.get("password"); server = (String) config.get("server"); channels = (List<String>) config.get("channels"); maxXKCD = (Integer) config.get("cachedMaxXKCD"); cachedUTC = (Long) config.get("cachedUTC"); noVoiceNicks = (Set<String>) config.get("noVoiceNicks"); masters = (Set<String>) config.get("masters"); if (masters == null) { masters = new HashSet<>(); masters.add("Everdras"); } if (noVoiceNicks == null) noVoiceNicks = new HashSet<>(); noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s)); masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s)); if (checkXKCDUpdate()) writeConfig(); else System.out.println("Loaded cached XKCD."); Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes"); dadLeaveTimes = new HashMap<>(); if (serialDadLeaveTimes != null) serialDadLeaveTimes.keySet().stream().forEach((time) -> { dadLeaveTimes.put(LocalDate.parse(time), LocalTime.parse((String) serialDadLeaveTimes.get(time))); }); } }
From source file:org.wso2.ppaas.tools.artifactmigration.ConversionTool.java
/** * Method to validate configuration inputs and redirect to console inputs * * @param propertyConstant//from w w w. ja va 2 s.c o m * @param propertyName */ private static void validateConfigurationInputs(String propertyConstant, String propertyName) { Console console = System.console(); if (System.getProperty(propertyConstant) == null || System.getProperty(propertyConstant).isEmpty()) { System.out.print("Enter the " + propertyName); if (propertyName.contains("Password")) { char[] passwordChars = console.readPassword(); System.setProperty(propertyConstant, new String(passwordChars)); } else { System.setProperty(propertyConstant, console.readLine()); } System.out.println(); } }
From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java
@BeforeClass public static void setupSuite() { Console console = System.console(); if (console != null) { console.printf("Knox Host: "); KNOX_HOST = console.readLine();//w ww. j av a 2 s . co m console.printf("Topology : "); TOPOLOGY_PATH = console.readLine(); console.printf("Username : "); TEST_USERNAME = console.readLine(); console.printf("Password: "); TEST_PASSWORD = new String(console.readPassword()); } else { JLabel label = new JLabel("Enter Knox host, topology, username, password:"); JTextField host = new JTextField(KNOX_HOST); JTextField topology = new JTextField(TOPOLOGY_PATH); JTextField username = new JTextField(TEST_USERNAME); JPasswordField password = new JPasswordField(TEST_PASSWORD); int choice = JOptionPane.showConfirmDialog(null, new Object[] { label, host, topology, username, password }, "Credentials", JOptionPane.OK_CANCEL_OPTION); assertThat(choice, is(JOptionPane.YES_OPTION)); TEST_USERNAME = username.getText(); TEST_PASSWORD = new String(password.getPassword()); KNOX_HOST = host.getText(); TOPOLOGY_PATH = topology.getText(); } TOPOLOGY_URL = String.format("%s://%s:%d/%s/%s", KNOX_SCHEME, KNOX_HOST, KNOX_PORT, KNOX_PATH, TOPOLOGY_PATH); WEBHDFS_URL = String.format("%s/%s", TOPOLOGY_URL, WEBHDFS_PATH); }
From source file:org.hawkular.wildfly.agent.installer.AgentInstaller.java
/** * Reads password from the console (stdin). * * @param message to present before reading * @return password or null if console is not available *///from w ww . j a v a 2 s . c om private static String readPasswordFromStdin(String message) { Console console = System.console(); if (console == null) { return null; } console.writer().write(message); console.writer().flush(); return String.valueOf(console.readPassword()); }
From source file:edu.umd.cs.submit.CommandLineSubmit.java
/** * @param submitUserFile// ww w. ja va 2 s . co m * @param courseKey * @param projectNumber * @param authenticationType * @param baseURL * @throws IOException * @throws UnsupportedEncodingException * @throws URISyntaxException * @throws HttpException */ public static void createSubmitUser(File submitUserFile, String courseKey, String projectNumber, String authenticationType, String baseURL) throws IOException, UnsupportedEncodingException, URISyntaxException, HttpException { PrintWriter newUserProjectFile; if (authenticationType.equals("openid")) { String[] result = getSubmitUserForOpenId(courseKey, projectNumber, baseURL); String classAccount = result[0]; String onetimePassword = result[1]; newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile)); newUserProjectFile.println("classAccount=" + classAccount); newUserProjectFile.println("oneTimePassword=" + onetimePassword); } else { String loginName, password; Console console = System.console(); System.out.println("Please enter your LDAP username and password"); System.out.print("LDAP username: "); loginName = console.readLine(); System.out.println("Password: "); password = new String(console.readPassword()); System.out.println("Thanks!"); System.out.println("Preparing for submission. Please wait..."); String url = baseURL + "/eclipse/NegotiateOneTimePassword"; PostMethod post = new PostMethod(url); post.addParameter("loginName", loginName); post.addParameter("password", password); post.addParameter("courseKey", courseKey); post.addParameter("projectNumber", projectNumber); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); // System.out.println("Preparing to execute method"); int status = client.executeMethod(post); // System.out.println("Post finished with status: " +status); if (status != HttpStatus.SC_OK) { throw new HttpException( "Unable to negotiate one-time password with the server: " + post.getResponseBodyAsString()); } InputStream inputStream = post.getResponseBodyAsStream(); BufferedReader userStream = new BufferedReader(new InputStreamReader(inputStream)); newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile)); while (true) { String line = userStream.readLine(); if (line == null) break; // System.out.println(line); newUserProjectFile.println(line); } userStream.close(); } newUserProjectFile.close(); if (!submitUserFile.canRead()) { System.out.println("Can't generate or access " + submitUserFile); System.exit(1); } }
From source file:edu.utah.bmi.ibiomes.cli.CLIUtils.java
/** * Connect to iBIOMES/*w w w . j a va 2 s .c o m*/ * @param password Password * @return Connection * @throws IOException * @throws CompressorException */ public static IRODSConnector getConnection(String username, String password, String server) throws IOException, JargonException, CompressorException { IRODSEnvironmentFile envFile = null; IRODSConnector cnx = null; Console objConsole = System.console(); if (objConsole == null) { System.err.println("Console Object is not available."); System.exit(1); } System.out.println("Authentication... "); try { envFile = IRODSEnvironmentFile.instance(); } catch (IOException e) { System.out.println("IRODS user info file not found!"); System.out.println("Make sure your .irodsEnv file exists in $HOME/.irods or $IBIOMES_HOME"); System.exit(1); } //while login fails while (cnx == null) { //retrieve iRODS password if (password == null) { if (username == null) username = envFile.getIrodsUserName(); System.out.println("iBIOMES password for " + username + ":"); char[] pwdArray = objConsole.readPassword(); password = String.copyValueOf(pwdArray); } //try to connect to iRODS system using default settings try { cnx = new IRODSConnector(username, password, server); try { //try to login IRODSAccessObjectFactory aoFactory = cnx.getFileSystem().getIRODSAccessObjectFactory(); aoFactory.getUserAO(cnx.getAccount()); } catch (JargonException exc) { System.out.println("\nLogin failed. Try again."); cnx = null; } } catch (IOException ioe) { System.out.println("\nCould not find login info..."); cnx = null; } catch (AuthenticationException ae) { System.out.println("\nLogin failed. Try again."); cnx = null; } password = null; } System.out.println("Authentication successful!"); return cnx; }
From source file:edu.utah.bmi.ibiomes.cli.CLIUtils.java
/** * Connect to iRODS using parameters given in command-line interface. * @return Connection object/* ww w .j a v a 2 s .c om*/ * @throws IOException * @throws JargonException */ public static IRODSConnector getConnectionFromCLI() throws IOException, JargonException { Console objConsole = System.console(); if (objConsole == null) { System.err.println("Console Object is not available."); System.exit(1); } BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); System.out.println("Host:"); String host = in.readLine(); System.out.println("Port [1247]:"); String iPort = in.readLine(); int port = 1247; if (iPort != null && iPort.length() > 0) port = Integer.parseInt(iPort); System.out.println("Zone:"); String zone = in.readLine(); System.out.println("Default resource:"); String server = in.readLine(); System.out.println("Username:"); String userName = in.readLine(); //retrieve iRODS password System.out.println("Password:"); char[] pwdArray = objConsole.readPassword(); String password = String.copyValueOf(pwdArray); IRODSConnector cnx = new IRODSConnector(host, port, userName, password, "", zone, server); try { //try to login IRODSAccessObjectFactory aoFactory = cnx.getFileSystem().getIRODSAccessObjectFactory(); aoFactory.getUserAO(cnx.getAccount()); System.out.println("\nConnected! (" + cnx.getAccount().toURI(false) + ")"); } catch (JargonException exc) { System.out.println("Login info: " + cnx.getAccount().getUserName() + "@" + cnx.getAccount().getHost() + ":" + cnx.getAccount().getPort() + ")."); System.out.println("Login failed. Try again."); cnx = null; } return cnx; }
From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java
/** * Ask the user for parameters missing on the command line *//*from w ww . jav a 2 s.c o m*/ private static void askInteractively(Console console, UserInfo userInfo, Action action) { System.out.println(action); System.out.print("login: "); if (!userInfo.isLoginSet()) { userInfo.setLogin(console.readLine()); } else { System.out.println(userInfo.getLogin()); } System.out.print("password: "); if ((action.isCreate() && !userInfo.isPasswordSet()) || (action.isUpdate() && !userInfo.isPasswordSet()) && !userInfo.isGroupSet()) { userInfo.setPassword(new String(console.readPassword())); } else { System.out.println("*******"); } if (action.isCreate() && !userInfo.isGroupSet()) { System.out.print("groups for user " + userInfo.getLogin() + ":"); String groupString = console.readLine(); userInfo.setGroups(Arrays.asList(groupString.split(","))); } }