References:
- https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_encodingUtil.htm
public class AwsS3Utility {
static String BUCKET_NAME = 'YOUR_BUCKET_NAME';
static String ACCESS_KEY = 'YOUR_ACCESS_KEY';
static String SECRET_KEY = 'YOUR_SECRET_KEY';
public static String getSignedDownloadUrl(String bucketKey, Integer expiresInSec) {
Datetime now = DateTime.now();
Datetime expiresAt = now.AddSeconds(expiresInSec); // Lifespan of the link
Long expires = expiresAt.getTime() / 1000;
String stringToSign = 'GET\n\n\n' + expires + '\n/' + BUCKET_NAME + '/' + bucketKey;
System.debug('redirectToS3Key stringToSign: ' + stringToSign);
String signingKey = EncodingUtil.base64Encode(Blob.valueOf(SECRET_KEY));
Blob mac = Crypto.generateMac('HMacSHA1', Blob.valueof(stringToSign), Blob.valueof(SECRET_KEY));
String signed= EncodingUtil.base64Encode(mac);
String codeSigned = EncodingUtil.urlEncode(signed,'UTF-8');
String url = 'https://' + BUCKET_NAME + '.s3.amazonaws.com/' + bucketKey + '?AWSAccessKeyId=' + ACCESS_KEY + '&Expires=' + expires + '&Signature=' + codeSigned;
return url;
}
}