-
Notifications
You must be signed in to change notification settings - Fork 0
/
password.go
45 lines (34 loc) · 1.02 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
package crypto
import (
"fmt"
"golang.org/x/crypto/bcrypt"
errCryptoAVA "github.com/ver13/ava/pkg/common/crypto/error"
errorAVA "github.com/ver13/ava/pkg/common/error"
)
type Password string
func NewPassword(password string) *Password {
p := new(Password)
p = (*Password)(&password)
return p
}
func (p *Password) Hash() (string, *errorAVA.Error) {
var hash []byte
if len(*p) > 0 {
var err error
hash, err = bcrypt.GenerateFromPassword([]byte(*p), 10)
if err != nil {
return "", errCryptoAVA.BcryptHash(err, "")
}
}
hashPassword := string(hash)
return hashPassword, nil
}
func (p *Password) ComparePassword(newPassword string) *errorAVA.Error {
if len(*p) == 0 || len(newPassword) == 0 {
return errCryptoAVA.PasswordIsEmpty(nil, fmt.Sprintf("Password: %p - NewPassword: %s.", p, newPassword))
}
if err := bcrypt.CompareHashAndPassword([]byte(*p), []byte(newPassword)); err != nil {
return errCryptoAVA.MismatchedHashAndPassword(err, "Hashed password is not the hash of the given password.")
}
return nil
}