-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsha1_hasher.go
69 lines (57 loc) · 1.33 KB
/
sha1_hasher.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package hasher
import (
"bytes"
"crypto/sha1"
randomstring "gopkg.in/go-passwd/randomstring.v1"
)
// SHA1Hasher hash password in SHA-1
type SHA1Hasher struct {
Salt *string
Iter *int
Password *[]byte
}
// NewSHA1Hasher returns a new SHA1 hasher instance
func NewSHA1Hasher(iterations *int, salt *string, hashedPassword *[]byte) Hasher {
return &SHA1Hasher{
Iter: iterations,
Salt: salt,
Password: hashedPassword,
}
}
// Code returns internal SHA-224 hasher code
func (h SHA1Hasher) Code() string {
return TypeSHA1
}
// Hash a password
func (h *SHA1Hasher) Hash(password string) []byte {
if h.Salt == nil {
salt := randomstring.Generate(DefaultSaltLength)
h.Salt = &salt
}
if h.Iter == nil {
iter := DefaultIter
h.Iter = &iter
}
bPassword := []byte(*h.Salt + password)
for i := 0; i < *h.Iter; i++ {
s := sha1.New()
s.Write(bPassword)
bPassword = s.Sum(nil)
}
return bPassword
}
// SetPassword sets a password
func (h *SHA1Hasher) SetPassword(plain string) {
hash := h.Hash(plain)
h.Password = &hash
}
// Check if hashed password is equal stored password hash
func (h *SHA1Hasher) Check(plain string) bool {
return bytes.Compare(h.Hash(plain), *h.Password) == 0
}
func (h *SHA1Hasher) String() string {
if h.Password == nil {
panic("password is not set")
}
return string(*h.Password)
}