PBKDF2 Derive Key Iterations
Derive a key with crypto/pbkdf2, confirm the same inputs reproduce it, and see how a different salt changes the whole output.
Code
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]))
}What runs when
The working surface is the function main — everything else is wiring.
Error handling is inline: 1 place test err != nil and branch immediately.
Watch out for
- The dependency list is empty; the language runtime covers it all.
Applying it
The signature holding the logic: func main()
Output lines are prefixed (derive failed:, key bytes:, hex prefix:), so each printed result can be traced to its step.
Statements that matter
if err != nil {
fmt.Println("derive failed:", err)
return
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- What does PBKDF2 Derive Key Iterations print when run?
- Running the file directly is enough — expect labeled output lines such as `derive failed:`, `key bytes:`, `hex prefix:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.