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 * https://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.nio.charset.Charset;
25 import java.util.Locale;
26
27 /**
28 * Utilities for mail examples
29 */
30 final class Utils {
31
32 /**
33 * 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
34 * all upper case, use the field as an environment variable name
35 *
36 * Note: there are no guarantees that the password cannot be snooped.
37 *
38 * Even using the console may be subject to memory snooping, however it should be safer than the other methods.
39 *
40 * STDIN may require creating a temporary file which could be read by others Environment variables may be visible by using PS
41 */
42 static String getPassword(final String user, String password) throws IOException {
43 if ("-".equals(password)) { // stdin
44 final BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
45 password = in.readLine();
46 } else if ("*".equals(password)) { // console
47 final Console con = System.console(); // Java 1.6
48 if (con == null) {
49 throw new IOException("Cannot access Console");
50 }
51 final char[] pwd = con.readPassword("Password for " + user + ": ");
52 password = new String(pwd);
53 } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name
54 final String tmp = System.getenv(password);
55 if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers)
56 password = tmp;
57 }
58 }
59 return password;
60 }
61
62 private Utils() {
63 // not instantiable
64 }
65
66 }