password

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Package password 提供 argon2id 密码哈希与校验。

哈希串采用 PHC 标准格式,自带算法参数:

$argon2id$v=19$m=65536,t=3,p=4$<base64 salt>$<base64 hash>

参数随哈希一同存储,因此调整默认参数不会使已有哈希失效—— 旧密码仍可校验,并可在用户下次登录时按需重算(见 NeedsRehash)。

Index

Constants

View Source
const MaxLength = 128

MaxLength 是密码最大长度。

必须设上限:argon2 的计算量与输入长度相关,不限长会让超长密码 成为廉价的 DoS 手段。72 字节以上的熵对本场景已无实际意义。

View Source
const MinLength = 8

MinLength 是密码最小长度。

取 8 位与 OWASP 建议一致;上限见 MaxLength。

Variables

View Source
var (
	// ErrMismatch 表示密码与哈希不匹配。
	ErrMismatch = errors.New("密码不匹配")
	// ErrInvalidHash 表示哈希串格式非法。
	ErrInvalidHash = errors.New("哈希串格式非法")
	// ErrEmptyPassword 表示密码为空。
	ErrEmptyPassword = errors.New("密码不能为空")
	// ErrBusy 表示哈希并发额度已满,稍后重试即可。
	ErrBusy = errors.New("密码校验繁忙,请稍后重试")
)

错误哨兵。

Functions

func Hash

func Hash(plain string) (string, error)

Hash 用默认参数生成 argon2id 哈希串。

func HashSlots

func HashSlots() int

HashSlots 返回进程级并发哈希额度的总量,供运维观测与容量估算。

func HashWithParams

func HashWithParams(plain string, p Params) (string, error)

HashWithParams 用指定参数生成 argon2id 哈希串。

func NeedsRehash

func NeedsRehash(encoded string) bool

NeedsRehash 报告已有哈希是否弱于当前默认参数。

用于在用户成功登录时透明升级哈希强度:此时明文密码在手, 是唯一能重算哈希的时机。

func Validate

func Validate(plain string) error

Validate 校验密码是否满足长度要求。

func Verify

func Verify(plain, encoded string) error

Verify 校验明文密码与哈希串是否匹配。

返回 ErrMismatch 表示密码错误,ErrInvalidHash 表示哈希串本身有问题。 调用方应对两者给出**相同**的对外提示,避免泄漏账号是否存在。

Types

type Params

type Params struct {
	// Memory 是内存开销,单位 KiB。
	Memory uint32
	// Iterations 是时间开销(迭代次数)。
	Iterations uint32
	// Parallelism 是并行度(线程数)。
	Parallelism uint8
	// SaltLength 是盐的字节数。
	SaltLength uint32
	// KeyLength 是输出哈希的字节数。
	KeyLength uint32
}

Params 是 argon2id 的开销参数。

func Decode

func Decode(encoded string) (p Params, salt, key []byte, err error)

Decode 解析 PHC 格式的 argon2id 哈希串。

func DefaultParams

func DefaultParams() Params

DefaultParams 返回默认开销参数。

取值参考 OWASP 对 argon2id 的建议(19 MiB / t=2 为下限),此处取更保守的 64 MiB / t=3。并行度跟随 CPU 核数但封顶 4:过高并不增加安全性, 却会在并发登录时放大内存占用。

Jump to

Keyboard shortcuts

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