Hashing & Crypto: SHA-256/512, bcrypt, Argon2, crypto/rand
"The Read function is now guaranteed not to fail. It will always return nil as the error result." — Go 1.24 release notes,
crypto/rand
Summary: Go's crypto/* packages give you hashes, MACs, password hashes, key derivation, random bytes, authenticated encryption, signatures and key agreement with small, hard-to-misuse APIs; the work is choosing the right primitive and the right parameters, not calling it. Focus: hash.Hash and streaming, SHA-2/SHA-3/BLAKE2, hash/fnv, hash/crc32, hash/maphash, crypto/hmac, hmac.Equal, crypto/subtle, bcrypt, argon2.IDKey, scrypt, crypto/pbkdf2, rehash on login, crypto/hkdf, crypto/rand, AES-GCM, XChaCha20-Poly1305, Ed25519, ECDSA P-256, RSA OAEP/PSS, crypto/ecdh, PEM/PKCS#8, FIPS 140-3 mode. Learning goal: Pick the right primitive for a job, call it correctly in Go (with tests that prove it), and recognise the classic mistakes: == on a MAC, a reused nonce, math/rand for a token, a bcrypt hash that silently ignores bytes past 72.
This page is the Go API walkthrough. The theory lives in three foundations chapters, and this page does not repeat it: what a hash is and why collisions matter is in Checksums & Hashing; the maths and modes behind AES-GCM, RSA, ECC and KDFs are in Cryptography Fundamentals; password storage policy, salts, peppers and signed tokens are in Password Hashing & Signed Tokens. The login flow built on top of these primitives (sessions, JWT, CSRF, password reset) is Authentication in Go, TLS and mTLS are HTTP/2, HTTPS, TLS & mTLS in Go, and the system-level view (key management, envelope encryption) is Cryptography in Practice. The Go code below is tested and lives once under docs/snippets/go/hashing-crypto/go/, so both language versions of this page import the same files.
Page map
| If you are looking for | Go to |
|---|---|
| One table per job, memorisable | Everything in one minute |
| Why the standard library looks the way it does | Why it exists |
| Go 1.24 changes, FIPS, x/crypto split | Where it comes from |
hash.Hash, io.Copy into sha256.New() | hash.Hash and streaming |
| SHA-256, SHA-512/256, SHA-3, BLAKE2 | SHA-2, SHA-3 and BLAKE2 |
hash/fnv, hash/crc32, hash/maphash | Non-cryptographic hashes |
hmac.Equal, subtle.ConstantTimeCompare, timing attacks | HMAC and constant-time comparison |
bcrypt cost, the 72-byte limit, argon2.IDKey, scrypt, PBKDF2 | Password hashing |
| Upgrading old hashes without a reset campaign | Rehash on login |
crypto/hkdf, one secret to many keys | Key derivation with HKDF |
rand.Read, rand.Text, rand.Int, secure tokens | crypto/rand and secure tokens |
cipher.NewGCM, AEAD.Seal/Open, ChaCha20-Poly1305 | Authenticated encryption |
| Why a repeated nonce destroys GCM | Nonce reuse and ECB |
ed25519, ecdsa P-256, RSA PSS | Signatures |
RSA OAEP and crypto/ecdh | Public-key encryption and key agreement |
PEM, PKCS#8, x509.MarshalPKCS8PrivateKey | Encoding keys |
GOFIPS140, GODEBUG=fips140=on | FIPS 140-3 mode |
| MD5, SHA-1, DSA, RC4, DES, CFB/OFB | Deprecated and dangerous |
| Exact error texts | Error texts decoded |
| The tested snippets, step by step | Solving the classic problems |
PHP password_hash, hash_hmac, sodium, openssl | For PHP/Laravel developers |
| Which primitive for which job | Choosing |
| Keys, rotation and services | In architecture |
| Run it on your machine | Lab |
Everything in one minute
| Job | Go call | Parameter that matters | Never |
|---|---|---|---|
| Fingerprint a file or blob | io.Copy(sha256.New(), f) then Sum(nil) | SHA-256 or SHA-512/256 | Read the whole file into memory first |
| Prove a message came from a key holder | hmac.New(sha256.New, key), compare with hmac.Equal | Key of 32 random bytes | == or bytes.Equal on tags |
| Store a password | argon2.IDKey (or bcrypt for legacy) | Argon2id 64 MiB, t=3, p=4 (RFC 9106 second option) | Plain SHA-256 or MD5 of a password |
| Derive keys from a master secret | hkdf.Key(sha256.New, secret, salt, info, n) | A distinct info per purpose | Reuse one key for encryption and MAC |
| Make a token, nonce, salt or key | rand.Read(b) or rand.Text() | 32 bytes for a token | math/rand for anything secret |
| Encrypt data | cipher.NewGCM or chacha20poly1305.NewX | Fresh nonce per message | ECB, CBC without a MAC, a reused nonce |
| Sign for others to verify | ed25519.Sign | Verify with ed25519.Verify | Verify with only a length check |
| Agree on a shared key | ecdh.X25519() then HKDF | Use the output as HKDF input | Use the raw ECDH bytes as a key |
| Satisfy a FIPS 140-3 requirement | GOFIPS140=v1.0.0 go build | Module version | Set GODEBUG=fips140=only in production |
| Hash family | Output | Package | When |
|---|---|---|---|
| SHA-256 | 32 bytes | crypto/sha256 | Default digest for integrity and content addressing |
| SHA-512 | 64 bytes | crypto/sha512 | 64-bit CPUs, bigger margin |
| SHA-512/256 | 32 bytes | sha512.Sum512_256 | SHA-256 size without length-extension |
| SHA-3-256 | 32 bytes | crypto/sha3 (Go 1.24) | Different design, SHAKE outputs |
| BLAKE2b-256 | 32 bytes | golang.org/x/crypto/blake2b | Fast, keyed mode built in |
| CRC-32C | 4 bytes | hash/crc32 | Corruption detection, not security |
| FNV-1a 64 | 8 bytes | hash/fnv | Simple hash tables, not security |
| maphash | 8 bytes | hash/maphash | In-process hash tables, seed per process |
Why it exists
Cryptography fails in the details. The standard library therefore does three things: it offers few algorithms, it hides the dangerous parameters behind constructors that choose safely, and it makes the safe path the short one (io.Copy into a hash, hmac.Equal, rand.Read that cannot fail, cipher.NewGCM that fixes the nonce size).
| Design choice | Weaker alternative | What Go does |
|---|---|---|
| One interface for all hashes | A function per algorithm | hash.Hash is an io.Writer: stream anything into it |
| Authenticated encryption as the default | Block cipher modes you assemble | cipher.AEAD: Seal and Open, one error for any tampering |
| Constant-time compare in the library | Developer remembers to avoid == | hmac.Equal, subtle.ConstantTimeCompare |
| Random source in one place | rand.Seed(time) | crypto/rand uses the OS CSPRNG; Read cannot fail since 1.24 |
| Experimental algorithms outside the stdlib | Everything in crypto/* | golang.org/x/crypto holds bcrypt, argon2, scrypt, chacha20poly1305, blake2b |
The picture to keep in mind is a bank vault with a window. A hash is the window: anyone can look at the fingerprint, nobody can reconstruct the contents. An HMAC is a stamp only key holders can make. Encryption is the vault door; the AEAD tag is the seal that shows nobody opened it.
Three common misunderstandings, up front
- "SHA-256 is fine for passwords because it is a strong hash." It is a fast hash. A GPU computes billions per second, so a stolen table of
sha256(password)falls to a dictionary in minutes. Passwords need a deliberately slow, memory-hard function: Argon2id, scrypt or bcrypt. - "Encryption means the data cannot be changed." Plain AES-CBC or CTR hides content but an attacker can flip bits. Only an authenticated mode (GCM, ChaCha20-Poly1305) detects modification. In Go, use
cipher.AEADand nothing else. - "A random-looking string from
math/randis a token."math/rand(andmath/rand/v2) are pseudo-random generators "suitable for tasks such as simulation, but it should not be used for security-sensitive work" (Go documentation). Tokens, salts, nonces and keys come fromcrypto/rand.
Where it comes from
Go shipped crypto/md5, crypto/sha1, crypto/sha256, crypto/aes, crypto/rsa and crypto/tls from its first release, written by the Go team in Go (no OpenSSL dependency, which is why CGO_ENABLED=0 binaries can still speak TLS). Newer or faster-moving algorithms went into golang.org/x/crypto, a separately versioned module: bcrypt, argon2, scrypt, chacha20poly1305, blake2b, sha3, hkdf, pbkdf2, nacl.
The Go 1.24 release (February 2025) promoted three of them: "The new crypto/hkdf package implements the HMAC-based Extract-and-Expand key derivation function HKDF, as defined in RFC 5869. The new crypto/pbkdf2 package implements the password-based key derivation function PBKDF2, as defined in RFC 8018. The new crypto/sha3 package implements the SHA-3 hash function and SHAKE and cSHAKE extendable-output functions, as defined in FIPS 202." The same release made rand.Read infallible, added rand.Text, added cipher.NewGCMWithRandomNonce, deprecated NewOFB, NewCFBEncrypter and NewCFBDecrypter, made rsa.GenerateKey refuse keys under 1024 bits, and introduced the Go Cryptographic Module for FIPS 140-3: "The new GOFIPS140 environment variable can be used to select the Go Cryptographic Module version to use in a build. The new fips140 GODEBUG setting can be used to enable FIPS 140-3 mode at runtime."
bcrypt is Provos and Mazières (1999); Argon2 won the Password Hashing Competition in 2015 and is specified in RFC 9106 (2021); HMAC is RFC 2104; HKDF is RFC 5869; ChaCha20-Poly1305 is RFC 8439; Ed25519 is RFC 8032; GCM is NIST SP 800-38D. Later releases kept the direction: Go 1.25 added ecdsa.ParseRawPrivateKey and sha3.SHA3.Clone, and Go 1.26 made the random parameter of ecdsa.GenerateKey, rsa.GenerateKey and similar functions ignored (a secure source is always used) and added crypto/hpke. The code on this page compiles with go 1.24.0 (the directive x/crypto v0.45.0 requires); package documentation was read in Go 1.27 for newer additions and in the Go 1.24 release notes for the version gates.
The concept catalogue
Every block has the same shape: plain words, the usual wrong belief, a definition, a timeline, real scenarios, per-primitive differences, and the fix with tested Go code (more code in Solving the classic problems).
hash.Hash and streaming Must-know
In plain words: every hash in the standard library is an object you write bytes into and later ask for the digest. You can feed it a file in 32 KiB pieces and get the same answer as hashing the whole file at once.
Common misunderstanding: "I need to read the file into a []byte to hash it." You do not, and for a 4 GiB upload you must not. Another one: sha256.Sum256 returns a slice. It returns a [32]byte array, so you slice it (sum[:]) before encoding.
Definition: hash.Hash embeds io.Writer ("It never returns an error") and adds Sum(b []byte) []byte (appends the digest and "does not change the underlying hash state"), Reset(), Size() and BlockSize(). Sum256, Sum512 and friends are one-shot helpers for data already in memory.
1 h := sha256.New() // state: initial vector
2 io.Copy(h, file) // Write called per buffer, state absorbs bytes
3 h.Sum(nil) // digest appended to nil; state unchanged
4 h.Write(more) // may continue after Sum
5 h.Reset() // back to the initial vector, reuse the objectReal scenario: an upload handler hashes the body while saving it with io.TeeReader(r.Body, h), so the ETag costs no second pass; a build tool verifies a downloaded binary against a published SHA-256; a content-addressed store names blobs by digest.
| Question | Answer |
|---|---|
Is a hash.Hash safe for concurrent use? | No: one goroutine per instance; create one per call |
Can I read Sum twice? | Yes, it does not change the state |
| Does the digest depend on write chunking? | No: Write("ab"); Write("c") equals Write("abc") |
| How do I save and resume a hash? | Standard hashes implement encoding.BinaryMarshaler |
Fix: stream, then encode once.
// Package digest shows the hash.Hash interface, streaming and the hash families.
package digest
import (
"crypto/sha256"
"crypto/sha3"
"crypto/sha512"
"encoding/hex"
"hash"
"hash/crc32"
"hash/fnv"
"hash/maphash"
"io"
"golang.org/x/crypto/blake2b"
)
// Reader hashes everything r yields without holding it in memory.
// hash.Hash is an io.Writer, so io.Copy streams straight into it.
func Reader(h hash.Hash, r io.Reader) (string, error) {
if _, err := io.Copy(h, r); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// SHA256Hex is the one-shot form for small inputs that already fit in memory.
func SHA256Hex(data []byte) string {
sum := sha256.Sum256(data) // [32]byte, a value, not a slice
return hex.EncodeToString(sum[:])
}
// Family returns the same message under several algorithms.
func Family(msg []byte) map[string]string {
b2, _ := blake2b.New256(nil) // nil key: plain hash; a key makes it a MAC
b2.Write(msg)
s3 := sha3.Sum256(msg)
s512 := sha512.Sum512(msg)
s512t256 := sha512.Sum512_256(msg) // SHA-512/256: not a truncation of SHA-512 output
return map[string]string{
"sha256": SHA256Hex(msg),
"sha512": hex.EncodeToString(s512[:]),
"sha512/256": hex.EncodeToString(s512t256[:]),
"sha3-256": hex.EncodeToString(s3[:]),
"blake2b256": hex.EncodeToString(b2.Sum(nil)),
}
}
// NonCrypto returns the three non-cryptographic hashes. None of them resists
// an attacker: use them for tables, shards and corruption checks only.
func NonCrypto(msg []byte, seed maphash.Seed) (fnv64a uint64, crc uint32, mh uint64) {
f := fnv.New64a()
f.Write(msg)
crc = crc32.Checksum(msg, crc32.MakeTable(crc32.Castagnoli))
mh = maphash.Bytes(seed, msg)
return f.Sum64(), crc, mh
}SHA-2, SHA-3 and BLAKE2 Must-know
In plain words: pick SHA-256 unless you have a reason not to. The others differ in speed, output size and resistance to one specific trick called length extension.
Common misunderstanding: "SHA-512/256 is SHA-512 cut to 256 bits." It uses different initial values, so its output is not a prefix of SHA-512's; the unit test checks that. Another one: "SHA-3 replaced SHA-2 because SHA-2 is broken." It was standardised (FIPS 202) as a structurally different backup; SHA-2 remains unbroken.
Definition: SHA-256 and SHA-512 are Merkle-Damgård hashes, so given H(m) and the length of m an attacker can compute H(m || padding || x) without knowing m. SHA-512/256 (a truncated variant with its own IVs), SHA-3 (sponge) and BLAKE2 are not vulnerable. HMAC is also immune, which is why you use HMAC, not H(key || msg), to authenticate.
1 attacker sees tag = SHA256(secret || "amount=10")
2 attacker computes SHA256(secret || "amount=10" || pad || "&amount=9999") // no secret needed
3 server checks SHA256(secret || message) -> equal: forged message accepted
4 with HMAC-SHA256 the same trick fails: the outer hash hides the inner stateReal scenario: content-addressed storage (container image layers are named by SHA-256 digests); go.sum records h1: hashes built from SHA-256; BLAKE2b for fast keyed hashing in a database engine; SHAKE256 for deriving an arbitrary number of bytes.
| Hash | Go API | Size | Length-extension safe | FIPS 140-3 approved |
|---|---|---|---|---|
| SHA-256 | sha256.New, sha256.Sum256 | 32 | No (use HMAC) | Yes |
| SHA-512 | sha512.New, sha512.Sum512 | 64 | No (use HMAC) | Yes |
| SHA-512/256 | sha512.New512_256, Sum512_256 | 32 | Yes | Yes |
| SHA-3-256 | sha3.New256, sha3.Sum256 | 32 | Yes | Yes |
| SHAKE256 | sha3.NewSHAKE256, SumSHAKE256(data, n) | any | Yes | Yes |
| BLAKE2b-256 | blake2b.New256(key) | 32 | Yes | No |
| MD5, SHA-1 | crypto/md5, crypto/sha1 | 16, 20 | n/a | Not for signatures |
Fix: digest.Family computes five digests of one message; TestKnownVectors checks SHA-256("abc") and SHA3-256("abc") against the published test vectors.
Non-cryptographic hashes Good to know
In plain words: some hashes are only meant to spread keys evenly or catch accidental bit flips. They are much faster and offer no protection against someone trying.
Common misunderstanding: "CRC-32 detects tampering." CRC is linear: an attacker can change the message and fix the checksum. It detects random corruption only. hash/maphash is not stable across processes: its seed is random, so never store its output.
Definition: hash/fnv (FNV-1 and FNV-1a, 32/64/128 bits) is a tiny multiply-xor hash; hash/crc32 supports the IEEE and Castagnoli (CRC-32C) polynomials with hardware acceleration; hash/maphash hashes []byte, strings and comparable values with a per-process random Seed, resistant to hash-flooding attacks on hash tables.
1 seed := maphash.MakeSeed() // random per call
2 maphash.Bytes(seed, key) % shards // stable within this process
3 restart the process // new seed, different shard: fine for a cache, wrong for persisted dataReal scenario: choosing a shard for an in-memory sharded map (maphash); detecting a truncated segment in a write-ahead log (crc32 Castagnoli, the same polynomial used by iSCSI and many storage engines); deterministic bucketing of a user ID for an experiment (fnv, because it must be stable across deploys).
| Hash | Stable across runs | Fast | Attack-resistant | Use for |
|---|---|---|---|---|
hash/fnv | Yes | Yes | No | Stable bucketing of trusted keys |
hash/crc32 | Yes | Hardware speed | No | Corruption checks, framing |
hash/maphash | No (random seed) | Yes | Against flooding only | In-process maps and sketches |
crypto/sha256 | Yes | Slower | Yes | Anything adversarial |
HMAC and constant-time comparison Must-know
In plain words: an HMAC is a hash that needs a secret key. If you receive a message and a correct tag, only someone with the key could have produced it. Comparing tags must not leak how many leading bytes matched.
Common misunderstanding: "Comparing two hex strings with == is fine because the tag is random." The comparison stops at the first different byte, so the time taken reveals the length of the matching prefix. A remote attacker who can measure responses guesses a valid tag one byte at a time (a timing attack). The same applies to API keys and reset tokens.
Definition: hmac.New(sha256.New, key) returns a hash.Hash implementing RFC 2104. hmac.Equal(a, b) compares "without leaking timing information". subtle.ConstantTimeCompare(x, y) returns 1 for equal contents, 0 otherwise, in time that depends only on the lengths, and returns 0 at once if the lengths differ.
1 attacker sends tag 00 00 00 ... -> server compares: first byte wrong, rejects in 12 ns
2 attacker sends tag a7 00 00 ... -> first byte right: rejects in 14 ns (slower!)
3 repeat for each byte position -> 256 * 32 = 8192 guesses instead of 2^256
4 hmac.Equal always walks every byte -> every wrong tag costs the sameReal scenario: verifying a webhook signature (X-Signature header), checking a signed download URL, comparing an API key hash, validating a CSRF token. Pass []byte, not strings, and compare digests of equal length.
| Comparison | Constant time | Notes |
|---|---|---|
a == b on strings | No | Early exit |
bytes.Equal(a, b) | No | Early exit |
hmac.Equal(a, b) | Yes | For MACs; the standard-library choice |
subtle.ConstantTimeCompare(a, b) == 1 | Yes (given equal lengths) | Hash both sides first if the length is secret |
bcrypt.CompareHashAndPassword | Yes inside | Do not re-compare its result |
Fix: the snippet includes a signed-URL helper (path plus expiry, base64url tag), the RFC 4231 test case 2, and tamper and expiry tests.
// Package mac signs and verifies messages with HMAC and compares in constant time.
package mac
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"strconv"
"strings"
"time"
)
// Sign returns an HMAC-SHA-256 tag.
func Sign(key, msg []byte) []byte {
m := hmac.New(sha256.New, key)
m.Write(msg)
return m.Sum(nil)
}
// Valid compares tags with hmac.Equal, which is constant time.
// Never use bytes.Equal or == on a MAC: they return at the first different byte.
func Valid(key, msg, tag []byte) bool {
return hmac.Equal(Sign(key, msg), tag)
}
// SameSecret compares two equal-purpose secrets (API keys, tokens) in constant
// time. ConstantTimeCompare returns 0 at once if the lengths differ, so hash
// both sides first if the length itself is secret.
func SameSecret(a, b []byte) bool {
ha, hb := sha256.Sum256(a), sha256.Sum256(b)
return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1
}
// SignURL builds "path?expires=<unix>&sig=<base64url>" for a signed link.
func SignURL(key []byte, path string, expires time.Time) string {
exp := strconv.FormatInt(expires.Unix(), 10)
tag := Sign(key, []byte(path+"\n"+exp))
return path + "?expires=" + exp + "&sig=" + base64.RawURLEncoding.EncodeToString(tag)
}
var ErrBadLink = errors.New("mac: link is invalid or expired")
// VerifyURL checks the tag first and the expiry second, both in one error.
func VerifyURL(key []byte, link string, now time.Time) error {
path, q, ok := strings.Cut(link, "?expires=")
if !ok {
return ErrBadLink
}
exp, sigPart, ok := strings.Cut(q, "&sig=")
if !ok {
return ErrBadLink
}
tag, err := base64.RawURLEncoding.DecodeString(sigPart)
if err != nil || !Valid(key, []byte(path+"\n"+exp), tag) {
return ErrBadLink
}
unix, err := strconv.ParseInt(exp, 10, 64)
if err != nil || now.Unix() > unix {
return ErrBadLink
}
return nil
}Password hashing: bcrypt, Argon2id, scrypt, PBKDF2 Must-know
In plain words: a password hash is a function made slow on purpose, with a random salt, so that guessing a billion passwords costs real money. It is the one place in programming where "faster" is a bug.
Common misunderstanding: "bcrypt with a long passphrase is safe at any length." bcrypt reads only the first 72 bytes. golang.org/x/crypto/bcrypt refuses longer input with bcrypt: password length exceeds 72 bytes rather than truncating silently, but other bcrypt implementations ignore the tail, so there two long passwords sharing their first 72 bytes are the same password. Another one: "a pepper or a salt makes SHA-256 enough". It does not; speed is the problem.
Definition: Argon2id (RFC 9106) is memory-hard: cost is set by memory in KiB, passes time and lanes threads; argon2.IDKey(password, salt, time, memory, threads, keyLen). The package documentation says: "RFC 9106 Section 4 recommends time=1, memory=210241024 KiB (2 GiB), and threads=4 as the first recommended option. If much less memory is available, it recommends time=3, memory=64*1024 KiB (64 MiB), and threads=4 as the second recommended option." bcrypt takes a cost between bcrypt.MinCost (4) and bcrypt.MaxCost (31); the work doubles with each step; bcrypt.DefaultCost is 10. scrypt takes N, r, p. PBKDF2 (crypto/pbkdf2, Go 1.24) only has an iteration count and is chosen when FIPS 140-3 compliance is required (OWASP: HMAC-SHA-256 with 600,000 or more iterations).
1 user registers "correct horse"
2 salt = 16 random bytes // unique per user, not secret
3 key = Argon2id(password, salt, t=3, m=64MiB, p=4)
4 store "$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>" // PHC string: parameters travel with the hash
5 login: parse parameters, recompute with the stored salt, compare in constant timeReal scenario: an e-commerce login endpoint (target about 100 to 500 ms on production hardware); a CLI that derives a file-encryption key from a passphrase (scrypt or Argon2id, then AES-GCM); a legacy PHP database of $2y$ bcrypt hashes that Go must verify (the Go bcrypt package verified $2b$ and $2y$ prefixed copies of a hash in a test run for this page).
| Function | Cost knob | Memory-hard | Go package | Typical 2025 setting | Limits |
|---|---|---|---|---|---|
| Argon2id | time, memory, threads | Yes | x/crypto/argon2 | m=64 MiB, t=3, p=4 (RFC 9106 option 2); OWASP minimum 19 MiB, t=2, p=1 | Needs memory per concurrent login |
| bcrypt | cost (log2 rounds) | No (4 KiB state) | x/crypto/bcrypt | cost 10 minimum (OWASP), 12 common | 72-byte password limit |
| scrypt | N, r, p | Yes | x/crypto/scrypt | N=2^17, r=8, p=1 (OWASP minimum) | Tuning three knobs |
| PBKDF2-HMAC-SHA-256 | iterations | No | crypto/pbkdf2 (1.24) | 600,000 or more | Cheap on GPUs; FIPS route |
Measured on the machine that wrote this page (Apple silicon, Go 1.27.4; see the Lab): bcrypt cost 10 took 65 ms, cost 12 took 183 ms, cost 14 took 740 ms, Argon2id with 64 MiB, t=3, p=4 took 27 ms. Your servers decide the target, not these numbers.
Fix: a PHC-string Argon2id wrapper, a bcrypt wrapper with the 72-byte error, scrypt and PBKDF2 for compatibility, and tests including the length limit.
// Package password stores and verifies passwords with Argon2id and bcrypt,
// and upgrades old hashes on the next successful login.
package password
import (
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/scrypt"
)
// Params are the Argon2id knobs. RFC 9106 section 4 gives two recommended
// sets; this is the "second recommended option" (64 MiB, t=3, p=4), which suits
// a login endpoint better than 2 GiB.
type Params struct {
Memory uint32 // KiB
Time uint32 // passes
Threads uint8 // lanes
SaltLen uint32
KeyLen uint32
}
var Default = Params{Memory: 64 * 1024, Time: 3, Threads: 4, SaltLen: 16, KeyLen: 32}
// HashArgon2id returns a PHC string: $argon2id$v=19$m=65536,t=3,p=4$salt$hash.
func HashArgon2id(pw string, p Params) (string, error) {
salt := make([]byte, p.SaltLen)
rand.Read(salt) // never fails since Go 1.24
key := argon2.IDKey([]byte(pw), salt, p.Time, p.Memory, p.Threads, p.KeyLen)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, p.Memory, p.Time, p.Threads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
var ErrBadHash = errors.New("password: unrecognised hash format")
func parseArgon2(enc string) (p Params, salt, key []byte, err error) {
parts := strings.Split(enc, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return p, nil, nil, ErrBadHash
}
var v int
if _, err = fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version {
return p, nil, nil, ErrBadHash
}
if _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads); err != nil {
return p, nil, nil, ErrBadHash
}
b64 := base64.RawStdEncoding
if salt, err = b64.DecodeString(parts[4]); err != nil {
return p, nil, nil, ErrBadHash
}
if key, err = b64.DecodeString(parts[5]); err != nil {
return p, nil, nil, ErrBadHash
}
p.SaltLen, p.KeyLen = uint32(len(salt)), uint32(len(key))
return p, salt, key, nil
}
// VerifyArgon2id recomputes with the stored parameters and compares in constant time.
func VerifyArgon2id(pw, enc string) (bool, error) {
p, salt, want, err := parseArgon2(enc)
if err != nil {
return false, err
}
got := argon2.IDKey([]byte(pw), salt, p.Time, p.Memory, p.Threads, p.KeyLen)
return subtle.ConstantTimeCompare(got, want) == 1, nil
}
// NeedsRehash is true when the stored hash is weaker than the current policy.
func NeedsRehash(enc string, target Params) bool {
if strings.HasPrefix(enc, "$2") { // bcrypt: always migrate to Argon2id
return true
}
p, _, _, err := parseArgon2(enc)
return err != nil || p.Memory < target.Memory || p.Time < target.Time || p.Threads < target.Threads
}
// Verify checks bcrypt or Argon2id hashes. On success it returns a replacement
// hash when the stored one is below policy; the caller persists it.
func Verify(pw, stored string, target Params) (ok bool, upgraded string, err error) {
if strings.HasPrefix(stored, "$2") {
if err := bcrypt.CompareHashAndPassword([]byte(stored), []byte(pw)); err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return false, "", nil
}
return false, "", err
}
} else if ok, err = VerifyArgon2id(pw, stored); err != nil || !ok {
return false, "", err
}
if NeedsRehash(stored, target) {
upgraded, err = HashArgon2id(pw, target)
}
return true, upgraded, err
}
// Bcrypt wraps GenerateFromPassword. bcrypt reads at most 72 bytes of the
// password; x/crypto returns bcrypt.ErrPasswordTooLong instead of truncating.
func Bcrypt(pw string, cost int) ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(pw), cost)
}
// Scrypt and PBKDF2 exist for compatibility with systems that already use them.
func Scrypt(pw string, salt []byte) ([]byte, error) {
return scrypt.Key([]byte(pw), salt, 1<<17, 8, 1, 32) // N=2^17 (128 MiB), r=8, p=1: OWASP minimum
}
func PBKDF2(pw string, salt []byte, iter int) ([]byte, error) {
return pbkdf2.Key(sha256.New, pw, salt, iter, 32)
}Rehash on login Important
In plain words: you cannot upgrade a stored password hash by itself, because you do not have the password. But every successful login hands you the plaintext for a moment, and that is when you rewrite the hash with stronger parameters.
Common misunderstanding: "To move from bcrypt to Argon2id, force every user to reset their password." You can migrate silently: verify with the old algorithm, rehash with the new one in the same request.
Definition: a hash string must name its algorithm and parameters ($2a$10$..., $argon2id$v=19$m=65536,t=3,p=4$...). At login, after a successful verify, compare those parameters with the current policy; if weaker, compute a new hash and store it with a guarded UPDATE.
T1 (login A) T2 (login B, same user)
1 SELECT hash -> $2a$10$... SELECT hash -> $2a$10$...
2 verify ok, needs rehash -> new1 verify ok, needs rehash -> new2
3 UPDATE ... SET hash=new1 WHERE hash=$2a$10
4 UPDATE ... SET hash=new2 WHERE hash=$2a$10 -- 0 rows, ignoredReal scenario: raising Argon2id memory from 19 MiB to 64 MiB after a hardware refresh; leaving a bcrypt cost-10 estate; changing the salt length. Users who never log in keep old hashes, so the audit query below tells you how many remain.
-- password column holds the PHC or bcrypt string; the prefix names the algorithm
CREATE TABLE users (
id bigint PRIMARY KEY,
email text NOT NULL UNIQUE,
password_hash text NOT NULL
);
-- guarded rehash: loses harmlessly if another login already upgraded the row
UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3;
-- how many accounts still carry which algorithm and parameters?
SELECT split_part(password_hash, '$', 2) AS algo,
split_part(password_hash, '$', 4) AS params,
count(*)
FROM users GROUP BY 1, 2 ORDER BY 3 DESC;Fix: password.Verify returns (ok, upgradedHash, err); the caller persists upgradedHash when non-empty. The test TestRehashOnLogin proves a bcrypt hash upgrades once and is then left alone.
Key derivation with HKDF Important
In plain words: you have one strong secret (a master key, or an ECDH result) and need several independent keys from it: one for encrypting, one for authenticating. HKDF stretches and labels one secret into many.
Common misunderstanding: "HKDF is for passwords." It is not: it assumes the input is already high-entropy. For a human passphrase use Argon2id or scrypt first, then HKDF if you need several keys.
Definition: HKDF (RFC 5869) is Extract (HMAC of the secret keyed by the salt, producing a pseudorandom key) then Expand (HMAC chain labelled by info). hkdf.Key(sha256.New, secret, salt, info, length) runs both. Different info strings give unrelated outputs from the same secret.
1 prk = HMAC(salt, secret) // Extract
2 enc = HKDF-Expand(prk, "app v1 encryption", 32)
3 mac = HKDF-Expand(prk, "app v1 mac", 32)
4 enc != mac; knowing one reveals nothing about the otherReal scenario: turning an ecdh shared secret into a session key; deriving per-tenant data keys from a master key with info = "tenant:42"; separating the cookie-signing key from the cookie-encryption key.
// Package kdf derives independent keys from one secret with HKDF (RFC 5869).
package kdf
import (
"crypto/hkdf"
"crypto/sha256"
)
// Subkey derives a purpose-bound key. Different info strings give unrelated keys.
func Subkey(master, salt []byte, info string, n int) ([]byte, error) {
return hkdf.Key(sha256.New, master, salt, info, n)
}
// Keys returns an encryption key and a MAC key for one master secret.
func Keys(master, salt []byte) (enc, mac []byte, err error) {
if enc, err = Subkey(master, salt, "app v1 encryption", 32); err != nil {
return nil, nil, err
}
mac, err = Subkey(master, salt, "app v1 mac", 32)
return enc, mac, err
}crypto/rand and secure tokens Must-know
In plain words: when you need something an attacker must not guess (a session token, a salt, a nonce, a key) ask the operating system for random bytes through crypto/rand.
Common misunderstanding: "Seeding math/rand with the time makes it random enough." Anyone who knows roughly when the token was created can enumerate the seeds. Another one: "rand.Read returns an error I must handle." Since Go 1.24 it "never returns an error, and always fills b entirely"; on failure the program crashes irrecoverably, which is the right outcome for a machine with a broken entropy source. Code that still checks err compiles and is harmless.
Definition: rand.Reader is the OS CSPRNG (getrandom(2) on Linux, arc4random_buf on macOS, ProcessPrng on Windows). rand.Read(b) fills a slice; rand.Text() returns a base32 string with at least 128 bits (26 characters); rand.Int(rand.Reader, max) returns a uniform integer in [0, max) without modulo bias; rand.Prime generates primes.
1 b := make([]byte, 32); rand.Read(b) // 256 bits
2 token := base64.RawURLEncoding.EncodeToString(b) // 43 characters, URL and cookie safe
3 store sha256(token) in the database // a leaked table gives no valid token
4 client sends token; server hashes it and looks up the digestReal scenario: session IDs and CSRF tokens; password-reset links (store the hash of the token, expire in 30 minutes); API keys shown once; six-digit codes (use rand.Int, then rate limit the check, because six digits are only 20 bits).
| Need | Use | Output |
|---|---|---|
| 256-bit URL-safe token | rand.Read 32 bytes, base64.RawURLEncoding | 43 characters |
| Convenient 128-bit token | rand.Text() | 26 base32 characters |
| Uniform number below n | rand.Int(rand.Reader, big.NewInt(n)) | *big.Int |
| Salt for a password hash | rand.Read 16 bytes | 16 bytes |
| Simulation, shuffling a playlist | math/rand/v2 | Not secret |
Fix: the token package, with a test that checks length, alphabet and uniqueness:
// Package token generates unguessable strings from crypto/rand.
package token
import (
"crypto/rand"
"encoding/base64"
"math/big"
)
// URLSafe returns 32 random bytes as 43 base64url characters (256 bits).
func URLSafe() string {
b := make([]byte, 32)
rand.Read(b) // since Go 1.24 Read never returns an error
return base64.RawURLEncoding.EncodeToString(b)
}
// Text uses the standard library helper: 26 base32 characters, 128 bits.
func Text() string { return rand.Text() }
// Below returns a uniform integer in [0, n) without modulo bias.
func Below(n int64) (int64, error) {
v, err := rand.Int(rand.Reader, big.NewInt(n))
if err != nil {
return 0, err
}
return v.Int64(), nil
}
// PIN returns a six-digit code. Rate-limit the endpoint that checks it.
func PIN() (string, error) {
n, err := Below(1_000_000)
if err != nil {
return "", err
}
const digits = "0123456789"
out := make([]byte, 6)
for i := 5; i >= 0; i-- {
out[i] = digits[n%10]
n /= 10
}
return string(out), nil
}Authenticated encryption: AES-GCM and ChaCha20-Poly1305 Must-know
In plain words: encrypt with a mode that also produces a tag. On decryption the tag is checked first; if anyone changed a single bit, you get an error and no plaintext.
Common misunderstanding: "The nonce is a secret, like the key." It is not secret; it must be unique per message under one key. You store it next to the ciphertext. Another one: "AES-256 vs AES-128 is the main security decision." The mode and nonce handling matter far more.
Definition: cipher.AEAD has Seal(dst, nonce, plaintext, aad) (appends ciphertext and tag to dst) and Open(dst, nonce, ciphertext, aad). aes.NewCipher(key) takes 16, 24 or 32 bytes; cipher.NewGCM(block) gives a 12-byte nonce and a 16-byte tag. Go 1.24 added cipher.NewGCMWithRandomNonce(block): Seal generates and prepends the nonce, the overhead is 28 bytes, and the documentation says "A given key MUST NOT be used to encrypt more than 2^32 messages". chacha20poly1305.NewX(key) (XChaCha20-Poly1305) takes a 24-byte nonce that is safe to pick at random.
1 key = 32 random bytes (from a KMS or rand.Read)
2 nonce = 12 random bytes, new for every Seal
3 out = nonce || ciphertext || tag(16) // gcm.Seal(nonce, nonce, plaintext, aad)
4 Open(nonce, ciphertext||tag, aad) // aad must be byte-identical or Open fails
5 error: "cipher: message authentication failed"Real scenario: encrypting a refresh token column in the database (aad = user ID, so a ciphertext copied to another row fails); an encrypted cookie; a file with a header (aad) and encrypted body; a message envelope between services.
| Primitive | Key | Nonce | Tag | Random nonce safe? | Prefer when |
|---|---|---|---|---|---|
AES-GCM (NewGCM) | 16/24/32 bytes | 12 bytes | 16 | Up to about 2^32 messages per key | AES hardware, FIPS |
AES-GCM random nonce (NewGCMWithRandomNonce) | 16/24/32 | 12 (hidden) | 16 | Enforced limit 2^32 | Simplest API (Go 1.24) |
| ChaCha20-Poly1305 | 32 | 12 | 16 | Risky at high volume | Software speed, TLS |
XChaCha20-Poly1305 (NewX) | 32 | 24 | 16 | Yes | Many messages, no counters |
Fix: AES-GCM with an explicit nonce prefix, the 1.24 random-nonce form, and XChaCha20-Poly1305, with tamper tests for all three:
// Package aead encrypts with AES-GCM and ChaCha20-Poly1305 and shows the two
// classic mistakes: nonce reuse and ECB-style block repetition.
package aead
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"golang.org/x/crypto/chacha20poly1305"
)
// NewKey returns a 32-byte key (AES-256 / ChaCha20-Poly1305).
func NewKey() []byte {
k := make([]byte, 32)
rand.Read(k)
return k
}
// Seal encrypts with AES-GCM and a fresh random 96-bit nonce stored in front of
// the ciphertext. aad is authenticated but not encrypted (tenant ID, record ID).
func Seal(key, plaintext, aad []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize()) // 12 bytes
rand.Read(nonce)
// Seal appends ciphertext||tag to its first argument, so nonce comes first.
return gcm.Seal(nonce, nonce, plaintext, aad), nil
}
var ErrShort = errors.New("aead: ciphertext shorter than nonce")
// Open reverses Seal. Any change to nonce, ciphertext, tag or aad fails with
// the single error "cipher: message authentication failed".
func Open(key, sealed, aad []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(sealed) < gcm.NonceSize() {
return nil, ErrShort
}
nonce, ct := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():]
return gcm.Open(nil, nonce, ct, aad)
}
// SealAuto uses Go 1.24 NewGCMWithRandomNonce: Seal generates the nonce and
// prepends it, Open reads it back. The standard library also enforces a limit
// of 2^32 encryptions per key, so rotate keys before that.
func SealAuto(key, plaintext, aad []byte) ([]byte, error) {
a, err := autoGCM(key)
if err != nil {
return nil, err
}
return a.Seal(nil, nil, plaintext, aad), nil
}
func OpenAuto(key, sealed, aad []byte) ([]byte, error) {
a, err := autoGCM(key)
if err != nil {
return nil, err
}
return a.Open(nil, nil, sealed, aad)
}
func autoGCM(key []byte) (cipher.AEAD, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewGCMWithRandomNonce(block)
}
// SealChaCha encrypts with XChaCha20-Poly1305: a 192-bit nonce is safe to pick
// at random for any realistic number of messages.
func SealChaCha(key, plaintext, aad []byte) ([]byte, error) {
a, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
nonce := make([]byte, a.NonceSize()) // 24 bytes
rand.Read(nonce)
return a.Seal(nonce, nonce, plaintext, aad), nil
}
func OpenChaCha(key, sealed, aad []byte) ([]byte, error) {
a, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
if len(sealed) < a.NonceSize() {
return nil, ErrShort
}
return a.Open(nil, sealed[:a.NonceSize()], sealed[a.NonceSize():], aad)
}
// XORLeak is the nonce-reuse mistake: two messages sealed under one key and one
// nonce. XOR of the ciphertext bodies equals XOR of the plaintexts, so an
// attacker who knows one message learns the other without the key.
func XORLeak(key, nonce, m1, m2 []byte) (leaked []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
c1 := gcm.Seal(nil, nonce, m1, nil)
c2 := gcm.Seal(nil, nonce, m2, nil)
n := min(len(m1), len(m2))
leaked = make([]byte, n)
for i := range leaked {
leaked[i] = c1[i] ^ c2[i]
}
return leaked, nil
}
// ECBRepeats encrypts each 16-byte block independently, which is what ECB is.
// It reports whether two equal plaintext blocks gave equal ciphertext blocks.
func ECBRepeats(key, plaintext []byte) (bool, error) {
block, err := aes.NewCipher(key)
if err != nil {
return false, err
}
bs := block.BlockSize()
seen := map[string]bool{}
for i := 0; i+bs <= len(plaintext); i += bs {
out := make([]byte, bs)
block.Encrypt(out, plaintext[i:i+bs])
if seen[string(out)] {
return true, nil
}
seen[string(out)] = true
}
return false, nil
}Nonce reuse and ECB Must-know
In plain words: GCM turns the key and nonce into a long random-looking stream and XORs it with your data. If you use the same key and nonce twice, you used the same stream twice, and XORing two ciphertexts cancels the stream out.
Common misunderstanding: "A counter or a timestamp is a fine nonce." A counter is fine if it never repeats, including across restarts, replicas and restored backups; a timestamp repeats. Random nonces avoid the coordination problem but need the 2^32 limit above.
Definition: with a repeated nonce, c1 XOR c2 = p1 XOR p2, so a known p1 reveals p2, and GCM's authentication key can also be recovered, letting an attacker forge messages. ECB mode (each 16-byte block encrypted independently) leaks equal blocks; Go deliberately offers no ECB mode, you would have to loop over Block.Encrypt yourself.
1 c1 = Seal(key, nonce N, "attack at dawn!!")
2 c2 = Seal(key, nonce N, "retreat at dusk!") // same key, same nonce: the mistake
3 c1[i] XOR c2[i] == p1[i] XOR p2[i] // the test in aead_test.go asserts exactly this
4 attacker knows p1 (a protocol header) -> p2 falls out without the keyReal scenario: a service that derives a nonce from a database row ID and re-encrypts after an update; a restored VM snapshot that replays a counter; copy-pasted example code with make([]byte, 12) as a constant nonce (all zeros) in production.
| Mistake | Effect | Prevention |
|---|---|---|
| Fixed or zero nonce | Plaintext XOR leaks; forgery | Random nonce per Seal |
| Counter reset after restore | Same | Random nonce or XChaCha20 |
ECB (looping Block.Encrypt) | Equal blocks visible | Use AEAD, never raw blocks |
| CBC or CTR without a MAC | Bit-flipping, padding oracles | AEAD |
| Key used past 2^32 messages | Random nonce collision | Rotate keys (HKDF per epoch) |
Signatures: Ed25519, ECDSA P-256, RSA-PSS Important
In plain words: a signature lets anyone with your public key check that you signed a message, without being able to sign themselves.
Common misunderstanding: "Verify just means the signature has the right length." Verify must be called and its boolean checked; a function that ignores the result accepts anything. Another one: "RSA signatures should use PKCS#1 v1.5 because everyone does." New designs should use PSS; PKCS#1 v1.5 is for interoperability.
Definition: ed25519.GenerateKey, ed25519.Sign(priv, msg), ed25519.Verify(pub, msg, sig) sign the message itself (64-byte signature, 32-byte public key). ecdsa.GenerateKey(elliptic.P256(), rand.Reader), ecdsa.SignASN1(rand, priv, digest) and ecdsa.VerifyASN1(&pub, digest, sig) sign a digest you compute (sha256.Sum256); the result is ASN.1 DER. rsa.SignPSS / rsa.VerifyPSS with crypto.SHA256 and PSSSaltLengthEqualsHash. Since Go 1.24, ecdsa.PrivateKey.Sign is deterministic (RFC 6979) when the random source is nil, and RSA keys under 1024 bits are refused.
1 signer: sig = Ed25519-Sign(priv, message) // 64 bytes
2 transmit: message || sig (public key known or published)
3 verifier: ok = Ed25519-Verify(pub, message, sig) // one changed byte: ok = false
4 a signed JWT, a release manifest, a webhook: the same three stepsReal scenario: signing release manifests; issuing short-lived tokens that many services verify with a public key (JWT with EdDSA or ES256, see JWT Deep Dive); verifying a vendor's webhook that signs with ECDSA.
| Scheme | Signature size | Key size | Notes |
|---|---|---|---|
| Ed25519 | 64 bytes | 32-byte public | Default for new systems; deterministic |
| ECDSA P-256 | about 70-72 bytes (DER) | 65-byte public (uncompressed) | Interop with JWT ES256, TLS, WebAuthn |
| RSA-PSS 2048 | 256 bytes | 256-byte modulus | Legacy interop; 3072-bit for new long-lived keys |
| RSA PKCS#1 v1.5 | 256 bytes | same | Only to interoperate |
Fix: the asym package has all three plus a tamper check; the next block imports it.
Public-key encryption and key agreement Good to know
In plain words: RSA can encrypt a small secret for someone who published a public key. ECDH lets two parties each combine their private key with the other's public key and arrive at the same secret, without sending it.
Common misunderstanding: "Encrypt the document with the RSA public key." RSA-OAEP encrypts only a few hundred bytes (crypto/rsa: message too long for RSA key size). Encrypt the data with AES-GCM and use RSA (or ECDH) only for the data key, a pattern called envelope encryption. And "the ECDH output is the key": it is raw material; run it through HKDF.
Definition: rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, msg, label) and rsa.DecryptOAEP(sha256.New(), nil, priv, ciphertext, label); the label must match or decryption fails with crypto/rsa: decryption error (a deliberately uninformative error). ecdh.X25519() or ecdh.P256() gives GenerateKey, PrivateKey.ECDH(remotePublic); an all-zero public key is rejected with crypto/ecdh: bad X25519 remote ECDH input: low order point.
1 Alice: a, A = X25519 keypair Bob: b, B = X25519 keypair
2 A -> Bob, B -> Alice (public keys, over any channel)
3 Alice: s = ECDH(a, B) Bob: s = ECDH(b, A) // same 32 bytes
4 both: key = HKDF-SHA256(s, info="session v1") -> AES-GCM / XChaCha20 keyReal scenario: encrypting a per-file data key for several recipients; TLS 1.3 key exchange (X25519); a Noise-style handshake between two services; wrapping a data key with a KMS public key.
// Package asym signs, verifies, encrypts and agrees on keys with public-key crypto.
package asym
import (
"crypto"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/hkdf"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
)
// Ed25519 signs the message itself (hashing is internal to the scheme).
func Ed25519(msg []byte) (ok, tampered bool) {
pub, priv, _ := ed25519.GenerateKey(rand.Reader)
sig := ed25519.Sign(priv, msg)
return ed25519.Verify(pub, msg, sig), ed25519.Verify(pub, append([]byte("x"), msg...), sig)
}
// ECDSAP256 hashes first, then signs the digest; the signature is ASN.1 DER.
func ECDSAP256(msg []byte) (ok, tampered bool, err error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return false, false, err
}
digest := sha256.Sum256(msg)
sig, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
if err != nil {
return false, false, err
}
other := sha256.Sum256(append([]byte("x"), msg...))
return ecdsa.VerifyASN1(&key.PublicKey, digest[:], sig), ecdsa.VerifyASN1(&key.PublicKey, other[:], sig), nil
}
// RSAOAEP encrypts a small secret (a data key, not a document) with OAEP.
// The label binds the ciphertext to a context, like AEAD associated data.
func RSAOAEP(secret, label []byte) ([]byte, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
ct, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &key.PublicKey, secret, label)
if err != nil {
return nil, err
}
return rsa.DecryptOAEP(sha256.New(), nil, key, ct, label)
}
// RSAPSS signs with PSS (the modern RSA signature padding), not PKCS#1 v1.5.
func RSAPSS(msg []byte) (ok bool, err error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return false, err
}
digest := sha256.Sum256(msg)
opts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
sig, err := rsa.SignPSS(rand.Reader, key, crypto.SHA256, digest[:], opts)
if err != nil {
return false, err
}
return rsa.VerifyPSS(&key.PublicKey, crypto.SHA256, digest[:], sig, opts) == nil, nil
}
// SharedKey runs X25519 between two parties and turns the raw shared secret
// into an AES key with HKDF. Never use the raw ECDH output as a key.
func SharedKey(info string) (alice, bob []byte, err error) {
curve := ecdh.X25519()
a, err := curve.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
b, err := curve.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
sa, err := a.ECDH(b.PublicKey())
if err != nil {
return nil, nil, err
}
sb, err := b.ECDH(a.PublicKey())
if err != nil {
return nil, nil, err
}
if alice, err = hkdf.Key(sha256.New, sa, nil, info, 32); err != nil {
return nil, nil, err
}
bob, err = hkdf.Key(sha256.New, sb, nil, info, 32)
return alice, bob, err
}Encoding keys: PEM, PKCS#8, PKIX Good to know
In plain words: a key in memory is a Go struct; to store or send it you serialise it to bytes and usually wrap those bytes in PEM, the -----BEGIN ...----- text format.
Common misunderstanding: "BEGIN RSA PRIVATE KEY and BEGIN PRIVATE KEY are the same." The first is PKCS#1 (RSA only); the second is PKCS#8, which holds any key type and names its algorithm. Go reports the mismatch: x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format).
Definition: x509.MarshalPKCS8PrivateKey(key) and x509.ParsePKCS8PrivateKey(der) (PEM type PRIVATE KEY); x509.MarshalPKIXPublicKey and ParsePKIXPublicKey (PEM type PUBLIC KEY); pem.EncodeToMemory(&pem.Block{...}) and pem.Decode(b), which returns a nil block if the input is not PEM. x509.MarshalECPrivateKey is the older EC PRIVATE KEY form. Parsing returns any, so assert the concrete type you accept.
1 der := x509.MarshalPKCS8PrivateKey(priv) // key -> bytes
2 pem.EncodeToMemory(&pem.Block{Type:"PRIVATE KEY", Bytes:der})
3 ...store in a secret manager, file mode 0600...
4 pem.Decode -> x509.ParsePKCS8PrivateKey -> k.(ed25519.PrivateKey) // check the typeReal scenario: loading a signing key from an environment variable or a mounted secret; publishing a JWKS-like public key; rejecting an RSA key when you expect Ed25519 (an attacker-supplied algorithm is a classic JWT bug).
// Package keys serialises keys as PEM: PKCS#8 for private, PKIX for public.
package keys
import (
"crypto/ed25519"
"crypto/x509"
"encoding/pem"
"errors"
)
// Marshal returns the two PEM blocks for an Ed25519 key pair.
func Marshal(priv ed25519.PrivateKey) (privPEM, pubPEM []byte, err error) {
der, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, nil, err
}
pubDER, err := x509.MarshalPKIXPublicKey(priv.Public())
if err != nil {
return nil, nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}),
pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}), nil
}
var ErrNotEd25519 = errors.New("keys: not an Ed25519 key")
// ParsePrivate decodes PKCS#8 PEM and checks the concrete type.
func ParsePrivate(b []byte) (ed25519.PrivateKey, error) {
blk, _ := pem.Decode(b)
if blk == nil || blk.Type != "PRIVATE KEY" {
return nil, errors.New("keys: no PRIVATE KEY block")
}
k, err := x509.ParsePKCS8PrivateKey(blk.Bytes)
if err != nil {
return nil, err
}
ed, ok := k.(ed25519.PrivateKey)
if !ok {
return nil, ErrNotEd25519
}
return ed, nil
}
func ParsePublic(b []byte) (ed25519.PublicKey, error) {
blk, _ := pem.Decode(b)
if blk == nil || blk.Type != "PUBLIC KEY" {
return nil, errors.New("keys: no PUBLIC KEY block")
}
k, err := x509.ParsePKIXPublicKey(blk.Bytes)
if err != nil {
return nil, err
}
ed, ok := k.(ed25519.PublicKey)
if !ok {
return nil, ErrNotEd25519
}
return ed, nil
}FIPS 140-3 mode Good to know
In plain words: some regulated customers require a validated cryptographic module. Go 1.24 ships one inside the standard library, so you build the same code with a flag instead of switching to a different crypto library.
Common misunderstanding: "FIPS mode makes the application more secure." The Go blog says FIPS 140 compliance "doesn't necessarily improve security"; it is a compliance requirement. And GODEBUG=fips140=only is "not intended to be used in production".
Definition: GOFIPS140 is a build-time variable (off default, latest, or a module version such as v1.0.0) selecting the Go Cryptographic Module and enabling FIPS mode by default; the fips140 GODEBUG setting turns it on at run time (on) or makes non-approved algorithms error or panic (only, a testing mode); crypto/fips140.Enabled() reports the state. In FIPS mode crypto/rand.Reader passes through an SP 800-90A DRBG, and cipher.NewGCM with caller-chosen nonces is rejected under only, which points you to NewGCMWithRandomNonce.
1 go build -> fips140.Enabled() == false
2 GOFIPS140=v1.0.0 go build -> true by default in that binary
3 GODEBUG=fips140=on ./app -> true at run time
4 GODEBUG=fips140=only ./app -> non-approved algorithms (for example MD5 in a signature) failReal scenario: a government or banking customer asking for FIPS-validated crypto; CI that runs the test suite once with GODEBUG=fips140=only to find calls that would break.
// Command fips prints whether FIPS 140-3 mode is on. Run it twice:
//
// go run ./fips
// GODEBUG=fips140=on go run ./fips
package main
import (
"crypto/fips140"
"crypto/sha256"
"fmt"
)
func main() {
sum := sha256.Sum256([]byte("abc"))
fmt.Printf("fips140.Enabled=%v sha256(abc)=%x\n", fips140.Enabled(), sum[:4])
}Deprecated and dangerous Important
In plain words: some packages are still in the standard library because old protocols need them, not because you should use them. MD5 deprecated for security use, SHA-1 likewise, is the headline.
Common misunderstanding: "It is in the standard library, so it is safe." The package documentation says otherwise for several.
| Package or function | Status in the docs | Use instead |
|---|---|---|
crypto/md5 | "MD5 is cryptographically broken and should not be used for secure applications" | SHA-256 (checksums for non-security legacy only) |
crypto/sha1 | "SHA-1 is cryptographically broken and should not be used for secure applications" | SHA-256; Go 1.24 x509 no longer verifies SHA-1 signatures |
crypto/dsa | Deprecated: "DSA is a legacy algorithm" | crypto/ed25519 |
crypto/des, crypto/rc4 | "cryptographically broken" | AES-GCM, ChaCha20-Poly1305 |
rsa.EncryptPKCS1v15 | Deprecated: "PKCS #1 v1.5 encryption is dangerous" | rsa.EncryptOAEP |
cipher.NewCFBEncrypter, NewOFB | Deprecated in Go 1.24: not authenticated | cipher.AEAD, or NewCTR if a stream is unavoidable |
x509.EncryptPEMBlock | Deprecated: legacy PEM encryption is insecure | PKCS#8 encrypted with a modern KDF, or a secret manager |
| RSA keys under 1024 bits | Refused since 1.24 (rsa1024min=0 restores) | 2048-bit minimum, 3072 for new long-lived keys |
Mechanics
Package map and versions Must-know
| Task | Standard library (version) | golang.org/x/crypto |
|---|---|---|
| SHA-2 | crypto/sha256, crypto/sha512 | none |
| SHA-3, SHAKE | crypto/sha3 (1.24) | sha3 (older) |
| BLAKE2 | none | blake2b, blake2s |
| HMAC | crypto/hmac | none |
| Password hash | crypto/pbkdf2 (1.24) | bcrypt, argon2, scrypt |
| HKDF | crypto/hkdf (1.24) | hkdf (older) |
| AEAD | crypto/cipher (AES-GCM) | chacha20poly1305 |
| Signatures | crypto/ed25519, crypto/ecdsa, crypto/rsa | none |
| Key agreement | crypto/ecdh | curve25519 (older) |
| Random | crypto/rand | none |
| Constant time | crypto/subtle | none |
| FIPS | crypto/fips140 (1.24) | none |
Error texts decoded Must-know
These are the exact strings the snippets produced (Go 1.27.4 on the author's machine, and x/crypto v0.45.0).
| Text | Cause | Fix |
|---|---|---|
crypto/aes: invalid key size 5 | Key not 16, 24 or 32 bytes | Derive or generate exactly 32 bytes |
crypto/cipher: incorrect nonce length given to GCM (panic) | Nonce is not 12 bytes | make([]byte, gcm.NonceSize()) |
cipher: message authentication failed | Wrong key, nonce, aad, or tampered data | Treat as tampering; do not reveal which |
bcrypt: password length exceeds 72 bytes | Password longer than bcrypt reads | Pre-hash with SHA-256 and base64 (a documented workaround), or use Argon2id |
crypto/rsa: message too long for RSA key size | OAEP plaintext larger than the modulus allows | Encrypt a data key, not the document |
crypto/rsa: decryption error | Wrong key, label or corrupted ciphertext | Intentionally uninformative |
crypto/rsa: 512-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size) | Key below 1024 bits | Use 2048 or more |
crypto/ecdh: bad X25519 remote ECDH input: low order point | Peer sent a degenerate public key | Abort the handshake |
x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format) | PKCS#1 bytes given to the PKCS#8 parser | Parse by PEM type |
Timing, in numbers Good to know
| Operation | Cost | Source |
|---|---|---|
| bcrypt cost 10 / 12 / 14 | 65 ms / 183 ms / 740 ms | Lab run on the author's machine |
| Argon2id 64 MiB, t=3, p=4 | 27 ms | Lab run on the author's machine |
| Each bcrypt cost step | doubles the work | bcrypt package documentation |
| Random-nonce GCM message limit | 2^32 per key | cipher.NewGCMWithRandomNonce source |
| Six-digit code | 10^6 values, about 20 bits | arithmetic |
Solving the classic problems
Verify a webhook signature
Problem: a vendor sends X-Signature: hex(HMAC-SHA256(secret, body)). Solution: read the raw body, compute the MAC, decode the header to bytes and use hmac.Equal. Advantage: constant time and byte-exact. Cost: you must read the body before parsing it.
func verifyWebhook(secret, body []byte, header string) bool {
want, err := hex.DecodeString(header)
if err != nil {
return false
}
return mac.Valid(secret, body, want) // hmac.Equal inside
}Store and check a password
| Step | Call | Where |
|---|---|---|
| Register | password.HashArgon2id(pw, password.Default) | password/password.go |
| Login | password.Verify(pw, stored, password.Default) | same |
| Persist upgrade | UPDATE ... WHERE password_hash = old | SQL above |
| Reject over-long input | check length before hashing (cap at e.g. 1024 bytes to bound CPU) | handler |
| Rate limit | per account and per IP | Rate Limiting in Go |
Encrypt a database column
Solution: aead.Seal(key, plaintext, aad) with aad = []byte("users.refresh_token:" + id), store the result in a bytea column, decrypt with the same aad. Advantage: a ciphertext copied to another row or column fails to open. Cost: you cannot search or index the ciphertext; for lookups keep an HMAC of the value (a blind index) in another column. Database-side options are in Encryption at Rest, in Transit & in Use.
Issue and check a reset token
1 token := token.URLSafe() // 43 chars, 256 bits
2 INSERT reset(user_id, token_hash, expires) VALUES (?, sha256(token), now()+30m)
3 email https://example.com/reset?token=<token>
4 later: look up by sha256(token); single use; delete the row on successA database leak then exposes only digests of tokens. Compare with subtle.ConstantTimeCompare only if you compare in application code; a database lookup by digest is already safe from timing because the digest is unguessable.
Sign and verify across services
Solution: the issuing service holds an Ed25519 private key; verifiers load only the public key (PKIX PEM). Rotate by publishing two public keys with key IDs. Advantage: verifiers cannot mint tokens. Cost: key distribution; see Cryptography in Practice.
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Hash a file or stream | SHA-256 via io.Copy | io.TeeReader for inline hashing | One pass, constant memory |
| Authenticate a message with a shared key | HMAC-SHA-256, hmac.Equal | Include a timestamp and an ID to stop replay | Forgery needs the key |
| Password storage, new system | Argon2id 64 MiB, t=3, p=4 | Rehash on login; per-user random salt | Memory-hard, RFC 9106 |
| Password storage, FIPS required | PBKDF2-HMAC-SHA-256, 600,000+ iterations | Same | Approved algorithm |
| Existing bcrypt estate | Keep bcrypt cost 10+; migrate on login | Reject over 72 bytes explicitly | No reset campaign |
| Random identifiers and tokens | crypto/rand 32 bytes, base64url | Store a hash of it | Unguessable, safe at rest |
| Encrypt data with a key you hold | AES-256-GCM or XChaCha20-Poly1305 | aad binding to the record | Integrity plus secrecy |
| Encrypt to someone's public key | ECDH (X25519) + HKDF + AEAD | RSA-OAEP only for legacy | Short, fast, standard |
| Signatures | Ed25519 | ECDSA P-256 for ES256 interop | Small, simple API |
| Quick checksum of trusted data | CRC-32C or FNV | none | Speed; no attacker |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One binary holds the password hasher, a session-token generator and perhaps an encrypted column. Keys come from an environment variable or a mounted file, read once at start. The Argon2id memory cost is per concurrent login: 64 MiB times 50 simultaneous logins is 3.2 GiB, so cap concurrency with a semaphore or a worker pool. The sql above is the whole schema.
Modular monolith and multiple databases
An identity module owns hashing and token issuance; other modules receive a verified user ID and never see a hash. Define a small interface (Hasher, Sealer) in the consumer and inject the implementation (see Mocking with Interfaces and DI), so tests use a fast Params and production uses the strong ones. Each module that stores secrets gets its own derived key via HKDF info = "module:billing", so a leak in one does not decrypt another.
Microservices
1 auth-service: Ed25519 private key (secret manager); signs access tokens
2 orders, billing: only the public key; verify locally, no call to auth per request
3 service -> service: mTLS for identity; HMAC or signed JWT for request-level claims
4 data keys: one KEK in a KMS; each service gets data keys wrapped by it (envelope encryption)
5 rotation: kid in the token header; verifiers accept the previous key for one token lifetimeWhat survives across a service boundary: a signature and a key ID. What does not: an in-memory nonce counter (two replicas both start at zero), so use random nonces or XChaCha20. Never ship the plaintext password across services; hash at the edge, once.
Distributed data: replicas, caches and backups
Hashes and ciphertexts replicate like any bytes; the hazards are different. A restored backup or a forked VM can replay a counter-based nonce; random nonces survive that. A cache of verified signatures is safe, a cache of decrypted values is a secret store and needs the same care as the database. Key rotation across replicas needs a window where both old and new keys decrypt (kid stored with each ciphertext). A password-hash upgrade writes to the primary; a replica read just before it sees the old hash, which still verifies, so the guarded UPDATE stays correct.
Scaling path: 1×, 10×, 100×
| Load | What breaks first | Change |
|---|---|---|
| 1× (hundreds of logins a day) | Nothing; defaults work | Argon2id 64 MiB, one key in an env file |
| 10× (logins per second) | CPU and memory from password hashing; login latency | Bound concurrency; dedicated auth pods; rate limit; keep parameters |
| 100× (many services, many tenants) | Key distribution, rotation, nonce uniqueness | KMS with envelope encryption; per-tenant HKDF keys; XChaCha20 or random-nonce GCM; verify signatures locally |
Lab
The programs run on the host with only the Go toolchain; no containers are needed.
cd docs/snippets/go/hashing-crypto/go
go test ./...
go run ./lab
go run ./fips
GODEBUG=fips140=on go run ./fipsReal output from the author's machine (Apple silicon, Go 1.27.4, go 1.24.0 module; timings vary):
bcrypt cost=10 65ms $2a$10$t5g3rFAG1o2kS...
bcrypt cost=12 183ms $2a$12$T0xCesVWiNOxi...
bcrypt cost=14 740ms $2a$14$al2MC..rSl/tD...
argon2id m=64MiB t=3 p=4 27ms $argon2id$v=19$m=65536,t=3,p=4$2NvN+xQx0...
login with bcrypt hash: ok=true upgraded=true
blake2b256 bddd813c63423972...
sha256 ba7816bf8f01cfea...
sha3-256 3a985da74fe225b2...
sha512 ddaf35a193617aba...
sha512/256 53048e2681941ef9...
token: 43 chars; text: 26 chars
open garbage: cipher: message authentication failed
bcrypt 73 bytes: bcrypt: password length exceeds 72 bytesfips140.Enabled=false sha256(abc)=ba7816bf
fips140.Enabled=true sha256(abc)=ba7816bfExperiments (expected results; the first four are asserted by the test suite, which was run):
| # | Do this | Expected |
|---|---|---|
| 1 | go test ./aead -run NonceReuse -v | Passes: XOR of ciphertexts equals XOR of plaintexts |
| 2 | Edit Open to flip one byte of the ciphertext and run go test ./aead | cipher: message authentication failed |
| 3 | go test ./password -run Bcrypt -v | 73-byte input returns bcrypt: password length exceeds 72 bytes |
| 4 | go test ./password -run Rehash -v | bcrypt hash upgrades to $argon2id$ once, then no rewrite |
| 5 | Set password.Default to m=19 MiB, t=2, p=1, run go run ./lab, then call NeedsRehash with a 64 MiB hash and the 19 MiB target | false: a stronger hash is never downgraded |
| 6 | go build -o app ./fips && GODEBUG=fips140=only ./app (expected, not run) | Runs; non-approved algorithms would fail |
Common misconceptions
| Belief | Reality |
|---|---|
| SHA-256 is fine for passwords | It is fast by design; use Argon2id, scrypt or bcrypt |
== on two MACs is fine | Early exit leaks the matching prefix length; use hmac.Equal |
rand.Read can fail, so I must handle the error | Since Go 1.24 it never returns an error; failure crashes the program |
math/rand seeded with the time is random enough for tokens | It is predictable; use crypto/rand |
| The nonce must be secret | It must be unique, not secret; store it with the ciphertext |
| Encryption alone protects integrity | Only AEAD modes authenticate; plain CBC/CTR can be bit-flipped |
| SHA-512/256 is SHA-512 truncated | It has its own initial values; outputs are unrelated |
| bcrypt accepts any password length | It uses 72 bytes; x/crypto returns ErrPasswordTooLong for more |
| A longer RSA key lets me encrypt a file | OAEP only fits a few hundred bytes; encrypt a data key |
| FIPS mode makes code safer | It is a compliance mode; fips140=only is not for production |
maphash output can be stored | The seed is per process; stored hashes would never match again |
| ECDH output is a ready key | Run it through HKDF first |
Cheat sheet
| Topic | Remember |
|---|---|
| Streaming hash | io.Copy(sha256.New(), r) then h.Sum(nil) |
| One-shot | sha256.Sum256(b) returns [32]byte; use sum[:] |
| MAC compare | hmac.Equal, never == |
| Secret compare | subtle.ConstantTimeCompare(a, b) == 1; hash first if lengths are secret |
| Password, new | Argon2id 64 MiB, t=3, p=4, 16-byte salt, PHC string |
| Password, legacy | bcrypt cost 10+, 72-byte limit, migrate on login |
| FIPS password | PBKDF2-HMAC-SHA-256, 600,000+ iterations |
| Keys from a key | hkdf.Key(sha256.New, secret, salt, info, n) with a distinct info |
| Tokens | 32 bytes from rand.Read, base64url; store the hash |
| Encrypt | AES-256-GCM random 12-byte nonce, or XChaCha20-Poly1305; bind with aad |
| Key limit | 2^32 random-nonce GCM messages per key |
| Sign | Ed25519 default; ECDSA P-256 for interop; RSA-PSS legacy |
| Key files | PKCS#8 PRIVATE KEY, PKIX PUBLIC KEY; type-assert after parse |
| FIPS | GOFIPS140=v1.0.0 at build; GODEBUG=fips140=on at run |
| Avoid | MD5, SHA-1, DSA, DES, RC4, CFB/OFB, PKCS#1 v1.5 encryption, ECB |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is sha256.Sum256([]byte(password)) a bad password hash even with a salt? Must-know
Answer
Answer: It is fast, so an attacker can test billions of guesses per second on GPUs; a salt only stops precomputed tables. Use argon2.IDKey or bcrypt. See Password hashing.
2 — What exactly does hmac.Equal protect against that bytes.Equal does not? Important
Answer
Answer: Timing side channels. bytes.Equal can return at the first differing byte, so response time reveals how many leading bytes were right. hmac.Equal takes the same time regardless. See HMAC and constant-time comparison.
3 — You get bcrypt: password length exceeds 72 bytes. What are your options? Important
Answer
Answer: Use Argon2id instead (no such limit), or, to keep bcrypt, pre-hash the password (for example SHA-256 then base64, so no NUL bytes) before bcrypt, or enforce a maximum length at registration. Never rely on silent truncation.
4 — Why does reusing a GCM nonce under one key break confidentiality? Must-know
Answer
Answer: The same keystream encrypts both messages, so c1 XOR c2 = p1 XOR p2. A known plaintext reveals the other, and the authentication key can be recovered too. The TestNonceReuseLeaksXOR test demonstrates it. See Nonce reuse and ECB.
5 — What changed about crypto/rand.Read in Go 1.24? Good to know
Answer
Answer: It is guaranteed not to fail: it always returns a nil error and crashes the program irrecoverably if the source fails. rand.Text was added in the same release.
6 — When is cipher.NewGCMWithRandomNonce the better call than NewGCM? Important
Answer
Answer: When you want the library to generate and prepend the 12-byte nonce (28-byte overhead). The cost is the documented limit of 2^32 messages per key, so rotate keys. See Authenticated encryption.
7 — How do you upgrade stored bcrypt hashes to Argon2id without a password reset? Important
Answer
Answer: Verify with bcrypt at login; on success compute HashArgon2id from the plaintext in hand and store it with a guarded UPDATE ... WHERE password_hash = old. See Rehash on login.
8 — Why must ECDH output go through HKDF? Important
Answer
Answer: The raw shared point is not uniformly random bytes and carries no context. HKDF extracts a uniform key and the info label binds it to a purpose. See Public-key encryption and key agreement.
9 — A function returns any from x509.ParsePKCS8PrivateKey. What must you do next, and why? Important
Answer
Answer: Type-assert to the one key type you accept (ed25519.PrivateKey). Accepting any key type lets an attacker or a misconfiguration substitute a weaker algorithm.
10 — What does GODEBUG=fips140=only do, and why not in production? Good to know
Answer
Answer: It makes non-approved algorithms return errors or panic. The Go documentation calls it a best-effort testing mode that "introduces crashes and potentially unhandled errors by design". Use GOFIPS140 at build time instead.
For PHP/Laravel developers
Go exposes primitives; PHP and Laravel wrap them in higher-level functions. The mapping:
| PHP | Go |
|---|---|
password_hash($pw, PASSWORD_ARGON2ID) | argon2.IDKey plus your own PHC encoding (this page's HashArgon2id) |
password_hash($pw, PASSWORD_BCRYPT) | bcrypt.GenerateFromPassword |
password_verify | bcrypt.CompareHashAndPassword or VerifyArgon2id |
password_needs_rehash | NeedsRehash (you write the policy) |
hash_hmac('sha256', $d, $k) | hmac.New(sha256.New, k) |
hash_equals | hmac.Equal or subtle.ConstantTimeCompare |
random_bytes(32) | rand.Read from crypto/rand |
sodium_crypto_secretbox | golang.org/x/crypto/nacl/secretbox, or AEAD as above |
openssl_encrypt($d, 'aes-256-gcm', $k, 0, $iv, $tag) | cipher.NewGCM + Seal (tag is appended) |
Laravel Hash::make, Crypt::encryptString | Your own wrappers; Laravel's encrypted payload is its own JSON envelope, so Go cannot read it without re-implementing that format |
// PHP: the same three jobs
$hash = password_hash($password, PASSWORD_ARGON2ID); // PHC string, salt included
if (password_verify($password, $hash) && password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
$hash = password_hash($password, PASSWORD_ARGON2ID); // rehash on login
}
$ok = hash_equals(hash_hmac('sha256', $body, $secret), $header); // constant timePHP's password_hash reads and writes the same PHC-style strings as the Go code here, so a PHP $argon2id$ hash verifies in Go and the reverse (with the same parameters encoded in the string). Interoperating openssl_encrypt with Go means agreeing on nonce placement and tag position; PHP returns the tag in a separate variable, Go appends it.
Glossary
| Term | Meaning |
|---|---|
hash.Hash | Interface: an io.Writer plus Sum, Reset, Size, BlockSize |
| Digest | The fixed-size output of a hash |
| Streaming | Feeding data in chunks with io.Copy instead of loading it |
| SHA-256 / SHA-512 | SHA-2 hashes with 32 / 64-byte outputs |
| SHA-512/256 | SHA-512 with its own IVs, truncated to 256 bits |
SHA-3 / crypto/sha3 | Sponge-based hash (FIPS 202), standard library since Go 1.24 |
| SHAKE | SHA-3 extendable-output function: choose the output length |
| BLAKE2 | Fast hash family with a keyed mode, in x/crypto/blake2b |
| Length extension | Computing `H(m |
| Non-cryptographic hash | fnv, crc32, maphash: speed and spread, no attacker model |
Seed (maphash) | Random per-process value; makes hashes unstable across runs |
| HMAC | Keyed hash (RFC 2104); proves the sender held the key |
hmac.Equal | Constant-time MAC comparison |
subtle.ConstantTimeCompare | Constant-time byte comparison returning 1 or 0 |
| Timing attack | Learning a secret from how long a comparison takes |
| Salt | Random per-hash value stored beside the hash; defeats precomputed tables |
| bcrypt cost | log2 of the number of rounds, 4 to 31 |
| 72 bytes | The password length bcrypt reads |
| Argon2id | Memory-hard password hash (RFC 9106) |
argon2.IDKey | Go function computing Argon2id |
| PHC string | $argon2id$v=19$m=...,t=...,p=...$salt$hash |
| scrypt | Memory-hard KDF with N, r, p |
| PBKDF2 | Iterated HMAC KDF, crypto/pbkdf2 since Go 1.24 |
| Rehash on login | Upgrading a hash after a successful verify |
| HKDF | Extract-and-expand key derivation (RFC 5869) |
info | HKDF label that separates derived keys |
crypto/rand | OS-backed cryptographically secure random source |
rand.Text | 26-character base32 secure string (Go 1.24) |
| Secure token | 32 random bytes encoded as base64url |
| base64url | Base64 variant safe for URLs and cookies (RawURLEncoding) |
| AEAD | Authenticated encryption with associated data |
Seal / Open | AEAD encrypt-and-tag / verify-and-decrypt |
| Nonce | Number used once per message under one key |
| Associated data (aad) | Authenticated but unencrypted context |
| AES-GCM | AEAD mode of AES; cipher.NewGCM |
| XChaCha20-Poly1305 | AEAD with a 24-byte nonce, chacha20poly1305.NewX |
| ECB | Per-block encryption that leaks repeated blocks; avoid |
| Ed25519 | EdDSA signature scheme, 64-byte signatures |
| ECDSA P-256 | NIST-curve signatures, DER-encoded |
| RSA-OAEP / RSA-PSS | Modern RSA encryption / signature paddings |
| ECDH / X25519 | Elliptic-curve key agreement |
| Envelope encryption | Data key encrypts data; a master key wraps the data key |
| PEM | Base64 text wrapper with BEGIN/END lines |
| PKCS#8 / PKIX | Standard encodings for private / public keys |
| FIPS 140-3 | US/Canada cryptographic module standard |
GOFIPS140 | Build variable selecting the Go Cryptographic Module |
| Pepper | Application-wide secret mixed into password hashing, kept outside the database |
References
- Go 1.24 release notes (crypto additions,
rand.Read,NewGCMWithRandomNonce, FIPS): go.dev/doc/go1.24; also Go 1.22, Go 1.25, Go 1.26 - FIPS 140-3: Go FIPS 140-3 documentation, blog The FIPS 140-3 Go Cryptographic Module
- Go source (read for behaviour): crypto/rand/rand.go, crypto/cipher/gcm.go, crypto/hmac/hmac.go, crypto/subtle/constant_time.go, crypto/x509/pkcs8.go, crypto/sha256/sha256.go
golang.org/x/cryptosource: bcrypt.go, argon2.go- Package documentation (
hash,crypto/*,math/rand/v2) was read withgo docon Go 1.27.4 because pkg.go.dev answers automated clients with HTTP 403; the same text is published at pkg.go.dev/crypto. - Standards: RFC 9106 Argon2, RFC 2104 HMAC, RFC 5869 HKDF, RFC 8439 ChaCha20-Poly1305, RFC 8032 Ed25519, NIST SP 800-38D GCM
- OWASP: Password Storage Cheat Sheet
- PHP manual: password_hash, hash_hmac, openssl_encrypt, sodium_crypto_secretbox
- Style and review guidance: Go Code Review Comments