33 lines
679 B
Go
33 lines
679 B
Go
package hash
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
var (
|
|
ErrHash = errors.New("wrong hash value")
|
|
)
|
|
|
|
func Hash(ctx context.Context, payload string) (string, error) {
|
|
bytes, err := bcrypt.GenerateFromPassword([]byte(payload), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return "", ErrHash
|
|
}
|
|
return string(bytes), nil
|
|
}
|
|
|
|
func CompareHash(ctx context.Context, hash string, payload string) bool {
|
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(payload))
|
|
return err == nil
|
|
}
|
|
|
|
func SHA256(ctx context.Context, payload string) string {
|
|
hash := sha256.Sum256([]byte(payload))
|
|
return hex.EncodeToString(hash[:])
|
|
}
|