Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SHA512 digest output differs from PHP script

Tags:

java

php

sha512

Can someone figure out why the output of these (php and java) snippets of code don't return the same SHA512 for the same input?

$password = 'whateverpassword';
$salt = 'ieerskzcjy20ec8wkgsk4cc8kuwgs8g';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
echo "digest: ".base64_encode($digest);
for ($i = 1; $i < 5000; $i++) {
  $digest = hash('sha512', $digest.$salted, true);
}
$encoded_pass = base64_encode($digest);
echo $encoded_pass;

This is the code on the android application:

public String processSHA512(String pw, String salt, int rounds)
{
    try {
        md = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException("No Such Algorithm");
    }

    String result = hashPw(pw, salt, rounds);
    System.out.println(result);
    return result;
}

private static String hashPw(String pw, String salt, int rounds) {
    byte[] bSalt;
    byte[] bPw;

    String appendedSalt = new StringBuilder().append('{').append(salt).append('}').toString();

    try {
        bSalt = appendedSalt.getBytes("ISO-8859-1");
        bPw = pw.getBytes("ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Unsupported Encoding", e);
    }

    byte[] digest = run(bPw, bSalt);
    Log.d(LCAT, "first hash: " + Base64.encodeBytes(digest));
    for (int i = 1; i < rounds; i++) {
        digest = run(digest, bSalt);
    }

    return Base64.encodeBytes(digest);
}

private static byte[] run(byte[] input, byte[] salt) {
    md.update(input);
    return md.digest(salt);
}

The library for base64 encoding is this: base64lib

This java code is actually some modified code I found around another question in StackOverflow. Although the Android code is running fine it doesn't match with the output from the php script. It doesn't even match the first hash!

Note 1: On php hash('sha512',$input, $raw_output) returns raw binary output

Note 2: On java I tried to change the charset (UTF-8, ASCII) but it also didn't work.

Note 3: The code from the server can not be changed, so I would appreciate any answer regarding how to change my android code.

like image 462
Joscandreu Avatar asked Jun 15 '26 23:06

Joscandreu


1 Answers

The first hash should be the same on the server and in Java. But then in the loop what gets appended to the digest is password{salt} in the PHP code, but only {salt} in the Java code.

like image 199
Henry Avatar answered Jun 18 '26 11:06

Henry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!