Argon2 Password Hashing
Hash passwords with Argon2id and a random salt, encode parameters into a PHC string, and verify in constant time.
Code
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime = 1
argonMemory = 64 * 1024
argonThreads = 4
argonKeyLen = 32
argonSaltLen = 16
)
func HashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("read salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return fmt.Sprintf(
"$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
argonMemory,
argonTime,
argonThreads,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
), nil
}
func VerifyPassword(password, encoded string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, fmt.Errorf("unsupported hash format")
}
var memory uint32
var timeCost uint32
var threads uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
return false, fmt.Errorf("parse parameters: %w", err)
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, fmt.Errorf("decode salt: %w", err)
}
want, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, fmt.Errorf("decode hash: %w", err)
}
got := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(want)))
return subtle.ConstantTimeCompare(got, want) == 1, nil
}
func main() {
encoded, err := HashPassword("correct horse battery staple")
if err != nil {
panic(err)
}
fmt.Println("encoded prefix:", encoded[:10])
match, err := VerifyPassword("correct horse battery staple", encoded)
if err != nil {
panic(err)
}
reject, err := VerifyPassword("wrong password", encoded)
if err != nil {
panic(err)
}
fmt.Println("match:", match, "reject:", reject)
}How the snippet works
Argon2 Password Hashing comes down to the functions HashPassword, VerifyPassword and main.
Every fallible call checks err != nil (7 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- External dependency:
golang.org/x/crypto/argon2— install it before running the snippet. - Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
Signature: func HashPassword(password string) (string, error)
Running the file prints labeled results such as encoded prefix:, match: — each operation’s effect is visible in the output.
Running the file executes main, which drives HashPassword and VerifyPassword in order.
Statements that carry the weight
return false, fmt.Errorf("parse parameters: %w", err)
return false, fmt.Errorf("decode salt: %w", err)
return false, fmt.Errorf("decode hash: %w", err)
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.
FAQ
- How are errors reported?
- As returned `error` values, checked at 7 sites — callers must branch on `err` before using the other return values. When a call fails in the entry flow, the run aborts via `panic(err)`.
- Do I need to install anything before running this?
- Yes: `golang.org/x/crypto/argon2` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.