+ Start a Discussion
RovRov 

Pseudo Code to Apex

// I am trying to translate the following pseudo code to Apex -> base64(hmac-sha256({accessKeySecret}, UTF8({stringToSign})))

// My atempt at translating to Apex
String dateString = Datetime.now().formatGmt('EEE, dd MMM yyyy HH:mm:ss Z'); 

String stringtoSign = 'GET\n\n\n'+dateString;

String secretAccessKey = '9PK^:WAvBrl1?jz3^U{7+)){igpCG\"Y;<.3DGy8gX+' +'\'' + '6p{|D2#MwI#It8{+@W?>*'; 

Blob mac = Crypto.generateMac('HMAC-SHA256', blob.valueOf(stringToSign),blob.valueOf(secretAccessKey)); 

String signature = EncodingUtil.base64Encode(mac); system.debug(signature);

This compiles correctly in Dev Console. However how do i ensure that that I have translated in the format as mentioned in the pseudo code. ? 
Alain CabonAlain Cabon
@Rov: that seems ok excepted the UTF8 encoding that is missing.

 UTF8({stringToSign}

String stringtoSign = 'GET\n\n\n'+dateString;
String encoded = EncodingUtil.urlEncode(stringtoSign , 'UTF-8');

There should be a method:  Crypto.verifyMac  but that doesn't work (?).
Boolean verified = Crypto.verifyMac('HMAC-SHA256', Blob.valueOf(stringToSign),Blob.valueOf(secretAccessKey), mac);
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm
 
RovRov
@alain cabon

I didn't understand what you are suggesting. 
 
Alain CabonAlain Cabon
@Rov;  only the  UTF8 encoding is missing ( pseudo code: UTF8({stringToSign} )

String stringtoSign = 'GET\n\n\n'+dateString;
String encoded = EncodingUtil.urlEncode(stringtoSign , 'UTF-8');
...
Blob mac = Crypto.generateMac('HMAC-SHA256', blob.valueOf(encoded ),blob.valueOf(secretAccessKey));

Moreover (in the other hand), the documentation shows a  method Crypto.verifyMac (for a verification only ), that is not necessary for the conversion only and that doesn't work.if you try it (problem in the documentation of Salesforce?).