Posted by & filed under Programming.

The last step in signing the API request to AWS is calculating the signature using the secret key. Here is a subroutine to calculate it in a bash script. Make sure openssl is at least 1.0.0

function sign {
  kSecret=$(printf "AWS4$1" | xxd -p -c 256)
  kDate=$(printf "$2" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$kSecret | xxd -p -c 256)
  kRegion=$(printf "$3" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$kDate | xxd -p -c 256)
  kService=$(printf "$4" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$kRegion | xxd -p -c 256)
  kSigning=$(printf "aws4_request" | openssl dgst -binary -sha256 -mac HMAC -macopt hexkey:$kService | xxd -p -c 256)
  signedString=$(printf "$5" | openssl dgst -binary -hex -sha256 -mac HMAC -macopt hexkey:$kSigning | sed 's/^.* //')
  $(printf $signedString > $6)
}

Call it using

sign $KEY $DATE $REGION $SERVICE "$STRING" $OUTPUT

AWS Signature v4 in Bash

One Response to “AWS Signature v4 in Bash”

  1. Landon R

    Dude you ROCK!!!! I was struggling with this for like 2 days..I was missing the last bit “sed ‘s/^.* //'” and using the wrong freaking openssl version…

Leave a Reply

  • (will not be published)