Friday 11 January 2013

Amazon S3 signature for Apex

Hi,

Please find below the method to return a valid signature generated in Salesforce's Apex language.
This signature is required to make any Rest/Soap call on Amazon's S3 servers.

Arguments to this method are : Current DateTime and the name of Operation that you want to perform for example "Get Object".

 public static String getSignature(DateTime now,String op){
       
        //format should be like 2006-01-01T12:00:00.000Z
        String formattednow = now.formatGmt('yyyy-MM-dd')+'T'+now.formatGmt('HH:mm:ss')+'.'+now.formatGMT('SSS')+'Z';
        System.Debug('Formatted date : '+formattednow);
       
        String canonical = 'AmazonS3'+op+formattednow; //"AmazonS3" + OPERATION + Timestamp
       
        System.debug('CANONICAL = '+canonical);
       
        Blob bsig = Crypto.generateMac('HmacSHA1', Blob.valueOf(canonical), Blob.valueOf(secretAccessKey));
       
       
        String signature = EncodingUtil.base64Encode(bsig);
        return signature;
    }