/
hash_sha.go
62 lines (52 loc) · 1.39 KB
/
hash_sha.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
package collect
import (
"bytes"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"fmt"
)
type SSHAEncoder struct {
}
// Encode encodes the []byte of raw password
func (enc SSHAEncoder) Encode(rawPassPhrase []byte) ([]byte, error) {
hash := makeSSHAHash(rawPassPhrase, makeSalt())
b64 := base64.StdEncoding.EncodeToString(hash)
return []byte(fmt.Sprintf("{SSHA}%s", b64)), nil
}
// Matches matches the encoded password and the raw password
func (enc SSHAEncoder) Matches(encodedPassPhrase, rawPassPhrase []byte) bool {
//strip the {SSHA}
eppS := string(encodedPassPhrase)[6:]
hash, err := base64.StdEncoding.DecodeString(eppS)
if err != nil {
return false
}
salt := hash[len(hash)-4:]
sha := sha1.New()
sha.Write(rawPassPhrase)
sha.Write(salt)
sum := sha.Sum(nil)
if bytes.Compare(sum, hash[:len(hash)-4]) != 0 {
return false
}
return true
}
// makeSalt make a 4 byte array containing random bytes.
func makeSalt() []byte {
sbytes := make([]byte, 4)
rand.Read(sbytes)
return sbytes
}
// makeSSHAHash make hasing using SHA-1 with salt. This is not the final output though. You need to append {SSHA} string with base64 of this hash.
func makeSSHAHash(passphrase, salt []byte) []byte {
sha := sha1.New()
sha.Write(passphrase)
sha.Write(salt)
h := sha.Sum(nil)
return append(h, salt...)
}
func HashSha(str string) string {
data, _ := SSHAEncoder{}.Encode([]byte(str))
return string(data)
}