Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding comparing MD5 hash

Tags:

java

security

I am no security expert and happen not to give it much thought since most of my app run on local intranet so who cares about security? :)

But actually, I am trying to make it right.

I have setup JDBC realm on glassfish and I am saving my password now with MD5 hashing using this code from the internet.

public static String getMD5(String input) 
{
    try
    {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(input.getBytes());

      byte byteData[] = md.digest();

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

Now my question is, during change password use case... is it just comparing if the hash are equal to validate if the password entered is the same from what is in my DB like this code below?

public static void main(String[] args)
throws NoSuchAlgorithmException
{
String currentPassword = "java";
String inputValue = "java1";

String string1 = getMD5(currentPassword);
String string2 = getMD5(inputValue);

System.out.println("Is equal = " + string1.equals(string2));
}

I have read somewhere that MD5 is a one way hashing so I cannot decrypt back the password to string?

Sorry, if my question is too simple but I'd just like to confirm my understanding?

Thanks

like image 640
Mark Estrada Avatar asked May 15 '26 22:05

Mark Estrada


1 Answers

The same password will always hash to the same value, so you can do the check you are talking about. Also, in general a hash function cannot be reversed. That is, given a hash of some password, you cannot deduce the password given the hash. However MD5 has been broken, so you should use some other hash function instead (like SHA-256). It's also worth noting that to really do this securely, you should salt the passwords before your hash them to prevent rainbow-table attacks.

like image 174
Oleksi Avatar answered May 18 '26 10:05

Oleksi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!