/
ssha512.go
66 lines (56 loc) · 2.01 KB
/
ssha512.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
// Package ssha512 provides functions to generate and validate {SSHA512} styled
// password schemes.
// The method used is defined in RFC 2307 and uses a salted SHA512 secure hashing
// algorithm
package ssha512
import (
"crypto/rand"
"crypto/sha512"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
)
// ErrNotSshaPassword occurs when Validate receives a non-SSHA512 hash
var ErrNotSshaPassword = errors.New("string is not a SSHA512 hashed password")
// ErrBase64DecodeFailed occurs when the given hash cannot be decode
var ErrBase64DecodeFailed = errors.New("base64 decode of hash failed")
// ErrNotMatching occurs when the given password and hash do not match
var ErrNotMatching = errors.New("hash does not match password")
// Generate encrypts a password with a random salt of definable length and
// returns the {SSHA512} encoding of the password
func Generate(password string, length uint8) (string, error) {
salt := make([]byte, length)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
hash := createHash(password, salt)
ret := fmt.Sprintf("{SSHA512}%s", base64.StdEncoding.EncodeToString(hash))
return ret, nil
}
// Validate compares a given password with a {SSHA512} encoded password
// Returns true is they match or an error otherwise
func Validate(password string, hash string) (bool, error) {
if len(hash) < 10 || string(hash[0:9]) != "{SSHA512}" {
return false, ErrNotSshaPassword
}
data, err := base64.StdEncoding.DecodeString(hash[9:])
if len(data) < 65 || err != nil {
return false, ErrBase64DecodeFailed
}
newhash := createHash(password, data[64:])
hashedpw := base64.StdEncoding.EncodeToString(newhash)
if subtle.ConstantTimeCompare([]byte(hashedpw), []byte(hash[9:])) == 1 {
return true, nil
}
return false, ErrNotMatching
}
// This function appends password and salt together to a byte array
func createHash(password string, salt []byte) []byte {
pass := []byte(password)
str := append(pass[:], salt[:]...)
sum := sha512.Sum512(str)
result := append(sum[:], salt[:]...)
return result
}