feat(core): 下沉查询密码工具与配置快照解码
Verify / verify (push) Canceled after 0s

This commit is contained in:
zhangdeman committed 2026-11-28 03:10:18 -08:00
1 parent bedcf4dd83
commit d2a9033695
23 files changed
+1544 -6

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
// Package password 提供账号密码哈希和常量时间验证。
package password
import (
"crypto/subtle"
"encoding/base64"
"golang.org/x/crypto/argon2"
)
const (
passwordHashPrefix = "$argon2id$v=19$m=65536,t=3,p=2$"
iterations uint32 = 3
memoryKiB uint32 = 64 * 1024
parallelism uint8 = 2
hashBytes uint32 = 32
)
// Hash 使用 Argon2id 生成账号密码哈希。
//
// 入参:
// - `salt` 表示账号独立的随机盐值。
// - `password` 表示待保护的明文密码。
//
// 返回:
// - `返回值1` 表示带算法及参数版本标识的密码哈希。
func Hash(salt, password string) string {
hash := argon2.IDKey([]byte(password), []byte(salt), iterations, memoryKiB, parallelism, hashBytes)
return passwordHashPrefix + base64.RawStdEncoding.EncodeToString(hash)
}
// Verify 以常量时间比较 Argon2id 账号密码哈希。
//
// 入参:
// - `salt` 表示账号独立的随机盐值。
// - `password` 表示本次登录提交的明文密码。
// - `storedHash` 表示数据库保存的密码哈希。
//
// 返回:
// - `返回值1` 表示密码是否匹配。
func Verify(salt, password, storedHash string) bool {
expectedHash := Hash(salt, password)
return subtle.ConstantTimeCompare([]byte(expectedHash), []byte(storedHash)) == 1
}
+33
View File
@@ -0,0 +1,33 @@
package password
import "testing"
// TestPasswordHash 验证 Argon2id 密码哈希的校验行为。
//
// 入参:
// - `t` 表示当前测试上下文。
//
// 返回:
// - 无返回值。
func TestPasswordHash(t *testing.T) {
const (
salt = "0123456789abcdef"
password = "safe-password"
)
newHash := Hash(salt, password)
// 来自迁移前实现的固定公开输入向量,不能因迁移重算账号哈希。
const legacy = "$argon2id$v=19$m=65536,t=3,p=2$bZYOvJXmIZjZB9pB8SfHP3+tg56rWnDsjzTHsc3NcAM"
if newHash != legacy {
t.Fatal("legacy hash format changed")
}
if !Verify(salt, password, newHash) {
t.Fatal("Argon2id 密码应校验成功")
}
if Verify(salt, "wrong-password", newHash) {
t.Fatal("错误密码不应校验成功")
}
if Verify(salt, password, "6f7a5ccfa9d4e28f") {
t.Fatal("非 Argon2id 密码摘要不应校验成功")
}
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.