实现说明
PBKDF2 派生密钥与迭代次数的核心是函数 main。
错误处理是内联的:1 处测试 err != nil 并立即分支。
使用要点
- 每一步打印都带着自己的标签:
derive failed:、key bytes:、hex prefix:。
常见问题
运行「PBKDF2 派生密钥与迭代次数」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 derive failed:、key bytes:、hex prefix: 这类标签。
核心语句
if err != nil {
fmt.Println("derive failed:", err)
return
}
代码示例
package main
import (
"crypto/pbkdf2"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
password := "correct horse battery staple"
salt := []byte("demo-salt-2026")
// PBKDF2 stretches a password with many hash iterations
key, err := pbkdf2.Key(sha256.New, password, salt, 120_000, 32)
if err != nil {
fmt.Println("derive failed:", err)
return
}
fmt.Println("key bytes:", len(key))
fmt.Println("hex prefix:", hex.EncodeToString(key[:8]))
// the same inputs always reproduce the same key
again, _ := pbkdf2.Key(sha256.New, password, salt, 120_000, 32)
fmt.Println("deterministic:", hex.EncodeToString(again) == hex.EncodeToString(key))
// a different salt produces an unrelated key
other, _ := pbkdf2.Key(sha256.New, password, []byte("another-salt"), 120_000, 32)
fmt.Println("salt changes key:", hex.EncodeToString(other) != hex.EncodeToString(key))
// a shorter key length is a prefix of a longer derivation
short, _ := pbkdf2.Key(sha256.New, password, salt, 120_000, 16)
fmt.Println("prefix match:", hex.EncodeToString(short) == hex.EncodeToString(key[:16]))
}