Login comparing user input to encrypted data in Mysql

Asked

Viewed 207 times

0

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

Save button code that records user and password encoded in 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;
    }
}
  • One thing I realized: I registered the password '123456' for a user and it was saved in the BD as '[B@4b00b75d'. When I try to log in with the same user and pass the password '123456', through the same process as Encrypt, System.out.println(Encrypt) captures the password as '[B@20feb86d'. Does anyone know what it can be?

2 answers

0


From what 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 form password and then use this encrypted value in 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, so just call the method every time you need to encrypt the password. It gets simpler, re-uses logic.

  • tried, but first gave an error that cannot convert byte[] to String. I converted Encrypt to String with String password2 = encrypt.toString(); and passed stmt.setString(2, password2);, but even so I could not make the comparison seems that '123456' when encrypted and saved in the database, it is with value different from '123456' when passed by the user in the login screen and encrypted for comparison. Could it be the jPasswordField? Thank you.

  • I advise you to use the library Apache Commons Codec to perform encryption. It’s much simpler. I will edit my previous reply by adding the code using this library, you will see how simple it is.

  • By the way, it will be necessary to save the password using also this change.

  • worked! I added the Base64 to convert. Thank you very much! : ) For anyone with the same doubt, I will put the modified code in a new answer right below.

0

Follow code modified and working.

Button to register the user:

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;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.