IT Share you

명령 줄에서 입력 숨기기

shareyou 2020. 12. 11. 20:54
반응형

명령 줄에서 입력 숨기기


Git 및 기타와 같은 명령 줄 인터페이스가 사용자의 입력을 숨길 수 있다는 것을 알고 있습니다 (암호에 유용함). Java에서 프로그래밍 방식으로이를 수행하는 방법이 있습니까? 나는 사용자로부터 암호 입력을 받고 있고 그들의 입력을 그 특정 줄에 "숨기기"를 원합니다 (그러나 그들 모두가 아님). 여기에 내 코드가 있습니다 (도움이 될 것 같지는 않지만 ...)

try (Scanner input = new Scanner(System.in)) {
  //I'm guessing it'd probably be some property you set on the scanner or System.in right here...
  System.out.print("Please input the password for " + name + ": ");
  password = input.nextLine();
}

시도해보십시오 java.io.Console.readPassword. 그래도 Java 6 이상을 실행해야합니다.

   /**
    * Reads a password or passphrase from the console with echoing disabled
    *
    * @throws IOError
    *         If an I/O error occurs.
    *
    * @return  A character array containing the password or passphrase read
    *          from the console, not including any line-termination characters,
    *          or <tt>null</tt> if an end of stream has been reached.
    */
    public char[] readPassword() {
        return readPassword("");
    }

그러나 이것은 Eclipse 콘솔에서 작동하지 않습니다 . 실제 콘솔 / 쉘 / 터미널 / 프롬프트 에서 프로그램을 실행 해야 테스트 할 수 있습니다.


네 할 수 있습니다. 이를 명령 줄 입력 마스킹이라고합니다. 이것을 쉽게 구현할 수 있습니다.

별도의 스레드를 사용하여 입력중인 에코 된 문자를 지우고 별표로 바꿀 수 있습니다. 이것은 아래 표시된 EraserThread 클래스를 사용하여 수행됩니다.

import java.io.*;

class EraserThread implements Runnable {
   private boolean stop;

   /**
    *@param The prompt displayed to the user
    */
   public EraserThread(String prompt) {
       System.out.print(prompt);
   }

   /**
    * Begin masking...display asterisks (*)
    */
   public void run () {
      stop = true;
      while (stop) {
         System.out.print("\010*");
     try {
        Thread.currentThread().sleep(1);
         } catch(InterruptedException ie) {
            ie.printStackTrace();
         }
      }
   }

   /**
    * Instruct the thread to stop masking
    */
   public void stopMasking() {
      this.stop = false;
   }
}

이 스레드를 사용하여

public class PasswordField {

   /**
    *@param prompt The prompt to display to the user
    *@return The password as entered by the user
    */
   public static String readPassword (String prompt) {
      EraserThread et = new EraserThread(prompt);
      Thread mask = new Thread(et);
      mask.start();

      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String password = "";

      try {
         password = in.readLine();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
      // stop masking
      et.stopMasking();
      // return the password entered by the user
      return password;
   }
}

이 링크 는 자세히 설명합니다.


JLine 2흥미로울 수 있습니다. 문자 마스킹뿐만 아니라 명령 줄 완성, 편집 및 기록 기능을 제공합니다. 결과적으로 CLI 기반 Java 도구에 매우 유용합니다.

입력을 마스킹하려면 :

String password = new jline.ConsoleReader().readLine(new Character('*'));

있습니다 :

Console cons;
char[] passwd;
if ((cons = System.console()) != null &&
    (passwd = cons.readPassword("[%s]", "Password:")) != null) {
    ...
    java.util.Arrays.fill(passwd, ' ');
}

출처

그러나 프로그램이 콘솔 창을 사용하는 최상위 프로세스가 아닌 백그라운드 프로세스로 실행되기 때문에 Eclipse와 같은 IDE에서는 작동하지 않는다고 생각합니다.

또 다른 방법은 JPasswordField다음과 같은 actionPerformed방법으로 in swing 을 사용하는 것 입니다 .

public void actionPerformed(ActionEvent e) {
    ...
    char [] p = pwdField.getPassword();
}

출처


The class Console has a method readPassword() that might solve your problem.

참고URL : https://stackoverflow.com/questions/10819469/hide-input-on-command-line

반응형