bottin/ssha.go

54 lines
1.3 KiB
Go
Raw Normal View History

2020-01-19 11:49:49 +00:00
package main
import (
2022-02-08 16:59:59 +00:00
"errors"
"github.com/jsimonetti/pwscheme/ssha"
"github.com/jsimonetti/pwscheme/ssha256"
"github.com/jsimonetti/pwscheme/ssha512"
)
const (
SSHA = "{SSHA}"
SSHA256 = "{SSHA256}"
SSHA512 = "{SSHA512}"
2020-01-19 11:49:49 +00:00
)
2022-02-08 16:59:59 +00:00
// Encode encodes the string to ssha512
func SSHAEncode(rawPassPhrase string) (string, error) {
return ssha512.Generate(rawPassPhrase, 16)
2020-01-19 11:49:49 +00:00
}
// Matches matches the encoded password and the raw password
2022-02-08 16:59:59 +00:00
func SSHAMatches(encodedPassPhrase string, rawPassPhrase string) (bool, error) {
hashType, err := determineHashType(encodedPassPhrase)
2020-01-19 11:49:49 +00:00
if err != nil {
2022-02-08 16:59:59 +00:00
return false, errors.New("invalid password hash stored")
2020-01-19 11:49:49 +00:00
}
2022-02-08 16:59:59 +00:00
switch hashType {
case SSHA:
return ssha.Validate(rawPassPhrase, encodedPassPhrase)
case SSHA256:
return ssha256.Validate(rawPassPhrase, encodedPassPhrase)
case SSHA512:
return ssha512.Validate(rawPassPhrase, encodedPassPhrase)
2020-01-19 11:49:49 +00:00
}
2022-02-08 16:59:59 +00:00
return false, errors.New("no matching hash type found")
2020-01-19 11:49:49 +00:00
}
2022-02-08 16:59:59 +00:00
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
}
2020-01-19 11:49:49 +00:00
2022-02-08 16:59:59 +00:00
return "", errors.New("no valid hash found")
2020-01-19 11:49:49 +00:00
}