diff --git a/hash/hash.go b/hash/hash.go index 975749f..953a426 100644 --- a/hash/hash.go +++ b/hash/hash.go @@ -1,6 +1,7 @@ package hash import ( + "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" @@ -28,6 +29,28 @@ var hashFuncs = map[string]HashFunc{ "SM3": Sm3, } +type hashComparer struct { + hashFunc HashFunc +} + +func New(fname string) (*hashComparer, error) { + f, err := ByName(fname) + if err != nil { + return nil, err + } + + return &hashComparer{ + hashFunc: f, + }, nil +} + +func (c *hashComparer) Verify(msg, target []byte) bool { + ret := c.hashFunc(msg) + ret.Bytes() + + return bytes.Compare(ret.Bytes(), target) == 0 +} + func ByName(name string) (HashFunc, error) { if f, ok := hashFuncs[strings.ToUpper(name)]; ok { return f, nil diff --git a/hmac/hmac.go b/hmac/hmac.go index d625b1b..2d677a2 100644 --- a/hmac/hmac.go +++ b/hmac/hmac.go @@ -1,6 +1,7 @@ package hmac import ( + "bytes" "crypto/hmac" "crypto/md5" "crypto/sha1" @@ -26,6 +27,29 @@ var hmacFuncs = map[string]HMacFunc{ "SM3": Sm3, } +type hashComparer struct { + key []byte + hashFunc HMacFunc +} + +func New(fname string, key []byte) (*hashComparer, error) { + f, err := ByName(fname) + if err != nil { + return nil, err + } + + return &hashComparer{ + key: key, + hashFunc: f, + }, nil +} + +func (c *hashComparer) Verify(msg, target []byte) bool { + ret := c.hashFunc(c.key, msg) + + return bytes.Compare(ret.Bytes(), target) == 0 +} + func ByName(name string) (HMacFunc, error) { if f, ok := hmacFuncs[strings.ToUpper(name)]; ok { return f, nil