1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00
This commit is contained in:
2022-04-18 10:01:55 +08:00
parent c5974b9ae7
commit 0ab7efb7ef
2 changed files with 47 additions and 0 deletions

View File

@ -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

View File

@ -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