3

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?

Community
  • 1
  • 1
JuanKman94
  • 112
  • 1
  • 7
  • I didn't even know you can implicitly cast to an integer within a foreach loop in Java. A shame you cannot convert it to a positive integer as well. – Maarten Bodewes Jun 07 '13 at 23:24

2 Answers2

6

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Thanks a lot! I tried first with the String.format... but it gave me a completely different output. So I went with the Guava libraries and I'm impressed with them, I'll be using them a lot. Thanks again! – JuanKman94 Jun 10 '13 at 06:16
1

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.

Marred
  • 11
  • 1