How to Generate a SHA256 HMAC Hash from a String in Go
Created
Modified
In cryptography, an HMAC (hash-based message authentication code) is a specific type of message authentication code (MAC) involving a cryptographic hash function and a secret cryptographic key.
Using hmac Package
The hmac.New()
function returns a new HMAC hash using the given hash.Hash type and key.
The following example should cover whatever you are trying to do:
package main
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
)
func main() {
s := "Hello"
key := "FDJ1mnhuzjFjTdwhq7DtZG2Cq9kuuEZCG"
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(s))
fmt.Printf("%x\n", h.Sum(nil))
fmt.Printf("%x\n", sha256.Sum256([]byte(s)))
}
b5352927e7a57a6485fa4afa7452b3817abe47d07c8aa2511bdcb9a43ac0f224 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
Generating a MD5 HMAC Hash
For example,
package main
import (
"crypto/hmac"
"crypto/md5"
"fmt"
)
func main() {
s := "Hello"
key := "FDJ1mnhuzjFjTdwhq7DtZG2Cq9kuuEZCG"
h := hmac.New(md5.New, []byte(key))
h.Write([]byte(s))
fmt.Printf("%x\n", h.Sum(nil))
}
ed1d2af782f2fa171867e4e810bf9a3d
block length:
Hash function H | b, bytes | L, bytes |
---|---|---|
MD5 | 64 | 16 |
SHA-1 | 64 | 20 |
SHA-224 | 64 | 28 |
SHA-256 | 64 | 32 |
SHA-512/224 | 128 | 28 |
SHA-512/256 | 128 | 32 |
SHA-384 | 128 | 48 |
SHA-512 | 128 | 64 |
SHA3-224 | 144 | 28 |
SHA3-256 | 136 | 32 |
SHA3-384 | 104 | 48 |
SHA3-512 | 72 | 64 |
out = H( in ) L = length( out ) b = H's internal block length |