Forum Discussion

Mosh's avatar
Icon for Professor rankProfessor
4 years ago

Using REST API from ServiceNow Scripting

I would like to use the REST API from ServiceNow but I'm not able to generate the HMAC using the ServiceNow Glide System native class GlideCertificateEncryption(), the resulting values don't match ...
  • Mosh's avatar
    4 years ago

    Solved it. For anyone who needs it here is how to generate the MAC part of the signature using only native ServiceNow script and classes.  (I had to write my own convertByteArrayToHex() utility as there was nothing I could find native in ServiceNow.)  The problem with using CryptoJS is that in ServiceNow it would only be allowed in a scoped app and I wanted to do this in the global scope.

    var HexUtil = 
      convertByteArrayToHex : function(byteArray)
        var hex = "";
        byteArray.forEach(function(byteValue) { hex += HexUtil.convertByteToHex(byteValue); });
        return hex;  
      convertByteToHex : function(b) 
        var hexChar = ["0""1""2""3""4""5""6""7","8""9""a""b""c""d""e""f"];
        return hexChar[(b >> 4& 0x0f+ hexChar[b & 0x0f];
    var key = "key";
    key = encodeURIComponent(key);
    key = GlideStringUtil.base64Encode(key);
    var msg = "message";
    msg = encodeURIComponent(msg);
    var mac = new GlideCertificateEncryption();
    signature = mac.generateMac(key, "HmacSHA256", msg);
    // Yes! bp7ym3X//Ft6uuUn1Y/a2y/kLnIZARl2kXNDBl9Y7Uo=
    var bytes = GlideStringUtil.base64DecodeAsBytes(signature);
    var hex = HexUtil.convertByteArrayToHex(bytes);
    // Yes! 6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a
    var hexB64 = GlideStringUtil.base64Encode(hex);