1 /*
   2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.security.util;
  27 
  28 import java.io.*;
  29 import java.nio.*;
  30 import java.nio.charset.*;
  31 import java.util.Arrays;
  32 
  33 /**
  34  * A utility class for reading passwords
  35  *
  36  */
  37 public class Password {
  38     /** Reads user password from given input stream. */
  39     public static char[] readPassword(InputStream in) throws IOException {
  40         return readPassword(in, false);
  41     }
  42 
  43     /** Reads user password from given input stream.
  44      * @param isEchoOn true if the password should be echoed on the screen
  45      */
  46     @SuppressWarnings("fallthrough")
  47     public static char[] readPassword(InputStream in, boolean isEchoOn)
  48             throws IOException {
  49 
  50         char[] consoleEntered = null;
  51         byte[] consoleBytes = null;
  52 
  53         try {
  54             // Use the new java.io.Console class
  55             Console con = null;
  56             if (!isEchoOn && in == System.in && ((con = System.console()) != null)) {
  57                 consoleEntered = con.readPassword();
  58                 // readPassword returns "" if you just print ENTER,
  59                 // to be compatible with old Password class, change to null
  60                 if (consoleEntered != null && consoleEntered.length == 0) {
  61                     return null;
  62                 }
  63                 consoleBytes = convertToBytes(consoleEntered);
  64                 in = new ByteArrayInputStream(consoleBytes);
  65             }
  66 
  67             // Rest of the lines still necessary for KeyStoreLoginModule
  68             // and when there is no console.
  69 
  70             char[] lineBuffer;
  71             char[] buf;
  72             int i;
  73 
  74             buf = lineBuffer = new char[128];
  75 
  76             int room = buf.length;
  77             int offset = 0;
  78             int c;
  79 
  80             boolean done = false;
  81             while (!done) {
  82                 switch (c = in.read()) {
  83                   case -1:
  84                   case '\n':
  85                       done = true;
  86                       break;
  87 
  88                   case '\r':
  89                     int c2 = in.read();
  90                     if ((c2 != '\n') && (c2 != -1)) {
  91                         if (!(in instanceof PushbackInputStream)) {
  92                             in = new PushbackInputStream(in);
  93                         }
  94                         ((PushbackInputStream)in).unread(c2);
  95                     } else {
  96                         done = true;
  97                         break;
  98                     }
  99                     /* fall through */
 100                   default:
 101                     if (--room < 0) {
 102                         buf = new char[offset + 128];
 103                         room = buf.length - offset - 1;
 104                         System.arraycopy(lineBuffer, 0, buf, 0, offset);
 105                         Arrays.fill(lineBuffer, ' ');
 106                         lineBuffer = buf;
 107                     }
 108                     buf[offset++] = (char) c;
 109                     break;
 110                 }
 111             }
 112 
 113             if (offset == 0) {
 114                 return null;
 115             }
 116 
 117             char[] ret = new char[offset];
 118             System.arraycopy(buf, 0, ret, 0, offset);
 119             Arrays.fill(buf, ' ');
 120 
 121             return ret;
 122         } finally {
 123             if (consoleEntered != null) {
 124                 Arrays.fill(consoleEntered, ' ');
 125             }
 126             if (consoleBytes != null) {
 127                 Arrays.fill(consoleBytes, (byte)0);
 128             }
 129         }
 130     }
 131 
 132     /**
 133      * Change a password read from Console.readPassword() into
 134      * its original bytes.
 135      *
 136      * @param pass a char[]
 137      * @return its byte[] format, similar to new String(pass).getBytes()
 138      */
 139     private static byte[] convertToBytes(char[] pass) {
 140         if (enc == null) {
 141             synchronized (Password.class) {
 142                 enc = sun.misc.SharedSecrets.getJavaIOAccess()
 143                         .charset()
 144                         .newEncoder()
 145                         .onMalformedInput(CodingErrorAction.REPLACE)
 146                         .onUnmappableCharacter(CodingErrorAction.REPLACE);
 147             }
 148         }
 149         byte[] ba = new byte[(int)(enc.maxBytesPerChar() * pass.length)];
 150         ByteBuffer bb = ByteBuffer.wrap(ba);
 151         synchronized (enc) {
 152             enc.reset().encode(CharBuffer.wrap(pass), bb, true);
 153         }
 154         if (bb.position() < ba.length) {
 155             ba[bb.position()] = '\n';
 156         }
 157         return ba;
 158     }
 159     private static volatile CharsetEncoder enc;
 160 }