使用fcavalieri/zorba Docker镜像调用hmac:compute异常,是否用法正确?
Let's break down what's happening here and fix the issue for you:
What's Going Wrong?
You're not actually misusing the hmac:compute module — but you're mixing up two different representations of the HMAC result:
- The
hmac:computefunction returns a binary byte sequence (the raw SHA256 HMAC value). - Zorba automatically serializes binary data as Base64 when outputting it, which gives you the string
97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg=. - When you Base64-decode this string, you get the raw binary bytes of the hash (which looks like "乱码" because those bytes aren't printable ASCII characters). Your expected value
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8is the hexadecimal string representation of that same binary data, not the binary data itself.
How to Get the Expected Hexadecimal Hash
To convert the binary HMAC result into the hexadecimal string you want, use Zorba's util:hex() function to encode the binary bytes as a hex string. Here's the corrected code:
util:hex(hmac:compute("The quick brown fox jumps over the lazy dog", "key", "SHA256"))
This will directly output the hexadecimal string you expected:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
A Quick Check
If you want to confirm, you can take the Base64 string you got, decode it to binary, then convert that binary to hex — you'll end up with the same expected value. But using util:hex() directly on the hmac:compute result is the cleanest way to get the hex string in Zorba.
内容的提问来源于stack exchange,提问作者Ben Flowers

