在Python Django中实现AWS S3 POST上传SigV4签名时与官方示例结果不匹配的问题求助
Hey, I've run into this exact signature mismatch issue before when building S3 POST upload workflows—let's break down what's going wrong here.
The Core Problem: You're Signing the Wrong Data
Looking at your code snippet, the key mistake is in what you're passing to the HMAC function. AWS requires that you sign the base64-encoded policy string, not the raw JSON policy bytes.
Your current code uses:
signature = hmac.new(sign_key, policy_bytes, hashlib.sha256).hexdigest()
But it should be using the encoded_policy (the base64 result) instead of policy_bytes:
signature = hmac.new(sign_key, encoded_policy, hashlib.sha256).hexdigest()
That's why your signature doesn't match the official example—you're hashing the wrong input entirely.
Confirming Your Policy Format Fix
You mentioned needing to manually add \r\n (CRLF) to each line of the policy, and that json.dumps or pprint didn't generate the correct structure. That's totally accurate because AWS's policy validation is extremely strict about whitespace and line breaks.
Make sure your raw policy string exactly matches the formatting in the official example (including indentation and CRLF line endings) before encoding it to base64. Even a missing newline or extra space will change the base64 output, which in turn breaks the signature.
Corrected Test Code
Here's how your test snippet should look with the fix applied:
# policy_string is your properly formatted JSON with CRLF line breaks policy_bytes = policy_string.encode("utf-8") encoded_policy = base64.b64encode(policy_bytes) # Using AWS test values sign_key = getSignatureKey('wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', '20151229', 'us-east-1', 's3') # Sign the base64-encoded policy, not the raw JSON bytes signature = hmac.new(sign_key, encoded_policy, hashlib.sha256).hexdigest() print("signature = ", signature)
This should generate the expected signature from the AWS example: 8afdbf4008c03f22c2cd3cdb72e4afbb1f6a588f3255ac628749a66d7f09699e
Quick Note for Multipart & iOS Background Uploads
Since you're planning to support these scenarios, once you get the basic POST signature working, ensure your policy includes conditions for multipart fields (like x-amz-multipart-part-number if needed) and that your iOS client correctly includes all required form data fields. Also, double-check your S3 bucket's CORS configuration to allow the headers needed for background transfers.
Hope this fixes your signature issue—let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Eric

