on Technology

Amazon S3 HMAC Signatures without PEAR or PHP5

The Amazon S3 proposal for uploading via POST describes how to assemble a policy document that can be used to create a time-sensitive signature. The obvious advantage to this method is that you don't have to worry about someone stealing your secret AWS key or uploading random files without your permission.

Here is the example policy document from the proposal:

This Policy document is Base64 encoded and the Signature is the HMAC of the Base64 encoding.

The application I am developing at work requires this signed policy method of uploading files to S3, however I needed to do it with PHP4 and preferably without any extra PEAR packages. This posed somewhat of a challenge, as all the tutorials I found on the web explained how to sign the policy using the PEAR Crypt_HMAC package or some feature of PHP5.

I eventually figured it out, and I'm here to show you how. The two functions used were found on the web (I don't remember exactly where) and worked perfectly for my situation.

(Note: I had a lot of trouble saving the contents of the following code in WordPress due to some Apache mod_security settings configured on my server.)

That's it! This method doesn't require PHP5 and doesn't require any additional PEAR packages.

Write a Comment



  1. Excellent piece of code!!!

    Verry good for people not interested in libs. Also a good basis for further dev on html post s3 tricks.

  2. You are my f*ing hero! I spent a lot of time trying to generate signatures using hash_hmac(‘sha1’) from the hash extension for php and it does NOT produce proper results (according to amazon). Thank you!

  3. Thanks Sam!

    I too tried the hash_hmac(‘sha1’) from the has extension and wasn’t able to get it working with Amazon’s stuff, but I never figured out why.

  4. MOUHAHAHAH . This is what i have been lookin for …. .
    Yes i tryied to combine javascript code with SHA1.js and php . But Didnt generate the matching signature . But this is just great . Thx to you.

  5. Thank you Raam Dev, excellent piece of code for Amazon S3.Can you help me generate a policy and signature for Google cloud storage even by some php code.

  6. How to allow only specific email address to view the file uploaded in amazon s3 which is set private.

    for example user1 has added a file in amazon s3,he wants only user2@test.com to view the file.

    Is it possile to acheive it through php code?

  7. Nice and thank you. I ran from the command line to use in a non-php implementation. Just added and populated the $secretkey variable, a simple policy and print $base64_policy;
    print ‘##############’;
    print $secretkey;