aboutsummaryrefslogtreecommitdiff
path: root/ssha.go
blob: cca51c7a9a28fa10514fd5405fdbefa6e06377e9 (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
54
55
56
57
58
59
60
61
62
63
64
65
package main

import (
	"errors"
	"regexp"
	"strings"

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

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

var scheme = regexp.MustCompile(`^{([0-9a-zA-Z]+)}`)

// 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) {
	cleanEncodedPass := uppercaseScheme(encodedPassPhrase)

	hashType, err := determineHashType(cleanEncodedPass)
	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")
}

func uppercaseScheme(hash string) string {
	return scheme.ReplaceAllStringFunc(hash, func(w string) string {
		return strings.ToUpper(w)
	})
}