Converting Hex string to Base64

Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-02-2020 03:37 PM
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(' '))
);
}
Labels:
- Labels:
-
Scripting and Coding
1 REPLY 1

Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-02-2020 09:06 PM
There's an article on the topic but the code looks similar to the code in question.