Login that compares user input with encrypted data in MySQL

0

I'm having trouble finding a way to compare the data entered by the user to a jPasswordField on the login screen and compare it with the encrypted password in AES and saved in the MySQL database. Can anyone help me?

Save button code that registers the user and password encoded in the BD:

private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {                                            

    if (jTextFieldUsername.getText().trim().equals("") || jPasswordFieldPassword.getPassword().equals("") || jPasswordFieldConfirmPassword.getPassword().equals("")){
            javax.swing.JOptionPane.showMessageDialog(null, "Please, inform a username and password.");

        } else {

            if(Arrays.equals(jPasswordFieldPassword.getPassword(), jPasswordFieldConfirmPassword.getPassword())){
                String password = new String(jPasswordFieldPassword.getPassword());
                System.out.println(password);
                try {
                    KeyGenerator kg = KeyGenerator.getInstance("AES");
                    SecretKey sk = kg.generateKey();
                    Cipher cipher = Cipher.getInstance("AES");
                    cipher.init(Cipher.ENCRYPT_MODE, sk);
                    byte [] encrypt = cipher.doFinal(password.getBytes());
                    System.out.println(encrypt);

                    String admin = "";
                    if(jRadioButtonAdministrator.isSelected()){
                        admin="Yes";
                    }else{
                        admin="No";
                    }
                    String vendor = "";
                    if(jRadioButtonVendor.isSelected()){
                        vendor="Yes";
                    }else{
                        vendor="No";
                    }
                    Connection con = ConexaoMySQL.getInstance().getConnection();

                    String cmd = "insert into users (username, password, administrator, vendor, idEmployee, status) VALUES "
                            + "('"+jTextFieldUsername.getText()+"', '"+encrypt+"', '"+admin+"', '"+vendor+"', '"+jTableEmployeeInfo.getValueAt(jTableEmployeeInfo.getSelectedRow(), 0).toString()+"', 'Active')";

                    con.createStatement().executeUpdate(cmd);

                    javax.swing.JOptionPane.showMessageDialog(null, "Username successfully registered.", "Success", 1);

                    dispose();

                    } catch (SQLException ex) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Connection/data error. Please, inform a username and a password", "Attention!", 2);
                    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
                        Logger.getLogger(RegisterNewUserJDialogForm.class.getName()).log(Level.SEVERE, null, ex);
                    }
            } else {
                    javax.swing.JOptionPane.showMessageDialog(null, "Fields password and confirm password do not match");
            }
        }
}  

Login button code LoginJDialogForm screen:

private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {                                             

    UserDAO dao = new UserDAO();
    if(dao.verifyLogin(jTextFieldUser.getText(), new String (jPasswordFieldPassword.getPassword()))){
        JOptionPane.showMessageDialog(null, "Welcome!");
        MainScreenForm main = new MainScreenForm();
        main.setVisible(true);
        dispose();
    }else{
        javax.swing.JOptionPane.showMessageDialog(null, "Incorrect username and/or password.");
    }
}    

UserDAO:

public class UserDAO {

    public boolean verifyLogin(String username, String password){
        Connection con = ConexaoMySQL.getInstance().getConnection();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        boolean verify = false;

        try {
            stmt = con.prepareStatement("SELECT * FROM users WHERE username = ? and password = ?");
            stmt.setString(1, username);
            stmt.setString(2, password);
            System.out.println(stmt);

            rs = stmt.executeQuery();

            if(rs.next()){
                verify=true;
            }

            } catch (SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(null, "Incorrect username and/or password");
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return verify;
    }
}
    
asked by anonymous 17.06.2017 / 20:32

2 answers

0

So I noticed, you are using the Select password value entered in the login form. To test with the database, you need to test the encrypted password. So you need to encrypt the recovered password of the form and then use this encrypted value in the select. Something like:

public boolean verifyLogin(String username, String password){
    Connection con = ConexaoMySQL.getInstance().getConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    boolean verify = false;

    String encrypt = DigestUtils.sha256Hex(password);

    /*KeyGenerator kg = KeyGenerator.getInstance("AES");
    SecretKey sk = kg.generateKey();
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sk);
    byte [] encrypt = cipher.doFinal(password.getBytes());*/

    try {
        stmt = con.prepareStatement("SELECT * FROM users WHERE username = ? and password = ?");
        stmt.setString(1, username);
        stmt.setString(2, encrypt);
        System.out.println(stmt);

        rs = stmt.executeQuery();

        if(rs.next()){
            verify=true;
        }

        } catch (SQLException ex) {
        javax.swing.JOptionPane.showMessageDialog(null, "Incorrect username and/or password");
        Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return verify;
}

The ideal would be to create a method with the encryption action, hence you would just call the method every time you need to encrypt the password. It's simpler, reuse logic.

    
17.06.2017 / 21:15
0

Follow the modified and up-to-date code.

User registration button:

private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {                                            

    if (jTextFieldUsername.getText().trim().equals("") || jPasswordFieldPassword.getPassword().equals("") || jPasswordFieldConfirmPassword.getPassword().equals("")){
            javax.swing.JOptionPane.showMessageDialog(null, "Please, inform a username and password.");

        } else {

            if(Arrays.equals(jPasswordFieldPassword.getPassword(), jPasswordFieldConfirmPassword.getPassword())){
                String password = new String(jPasswordFieldPassword.getPassword());
                System.out.println(password);
                try {
                    MessageDigest digest = MessageDigest.getInstance("SHA-256");
                    byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
                    String encodedPassword = Base64.getEncoder().encodeToString(hash);

                    String admin = "";
                    if(jRadioButtonAdministrator.isSelected()){
                        admin="Yes";
                    }else{
                        admin="No";
                    }
                    String vendor = "";
                    if(jRadioButtonVendor.isSelected()){
                        vendor="Yes";
                    }else{
                        vendor="No";
                    }
                    Connection con = ConexaoMySQL.getInstance().getConnection();

                    String cmd = "insert into users (username, password, administrator, vendor, idEmployee, status) VALUES "
                            + "('"+jTextFieldUsername.getText()+"', '"+encodedPassword+"', '"+admin+"', '"+vendor+"', '"+jTableEmployeeInfo.getValueAt(jTableEmployeeInfo.getSelectedRow(), 0).toString()+"', 'Active')";

                    con.createStatement().executeUpdate(cmd);
                    System.out.println(cmd);
                    javax.swing.JOptionPane.showMessageDialog(null, "Username successfully registered.", "Success", 1);

                    dispose();

                } catch (SQLException ex) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Connection/data error. Please, inform a username and a password", "Attention!", 2);

                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(RegisterNewUserJDialogForm.class.getName()).log(Level.SEVERE, null, ex);
                }

            } else {
                    javax.swing.JOptionPane.showMessageDialog(null, "Fields password and confirm password do not match");
            }
        }
}                  

Login button:

private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {                                             

    UserDAO dao = new UserDAO();
    if(dao.verifyLogin(jTextFieldUser.getText(), new String (jPasswordFieldPassword.getPassword()))){
        JOptionPane.showMessageDialog(null, "Welcome!");
        MainScreenForm main = new MainScreenForm();
        main.setVisible(true);
        dispose();
    }else{
        javax.swing.JOptionPane.showMessageDialog(null, "Incorrect username and/or password.");
        jTextFieldUser.setText("");
        jPasswordFieldPassword.setText("");
    }

}      

UserDAO:

public class UserDAO {

    public boolean verifyLogin(String username, String password){
        Connection con = ConexaoMySQL.getInstance().getConnection();
        PreparedStatement stmt = null;
        ResultSet rs = null;
        boolean verify = false;
        System.out.println(password);

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
            String encodedPassword = Base64.getEncoder().encodeToString(hash);

            stmt = con.prepareStatement("SELECT * FROM users WHERE username = ? and password = ?");
            stmt.setString(1, username);
            stmt.setString(2, encodedPassword);
            System.out.println(stmt);

            rs = stmt.executeQuery();

            if(rs.next()){
                String administratorDB = rs.getString("administrator");
                String statusDB = rs.getString("status");

                if("Yes".equals(administratorDB) && "Active".equals(statusDB)){
                verify=true;
                }else{
                    javax.swing.JOptionPane.showMessageDialog(null, "The informed username does not have administrator permission.");

                }
            }

        } catch (SQLException | NoSuchAlgorithmException ex) {
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);

        }

        return verify;
    }
}
    
18.06.2017 / 00:18