Created
March 19, 2018 20:58
-
-
Save lansana/8895a892aa5f9bfc3f49d90589dbe421 to your computer and use it in GitHub Desktop.
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 hmac | |
import ( | |
"crypto/hmac" | |
"crypto/sha256" | |
"crypto/sha512" | |
"encoding/base64" | |
"encoding/hex" | |
"hash" | |
) | |
func newHmac(h func() hash.Hash, key []byte, message []byte) []byte { | |
mac := hmac.New(h, key) | |
mac.Write(message) | |
return mac.Sum(nil) | |
} | |
func New(h func() hash.Hash, key []byte, message []byte) []byte { | |
return newHmac(h, key, message) | |
} | |
func HexDigest(h func() hash.Hash, key []byte, message []byte) string { | |
return hex.EncodeToString(New(h, key, message)) | |
} | |
func Base64Digest(h func() hash.Hash, key []byte, message []byte) string { | |
return base64.StdEncoding.EncodeToString(New(h, key, message)) | |
} | |
func HexSha512(key []byte, message []byte) string { | |
return HexDigest(sha512.New, key, message) | |
} | |
func HexSha256(key []byte, message []byte) string { | |
return HexDigest(sha256.New, key, message) | |
} | |
func Base64Sha512(key []byte, message []byte) string { | |
return Base64Digest(sha512.New, key, message) | |
} | |
func Base64Sha256(key []byte, message []byte) string { | |
return Base64Digest(sha256.New, key, message) | |
} | |
func Validate(h func() hash.Hash, key, message, expected []byte) bool { | |
return hmac.Equal([]byte(New(h, key, message)), expected) | |
} | |
func ValidateHex(h func() hash.Hash, key, message, expected []byte) bool { | |
return hmac.Equal([]byte(HexDigest(h, key, message)), expected) | |
} | |
func ValidateBase64(h func() hash.Hash, key, message, expected []byte) bool { | |
return hmac.Equal([]byte(Base64Digest(h, key, message)), expected) | |
} | |
func ValidateHexSha512(key, message, expected []byte) bool { | |
return hmac.Equal([]byte(HexSha512(key, message)), []byte(expected)) | |
} | |
func ValidateHexSha256(key, message, expected []byte) bool { | |
return hmac.Equal([]byte(HexSha256(key, message)), []byte(expected)) | |
} | |
func ValidateBase64Sha512(key, message, expected []byte) bool { | |
return hmac.Equal([]byte(Base64Sha512(key, message)), []byte(expected)) | |
} | |
func ValidateBase64Sha256(key, message, expected []byte) bool { | |
return hmac.Equal([]byte(Base64Sha256(key, message)), []byte(expected)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment