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.

GoSecurity Boundaries

Code

gosnippet
34 lines
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

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:`.