I needed to calculate the same SHA-512 hashes in Java and PHP. I thought that this would be a quite easy exercise. Unfortunately, it was not, so I decided to publish the code that finally produces the same hashes. First, let us have a look at the PHP code, which is really easy:
$toHash = 'someRandomString'; $hash = hash('sha512', $to_hash);
Easy, isn’t it? 🙂 In Java, it is a bit more complicated:
public String generateHash() { String toHash = "someRandomString"; MessageDigest md = null; byte[] hash = null; try { md = MessageDigest.getInstance("SHA-512"); hash = md.digest(toHash.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return convertToHex(hash); } /** * Converts the given byte[] to a hex string. * @param raw the byte[] to convert * @return the string the given byte[] represents */ private String convertToHex(byte[] raw) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < raw.length; i++) { sb.append(Integer.toString((raw[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); }
This will result in exactly the same SHA-512 hash in Java and in PHP.
If that helps someone, I am happy to read your comment 🙂
Thank you very much, saved me a lot of time 🙂
Heeeey! I spend last 30 minutes messing with this, your convertToHex() made the trick I needed …. Thank you 🙂 !!
Thank you very much!!! 😀
I spent the last 2 weeks trying to get my java hash to match my PHP. The problem was that I was using the wrong PHP function
I was using: crypt()
I should have used: hash()
Thank you so much for posting this.
I don’t know what the difference is?
crypt()
http://php.net/manual/en/function.crypt.php
hash()
http://php.net/manual/en/function.hash.php
crypt
is the older version of producing a hash in PHP. As stated in the documentation, it will use the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.hash
is the newer, more flexible alternative. Here, you can specify which hashing algorithm you want to use. Of course, you have to make sure to use the same hashing algorithm on the PHP- and on the Java-side.Thank you for conversion from bytes to string, it was very helpful 😉
Good job ! you rox!