-
-
Notifications
You must be signed in to change notification settings - Fork 544
/
Copy pathhash.go
32 lines (28 loc) · 804 Bytes
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package util
import (
"encoding/base64"
"errors"
"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 errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("cannot verify password: %w", err)
}
return true, nil
}