I'm having trouble trying to figure out what is required for the signature. I see some examples using hex, and others I see using base64. Which one is it?
Base64.encode64(OpenSSL::HMAC.digest('sha256', getSignatureKey, @policy)).gsub(/\n|\r/, '')
Or:
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), getSignatureKey, @policy).gsub(/\n|\r/, '')
Okay, so I got it. There are two very important things to consider when creating the signature. A) how the signature is calculated, and B) how your bucket policy is set up. I'm assuming that your CORS are configured to allow a post, and that your IAM user/group has s3 access; and really should only have s3 access.
The bucket policy for the form data requires:
["starts-with", "$key", "{{intended_file_path}}"],
"x-amz-credential",
"x-amz-algorithm",
"x-amz-date",
"bucket"
The ["starts-with", "$key" should be the intended file destination path - ie, "uploads", or "user/jack/", or "images", whatever - see example below.
Here is how I signed my signatures, as well as my bucket policy.
Bucket Config:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Allow Get",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example-development/*"
},
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789:user/example"
},
"Action": "s3:*",
"Resource": ["arn:aws:s3:::example-development/*","arn:aws:s3:::example-development"]
}
]
}
Backend:
def string_to_sign
@time = Time.now.utc
@time_policy = @time.strftime('%Y%m%dT000000Z')
@date_stamp = @time.strftime('%Y%m%d')
ret = {"expiration" => 10.hours.from_now.utc.iso8601,
"conditions" => [
{"bucket" => ENV["aws_bucket"]},
{"x-amz-credential": "#{ENV["aws_access_key"]}/#{@date_stamp}/us-west-2/s3/aws4_request"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{ "acl": "public-read" },
{"x-amz-date": @time_policy },
["starts-with", "$key", "uploads"],
]
}
@policy = Base64.encode64(ret.to_json).gsub(/\n|\r/, '')
end
def getSignatureKey
kDate = OpenSSL::HMAC.digest('sha256', ("AWS4" + ENV["aws_secret_key"]), @date_stamp)
kRegion = OpenSSL::HMAC.digest('sha256', kDate, 'us-west-2')
kService = OpenSSL::HMAC.digest('sha256', kRegion, 's3')
kSigning = OpenSSL::HMAC.digest('sha256', kService, "aws4_request")
end
def sig
sig = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), getSignatureKey, @policy).gsub(/\n|\r/, '')
end