SHA256 in PHP and Java

I am porting Java code to PHP code. In Java, I have a SHA256 hash as shown 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 have a hash as shown below:

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

I run the sample code as with input = "test" . However, I have two hash lines that do not match:

 Java: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2bb822cd15d6c15b0f0a8 PHP: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 

Can someone explain to me why and how to make them fit together? Please note that I cannot change the Java implementation code, only to modify PHP.

Really appreciate it!

+2
java php hash sha256
source share
2 answers

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

In the Java version, the same checksum is returned with two 0 selected. This is due to the way you convert bytes to hexadecimal. Instead of & using 0xFF use String.format() , as in this answer :

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

I understand, you say that you cannot change the Java code, but it is wrong !

+6
source share

The PHP version is correct. But we can change 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

0
source share

All Articles