totpgenerator

TOTP code generator
git clone git://git.wimdupont.com/totpgenerator.git
Log | Files | Refs | README | LICENSE

PasswordReader.java (1332B)


      1 package com.wimdupont.service;
      2 
      3 import javax.swing.JLabel;
      4 import javax.swing.JOptionPane;
      5 import javax.swing.JPanel;
      6 import javax.swing.JPasswordField;
      7 import java.io.Console;
      8 
      9 public class PasswordReader {
     10 
     11     public static char[] getPassword() {
     12         String prompt = "Enter password";
     13         Console console = System.console();
     14         return console == null
     15                 ? getPasswordByPanel(prompt)
     16                 : getPasswordByConsole(prompt, console);
     17     }
     18 
     19     private static char[] getPasswordByConsole(String prompt, Console console) {
     20         System.out.println(prompt);
     21         return console.readPassword();
     22     }
     23 
     24     private static char[] getPasswordByPanel(String prompt) {
     25         var panel = new JPanel();
     26         var passwordField = new JPasswordField(10);
     27         panel.add(new JLabel("Password"));
     28         panel.add(passwordField);
     29         var pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
     30             @Override
     31             public void selectInitialValue() {
     32                 passwordField.requestFocusInWindow();
     33             }
     34         };
     35         pane.createDialog(null, prompt)
     36                 .setVisible(true);
     37 
     38         return passwordField.getPassword().length == 0
     39                 ? new char[0]
     40                 : passwordField.getPassword();
     41     }
     42 }