问题描述
我将一些Java代码移植到PHP代码中。在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();
}
在PHP中,我将哈希表示如下:
$ hash = hash(sha256,utf8_encode($ input));
我使用 input =test 即可。然而,我得到了2个不一样的哈希字符串:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b
有人可以向我解释为什么以及如何让他们相互匹配?请注意,我无法修改Java实现代码,只能修改PHP。
真的很感谢!
PHP版本正确; test 的SHA-256校验和为 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
。
Java版本正在返回与两个 0
s相同的校验和被剥离出来。这是因为你将字节转换为十六进制。用&
来替代 0xFF
,而不是 String.format()
,如所示:
hexStrBuilder.append(String.format(%02x,shaByteArr [i]));
我知道你说你不能修改Java代码,但它是错误的!
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!
The PHP version is correct; the SHA-256 checksum of test is 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
.
The Java version is returning the same checksum with two 0
s 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!
这篇关于在PHP和SHA256中Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!