user6139543
user6139543

Reputation:

SHA1 not producing same hash value for same string input?

I am busy with a login JFrame where the system will request the user to enter a username and password. The passwords are hashed using SHA-1 and stored in MySQL

The problem I am having is that the output is not consistently the same for the exact same password string. I need to have a hash using SHA1 that will produce the same output so that I can verify it against the hash in the database, to prove that the user has entered the correct password.

Here is my coding for the sha1.

try
        {
            String password = txtPassword.getPassword().toString();

            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(password.getBytes());

            byte byteData[] = md.digest();

            //convert the byte to hex format
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
             sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }

            System.out.println("Hex format : " + sb.toString());


        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(this, e);
        }

Is there a problem with the coding above that will cause it to produce different outputs for the same string.

Upvotes: 1

Views: 1135

Answers (2)

Fernando Mendez
Fernando Mendez

Reputation: 2769

String password = txtPassword.getPassword().toString();

What is the code for this? This is most likely where the issue is, since setting password = "test" will give you the same results repeatedly.

Edit :

Try this : String password = new String(txtPassword.getPassword());

Upvotes: 0

user6139543
user6139543

Reputation:

I have been trying different coding and I have found that the problem was with the obtaining the password from the JPasswordField.

The solution I came to which produced the same hash for the password was one line that I had to edit from String password = txtPassword.getPassword().toString(); to this String password = String.valueOf(txtPassword.getText());

I realized that the problem was with reading it as a string not as a value.

Thanks for responses

Upvotes: 1

Related Questions