Add support for password hashes as an optional alternative to plaintext passwords (#216)

This commit is contained in:
Marcus Wichelmann 2022-09-30 10:24:54 +02:00 committed by GitHub
parent 29b017f277
commit 2c2db61158
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 67 additions and 10 deletions

30
util/hash.go Normal file
View file

@ -0,0 +1,30 @@
package util
import (
"encoding/base64"
"fmt"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(plaintext string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(plaintext), 14)
if err != nil {
return "", fmt.Errorf("cannot hash password: %w", err)
}
return base64.StdEncoding.EncodeToString(bytes), nil
}
func VerifyHash(base64Hash string, plaintext string) (bool, error) {
hash, err := base64.StdEncoding.DecodeString(base64Hash)
if err != nil {
return false, fmt.Errorf("cannot decode base64 hash: %w", err)
}
err = bcrypt.CompareHashAndPassword(hash, []byte(plaintext))
if err == bcrypt.ErrMismatchedHashAndPassword {
return false, nil
}
if err != nil {
return false, fmt.Errorf("cannot verify password: %w", err)
}
return true, nil
}