aboutsummaryrefslogblamecommitdiff
path: root/ssha.go
blob: 202ce12ed44da0a9847ff25c392b72f2113b2917 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14


            










                                                

 


                                                       


                                                            

                                                                                
                       
                                                                        
         
 






                                                                         
         
 
                                                               

 









                                                            
 
                                                    
 
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")
}