Search code examples
phpgocryptographypbkdf2

Why is Php pbkdf2 output is coming out different from golang?


I am trying to figure this out for hours. I have used the same pbkdf2 algorithm in PHP and golang and somehow the output's different.

Golang

saltString := "e7655f410aa38e1ca05de7a7fd8fb84c"
password := "vibhor123"
salt, err := hex.DecodeString(saltString)
if err != nil {
    panic(err)
}
fmt.Println(salt)
fmt.Println(fmt.Sprintf("%x", pbkdf2.Key([]byte(input.Password), salt, 4096, sha256.Size, sha256.New)))

Output

3d70b8536a7b26d67419e220e1c244a1cc9431a3c23999c2f993d8a3a4dda13a

PHP

$salt = "e7655f410aa38e1ca05de7a7fd8fb84c";
$password = "vibhor123";
echo(hash_pbkdf2("sha256", $password, $salt, 4096));

Output

a8595b29ddb1a7819bae7e9d8809f26f053b3877197ed44e05e279459a826c64

According to my understanding both should match.


Solution

  • PHP's hash_pbkdf2's salt must be presented as a binary string, not as a hex string. Simply use hex2bin to convert it to the raw binary. See https://3v4l.org/IIXFM.

    $salt = "e7655f410aa38e1ca05de7a7fd8fb84c";
    $password = "vibhor123";
    echo(hash_pbkdf2("sha256", $password, hex2bin($salt), 4096));
    
    3d70b8536a7b26d67419e220e1c244a1cc9431a3c23999c2f993d8a3a4dda13a