PHP 的散列函数返回的原始输出是否与 pack('H*') 相同?

Is the raw output returned by PHP's hashing functions the same as pack('H*')?

PHP 的各种散列函数,如 md5()sha1()hash()hash_pbkdf2()hash_hmac() 允许您设置 $ raw_output = false 并获取原始二进制数据。

我整理了一个使用 mcrypthash_pbkdf2 加密的 class。创建密钥时,以下两个代码都有效:

// Version 1
private function createKey($salt, $password) {
    // Hash the key
    $key = hash_pbkdf2('sha256', $password, $salt, 5000, 32, true);
    return $key;
}

// Version 2
private function createKey($salt, $password) {
    // Hash the key
    $key = hash_pbkdf2('sha256', $password, $salt, 5000);
    // Pack the key into a binary hex string
    $key = pack('H*', $key);
    return $key;
}

它们都生成相同的密钥大小,但它们都在做同样的事情吗?考虑到我将其用于加密,是否比另一个更安全?

如果你想要原始的二进制结果,你应该使用 hash_pbkdf2$raw_output = true。它将生成您想要的字节,无需任何编码。

hash_pbkdf2 内部使用 bin2hex 将二进制字符串编码为十六进制。这是一个额外的操作。当您随后使用 pack 将十六进制解码为二进制字符串时,您还有另一个不必要的操作。

使用十六进制输出并将其解码回二进制不会提高您的安全性。如果有的话,它可能会减少它,因为密码黑客可能不会使用这些不必要的步骤。

如果您担心 bin2hex 是否真的会反转 pack("H*"),您应该使用 hex2bin,因为它们 companion functions 可能会相互反转。