Producing The Same SHA-512 Hash In Java And PHP

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 🙂

7 Gedanken zu „Producing The Same SHA-512 Hash In Java And PHP“

    1. 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.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert