1 parent
bedcf4dd83
commit
d2a9033695
23 files changed
+1544
-6
No files matched your search
@@ -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
|
||||
}
|
||||