List of usage examples for java.io Console readPassword
public char[] readPassword(String fmt, Object... args)
From source file:keepassj.cli.KeepassjCli.java
/** * @param args the command line arguments * @throws org.apache.commons.cli.ParseException * @throws java.io.IOException/*from w ww .ja v a 2s . co m*/ */ public static void main(String[] args) throws ParseException, IOException { Options options = KeepassjCli.getOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!KeepassjCli.validateOptions(cmd)) { HelpFormatter help = new HelpFormatter(); help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options); } else { String password; if (cmd.hasOption('p')) { password = cmd.getOptionValue('p'); } else { Console console = System.console(); char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f')); password = String.valueOf(hiddenString); } KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k')); System.out.println("Description:" + instance.db.getDescription()); PwGroup rootGroup = instance.db.getRootGroup(); System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries"); if (cmd.hasOption('l')) { instance.printEntries(rootGroup.GetEntries(true), false); } else if (cmd.hasOption('s')) { PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s')); System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s')); instance.printEntries(results, false); } else if (cmd.hasOption('i')) { System.out.println("Entering interactive mode."); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String input = null; PwObjectList<PwEntry> results = null; while (!"\\q".equals(input)) { if (results != null) { System.out.println("Would you like to view a specific entry? y/n"); input = bufferedReader.readLine(); if ("y".equalsIgnoreCase(input)) { System.out.print("Enter the title number:"); input = bufferedReader.readLine(); instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1 } results = null; System.out.println(); } else { System.out.print("Enter something to search for (or \\q to quit):"); input = bufferedReader.readLine(); if (!"\\q".equalsIgnoreCase(input)) { results = instance.search(input); instance.printEntries(results, true); } } } } // Close before exit instance.db.Close(); } }
From source file:com.floragunn.searchguard.tools.Hasher.java
public static void main(final String[] args) { final Options options = new Options(); final HelpFormatter formatter = new HelpFormatter(); options.addOption(// w w w .j a v a 2s.com Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build()); options.addOption(Option.builder("env").argName("name environment variable").hasArg() .desc("name environment variable to read password from").build()); final CommandLineParser parser = new DefaultParser(); try { final CommandLine line = parser.parse(options, args); if (line.hasOption("p")) { System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8"))); } else if (line.hasOption("env")) { final String pwd = System.getenv(line.getOptionValue("env")); if (pwd == null || pwd.isEmpty()) { throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set"); } System.out.println(hash(pwd.getBytes("UTF-8"))); } else { final Console console = System.console(); if (console == null) { throw new Exception("Cannot allocate a console"); } final char[] passwd = console.readPassword("[%s]", "Password:"); System.out.println(hash(new String(passwd).getBytes("UTF-8"))); } } catch (final Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); formatter.printHelp("hasher.sh", options, true); System.exit(-1); } }
From source file:de.petendi.ethereum.secure.proxy.Application.java
public static void main(String[] args) { try {/*from www .j ava2 s . com*/ cmdLineResult = new CmdLineResult(); cmdLineResult.parseArguments(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); System.out.println("Usage:"); cmdLineResult.printExample(); System.exit(-1); return; } File workingDirectory = new File(System.getProperty("user.home")); if (cmdLineResult.getWorkingDirectory().length() > 0) { workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile(); } ArgumentList argumentList = new ArgumentList(); argumentList.setWorkingDirectory(workingDirectory); File certificate = new File(workingDirectory, "seccoco-secured/cert.p12"); if (certificate.exists()) { char[] passwd = null; if (cmdLineResult.getPassword() != null) { System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!"); passwd = cmdLineResult.getPassword().toCharArray(); } else { Console console = System.console(); if (console != null) { passwd = console.readPassword("[%s]", "Enter application password:"); } else { System.out.print("No suitable console found for entering password"); System.exit(-1); } } argumentList.setTokenPassword(passwd); } try { SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList); seccoco = seccocoFactory.create(); } catch (InitializationException e) { System.out.println(e.getMessage()); System.exit(-1); } try { System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl()); URL url = new URL(cmdLineResult.getUrl()); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); String additionalHeaders = cmdLineResult.getAdditionalHeaders(); if (additionalHeaders != null) { StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ","); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":"); headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken()); } } settings = new Settings(cmdLineResult.isExposeWhisper(), headers); jsonRpcHttpClient = new JsonRpcHttpClient(url); jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener()); jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers); if (cmdLineResult.isExposeWhisper()) { jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers); } System.out.println("Connection succeeded"); } catch (Throwable e) { System.out.println("Connection failed: " + e.getMessage()); System.exit(-1); } SpringApplication app = new SpringApplication(Application.class); app.setBanner(new Banner() { @Override public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) { //send the Spring Boot banner to /dev/null } }); app.run(new String[] {}); }
From source file:cloud.elasticity.elastman.App.java
/** * The entry point to the ElastMan main program. * /* w ww . j a va2 s .co m*/ * @param args The first argument is the mode which can be inter, ident, or control * corresponding to interactive mode, system identification mode, or control mode. * The second argument is the configuration file * The third argument is password password */ public static void main(String[] args) { // 1) parse the command line // For more information http://commons.apache.org/cli/ Options options = new Options(); options.addOption("i", "ident", false, "Enter system identification mode."); options.addOption("c", "control", false, "Enter controller mode."); options.addOption("o", "options", true, "Configuration file. Default elastman.conf"); options.addOption("u", "username", true, "Username in the form Tenant:UserName"); options.addOption("p", "password", true, "User password"); options.addOption("k", "keyname", true, "Name of SSH key to use"); options.addOption("z", "zone", true, "The OpenStack availability zone such as the default RegionOne"); options.addOption("e", "endpoint", true, "The URL to access OpenStack API such as http://192.168.1.1:5000/v2.0/"); options.addOption("s", "syncserver", true, "The URL access the WebSyncServer"); options.addOption("h", "help", false, "Print this help"); CommandLineParser parser = new GnuParser(); try { cmd = parser.parse(options, args); } catch (ParseException e2) { System.out.println(e2.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ElastMan", options, true); System.exit(1); } // if h then show help and exit if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ElastMan", options, true); System.exit(0); } // 2) Try to load the properties file. // Command line arguments override settings in the properties file // If no properties file exists. defaults will be used String filename = "control.prop"; // the default file name if (cmd.hasOption("o")) { filename = cmd.getOptionValue("o"); } Props.load(filename, cmd); // Props.save(filename); // System.exit(-1); // 3) If no password in command line nor in config file then ask the user if (Props.password == null) { Console cons; char[] passwd; if ((cons = System.console()) != null && // more secure and without echo! (passwd = cons.readPassword("[%s]", "Password:")) != null) { Props.password = new String(passwd); } else { // if you don't have a console! E.g., Running in eclipse System.out.print("Password: "); Props.password = scanner.nextLine(); } } // 4) Start the UI App app = new App(); app.textUI(args); }
From source file:org.apache.shiro.tools.hasher.Hasher.java
private static char[] readPassword(boolean confirm) { if (!JavaEnvironment.isAtLeastVersion16()) { String msg = "Password hashing (prompt without echo) uses the java.io.Console to read passwords " + "safely. This is only available on Java 1.6 platforms and later."; throw new IllegalArgumentException(msg); }/*from w w w .ja v a2s . c om*/ java.io.Console console = System.console(); if (console == null) { throw new IllegalStateException( "java.io.Console is not available on the current JVM. Cannot read passwords."); } char[] first = console.readPassword("%s", "Password to hash: "); if (first == null || first.length == 0) { throw new IllegalArgumentException("No password specified."); } if (confirm) { char[] second = console.readPassword("%s", "Password to hash (confirm): "); if (!Arrays.equals(first, second)) { String msg = "Password entries do not match."; throw new IllegalArgumentException(msg); } } return first; }
From source file:fr.ortolang.diffusion.client.cmd.Command.java
protected String[] getCredentials(CommandLine cmd) throws OrtolangClientException { String username;/*w ww . j av a2s. c om*/ String password = null; if (cmd.hasOption("U")) { username = cmd.getOptionValue("U"); if (cmd.hasOption("P")) { password = cmd.getOptionValue("P"); } else { Console cons; char[] passwd; if ((cons = System.console()) != null && (passwd = cons.readPassword("[%s]", "Password:")) != null) { password = new String(passwd); } } return new String[] { username, password }; } throw new OrtolangClientException("Username and/or password missing"); }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.security.DefaultSecretCallbackHandler.java
/** * {@inheritDoc}/* w w w .j a v a2s .c om*/ */ public void handleSingleSecretCallback(SingleSecretCallback singleSecretCallback) { if (keyStorePassWord == null && privateKeyPassWord == null) { String textFileName; String passwords[]; String productHome = System.getProperty(CommonConstants.CARBON_HOME); String osName = System.getProperty("os.name"); if (!osName.toLowerCase().contains("win")) { textFileName = "password"; } else { textFileName = "password.txt"; } keyDataFile = new File(productHome + File.separator + textFileName); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile); privateKeyPassWord = keyStorePassWord = passwords[0]; if (!deleteConfigFile()) { handleException("Error deleting Password config File"); } } else { Console console; char[] password; if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore and Private Key Password :")) != null) { keyStorePassWord = String.valueOf(password); privateKeyPassWord = keyStorePassWord; } } } if (singleSecretCallback.getId().equals("identity.key.password")) { singleSecretCallback.setSecret(privateKeyPassWord); } else { singleSecretCallback.setSecret(keyStorePassWord); } }
From source file:org.wso2.carbon.identity.agent.userstore.security.DefaultSecretCallbackHandler.java
/** * {@inheritDoc}/*from w w w . ja va2 s .c o m*/ */ public void handleSingleSecretCallback(SingleSecretCallback singleSecretCallback) { if (keyStorePassWord == null && privateKeyPassWord == null) { String textFileName; String passwords[]; String productHome = System.getProperty(CommonConstants.CARBON_HOME); String osName = System.getProperty("os.name"); if (!osName.toLowerCase().contains("win")) { textFileName = "password"; } else { textFileName = "password.txt"; } keyDataFile = new File(productHome + File.separator + textFileName); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile); privateKeyPassWord = keyStorePassWord = passwords[0]; if (!deleteConfigFile()) { handleException("Error deleting Password org.wso2.carbon.identity.agent.outbound.config File"); } } else { Console console; char[] password; if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore and Private Key Password :")) != null) { keyStorePassWord = String.valueOf(password); privateKeyPassWord = keyStorePassWord; } } } if (singleSecretCallback.getId().equals("identity.key.password")) { singleSecretCallback.setSecret(privateKeyPassWord); } else { singleSecretCallback.setSecret(keyStorePassWord); } }
From source file:com.mijecu25.sqlplus.SQLPlus.java
/** * Create an SQLPlusConnection by taking the credentials from the user. * * @throws IOException if there is an I/O error while reading input from the user. * @throws SQLException if there is an error while establishing a connection. *//*from w w w. j a va2s .c o m*/ private static void createSQLPlusConnection() throws IOException, SQLException { if (false) { System.out.println("You will now enter the credentials to connect to your database"); // Add credentials System.out.print(SQLPlus.PROMPT + "Host(default " + SQLPlusConnection.getDefaultHost() + "): "); String host = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("User entered host:" + host); // TODO validate host // if(!host.isEmpty()) { // // The Console object for the JVM could not be found. Alert the user and throw a // // NullPointerException that the caller will handle // SQLPlus.logger.fatal(Messages.FATAL + "The user wants to use a host that is not supported"); // System.out.println(Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the host that you entered"); // // SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the " // + "calling class"); // throw new IllegalArgumentException(); // } System.out.print(SQLPlus.PROMPT + "Database(default " + SQLPlusConnection.getDefaultDatabase() + "): "); String database = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("User entered database:" + database); if (database.isEmpty()) { database = SQLPlusConnection.getDefaultDatabase(); SQLPlus.logger.info("Using default database:" + database); } String port = ""; // While the port is not numeric while (!StringUtils.isNumeric(port)) { System.out.print(SQLPlus.PROMPT + "Port (default " + SQLPlusConnection.getDefaultPort() + "): "); port = SQLPlus.console.readLine().trim(); SQLPlus.logger.info("Port entered: " + port); SQLPlus.logger.info("Port string length: " + port.length()); // If the port is empty if (port.isEmpty()) { // Assume that the user wants to use the default port. Continue to the next step break; } // If the port has more than 5 numbers or is not numberic if (port.length() > 5 || !StringUtils.isNumeric(port)) { SQLPlus.logger.warn("The user provided an invalid port number: " + port); System.out.println( Messages.WARNING + "You need to provided a valid port number " + "from 0 to 65535"); // Set the port to the empty string to ask the user again port = ""; } } SQLPlus.logger.info("User entered port:" + port); String username = ""; // While the username is empty while (username.isEmpty()) { System.out.print(SQLPlus.PROMPT + "Username: "); username = SQLPlus.console.readLine().trim(); // If the username is empty if (username.isEmpty()) { SQLPlus.logger.warn("The user did not provide a username"); System.out.println(Messages.WARNING + "You cannot have an empty username"); } } SQLPlus.logger.info("User entered username:" + username); // Reset the jline console since we are going to use the regular console to securely get the password SQLPlus.resetConsole(); // Get the console for safe password entry Console javaConsole = System.console(); // If the console is null if (javaConsole == null) { // The Console object for the JVM could not be found. Alert the user and throw a // NullPointerException that the caller will handle SQLPlus.logger.fatal("A JVM Console object to enter a password was not found"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. " + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line."); SQLPlus.logger.info( "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class"); throw new NullPointerException(); } // Read the password without echoing the result char[] password = javaConsole.readPassword("%s", SQLPlus.PROMPT + "Password:"); // If the password is null if (password == null) { // The Console object for the JVM could not be found. Alert the user and throw a // NullPointerException that the caller will handle SQLPlus.logger.fatal("The password captured by the JVM Console object returned null"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " was not able to get the password you entered from" + "your JVM's Console object. Try running " + SQLPlus.PROGRAM_NAME + " from the command line or a different" + "terminal program"); SQLPlus.logger.info( "Throwing a " + NullPointerException.class.getSimpleName() + " to the " + "calling class"); throw new NullPointerException(); } SQLPlus.logger.info("User entered some password"); System.out.println(); // Create a connection based on the database system switch (database) { case SQLPlusMySQLConnection.MYSQL: // If the default port and host are used if (port.isEmpty() && host.isEmpty()) { SQLPlus.logger.info("Connection with username, password"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password); } // If the default port is used else if (port.isEmpty()) { SQLPlus.logger.info("Connection with username, password, and host"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host); } // All the values were provided by the user else { SQLPlus.logger.info("Connection with all credentials"); sqlPlusConnection = SQLPlusMySQLConnection.getConnection(username, password, host, port); } break; default: // Database entered is not supported SQLPlus.logger.fatal(Messages.FATAL + "The database system " + database + " is not supported"); System.out.println( Messages.ERROR + SQLPlus.PROGRAM_NAME + " does not support the database that you entered"); SQLPlus.logger.info("Throwing a " + IllegalArgumentException.class.getSimpleName() + " to the " + "calling class"); throw new IllegalArgumentException(); } // Delete any traces of password in memory by filling the password array with with random characters // to minimize the lifetime of sensitive data in memory. Then call the garbage collections java.util.Arrays.fill(password, Character.MIN_VALUE); System.gc(); // Recreate the jline console SQLPlus.console = new ConsoleReader(); SQLPlus.console.setHandleUserInterrupt(true); } // TODO remove this which is for testing SQLPlus.logger.info("Connection with username, password, and host"); SQLPlusConnection sqlPlusConnection = SQLPlusMySQLConnection.getConnection("sqlplus", new char[0], SQLPlusConnection.getDefaultHost()); // TODO this does have to be in the final code SQLPlus.logger.info("Created and returning a SQLPlusConnection " + sqlPlusConnection); SQLPlus.sqlPlusConnection = sqlPlusConnection; }
From source file:org.wso2.carbon.securevault.DefaultSecretCallbackHandler.java
public void handleSingleSecretCallback(SingleSecretCallback singleSecretCallback) { if (keyStorePassWord == null && privateKeyPassWord == null) { String textFileName;/* www . ja v a 2 s . c o m*/ String textFileName_tmp; String textFilePersist; boolean sameKeyAndKeyStorePass = true; boolean persistPassword = false; String passwords[]; String carbonHome = System.getProperty(CARBON_HOME); String osName = System.getProperty("os.name"); if (osName.toLowerCase().indexOf("win") == -1) { textFileName = "password"; textFileName_tmp = "password-tmp"; textFilePersist = "password-persist"; } else { textFileName = "password.txt"; textFileName_tmp = "password-tmp.txt"; textFilePersist = "password-persist.txt"; } String keyPassword = System.getProperty(KEY_PASSWORD); if (keyPassword != null && keyPassword.trim().equals("true")) { sameKeyAndKeyStorePass = false; } String persistPasswordProperty = System.getProperty(PERSIST_PASSWORD); if (persistPasswordProperty != null && persistPasswordProperty.trim().equals("true")) { persistPassword = true; } keyDataFile = new File(carbonHome + File.separator + textFileName); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } if (!persistPassword) { if (!renameConfigFile(textFileName_tmp)) { handleException("Error renaming Password config File"); } } } else { keyDataFile = new File(carbonHome + File.separator + textFileName_tmp); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } if (!persistPassword) { if (!deleteConfigFile()) { handleException("Error deleting Password config File"); } } } else { keyDataFile = new File(carbonHome + File.separator + textFilePersist); if (keyDataFile.exists()) { passwords = readPassword(keyDataFile, sameKeyAndKeyStorePass); keyStorePassWord = passwords[0]; if (sameKeyAndKeyStorePass) { privateKeyPassWord = keyStorePassWord; } else { privateKeyPassWord = passwords[1]; } } else { Console console; char[] password; if (sameKeyAndKeyStorePass) { if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore and Private Key Password :")) != null) { keyStorePassWord = String.valueOf(password); privateKeyPassWord = keyStorePassWord; } } else { if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter KeyStore Password :")) != null) { keyStorePassWord = String.valueOf(password); } if ((console = System.console()) != null && (password = console.readPassword("[%s]", "Enter Private Key Password : ")) != null) { privateKeyPassWord = String.valueOf(password); } } } } } } if (singleSecretCallback.getId().equals("identity.key.password")) { singleSecretCallback.setSecret(privateKeyPassWord); } else { singleSecretCallback.setSecret(keyStorePassWord); } }