I solved the problem. Amazon S3 requires the headers to be in alphabetical order.
All the documentation shows the header as : x-amz-server-side-encryptionBut when creating the canonical request we need to specify it like this (Camel case). Got me stumped for a while.
defaults.put('X-Amz-Server-Side-Encryption','aws:kms');
or
defaults.put('X-Amz-Server-Side-Encryption','AES256');