diff options
author | siddharth <s@ricketyspace.net> | 2022-03-29 21:43:09 -0400 |
---|---|---|
committer | siddharth <s@ricketyspace.net> | 2022-03-29 21:43:09 -0400 |
commit | 662d01e11276c717bdbfb4e053248cbdfe142a4f (patch) | |
tree | 2d0e4d043bcfa9447227d44f1de1824c906bdf2a /lib/sha256.go | |
parent | eadd6510088f87b012361bfc80332cafd5af7615 (diff) |
lib: add HmacSha256
Diffstat (limited to 'lib/sha256.go')
-rw-r--r-- | lib/sha256.go | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/lib/sha256.go b/lib/sha256.go index da6dd7c..10b96b5 100644 --- a/lib/sha256.go +++ b/lib/sha256.go @@ -190,3 +190,41 @@ func (s *Sha256) Hash() []byte { return d } + +func (s *Sha256) Mac(secret, msg []byte) []byte { + s.Message(append(secret, msg...)) + return s.Hash() +} + +func (s *Sha256) MacVerify(secret, msg, mac []byte) bool { + s.Message(append(secret, msg...)) + if BytesEqual(s.Hash(), mac) { + return true + } + return false +} + +// HMAC-SHA256. +func HmacSha256(key, msg []byte) []byte { + // Initialize SHA-256 object. + sha := Sha256{} + sha.Init([]uint32{}) + + // Modify key based on it's size. + if len(key) > 64 { // > blocksize (64 bytes) + sha.Message(key) + key = sha.Hash() + } + if len(key) < 64 { // < blocksize (64 bytes) + // Pad with zeroes up to 64 bytes. + key = append(key, make([]byte, 64-len(key))...) + } + + // Outer padded key. + opk := FixedXORBytes(key, FillBytes(0x5c, 64)) + + // Inner padded key. + ipk := FixedXORBytes(key, FillBytes(0x36, 64)) + + return sha.Mac(opk, sha.Mac(ipk, msg)) +} |