JuanKman94
JuanKman94

Reputation: 112

MySQL SHA256 and Java MessageDigest SHA-256 don't match

I've been trying to encrypt some user passwords on a project but I can't seem to get it working properly. I've decided to use the SHA-256 algorithm and when I introduce a password to MySQL using the Sha2(Example,256) It adds two zeros to the crypted password. In Java I used this to hash the text on the program but can't get the equal result.

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest("ContrasenhaPassword".getBytes("UTF-8"));

        StringBuilder hexString = new StringBuilder();
        for (int i: hash) {
            hexString.append(Integer.toHexString(0XFF & i));
        }
        String Hashed = new String(hexString);
        System.out.println(hexString);
        System.out.println(Hashed);
        // Below, MySQL Output for SHA2('ContrasenhaPassword',256)
        System.out.println("d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78");
        System.out.println(Hashed.equals(hexString));
        } catch (Exception e) {
        e.printStackTrace();
        }

The output I get is:

        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c87e1a428274de048f49d78
        d17bf0da90f56b8fc627bac6523ffd284aa0d82c870e1a0428274de048f49d78
        false 
        BUILD SUCCESSFUL (total time: 0 seconds)

Any ideas?

Upvotes: 3

Views: 3278

Answers (2)

Marred
Marred

Reputation: 11

Can't you add the missing zero

for (int i: hash) 
{
    if(Integer.toHexString(0xFF & i).length() == 2)
        hexString.append(Integer.toHexString(0xFF & i));
    else
        hexString.append ( 0x00 + Integer.toHexString(0xFF & i));
}

It seems OK to me.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198461

The difference is in how you're printing them out:

for (int i: hash) {
  hexString.append(Integer.toHexString(0XFF & i));
}

leaves off leading zeroes, so there's one byte formatted as "e" instead of "0e". Probably the simplest alternative would be

for (int i: hash) {
  hexString.append(String.format("%02x", i));
}

Alternately, if you can use Guava, the whole thing can be done much more simply with

Hashing.sha256().hashString("ContrasenhaPassword", Charsets.UTF_8).toString()

which gives you the (properly formatted) hex-encoded SHA-256 hash in a single line.

Upvotes: 6

Related Questions