I am trying to convert the below javascript code into apex. The javascript code is below-

timestamp = Math.round((new Date()).getTime() / 1000);
var method = request.method;
var path = request.url.replace(/^.*\/\/[^\/]+/, '');
var prehash = timestamp + '-' + method + '-' + path;
var secret = 'xxxxx';
var username = '';
var hash = CryptoJS.HmacSHA256(prehash, secret);

The hash being generated here looks like -


The apex code is below-

string timestmp = String.valueof((DateTime.now().getTime())/1000);
string method ='POST';
string testurl='';
string path = testurl.replace('/^.*\\/\\/[^\\/]+/', '');
string prehash = timestmp + '-' + method + '-' + path;
string secret = 'xxxxx';
string username = '';
String algorithmName='HmacSHA256';
Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(prehash), Blob.valueOf(secret));
string hash = EncodingUtil.base64Encode(hmacData);

The hash being generated by apex looks like -


I want the hash being generated by apex to be similar in format to the hash being generated by javascript. Can anyone pls advice how should I modify my code to meet my requirement.


The output of your JavaScript is hexadecimal text (Base 16). The output of your Apex is Base64.

To generate a hexadecimal string in Apex, use EncodingUtil.convertToHex(blob) rather than base64Encode().

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.