[英]PHP sha256 hash different than Java Guava one
我正在嘗試使用 PHP 驗證通過 Java Guava Hashing class 生成的 sha256 哈希,但似乎無法做到。 我無法觸摸 Java 文件,因此必須在 PHP 端進行修復。 PHP 和 Java 都使用 UTF-8 編碼。 我錯過了什么?
Java:
package org.test.hash;
import com.google.common.hash.Hashing;
public class Main {
public static void main(String[] args) throws Exception
{
String salt = "0123456789012345";
String password = "password";
System.out.println(
Hashing.sha256().hashUnencodedChars(salt + "|" + password).toString()
);
}
}
Output:
818112d34d341ace8b9325fce61e676a125f733e25c28c9ed172c1f7d2c3aa6c
PHP:
$salt = "0123456789012345";
$password = "password";
print_r(hash("sha256", $salt . "|" . $password));
Output:
1f0a70940ae365e930c51e3de4c0a82f853f7663fc17acd36406982666685703
這是字符串編碼的差異,用 Python 檢查以下內容:
>>> from hashlib import sha256
>>> string = "0123456789012345|password"
>>> sha256(string.encode("utf-8")).hexdigest()
'1f0a70940ae365e930c51e3de4c0a82f853f7663fc17acd36406982666685703'
>>> sha256(string.encode("utf-16-le")).hexdigest()
'818112d34d341ace8b9325fce61e676a125f733e25c28c9ed172c1f7d2c3aa6c'
>>> string.encode("utf-8").hex()
'303132333435363738393031323334357c70617373776f7264'
>>> string.encode("utf-16-le").hex()
'30003100320033003400350036003700380039003000310032003300340035007c00700061007300730077006f0072006400'
感謝評論中的建議,我想通了。 Java 端(使用hashUnencodedChars
而不是hashString
)上的錯誤實現似乎導致從源編碼(在我的情況下為 UTF-8)轉換為 UTF-16LE。 這是在 PHP 端解決此問題的方法:
$salt = "0123456789012345";
$password = "password";
$salted = mb_convert_encoding($salt . "|" . $password, "UTF-16LE", "UTF-8")
print_r(hash("sha256", $salted));
Output:
818112d34d341ace8b9325fce61e676a125f733e25c28c9ed172c1f7d2c3aa6c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.