Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 147 ยท Standard Library

Hashing and Cryptography

Use Go's standard library for hashing and cryptography - SHA-256 and SHA-3, HMAC, secure random numbers, AES-GCM encryption, PBKDF2, constant-time comparison, fnv and maphash, and what not to build yourself.

Almost every program eventually touches security: checking that a downloaded file wasn't corrupted, signing a cookie, generating a session token, storing a password, encrypting a field. Go's standard library includes well-reviewed implementations of the common building blocks under crypto/ and hash/, with simple APIs that are hard to misuse.

The most valuable lesson here is not an API but a rule: use the standard building blocks and never invent your own cryptography. This lesson shows the pieces you will actually use, and is honest about which job needs which tool, because choosing the wrong one (a plain hash for passwords, math/rand for tokens) is how real vulnerabilities happen.

Hash functions

A hash function turns any amount of data into a fixed-size digest: the same input always gives the same digest, a tiny change gives a completely different one, and you can't practically go backwards or find two inputs with the same digest. Use it to check integrity, fingerprint content or build identifiers.

Go SHA-256 and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

crypto/sha256 and crypto/sha512 are the everyday choices; crypto/sha3 is in the standard library since Go 1.24. crypto/md5 and crypto/sha1 still exist for compatibility with old protocols and file checksums, but both are broken for security: attackers can create collisions, so never use them to verify anything an attacker might tamper with.

Hashing streams

Hash objects implement io.Writer, so you can feed them data piece by piece or with io.Copy and never hold a whole file in memory:

Go hash.Hash as an io.Writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

h.Sum(b) appends the digest to b; passing nil is the usual call.

HMAC: hashing with a secret key

A plain hash proves nothing about who made it: anyone can hash a modified message. An HMAC (hash-based message authentication code) mixes a secret key into the hash, so only a holder of the key can produce or verify the tag. It is the right tool for signing cookies, webhooks and API requests between services that share a secret.

When you check a tag, compare with hmac.Equal, which takes the same time no matter where the first difference is. A normal == leaks that information through timing:

Go Signing and verifying with HMAC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For comparing other secrets (tokens, API keys), crypto/subtle offers subtle.ConstantTimeCompare(a, b), which returns 1 when two byte slices are equal and examines all bytes either way.

Secure random numbers: crypto/rand

Tokens, keys, salts and nonces need unpredictable randomness. math/rand is fast but predictable, so it must never be used for security. crypto/rand reads from the operating system's cryptographically secure source:

Go crypto/rand for tokens and keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The values themselves are different on every run, so the example prints only lengths and properties. As of Go 1.24, rand.Read never returns an error in practice (it crashes the program if the system's random source fails), but checking the error is still good style for older versions. Use rand.Text() when you just need a random token string.

Encrypting data: AES-GCM

Encryption keeps data confidential. The modern recommendation for symmetric encryption (one shared key) is an AEAD mode such as AES-GCM, which encrypts and authenticates: if anyone changes a single byte of the ciphertext, decryption fails instead of returning garbage. Two rules matter:

  1. Use a fresh random nonce (a number used once) for every message with the same key, and store it next to the ciphertext. Reusing a nonce with GCM destroys its security.
  2. Keep the key secret and out of your source code.
Go AES-GCM round trip and tamper detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The twelve-byte nonce plus the sixteen-byte authentication tag explain why the sealed message is 28 bytes longer than the plaintext. Never use raw AES blocks (ECB), and avoid cipher.NewCBCEncrypter and friends in new code, since they provide no authentication. For public-key tasks, the standard library offers crypto/ed25519 for signatures, crypto/ecdh for key exchange and crypto/tls for network connections, but these are better learned with a dedicated protocol guide.

Passwords need special treatment

A fast hash like SHA-256 is a bad way to store passwords: attackers can try billions of guesses per second. Password storage needs a deliberately slow, salted key derivation function: bcrypt, scrypt, Argon2id or PBKDF2.

  • bcrypt, scrypt and argon2 live in the golang.org/x/crypto module, which is outside the standard library (it is maintained by the Go team, but you must go get it, so it can't run in our editor). The read-only sketch below is how bcrypt is normally used.
  • Since Go 1.24 the standard library has crypto/pbkdf2 (and crypto/hkdf), which are acceptable when you cannot add a dependency, with a high iteration count.
Go
import "golang.org/x/crypto/bcrypt"

hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
// store string(hash) in the database

err = bcrypt.CompareHashAndPassword(hash, []byte(attempt))
if err != nil {
	// wrong password
}

bcrypt generates a random salt for you and stores it inside the hash string, so you need only one database column. Here is a standard-library PBKDF2 version you can run:

Go PBKDF2 with a random salt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The salt (random bytes stored beside the hash) makes identical passwords hash differently and defeats precomputed tables. You store the salt, the iteration count and the hash.

Non-cryptographic hashes

Sometimes you just need a fast, well-spread number: for a hash table, sharding, a quick checksum or a cache key. The hash/ packages are made for that. They offer no security; an attacker can craft collisions.

Go fnv, crc32 and maphash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

fnv and crc32 give the same result everywhere, which is useful for stable sharding and file checksums. maphash follows the randomized-seed idea Go's own maps use; its values change every run, so never store them.

What not to roll yourself

  • Don't design your own cipher, hash or protocol. Combine tested primitives such as AES-GCM and HMAC.
  • Don't use math/rand for anything an attacker must not guess.
  • Don't use MD5 or SHA-1 for security, and don't use fast hashes for passwords.
  • Don't compare secrets with ==. Use hmac.Equal or subtle.ConstantTimeCompare.
  • Don't reuse nonces or hard-code keys; load keys from the environment or a secrets manager.
  • Prefer high-level tools such as TLS (crypto/tls), age, or your database's encryption over assembling primitives yourself.

Cryptography code that "works" in a test can still be completely insecure. When in doubt, use a vetted library or a managed service, and ask someone who does security for a living to review anything that protects real user data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does sha256.Sum256([]byte("a")) return?

    Sum256 returns a fixed-size [32]byte array. Format it with %x or hex.EncodeToString(sum[:]).
  2. 2. Why use hmac.Equal instead of == to compare two MACs?

    A normal comparison can stop at the first different byte, which leaks information through timing. Constant-time comparison does not.
  3. 3. Which package must you use to generate an API token?

    Only crypto/rand draws from the operating system's secure random source. The math packages are predictable.
  4. 4. What goes wrong if you encrypt two messages with AES-GCM using the same key and the same nonce?

    Nonce reuse with GCM can reveal data and allow forgeries. Generate a random nonce for every Seal call and store it with the ciphertext.
  5. 5. Why is plain SHA-256 a poor choice for storing passwords?

    Password hashing should be slow and salted (bcrypt, scrypt, Argon2id, PBKDF2) to make guessing expensive.

Summary

  • Hash functions (sha256, sha512, sha3) produce fixed-size digests; hash streams through the io.Writer interface. MD5 and SHA-1 are not safe for security.
  • Use HMAC (hmac.New) for authenticated tags with a shared secret, and hmac.Equal or subtle.ConstantTimeCompare to compare secrets.
  • Generate tokens, keys, salts and nonces with crypto/rand (rand.Read, rand.Text), never with math/rand.
  • Encrypt with AES-GCM: random nonce per message, key kept secret; tampering is detected on Open.
  • Store passwords with a slow, salted function: bcrypt/scrypt/argon2 from x/crypto, or crypto/pbkdf2 from the standard library.
  • hash/fnv, hash/crc32 and hash/maphash are fast non-cryptographic hashes for tables, checksums and sharding.
  • Compose proven primitives; do not invent your own cryptography.

Next: URLs and Network Basics moves from data protection to talking over the network.