-
Notifications
You must be signed in to change notification settings - Fork 181
/
password.go
45 lines (38 loc) · 1.11 KB
/
password.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
38
39
40
41
42
43
44
45
// Copyright (c) 2012-2014 Jeremy Latt
// released under the MIT license
package irc
import (
"encoding/base64"
"errors"
"golang.org/x/crypto/bcrypt"
)
var (
// ErrEmptyPassword means that an empty password was given.
ErrEmptyPassword = errors.New("empty password")
)
// GenerateEncodedPassword returns an encrypted password, encoded into a string with base64.
func GenerateEncodedPassword(passwd string) (encoded string, err error) {
if passwd == "" {
err = ErrEmptyPassword
return
}
bcrypted, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.MinCost)
if err != nil {
return
}
encoded = base64.StdEncoding.EncodeToString(bcrypted)
return
}
// DecodePasswordHash takes a base64-encoded password hash and returns the appropriate bytes.
func DecodePasswordHash(encoded string) (decoded []byte, err error) {
if encoded == "" {
err = ErrEmptyPassword
return
}
decoded, err = base64.StdEncoding.DecodeString(encoded)
return
}
// ComparePassword compares a given password with the given hash.
func ComparePassword(hash, password []byte) error {
return bcrypt.CompareHashAndPassword(hash, password)
}