-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsha512_256_hasher.go
69 lines (57 loc) · 1.41 KB
/
sha512_256_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/sha512"
randomstring "gopkg.in/go-passwd/randomstring.v1"
)
// SHA512_256Hasher hash password in SHA-512/256
type SHA512_256Hasher struct {
Salt *string
Iter *int
Password *[]byte
}
// NewSHA512_256Hasher returns a new plain hasher instance
func NewSHA512_256Hasher(iterations *int, salt *string, hashedPassword *[]byte) Hasher {
return &SHA512_256Hasher{
Iter: iterations,
Salt: salt,
Password: hashedPassword,
}
}
// Code returns internal SHA-512/256 hasher code
func (h SHA512_256Hasher) Code() string {
return TypeSHA512_256
}
// Hash a password
func (h *SHA512_256Hasher) 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 := sha512.New512_256()
s.Write(bPassword)
bPassword = s.Sum(nil)
}
return bPassword
}
// SetPassword sets a password
func (h *SHA512_256Hasher) SetPassword(plain string) {
hash := h.Hash(plain)
h.Password = &hash
}
// Check if hashed password is equal stored password hash
func (h *SHA512_256Hasher) Check(plain string) bool {
return bytes.Compare(h.Hash(plain), *h.Password) == 0
}
func (h *SHA512_256Hasher) String() string {
if h.Password == nil {
panic("password is not set")
}
return string(*h.Password)
}