Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Converting Hex string to Base64

Roy Verrips
Tera Expert

Hi 

I needed to validate a payload that was HMAC signed by a third party.   I found this is possible, but as the signature string. I received is in HEX I needed a function to convert that to Base64 (as outputted when signing with the same key within ServiceNow) 

A sample script that currently works is included below - Just checking if there's a better way to convert from hex to Base64. 

Thanks

Roy

var data = 'This is a test of payload data';
var secret = 'secret';
var EXTGeneratedSignature = '6d77f08aac96b28aa442960af0a0d5e0b9a80791aecb7b47829320bc724a408d';
// signature was generated by https://www.freeformatter.com/hmac-generator.html using sha256

var key = gs.base64Encode(secret);
var mac = new CertificateEncryption;
var SNgeneratedSignature = mac.generateMac(key, 'HmacSHA256', data);
var EXTdecode = hexToBase64(EXTGeneratedSignature);
if (SNgeneratedSignature == EXTdecode) {
	gs.info('The signature is valid');
} else {
	gs.info('the signature is not valid');
}

function hexToBase64(str) {
    function btoa(bin) {
        var tableStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
        var table = tableStr.split('');
        for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
            var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
            if ((a | b | c) > 255) throw new Error('String contains an invalid character');
            base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
            (isNaN(b) ? '=' : table[((b << 2) & 63) | (c >> 6)]) +
            (isNaN(b + c) ? '=' : table[c & 63]);
        }
        return base64.join('');
    }
    return btoa(String.fromCharCode.apply(null,
        str.replace(/\r|\n/g, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' '))
        );
}
1 REPLY 1

Hitoshi Ozawa
Giga Sage
Giga Sage

There's an article on the topic but the code looks similar to the code in question.

https://community.servicenow.com/community?id=community_article&sys_id=239ca483dbf23b044819fb2439961...