1

here's my problem, I am working on a system where user can create an account, the user launches a program, he clicks on the register button. A new page appears and he has to enter his information(username, password). Then his information is stored into a local DB. The problem is when a user create his account his information is stored in DB but the password is a String so everyone can see what the password it is . I want to hash the password into my java program first then store it into DB. But I don't understand how to that because I use "Windows Builder" to do the interface, so the user enter his password in a JPasswordField. I don't know how to obtain the password that the user wrote, hash it, and send it to the DB.

For now I have a program where I can store the information I need, and I have a program where I can hash a word into different types of hash. I also use the salt method I saw it's better for the password, none of them will have the same hash code.

The code to store information :

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;

public class Register extends JFrame {

private JPanel contentPane;
private JTextField txtUsername;
private JPasswordField pwdPassword;
private JPasswordField pwdConfpassword;
private JButton btnSubmit;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Register frame = new Register();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Register() {
    super("Register");
    conn = DatabaseConnection.connection();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblUsername = new JLabel("Username");
    lblUsername.setBounds(96, 68, 71, 14);
    contentPane.add(lblUsername);

    JLabel lblPassword = new JLabel("Password");
    lblPassword.setBounds(96, 93, 80, 14);
    contentPane.add(lblPassword);

    JLabel lblconfPassword = new JLabel("Confirm password");
    lblconfPassword.setBounds(97, 122, 91, 14);
    contentPane.add(lblconfPassword);

    txtUsername = new JTextField();
    txtUsername.setBounds(204, 65, 86, 20);
    contentPane.add(txtUsername);
    txtUsername.setColumns(10);

    pwdPassword = new JPasswordField();
    pwdPassword.setBounds(201, 90, 89, 20);
    contentPane.add(pwdPassword);

    pwdConfpassword = new JPasswordField();
    pwdConfpassword.setBounds(211, 119, 79, 20);
    contentPane.add(pwdConfpassword);

    btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {

                stmt = conn.createStatement();
                String RegUsername = txtUsername.getText();
                String RegPassword = pwdPassword.getText();
                String sql = "INSERT INTO account(Username, Password) VALUES('"+RegUsername+"', '"+RegPassword+"')";

                stmt.executeUpdate(sql);
                JOptionPane.showMessageDialog(null,"Account created");
            }catch(Exception e1) {
                JOptionPane.showMessageDialog(null,e1);
            }

        }
    });
    btnSubmit.setBounds(78, 202, 89, 23);
    contentPane.add(btnSubmit);
}

The code to hash password :

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class hash {
public static void main(String[] args) throws Exception {

String Password = "Maria";
String algorithm = "MD5";
byte[] salt = createSalt();
System.out.println("test : " +generateHash(Password, algorithm, salt));
}
private static String generateHash(String Password, String algorithm,                                             byte[] salt) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.reset();
digest.update(salt);
byte[] hash = digest.digest(Password.getBytes());
return bytesToStringHex(hash);
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToStringHex(byte[] bytes) {
char [] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length;j++) {
    int v = bytes[j] & 0xFF;
    hexChars[j * 2] = hexArray[v >>>4];
    hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] createSalt() {
    byte[] bytes = new byte[20];
    SecureRandom random = new SecureRandom();
    random.nextBytes(bytes);
    return bytes;
}
}

My goal is that the user can register and his password is stored in the DB but the password is hash following a certain type of hash and also he can log in with his account so the password can be decrypt and compare with the one encrypt.

Sincerely, Molka

Kishore Tulsiani
  • 1,106
  • 13
  • 29
Molka
  • 11
  • 1
  • 5
  • Welcome to Stack Overflow! Please take the [tour](/tour), have a look around, and read through the [help center](/help), in particular [How do I ask a good question?](/help/how-to-ask) and [What topics can I ask about here?](/help/on-topic). – Timothy Truckle Dec 27 '18 at 23:26
  • See [Cryptographic hash function](https://en.wikipedia.org/wiki/Cryptographic_hash_function#Password_verification) and [Salt (cryptography)](https://en.wikipedia.org/wiki/Salt_(cryptography)) on Wikipedia. –  Dec 28 '18 at 01:26

2 Answers2

1

First thing, you can't access the generateHash since it is private. You will need to change it to public. Then you can hook it into the actionPerformed method. Then just save the result in the password row in your database.

Second never use MD5 for hashing of passwords. You want to use bcrypt or another secure algorithm. Here is an example how to do that. https://www.stubbornjava.com/posts/hashing-passwords-in-java-with-bcrypt

Lastly, you do not seem to know what you are doing (no offense). I would strongly advise against implementing any security-related code if it is for the real world. It is easy to make a mistake and it can have disastrous effects. If it is for the real world ask someone more senior to write it for you while you shadow them. If it is not for the real world then hack away to your heart's content with the help of the example I gave you.

Icy Creature
  • 1,875
  • 2
  • 28
  • 53
  • Thanks for your answer. I will change it to public. Ok I will try to follow the tutorial you sent me. I'm a beginner in programming in general. What I'm doing is for a school project, we didn't have such courses about programming and java. I use Java because we did few things but not because I like it or I know how to use java. I will follow the tutorial and I comeback if things don't go well. Sincerely, Molka – Molka Dec 28 '18 at 02:44
0

make generateHash a public method of hash class then just call it up before writing the data to database:

public void actionPerformed(ActionEvent e) {
        try {

            stmt = conn.createStatement();
            String RegUsername = txtUsername.getText();
            String RegPassword = hash.generateHash(pwdPassword.getText(),"sha-512");
            String sql = "INSERT INTO account(Username, Password) VALUES('"+RegUsername+"', '"+RegPassword+"')";

            stmt.executeUpdate(sql);
            JOptionPane.showMessageDialog(null,"Account created");
        }catch(Exception e1) {
            JOptionPane.showMessageDialog(null,e1);
        }

    }
kamyar haqqani
  • 748
  • 6
  • 19