Created
April 15, 2017 05:51
-
-
Save eamonnmcevoy/00ff416f74455ef5b3fbe2f9d7eff1a6 to your computer and use it in GitHub Desktop.
crypto/hash.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package crypto | |
import ( | |
"errors" | |
"strings" | |
"github.com/google/uuid" | |
"golang.org/x/crypto/bcrypt" | |
) | |
//Hash implements root.Hash | |
type Hash struct{} | |
var deliminator = "||" | |
//Generate a salted hash for the input string | |
func (c *Hash) Generate(s string) (string, error) { | |
salt := uuid.New().String() | |
saltedBytes := []byte(s + salt) | |
hashedBytes, err := bcrypt.GenerateFromPassword(saltedBytes, bcrypt.DefaultCost) | |
if err != nil { | |
return "", err | |
} | |
hash := string(hashedBytes[:]) | |
return hash + deliminator + salt, nil | |
} | |
//Compare string to generated hash | |
func (c *Hash) Compare(hash string, s string) error { | |
parts := strings.Split(hash, deliminator) | |
if len(parts) != 2 { | |
return errors.New("Invalid hash, must have 2 parts") | |
} | |
incoming := []byte(s + parts[1]) | |
existing := []byte(parts[0]) | |
return bcrypt.CompareHashAndPassword(existing, incoming) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment