SHA256 in PHP & Java

流过昼夜 提交于 2020-01-01 07:08:08

问题


I'm porting some Java code to PHP code. In Java I have a hash SHA256 code as below:

public static String hashSHA256(String input)
        throws NoSuchAlgorithmException {
    MessageDigest mDigest = MessageDigest.getInstance("SHA-256");

byte[] shaByteArr = mDigest.digest(input.getBytes(Charset.forName("UTF-8")));
    StringBuilder hexStrBuilder = new StringBuilder();
    for (int i = 0; i < shaByteArr.length; i++) {
        hexStrBuilder.append(Integer.toHexString(0xFF & shaByteArr[i]));
    }

    return hexStrBuilder.toString();
}

In PHP, I hash as below:

$hash = hash("sha256", utf8_encode($input));

I run the sample code with both input = "test". However, I got 2 hash strings which are not the same:

Java: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2bb822cd15d6c15b0f0a8
PHP: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Can someone explain to me why and how to get them match each other? Please note that I cannot modify the Java implementation code, only to modify PHP.

Really appreciate!


回答1:


The PHP version is correct; the SHA-256 checksum of test is 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.

The Java version is returning the same checksum with two 0s stripped out. This is because of the way you're converting bytes into hex. Instead of &ing them with 0xFF, use String.format(), as in this answer:

hexStrBuilder.append(String.format("%02x", shaByteArr[i]));

I realise you say you cannot modify the Java code, but it is incorrect!




回答2:


The PHP version is correct. But we can modify the result to have the same result with java code.

function hash256($input) {
    $hash = hash("sha256", utf8_encode($input));
    $output = "";
    foreach(str_split($hash, 2) as $key => $value) {
        if (strpos($value, "0") === 0) {
            $output .= str_replace("0", "", $value);
        } else {
            $output .= $value;
        }
    }
    return $output;
}

echo hash256("test");

result: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2bb822cd15d6c15b0f0a8



来源:https://stackoverflow.com/questions/23066005/sha256-in-php-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!