2

Description

In order to upload files from a visual force page to s3 via AJAX. I had to find a way to generate a valid s3 policy and signature.

The issue

How to generate a signature and policy in SFDC?

1 Answer 1

3

My solution

/**
* @description S3 Policy and signature 
*/
public class S3PolicySignatureGenerator
{
    private String bucket;
    private String accessKeyId;
    private String secret;
    private String policy;

    public S3PolicySignatureGenerator(String bucket, String accessKeyId, String secret)
    {
        this.bucket = bucket;
        this.accessKeyId = accessKeyId;
        this.secret = secret;
    }
    /**
    * @description policy
    */
    public String getPolicy()
    {
        if (policy == null)
        {
            Map<String, Object> signatureObject = new Map<String, Object>
            {
                'expiration' => '2015-12-01T12:00:00.000Z',
                'conditions' => new List<Object>{
                    new Map<String, String>{'bucket' => bucket},
                    new Map<String, String>{'acl' => 'public-read'},
                    new List<String>{'starts-with', '$key', ''},
                    new List<String>{'starts-with', '$Content-Type', ''},
                    new Map<String, String>{'success_action_status' => '201'},
                    new Map<String, String>{'X-Requested-With' => 'xhr'}
                    // add more paramters here
                }
            };
            String signatureString = Json.serialize(signatureObject);
            Blob policyBlob = Blob.valueOf(signatureString);
            policy = EncodingUtil.base64Encode(policyBlob);
        }

        return policy;

    }
    /**
    * @description getAccessKey
    */
    public String getAccessKeyId()
    {
        return accessKeyId;
    }

    /**
    * @description sign req
    */
    public String getSignature()
    {

        Blob signature = Crypto.generateMac('hmacSHA1', Blob.valueOf(getPolicy()), Blob.valueOf(secret));
        return EncodingUtil.base64Encode(signature);
    }
}
3
  • You post the question and the answer in the same time ? Why ?
    – SF_user
    Aug 5, 2014 at 12:19
  • 1
    to find the answer in the future a bit easier. Aug 5, 2014 at 12:19
  • is it possible to post the vf page? i want to achieve this and also save the url into a field
    – manza
    Aug 9, 2014 at 8:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .