0

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 -

2AE14BDA56ABE98BE42145843796E7D82CE7173993D0F9B19C837127B88D4D08

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 -

QR4Z80VYHP0Y1QURWA9KLP3LPB+WJT6LWMP4I4VPR7W=

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.

3

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().

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.