1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.commons.net.examples.mail; 19 20 import java.io.BufferedReader; 21 import java.io.Console; 22 import java.io.IOException; 23 import java.io.InputStreamReader; 24 import java.util.Locale; 25 26 /** 27 * Utilities for mail examples 28 */ 29 class Utils { 30 31 /** 32 * If the initial password is: '*' - replace it with a line read from the system console '-' - replace it with next line from STDIN 'ABCD' - if the input is 33 * all upper case, use the field as an environment variable name 34 * 35 * Note: there are no guarantees that the password cannot be snooped. 36 * 37 * Even using the console may be subject to memory snooping, however it should be safer than the other methods. 38 * 39 * STDIN may require creating a temporary file which could be read by others Environment variables may be visible by using PS 40 */ 41 static String getPassword(final String user, String password) throws IOException { 42 if ("-".equals(password)) { // stdin 43 final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 44 password = in.readLine(); 45 } else if ("*".equals(password)) { // console 46 final Console con = System.console(); // Java 1.6 47 if (con == null) { 48 throw new IOException("Cannot access Console"); 49 } 50 final char[] pwd = con.readPassword("Password for " + user + ": "); 51 password = new String(pwd); 52 } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name 53 final String tmp = System.getenv(password); 54 if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers) 55 password = tmp; 56 } 57 } 58 return password; 59 } 60 61 private Utils() { 62 // not instantiable 63 } 64 65 }