[SalesForce] Creating Amazon S3 Signing Key using Apex

I had an Apex class in which I could connect to my Amazon S3 bucket by creating a request using Sig v.2 for AWS. I now need to change my code to Sig V.4 to connect to a different S3 region. I've been following the instructions on http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.htm

I get an error as follows from Amazon "The request signature we calculated does not match the signature you provided. Check your key and signing method.")

Possible Issue 1 that I can think of: I am creating my signing key incorrectly using Apex.

For Possible Issue 1 I tried to create my Signing Key using the following code

        Blob secretKeyBlob = Blob.valueOf('AWS4' + secretKey);
        Blob dateStringBlob = Blob.valueOf('20141015');
        Blob dateKeyBlob = Crypto.generateMac('hmacSHA256', dateStringBlob, secretKeyBlob);
        Blob regionBlob = Blob.valueOf('eu-west-1');
        Blob dateRegionKeyBlob = Crypto.generateMac('hmacSHA256', regionBlob, dateKeyBlob);
        Blob serviceBlob = Blob.valueOf('s3');
        Blob dateRegionServiceKeyBlob = Crypto.generateMac('hmacSHA256', serviceBlob, dateRegionKeyBlob);
        Blob requestBlob = Blob.valueOf('aws4_request');
        Blob signingKeyBlob = Crypto.generateMac('hmacSHA256', requestBlob, dateRegionServiceKeyBlob);

This is based on the hmacSHA256 signing key representation in the diagram on the page and the following sample given in the page

signing key = HMAC-SHA256(HMAC-SHA256(HMAC-SHA256(HMAC-SHA256("AWS4" + "<YourSecretAccessKey>","20130524"),"us-east-1"),"s3"),"aws4_request")

Should my Apex code work correctly & similar to the pseudocode above as taken from the AWS page? I would have thought my Apex was correct.

I've no way of validating if my signing key is correct therefore I'm not sure if this is the error cause.

Best Answer

I was able to produce a working client with Signature Version 4 Signing by utilising the solution from this existing answer.