mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-29 14:06:36 +08:00
528240026d
- make format 现在与 code-check 使用同一格式化器(golangci-lint fmt),消除 goimports -local 与 gofumpt 的格式拉锯 - .golangci.yml 关闭默认 50/3 截断,完整上报所有问题(只增强不弱化) - 全库 gofumpt 规范化(203 files, 纯格式无行为变更)
51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
// Copyright 2026 Arctel.net
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package util
|
|
|
|
import (
|
|
"sync"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// HashPassword 使用 bcrypt 对密码进行哈希处理
|
|
func HashPassword(password string) (string, error) {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(hash), nil
|
|
}
|
|
|
|
var (
|
|
dummyPasswordHashOnce sync.Once
|
|
dummyPasswordHash string
|
|
)
|
|
|
|
func dummyHash() string {
|
|
dummyPasswordHashOnce.Do(func() {
|
|
hash, err := bcrypt.GenerateFromPassword([]byte("x"), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return
|
|
}
|
|
dummyPasswordHash = string(hash)
|
|
})
|
|
return dummyPasswordHash
|
|
}
|
|
|
|
// CheckPasswordHash 比较 bcrypt 哈希值与明文密码是否匹配
|
|
func CheckPasswordHash(hash, password string) bool {
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
|
}
|
|
|
|
// DummyCheckPassword runs a bcrypt compare against a dummy hash so missing-user
|
|
// login failures take a similar amount of time as a real password miss.
|
|
func DummyCheckPassword(password string) {
|
|
hash := dummyHash()
|
|
if hash == "" {
|
|
return
|
|
}
|
|
_ = CheckPasswordHash(hash, password)
|
|
}
|