crypto

package
v2.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 19 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package crypto contains the primitives theauth-go uses for password hashing (Argon2id), opaque session and reset tokens (crypto/rand plus SHA-256), AES-256-GCM symmetric encryption for OAuth tokens at rest, PKCE code verifier and S256 challenge generation, and salted SHA-256 recovery-code hashing.

The functions in this package are safe to call from multiple goroutines. They have no internal state. AES key inputs must be exactly 32 bytes (see AESKeyLen); pass shorter or longer slices and Encrypt and Decrypt return ErrInvalidKeyLength.

Index

Examples

Constants

View Source
const AESKeyLen = 32

AESKeyLen is the required key length in bytes for Encrypt/Decrypt (AES-256).

Variables

View Source
var ErrCiphertextTooShort = errors.New("theauth/crypto: ciphertext too short")

ErrCiphertextTooShort is returned when the supplied ciphertext is shorter than the GCM nonce, meaning it cannot be a valid Encrypt output.

View Source
var ErrInvalidKeyLength = errors.New("theauth/crypto: encryption key must be 32 bytes")

ErrInvalidKeyLength is returned when the supplied key is not exactly AESKeyLen.

View Source
var ErrInvalidPasswordHash = errors.New("crypto: invalid password hash")

ErrInvalidPasswordHash is returned by VerifyPassword when the stored PHC string cannot be parsed. Callers should treat this as a server-side fault, not a credential mismatch.

Functions

func CodeChallenge

func CodeChallenge(verifier string) string

CodeChallenge derives the S256 code challenge from a verifier per RFC 7636 section 4.2: challenge = base64url(sha256(ASCII(verifier))), no padding. Callers send this value as code_challenge with code_challenge_method=S256 on the authorize request, then send the original verifier as code_verifier on the token exchange. The provider recomputes and compares.

func Decrypt

func Decrypt(key, ciphertext []byte) ([]byte, error)

Decrypt reverses Encrypt: it splits off the 12-byte nonce prefix, then authenticates and decrypts the remainder. Returns an error if the key is the wrong length, the ciphertext is too short, or the authentication tag fails (wrong key or tampered ciphertext).

func DefaultHashConcurrency added in v2.8.0

func DefaultHashConcurrency() int

DefaultHashConcurrency is NumCPU divided by the Argon2id thread count, at least 1: enough to keep every core busy without queueing memory.

func Encrypt

func Encrypt(key, plaintext []byte) ([]byte, error)

Encrypt seals plaintext with AES-256-GCM and returns nonce || ciphertext. The 12-byte nonce is generated from crypto/rand and prepended so that Decrypt can split it back out without out-of-band metadata. key must be exactly 32 bytes (AES-256); other lengths return ErrInvalidKeyLength.

Example

ExampleEncrypt shows a round trip with a 32 byte key. The output of Encrypt is the random 12 byte nonce concatenated with the ciphertext and the GCM auth tag.

package main

import (
	"bytes"
	"fmt"

	"github.com/glincker/theauth-go/v2/crypto"
)

func main() {
	key := bytes.Repeat([]byte{0x42}, crypto.AESKeyLen)
	plaintext := []byte("hello, theauth")

	ciphertext, err := crypto.Encrypt(key, plaintext)
	if err != nil {
		panic(err)
	}
	got, err := crypto.Decrypt(key, ciphertext)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(got))
}
Output:
hello, theauth

func FormatPBKDF2Hash added in v2.8.0

func FormatPBKDF2Hash(algo string, iterations int, salt, key []byte) string

FormatPBKDF2Hash builds the stored string from raw salt and key bytes.

func GenerateRecoveryCode

func GenerateRecoveryCode() (string, error)

GenerateRecoveryCode draws recoveryCodeBytes from crypto/rand and returns the lowercase hex encoding (10 chars). Returned errors propagate any RNG failure; callers should bail on the whole enrollment.

func HashPassword

func HashPassword(plain string) (string, error)

HashPassword returns an argon2id PHC-formatted hash of the plain password. Format:

$argon2id$v=19$m=<KiB>,t=<iters>,p=<threads>$<base64(salt)>$<base64(hash)>

Salt is freshly random per call, two hashes of the same password differ.

func HashRecoveryCode

func HashRecoveryCode(code string) ([]byte, error)

HashRecoveryCode produces a 48-byte storage value laid out as salt(16) || sha256(salt || code)(32). The salt is per-code random, so two rows holding the same plaintext code produce different hashes. Pre-computed rainbow tables are defeated by the salt alone; the sha256 digest then sits behind a 2^40 brute-force barrier per row.

func HashToken

func HashToken(token string) []byte

HashToken returns sha256(token) as raw bytes, store this, never the token itself.

func IsBcryptHash

func IsBcryptHash(hash string) bool

IsBcryptHash reports whether hash looks like a bcrypt PHC string. Bcrypt hashes start with "$2a$", "$2b$", or "$2x$".

func IsLegacyHash added in v2.8.0

func IsLegacyHash(hash string) bool

IsLegacyHash reports whether hash is any non-Argon2id format theauth can verify during a migration window (bcrypt or PBKDF2).

func IsPBKDF2Hash added in v2.8.0

func IsPBKDF2Hash(hash string) bool

IsPBKDF2Hash reports whether hash is a legacy PBKDF2 string.

func NeedsRehash added in v2.8.0

func NeedsRehash(phc string) bool

NeedsRehash reports whether phc is a well-formed argon2id hash whose memory, time or thread cost is below the current defaults, so callers can transparently upgrade it after a successful login. Malformed hashes and hashes at or above the current cost report false.

func NewCodeVerifier

func NewCodeVerifier() (string, error)

NewCodeVerifier returns a fresh PKCE code verifier suitable for an authorization code exchange per RFC 7636. The result is 43 base64url (no-pad) characters of cryptographically random data, which sits at the low end of the [43,128] legal range.

func NewToken

func NewToken() (string, error)

NewToken returns a 32-byte cryptographically random token, URL-safe-base64-encoded.

func SetHashConcurrency added in v2.8.0

func SetHashConcurrency(n int)

SetHashConcurrency bounds how many Argon2id hashes or verifications run at once; further callers wait their turn. n <= 0 restores the default. Computations already running finish under the previous bound.

func VerifyLegacyBcrypt

func VerifyLegacyBcrypt(plain, hash string) (bool, error)

VerifyLegacyBcrypt checks plain against a bcrypt hash. It returns true when the password matches and false when it does not. An error is returned only for malformed hashes (e.g. wrong version byte), not for mismatches.

This function is used during the Auth0 migration window when Config.PasswordPolicy.AllowLegacyBcrypt is true. Once all active users have logged in and had their hashes re-hashed with Argon2id, this path becomes unreachable and the config knob should be set back to false.

func VerifyLegacyPBKDF2 added in v2.8.0

func VerifyLegacyPBKDF2(plain, stored string) (bool, error)

VerifyLegacyPBKDF2 checks plain against a legacy PBKDF2 hash. A mismatch is (false, nil); only a malformed hash returns an error.

func VerifyPassword

func VerifyPassword(plain, phc string) (bool, error)

VerifyPassword parses the PHC string and constant-time-compares the supplied plain password against it. Returns (true, nil) on match, (false, nil) on mismatch, and (false, ErrInvalidPasswordHash) on a malformed hash.

func VerifyPasswordWithLegacyFallback

func VerifyPasswordWithLegacyFallback(plain, storedHash string, allowLegacy bool) (matched bool, newArgon2Hash string, err error)

VerifyPasswordWithLegacyFallback is a drop-in replacement for VerifyPassword that also accepts bcrypt hashes when allowLegacy is true. On a successful bcrypt match it calls onLegacyAccepted with the user ID and the NEW Argon2id hash so the caller can persist the upgrade asynchronously.

Callers should schedule the hash upgrade via a goroutine or a job queue so the user-facing latency stays unchanged.

Returns (matched bool, newHash string, err error). newHash is non-empty only when a bcrypt hash was accepted, or an Argon2id hash with parameters below the current baseline matched, and was re-hashed successfully.

func VerifyRecoveryCode

func VerifyRecoveryCode(stored []byte, code string) bool

VerifyRecoveryCode re-hashes the supplied plaintext using the salt extracted from the stored value and compares in constant time. Returns false on any malformed input (including a stored value shorter than the salt prefix).

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL