How to get HMAC SHA1 hash and Base64 encoding in AppScript

base64rstudiosha1

I currently have a small piece of code to get an authorization string in R Studio. I am trying to replicate the same function in App Script, but I have not been able to get the same result.

The code in R Studio is:

library(digest)
library(openssl)

sec_key <- "secret-key"
checksum_string <- "checksum-string"
checksum <- base64_encode(hmac(sec_key, checksum_string, algo = "sha1", raw = T))

Result after hash: 32 e1 f7 da c6 5b 16 fe 02 5b 90 f9 98 65 2b 2c 2e 22 c9 ad
Result after base64 encode: "MuH32sZbFv4CW5D5mGUrLC4iya0="

Meanwhile, the code that I am using in AppScript is:

function get_checksum{
   var sec_key = "secret-key"
   var checksum_string = "checksum-string"
   var hash = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_1, sec_key, checksum_string)
   var checksum = Utilities.base64Encode(hash)
}
Result after hash: [107.0, -81.0, -127.0, -126.0, -93.0, 108.0, 110.0, -26.0, -29.0, 70.0, -90.0, -44.0, -100.0, -107.0, 25.0, 54.0, 86.0, 22.0, -82.0, -97.0]
Result after base64 encoding: "a6+BgqNsbubjRqbUnJUZNlYWrp8="

As you can see, I am not getting the same results.

I am guessing that there is a function that I should use for the hash so that I can get a "raw" result, but I do not know it and have not been able to find it.

I will appreciate if anyone can point me in the right direction.

Best Answer

According to the documentation, the HMAC function in AppScript takes parameters the other way around – message before key.

$ python3
>>> import hmac, base64
>>> HMAC = lambda key, msg: base64.b64encode(hmac.HMAC(key, msg, 'sha1').digest())
>>> HMAC(key=b'secret-key', msg=b'checksum-string')
b'MuH32sZbFv4CW5D5mGUrLC4iya0='
>>> HMAC(key=b'checksum-string', msg=b'secret-key')
b'a6+BgqNsbubjRqbUnJUZNlYWrp8='
Related Question