66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
package util
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func SHA224String(password string) string {
|
|
hash := sha256.New224()
|
|
hash.Write([]byte(password))
|
|
val := hash.Sum(nil)
|
|
str := ""
|
|
for _, v := range val {
|
|
str += fmt.Sprintf("%02x", v)
|
|
}
|
|
return str
|
|
}
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
if len(strings.TrimSpace(password)) < 6 {
|
|
return "", errors.New("password too short")
|
|
}
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(hash), nil
|
|
}
|
|
|
|
func IsBcryptHash(hash string) bool {
|
|
return strings.HasPrefix(hash, "$2a$") || strings.HasPrefix(hash, "$2b$") || strings.HasPrefix(hash, "$2y$")
|
|
}
|
|
|
|
func VerifyPassword(password string, storedHash string) (ok bool, legacy bool) {
|
|
if IsBcryptHash(storedHash) {
|
|
err := bcrypt.CompareHashAndPassword([]byte(storedHash), []byte(password))
|
|
return err == nil, false
|
|
}
|
|
return SHA224String(password) == storedHash, true
|
|
}
|
|
|
|
func HmacSHA256Hex(payload string, secret string) string {
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write([]byte(payload))
|
|
sum := mac.Sum(nil)
|
|
str := ""
|
|
for _, v := range sum {
|
|
str += fmt.Sprintf("%02x", v)
|
|
}
|
|
return str
|
|
}
|
|
|
|
func PeerSecretDigest(rawSecret string) string {
|
|
secretKey := strings.TrimSpace(os.Getenv("HY2XS_PEER_SECRET_KEY"))
|
|
if secretKey == "" {
|
|
secretKey = "hy2xs-peer-secret-key"
|
|
}
|
|
return HmacSHA256Hex(rawSecret, secretKey)
|
|
}
|