/
sha1.go
69 lines (56 loc) · 1.29 KB
/
sha1.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 pwcrypto
import (
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
)
type SHA1Crypto struct {
saltLen int
}
var _ Algorithm = SHA1Crypto{}
// Create PBKDF2 with recommended options
func NewSHA1Crypto() SHA1Crypto {
return NewSHA1CryptoWithOptions(32)
}
func NewSHA1CryptoWithOptions(saltLen int) SHA1Crypto {
return SHA1Crypto{
saltLen: saltLen,
}
}
func (a SHA1Crypto) ID() string {
return "sha1"
}
func (a SHA1Crypto) Hash(input string) (string, error) {
salt := make([]byte, a.saltLen)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
hashed := a.hashVal(salt, input)
return fmt.Sprintf("%s|%x", hashed, salt), nil
}
func (a SHA1Crypto) Check(input, hashed string) (bool, bool, error) {
parts := strings.Split(hashed, "|")
if len(parts) != 2 {
return false, false, errors.New("Not a good hash value!")
}
toMatch := parts[0]
salt, err := hex.DecodeString(parts[1])
if err != nil {
return false, false, err
}
inputhashed := a.hashVal(salt, input)
valid := inputhashed == toMatch
mustUpgrade := valid && len(salt) != a.saltLen
return valid, mustUpgrade, nil
}
func (a SHA1Crypto) hashVal(salt []byte, input string) string {
h := sha1.New()
h.Write(salt)
_, _ = io.WriteString(h, input)
return fmt.Sprintf("%x", h.Sum(nil))
}