-
-
Notifications
You must be signed in to change notification settings - Fork 480
/
bcrypt.go
37 lines (28 loc) · 860 Bytes
/
bcrypt.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
33
34
35
36
37
package bcrypt
import (
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
const (
cost = 12
)
// Prefix is set to be compatible with Dovecot. Can be set to an empty string.
var Prefix = "{BLF-CRYPT}"
// Generate generates a new Bcrypt hash with recommended values for it's
// cost parameter.
func Generate(password string) (string, error) {
h, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return "", fmt.Errorf("failed to generate password hash: %w", err)
}
return Prefix + string(h), nil
}
// Validate validates the password against the given hash.
func Validate(password, hash string) error {
hash = strings.TrimPrefix(hash, Prefix)
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)); err != nil {
return fmt.Errorf("failed to validate password hash %s: %w", hash, err)
}
return nil
}