HKDF Key Derivation
Derive separate encryption keys from one shared secret with HKDF extract, expand, and label binding instead of reusing raw keys.
Code
package main
import (
"crypto/hkdf"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
// 输入密钥材料:通常来自密钥交换或口令哈希
secret := []byte("shared-secret-from-key-exchange")
salt := []byte("session-2026-11-17")
info := []byte("aes-256-gcm key")
// Extract:把分布不均的 secret 压成固定长度伪随机密钥
prk, err := hkdf.Extract(sha256.New, secret, salt)
if err != nil {
fmt.Println("extract failed:", err)
return
}
fmt.Println("prk bytes:", len(prk))
// Expand:按 info 派生指定长度的子密钥
key, err := hkdf.Expand(sha256.New, prk, info, 32)
if err != nil {
fmt.Println("expand failed:", err)
return
}
fmt.Println("derived key:", hex.EncodeToString(key))
// Key = Extract + Expand,一步完成
key2, err := hkdf.Key(sha256.New, secret, salt, info, 32)
if err != nil {
fmt.Println("derive failed:", err)
return
}
fmt.Println("same key:", hex.EncodeToString(key2) == hex.EncodeToString(key))
// 换 info 得到不同子密钥:同一 PRK 可派生多条用途密钥
nonceKey, err := hkdf.Expand(sha256.New, prk, []byte("nonce key"), 16)
if err != nil {
fmt.Println("expand failed:", err)
return
}
fmt.Println("nonce bytes:", len(nonceKey), "| differs:", hex.EncodeToString(nonceKey) != hex.EncodeToString(key[:16]))
}Inside the snippet
Everything happens inside the function main.
Error handling is inline: 4 places test err != nil and branch immediately.
Using it
The run emits 7 labeled sections — extract failed:, prk bytes:, expand failed:, derived key:, derive failed:, same key:, nonce bytes: — one per step.
The key statements that remain
if err != nil {
fmt.Println("extract failed:", err)
return
}
if err != nil {
fmt.Println("expand failed:", err)
return
}
if err != nil {
fmt.Println("derive failed:", err)
return
}
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.
FAQ
- What does HKDF Key Derivation print when run?
- Invoke the file as-is — the `extract failed:`, `prk bytes:`, `expand failed:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.