Skip to content

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 forGo to
One table per job, memorisableEverything in one minute
Why the standard library looks the way it doesWhy it exists
Go 1.24 changes, FIPS, x/crypto splitWhere it comes from
hash.Hash, io.Copy into sha256.New()hash.Hash and streaming
SHA-256, SHA-512/256, SHA-3, BLAKE2SHA-2, SHA-3 and BLAKE2
hash/fnv, hash/crc32, hash/maphashNon-cryptographic hashes
hmac.Equal, subtle.ConstantTimeCompare, timing attacksHMAC and constant-time comparison
bcrypt cost, the 72-byte limit, argon2.IDKey, scrypt, PBKDF2Password hashing
Upgrading old hashes without a reset campaignRehash on login
crypto/hkdf, one secret to many keysKey derivation with HKDF
rand.Read, rand.Text, rand.Int, secure tokenscrypto/rand and secure tokens
cipher.NewGCM, AEAD.Seal/Open, ChaCha20-Poly1305Authenticated encryption
Why a repeated nonce destroys GCMNonce reuse and ECB
ed25519, ecdsa P-256, RSA PSSSignatures
RSA OAEP and crypto/ecdhPublic-key encryption and key agreement
PEM, PKCS#8, x509.MarshalPKCS8PrivateKeyEncoding keys
GOFIPS140, GODEBUG=fips140=onFIPS 140-3 mode
MD5, SHA-1, DSA, RC4, DES, CFB/OFBDeprecated and dangerous
Exact error textsError texts decoded
The tested snippets, step by stepSolving the classic problems
PHP password_hash, hash_hmac, sodium, opensslFor PHP/Laravel developers
Which primitive for which jobChoosing
Keys, rotation and servicesIn architecture
Run it on your machineLab

Everything in one minute ​

JobGo callParameter that mattersNever
Fingerprint a file or blobio.Copy(sha256.New(), f) then Sum(nil)SHA-256 or SHA-512/256Read the whole file into memory first
Prove a message came from a key holderhmac.New(sha256.New, key), compare with hmac.EqualKey of 32 random bytes== or bytes.Equal on tags
Store a passwordargon2.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 secrethkdf.Key(sha256.New, secret, salt, info, n)A distinct info per purposeReuse one key for encryption and MAC
Make a token, nonce, salt or keyrand.Read(b) or rand.Text()32 bytes for a tokenmath/rand for anything secret
Encrypt datacipher.NewGCM or chacha20poly1305.NewXFresh nonce per messageECB, CBC without a MAC, a reused nonce
Sign for others to verifyed25519.SignVerify with ed25519.VerifyVerify with only a length check
Agree on a shared keyecdh.X25519() then HKDFUse the output as HKDF inputUse the raw ECDH bytes as a key
Satisfy a FIPS 140-3 requirementGOFIPS140=v1.0.0 go buildModule versionSet GODEBUG=fips140=only in production
Hash familyOutputPackageWhen
SHA-25632 bytescrypto/sha256Default digest for integrity and content addressing
SHA-51264 bytescrypto/sha51264-bit CPUs, bigger margin
SHA-512/25632 bytessha512.Sum512_256SHA-256 size without length-extension
SHA-3-25632 bytescrypto/sha3 (Go 1.24)Different design, SHAKE outputs
BLAKE2b-25632 bytesgolang.org/x/crypto/blake2bFast, keyed mode built in
CRC-32C4 byteshash/crc32Corruption detection, not security
FNV-1a 648 byteshash/fnvSimple hash tables, not security
maphash8 byteshash/maphashIn-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 choiceWeaker alternativeWhat Go does
One interface for all hashesA function per algorithmhash.Hash is an io.Writer: stream anything into it
Authenticated encryption as the defaultBlock cipher modes you assemblecipher.AEAD: Seal and Open, one error for any tampering
Constant-time compare in the libraryDeveloper remembers to avoid ==hmac.Equal, subtle.ConstantTimeCompare
Random source in one placerand.Seed(time)crypto/rand uses the OS CSPRNG; Read cannot fail since 1.24
Experimental algorithms outside the stdlibEverything 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 ​

  1. "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.
  2. "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.AEAD and nothing else.
  3. "A random-looking string from math/rand is a token." math/rand (and math/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 from crypto/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.

text
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 object

Real 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.

QuestionAnswer
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.

go
// 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.

text
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 state

Real 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.

HashGo APISizeLength-extension safeFIPS 140-3 approved
SHA-256sha256.New, sha256.Sum25632No (use HMAC)Yes
SHA-512sha512.New, sha512.Sum51264No (use HMAC)Yes
SHA-512/256sha512.New512_256, Sum512_25632YesYes
SHA-3-256sha3.New256, sha3.Sum25632YesYes
SHAKE256sha3.NewSHAKE256, SumSHAKE256(data, n)anyYesYes
BLAKE2b-256blake2b.New256(key)32YesNo
MD5, SHA-1crypto/md5, crypto/sha116, 20n/aNot 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.

text
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 data

Real 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).

HashStable across runsFastAttack-resistantUse for
hash/fnvYesYesNoStable bucketing of trusted keys
hash/crc32YesHardware speedNoCorruption checks, framing
hash/maphashNo (random seed)YesAgainst flooding onlyIn-process maps and sketches
crypto/sha256YesSlowerYesAnything 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.

text
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 same

Real 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.

ComparisonConstant timeNotes
a == b on stringsNoEarly exit
bytes.Equal(a, b)NoEarly exit
hmac.Equal(a, b)YesFor MACs; the standard-library choice
subtle.ConstantTimeCompare(a, b) == 1Yes (given equal lengths)Hash both sides first if the length is secret
bcrypt.CompareHashAndPasswordYes insideDo 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.

go
// 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).

text
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 time

Real 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).

FunctionCost knobMemory-hardGo packageTypical 2025 settingLimits
Argon2idtime, memory, threadsYesx/crypto/argon2m=64 MiB, t=3, p=4 (RFC 9106 option 2); OWASP minimum 19 MiB, t=2, p=1Needs memory per concurrent login
bcryptcost (log2 rounds)No (4 KiB state)x/crypto/bcryptcost 10 minimum (OWASP), 12 common72-byte password limit
scryptN, r, pYesx/crypto/scryptN=2^17, r=8, p=1 (OWASP minimum)Tuning three knobs
PBKDF2-HMAC-SHA-256iterationsNocrypto/pbkdf2 (1.24)600,000 or moreCheap 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.

go
// 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.

POST /loginemail + passwordSELECT hashusers WHERE emailVerifyprefix $2a$ → bcryptprefix $argon2id$ → Argon2idmismatch401, same messageand similar timingmatchweaker thanpolicy?yesRehash nowArgon2id(m,t,p) from theplaintext in memoryUPDATE users SET hashWHERE id AND hash = oldnoIssue session; row unchangedThe plaintext exists only during this request. Passwords that never log in again keep their old hash.
text
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, ignored

Real 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.

sql
-- 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.

text
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 other

Real 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.

go
// 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.

text
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 digest

Real 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).

NeedUseOutput
256-bit URL-safe tokenrand.Read 32 bytes, base64.RawURLEncoding43 characters
Convenient 128-bit tokenrand.Text()26 base32 characters
Uniform number below nrand.Int(rand.Reader, big.NewInt(n))*big.Int
Salt for a password hashrand.Read 16 bytes16 bytes
Simulation, shuffling a playlistmath/rand/v2Not secret

Fix: the token package, with a test that checks length, alphabet and uniqueness:

go
// 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.

Stored value = nonce || ciphertext || tagnonce12 bytes, randomciphertextsame length as the plaintext (CTR keystream XOR)tag16 bytes (GHASH)Associated data (aad)tenant=7, row id: not storedfeeds the tag, never the ciphertextRules for the noncenever repeat under one key: reuse leaks the XOR of plaintextsrandom 96-bit is safe up to about 2^32 messages per keyOpen(nonce, ciphertext, tag, aad)1. recompute the tag over aad and ciphertext2. constant-time compare with the stored tag3. equal: decrypt and return the plaintext4. any bit differs: no plaintext at all, error"cipher: message authentication failed"
text
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.

PrimitiveKeyNonceTagRandom nonce safe?Prefer when
AES-GCM (NewGCM)16/24/32 bytes12 bytes16Up to about 2^32 messages per keyAES hardware, FIPS
AES-GCM random nonce (NewGCMWithRandomNonce)16/24/3212 (hidden)16Enforced limit 2^32Simplest API (Go 1.24)
ChaCha20-Poly1305321216Risky at high volumeSoftware speed, TLS
XChaCha20-Poly1305 (NewX)322416YesMany 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:

go
// 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.

text
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 key

Real 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.

MistakeEffectPrevention
Fixed or zero noncePlaintext XOR leaks; forgeryRandom nonce per Seal
Counter reset after restoreSameRandom nonce or XChaCha20
ECB (looping Block.Encrypt)Equal blocks visibleUse AEAD, never raw blocks
CBC or CTR without a MACBit-flipping, padding oraclesAEAD
Key used past 2^32 messagesRandom nonce collisionRotate 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.

text
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 steps

Real 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.

SchemeSignature sizeKey sizeNotes
Ed2551964 bytes32-byte publicDefault for new systems; deterministic
ECDSA P-256about 70-72 bytes (DER)65-byte public (uncompressed)Interop with JWT ES256, TLS, WebAuthn
RSA-PSS 2048256 bytes256-byte modulusLegacy interop; 3072-bit for new long-lived keys
RSA PKCS#1 v1.5256 bytessameOnly 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.

text
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 key

Real 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.

go
// 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.

text
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 type

Real 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).

go
// 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.

text
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) fail

Real 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.

go
// 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 functionStatus in the docsUse 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/dsaDeprecated: "DSA is a legacy algorithm"crypto/ed25519
crypto/des, crypto/rc4"cryptographically broken"AES-GCM, ChaCha20-Poly1305
rsa.EncryptPKCS1v15Deprecated: "PKCS #1 v1.5 encryption is dangerous"rsa.EncryptOAEP
cipher.NewCFBEncrypter, NewOFBDeprecated in Go 1.24: not authenticatedcipher.AEAD, or NewCTR if a stream is unavoidable
x509.EncryptPEMBlockDeprecated: legacy PEM encryption is insecurePKCS#8 encrypted with a modern KDF, or a secret manager
RSA keys under 1024 bitsRefused since 1.24 (rsa1024min=0 restores)2048-bit minimum, 3072 for new long-lived keys

Mechanics ​

Package map and versions Must-know ​

TaskStandard library (version)golang.org/x/crypto
SHA-2crypto/sha256, crypto/sha512none
SHA-3, SHAKEcrypto/sha3 (1.24)sha3 (older)
BLAKE2noneblake2b, blake2s
HMACcrypto/hmacnone
Password hashcrypto/pbkdf2 (1.24)bcrypt, argon2, scrypt
HKDFcrypto/hkdf (1.24)hkdf (older)
AEADcrypto/cipher (AES-GCM)chacha20poly1305
Signaturescrypto/ed25519, crypto/ecdsa, crypto/rsanone
Key agreementcrypto/ecdhcurve25519 (older)
Randomcrypto/randnone
Constant timecrypto/subtlenone
FIPScrypto/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).

TextCauseFix
crypto/aes: invalid key size 5Key not 16, 24 or 32 bytesDerive or generate exactly 32 bytes
crypto/cipher: incorrect nonce length given to GCM (panic)Nonce is not 12 bytesmake([]byte, gcm.NonceSize())
cipher: message authentication failedWrong key, nonce, aad, or tampered dataTreat as tampering; do not reveal which
bcrypt: password length exceeds 72 bytesPassword longer than bcrypt readsPre-hash with SHA-256 and base64 (a documented workaround), or use Argon2id
crypto/rsa: message too long for RSA key sizeOAEP plaintext larger than the modulus allowsEncrypt a data key, not the document
crypto/rsa: decryption errorWrong key, label or corrupted ciphertextIntentionally uninformative
crypto/rsa: 512-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size)Key below 1024 bitsUse 2048 or more
crypto/ecdh: bad X25519 remote ECDH input: low order pointPeer sent a degenerate public keyAbort the handshake
x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format)PKCS#1 bytes given to the PKCS#8 parserParse by PEM type

Timing, in numbers Good to know ​

OperationCostSource
bcrypt cost 10 / 12 / 1465 ms / 183 ms / 740 msLab run on the author's machine
Argon2id 64 MiB, t=3, p=427 msLab run on the author's machine
Each bcrypt cost stepdoubles the workbcrypt package documentation
Random-nonce GCM message limit2^32 per keycipher.NewGCMWithRandomNonce source
Six-digit code10^6 values, about 20 bitsarithmetic

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.

go
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 ​

StepCallWhere
Registerpassword.HashArgon2id(pw, password.Default)password/password.go
Loginpassword.Verify(pw, stored, password.Default)same
Persist upgradeUPDATE ... WHERE password_hash = oldSQL above
Reject over-long inputcheck length before hashing (cap at e.g. 1024 bytes to bound CPU)handler
Rate limitper account and per IPRate 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 ​

text
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 success

A 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 ​

What must hold?Same bytes as before?(no attacker)Secret stays secret orcomes from a secretWho sent it, was itchanged? (attacker)Hash (hash.Hash)table / shard / sketch:hash/maphash, hash/fnvcorruption check:hash/crc32 (Castagnoli)content fingerprint, ETag:sha256, sha512, sha3,blake2bMD5 and SHA-1: not foranything adversarialSecrets and keysstore a password:argon2.IDKey, bcryptlegacy KDF: scrypt, pbkdf2many keys from one key:hkdfencrypt: AES-GCM,XChaCha20-Poly1305random: crypto/randAuthenticityshared key:hmac + hmac.Equalpublic key signature:ed25519 (default),ecdsa P-256 (interop)RSA-PSS (legacy)key agreement: ecdhthen hkdf
SituationChooseExtra techniqueReason
Hash a file or streamSHA-256 via io.Copyio.TeeReader for inline hashingOne pass, constant memory
Authenticate a message with a shared keyHMAC-SHA-256, hmac.EqualInclude a timestamp and an ID to stop replayForgery needs the key
Password storage, new systemArgon2id 64 MiB, t=3, p=4Rehash on login; per-user random saltMemory-hard, RFC 9106
Password storage, FIPS requiredPBKDF2-HMAC-SHA-256, 600,000+ iterationsSameApproved algorithm
Existing bcrypt estateKeep bcrypt cost 10+; migrate on loginReject over 72 bytes explicitlyNo reset campaign
Random identifiers and tokenscrypto/rand 32 bytes, base64urlStore a hash of itUnguessable, safe at rest
Encrypt data with a key you holdAES-256-GCM or XChaCha20-Poly1305aad binding to the recordIntegrity plus secrecy
Encrypt to someone's public keyECDH (X25519) + HKDF + AEADRSA-OAEP only for legacyShort, fast, standard
SignaturesEd25519ECDSA P-256 for ES256 interopSmall, simple API
Quick checksum of trusted dataCRC-32C or FNVnoneSpeed; 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 ​

text
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 lifetime

What 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× ​

LoadWhat breaks firstChange
1× (hundreds of logins a day)Nothing; defaults workArgon2id 64 MiB, one key in an env file
10× (logins per second)CPU and memory from password hashing; login latencyBound concurrency; dedicated auth pods; rate limit; keep parameters
100× (many services, many tenants)Key distribution, rotation, nonce uniquenessKMS 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.

text
cd docs/snippets/go/hashing-crypto/go
go test ./...
go run ./lab
go run ./fips
GODEBUG=fips140=on go run ./fips

Real output from the author's machine (Apple silicon, Go 1.27.4, go 1.24.0 module; timings vary):

text
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 bytes
text
fips140.Enabled=false sha256(abc)=ba7816bf
fips140.Enabled=true sha256(abc)=ba7816bf

Experiments (expected results; the first four are asserted by the test suite, which was run):

#Do thisExpected
1go test ./aead -run NonceReuse -vPasses: XOR of ciphertexts equals XOR of plaintexts
2Edit Open to flip one byte of the ciphertext and run go test ./aeadcipher: message authentication failed
3go test ./password -run Bcrypt -v73-byte input returns bcrypt: password length exceeds 72 bytes
4go test ./password -run Rehash -vbcrypt hash upgrades to $argon2id$ once, then no rewrite
5Set 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 targetfalse: a stronger hash is never downgraded
6go build -o app ./fips && GODEBUG=fips140=only ./app (expected, not run)Runs; non-approved algorithms would fail

Common misconceptions ​

BeliefReality
SHA-256 is fine for passwordsIt is fast by design; use Argon2id, scrypt or bcrypt
== on two MACs is fineEarly exit leaks the matching prefix length; use hmac.Equal
rand.Read can fail, so I must handle the errorSince Go 1.24 it never returns an error; failure crashes the program
math/rand seeded with the time is random enough for tokensIt is predictable; use crypto/rand
The nonce must be secretIt must be unique, not secret; store it with the ciphertext
Encryption alone protects integrityOnly AEAD modes authenticate; plain CBC/CTR can be bit-flipped
SHA-512/256 is SHA-512 truncatedIt has its own initial values; outputs are unrelated
bcrypt accepts any password lengthIt uses 72 bytes; x/crypto returns ErrPasswordTooLong for more
A longer RSA key lets me encrypt a fileOAEP only fits a few hundred bytes; encrypt a data key
FIPS mode makes code saferIt is a compliance mode; fips140=only is not for production
maphash output can be storedThe seed is per process; stored hashes would never match again
ECDH output is a ready keyRun it through HKDF first

Cheat sheet ​

TopicRemember
Streaming hashio.Copy(sha256.New(), r) then h.Sum(nil)
One-shotsha256.Sum256(b) returns [32]byte; use sum[:]
MAC comparehmac.Equal, never ==
Secret comparesubtle.ConstantTimeCompare(a, b) == 1; hash first if lengths are secret
Password, newArgon2id 64 MiB, t=3, p=4, 16-byte salt, PHC string
Password, legacybcrypt cost 10+, 72-byte limit, migrate on login
FIPS passwordPBKDF2-HMAC-SHA-256, 600,000+ iterations
Keys from a keyhkdf.Key(sha256.New, secret, salt, info, n) with a distinct info
Tokens32 bytes from rand.Read, base64url; store the hash
EncryptAES-256-GCM random 12-byte nonce, or XChaCha20-Poly1305; bind with aad
Key limit2^32 random-nonce GCM messages per key
SignEd25519 default; ECDSA P-256 for interop; RSA-PSS legacy
Key filesPKCS#8 PRIVATE KEY, PKIX PUBLIC KEY; type-assert after parse
FIPSGOFIPS140=v1.0.0 at build; GODEBUG=fips140=on at run
AvoidMD5, SHA-1, DSA, DES, RC4, CFB/OFB, PKCS#1 v1.5 encryption, ECB

Self-check: questions & answers ​

Show:
  • 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:

PHPGo
password_hash($pw, PASSWORD_ARGON2ID)argon2.IDKey plus your own PHC encoding (this page's HashArgon2id)
password_hash($pw, PASSWORD_BCRYPT)bcrypt.GenerateFromPassword
password_verifybcrypt.CompareHashAndPassword or VerifyArgon2id
password_needs_rehashNeedsRehash (you write the policy)
hash_hmac('sha256', $d, $k)hmac.New(sha256.New, k)
hash_equalshmac.Equal or subtle.ConstantTimeCompare
random_bytes(32)rand.Read from crypto/rand
sodium_crypto_secretboxgolang.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::encryptStringYour own wrappers; Laravel's encrypted payload is its own JSON envelope, so Go cannot read it without re-implementing that format
php
// 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 time

PHP'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 ​

TermMeaning
hash.HashInterface: an io.Writer plus Sum, Reset, Size, BlockSize
DigestThe fixed-size output of a hash
StreamingFeeding data in chunks with io.Copy instead of loading it
SHA-256 / SHA-512SHA-2 hashes with 32 / 64-byte outputs
SHA-512/256SHA-512 with its own IVs, truncated to 256 bits
SHA-3 / crypto/sha3Sponge-based hash (FIPS 202), standard library since Go 1.24
SHAKESHA-3 extendable-output function: choose the output length
BLAKE2Fast hash family with a keyed mode, in x/crypto/blake2b
Length extensionComputing `H(m
Non-cryptographic hashfnv, crc32, maphash: speed and spread, no attacker model
Seed (maphash)Random per-process value; makes hashes unstable across runs
HMACKeyed hash (RFC 2104); proves the sender held the key
hmac.EqualConstant-time MAC comparison
subtle.ConstantTimeCompareConstant-time byte comparison returning 1 or 0
Timing attackLearning a secret from how long a comparison takes
SaltRandom per-hash value stored beside the hash; defeats precomputed tables
bcrypt costlog2 of the number of rounds, 4 to 31
72 bytesThe password length bcrypt reads
Argon2idMemory-hard password hash (RFC 9106)
argon2.IDKeyGo function computing Argon2id
PHC string$argon2id$v=19$m=...,t=...,p=...$salt$hash
scryptMemory-hard KDF with N, r, p
PBKDF2Iterated HMAC KDF, crypto/pbkdf2 since Go 1.24
Rehash on loginUpgrading a hash after a successful verify
HKDFExtract-and-expand key derivation (RFC 5869)
infoHKDF label that separates derived keys
crypto/randOS-backed cryptographically secure random source
rand.Text26-character base32 secure string (Go 1.24)
Secure token32 random bytes encoded as base64url
base64urlBase64 variant safe for URLs and cookies (RawURLEncoding)
AEADAuthenticated encryption with associated data
Seal / OpenAEAD encrypt-and-tag / verify-and-decrypt
NonceNumber used once per message under one key
Associated data (aad)Authenticated but unencrypted context
AES-GCMAEAD mode of AES; cipher.NewGCM
XChaCha20-Poly1305AEAD with a 24-byte nonce, chacha20poly1305.NewX
ECBPer-block encryption that leaks repeated blocks; avoid
Ed25519EdDSA signature scheme, 64-byte signatures
ECDSA P-256NIST-curve signatures, DER-encoded
RSA-OAEP / RSA-PSSModern RSA encryption / signature paddings
ECDH / X25519Elliptic-curve key agreement
Envelope encryptionData key encrypts data; a master key wraps the data key
PEMBase64 text wrapper with BEGIN/END lines
PKCS#8 / PKIXStandard encodings for private / public keys
FIPS 140-3US/Canada cryptographic module standard
GOFIPS140Build variable selecting the Go Cryptographic Module
PepperApplication-wide secret mixed into password hashing, kept outside the database

References ​

Built by Morteza Negahi