google-apps-scriptencryptionsha256hmac

Generate SHA-256 HMAC in Base64 in Google AppScript


I would like to generate a base64 HMAC Authentication Code in Google Appscript.

This website - provides the exact solution: https://www.devglan.com/online-tools/hmac-sha256-online

I just somehow cant get it working natively in Google Appscript.

This is what I have at the moment - but its not giving me the right key:

function HMAC() {

var urlParam = "message";
var APIkey = 'secret';

  var hash = Utilities.computeHmacSha256Signature(urlParam, APIkey).reduce(function(str,chr){
    chr = (chr < 0 ? chr + 256 : chr).toString(16);
    return str + (chr.length==1?'0':'') + chr;
  },'');;

  Logger.log(Utilities.base64Encode(hash));
}

Solution

  • function HMAC() {
     var urlParam = "message";
     var APIkey = 'secret';
    
     // Compute HMAC-SHA256 hash
     var hash = Utilities.computeHmacSha256Signature(urlParam, APIkey,Utilities.Charset.UTF_8);
    
     // Convert byte array to Base64
     var base64Hash = Utilities.base64Encode(hash);
    
     // Log the Base64 encoded HMAC
     Logger.log(base64Hash);
    
     return base64Hash;
    }
    
    1. Byte Conversion: Utilities.computeHmacSha256Signature is given the message and the secret key. Here, Utilities.Charset.UTF_8 ensures that the string is encoded properly before the hash computation.

    2. Base64 Encoding: Instead of converting the byte array to a hexadecimal string first, you directly encode it into Base64. This is done using Utilities.base64Encode, which correctly handles the byte array.