[英]SHA256 in PHP & Java
I'm porting some Java code to PHP code. 我正在将一些Java代码移植到PHP代码中。 In Java I have a hash SHA256 code as below:
在Java中,我有一个哈希SHA256代码,如下所示:
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: 在PHP中,我哈希如下:
$hash = hash("sha256", utf8_encode($input));
I run the sample code with both input = "test" . 我用input =“test”运行示例代码。 However, I got 2 hash strings which are not the same:
但是,我得到了2个不同的哈希字符串:
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.
请注意,我无法修改Java实现代码,只能修改PHP。
Really appreciate! 万分感激!
The PHP version is correct; PHP版本是正确的; the SHA-256 checksum of test is
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
. 测试的SHA-256校验和是
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
。
The Java version is returning the same checksum with two 0
s stripped out. Java版本返回相同的校验和,其中两个
0
被剥离。 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 : 而不是
&
与荷兰国际集团他们0xFF
,使用String.format()
在这个答案 :
hexStrBuilder.append(String.format("%02x", shaByteArr[i]));
I realise you say you cannot modify the Java code, but it is incorrect ! 我意识到你说你不能修改Java代码,但它是不正确的 !
The PHP version is correct. PHP版本是正确的。 But we can modify the result to have the same result with java code.
但是我们可以修改结果以使用java代码获得相同的结果。
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 结果:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2bb822cd15d6c15b0f0a8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.