大网数据广告活动
PHP 语言与运行手册

hash_hkdf · Generate a HKDF key derivation of a supplied key input

· 52CE 我爱测

hash_hkdf — Generate a HKDF key derivation of a supplied key input

hash_hkdf

(PHP 7 >= 7.1.2, PHP 8)

hash_hkdf — Generate a HKDF key derivation of a supplied key input

说明

function hash_hkdf(
    string $algo,
    #[\SensitiveParameter] string $key,
    int $length = 0,
    string $info = "",
    string $salt = ""
): string

参数

algo

Name of selected hashing algorithm (e.g. "sha256"). For a list of supported algorithms see hash_hmac_algos().

注意:

Non-cryptographic hash functions are not allowed.

key

Input keying material (raw binary). Cannot be empty.

length

Desired output length in bytes. Cannot be greater than 255 times the chosen hash function size.

If length is 0, the output length will default to the chosen hash function size.

info

Application/context-specific info string.

salt

Salt to use during derivation.

While optional, adding random salt significantly improves the strength of HKDF.

返回值

Returns a string containing a raw binary representation of the derived key (also known as output keying material - OKM).

错误/异常

Throws a ValueError exception if key is empty, algo is unknown/non-cryptographic, length is less than 0 or too large (greater than 255 times the size of the hash function).

更新日志

版本 说明
8.0.0 Now throws a ValueError exception on error. Previously, false was returned and an E_WARNING message was emitted.

示例

The example below produces a pair of separate keys, suitable for creation of an encrypt-then-HMAC construct, using AES-256 and SHA-256 for encryption and authentication respectively.

示例 #1 hash_hkdf() example

<?php
// Generate a random key, and salt to strengthen it during derivation.
$inputKey = random_bytes(32);
$salt = random_bytes(16);

// Derive a pair of separate keys, using the same input created above.
$encryptionKey = hash_hkdf('sha256', $inputKey, 32, 'aes-256-encryption', $salt);
$authenticationKey = hash_hkdf('sha256', $inputKey, 32, 'sha-256-authentication', $salt);

var_dump($encryptionKey !== $authenticationKey); // bool(true)
?>

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。