Consistant Hashing

Using SHA-256 and Java

Page 1 of 1

1 Replies - 889 Views - Last Post: 09 March 2010 - 08:45 AM Rate Topic: -----

#1 depricated   User is offline

  • Nero


Reputation: 2532
  • View blog
  • Posts: 6,273
  • Joined: 13-September 08

Consistant Hashing

Posted 09 March 2010 - 08:15 AM

I'm currently trying to run the same hashing algorithm in two different languages.

The algorithm produces the same salted password before hashing, whether in PHP or Java. However, after hashing, identical passwords hash differently. Both claim to be using SHA-256.

Let me show you the methods I'm using:
The PHP Method is:

$hashedpw = hash("sha256", $saltedpw);

This returns a String of the hash.

The Java Method is:

called by _password = byteToBase64(getHash(saltedpw));

private byte[] getHash(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();

        return digest.digest(password.getBytes("UTF-8"));
    }
    public String byteToBase64(byte[] data)
    {
       BASE64Encoder endecoder = new BASE64Encoder();
        return endecoder.encode(data);
    }


What they return are drastically different:
On salting and hashing Welcome1234
PHP Returns: 34e385b93c2b87b6c33ecf8e39c2ef30d8d17e9e8e2b3f594b6263ccf308a0d3
Java Returns: NOOFuTwrh7bDPs+OOcLvMNjRfp6OKz9ZS2JjzPMIoNM=

All I can fathom is that the way I'm trying to Hash isn't the same as the PHP Hash method. Does anyone know how I can emulate this in Java?

one clear difference is that the first is hexadecimal and the other isn't.

This post has been edited by depricated: 09 March 2010 - 08:22 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Consistant Hashing

#2 depricated   User is offline

  • Nero


Reputation: 2532
  • View blog
  • Posts: 6,273
  • Joined: 13-September 08

Re: Consistant Hashing

Posted 09 March 2010 - 08:45 AM

yay google

public static String getHexString(byte[] B)/> throws Exception {
  String result = "";
  for (int i=0; i < b.length; i++) {
    result +=
          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
  }
  return result;
}


Now my Java Algorithm gives:
34e385b93c2b87b6c33ecf8e39c2ef30d8d17e9e8e2b3f594b6263ccf308a0d3


Which appears to be identical to my PHP one which gives:
34e385b93c2b87b6c33ecf8e39c2ef30d8d17e9e8e2b3f594b6263ccf308a0d3

Hip hip HOORAY!

Three cheers for http://rgagnon.com/j.../java-0596.html
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1