aboutsummaryrefslogtreecommitdiff
path: root/ssha.go
blob: 202ce12ed44da0a9847ff25c392b72f2113b2917 (plain) (blame)
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
package main

import (
	"errors"

	"github.com/jsimonetti/pwscheme/ssha"
	"github.com/jsimonetti/pwscheme/ssha256"
	"github.com/jsimonetti/pwscheme/ssha512"
)

const (
	SSHA    = "{SSHA}"
	SSHA256 = "{SSHA256}"
	SSHA512 = "{SSHA512}"
)

// Encode encodes the string to ssha512
func SSHAEncode(rawPassPhrase string) (string, error) {
	return ssha512.Generate(rawPassPhrase, 16)
}

// Matches matches the encoded password and the raw password
func SSHAMatches(encodedPassPhrase string, rawPassPhrase string) (bool, error) {
	hashType, err := determineHashType(encodedPassPhrase)
	if err != nil {
		return false, errors.New("invalid password hash stored")
	}

	switch hashType {
	case SSHA:
		return ssha.Validate(rawPassPhrase, encodedPassPhrase)
	case SSHA256:
		return ssha256.Validate(rawPassPhrase, encodedPassPhrase)
	case SSHA512:
		return ssha512.Validate(rawPassPhrase, encodedPassPhrase)
	}

	return false, errors.New("no matching hash type found")
}

func determineHashType(hash string) (string, error) {
	if len(hash) >= 7 && string(hash[0:6]) == SSHA {
		return SSHA, nil
	}
	if len(hash) >= 10 && string(hash[0:9]) == SSHA256 {
		return SSHA256, nil
	}
	if len(hash) >= 10 && string(hash[0:9]) == SSHA512 {
		return SSHA512, nil
	}

	return "", errors.New("no valid hash found")
}