S3签名不匹配错误 - SignatureDoesNotMatch

时间:2015-10-16 18:38:00

标签: java amazon-s3 digital-signature

我正在使用AWS' S3示例文件上传但似乎无法获得与其计算值匹配的签名。任何建议将不胜感激。

示例:https://aws.amazon.com/articles/1434

使用Tomcat 8,Java 1.8.60

我的JSP文件:

<%@ page import="java.util.Base64" %>
<%@ page import="javax.crypto.Mac" %>
<%@ page import="javax.crypto.spec.SecretKeySpec" %>

<html>

<head>
   <meta http-equiv="Content-Type" content="image/jpeg; charset=UTF-8" />
</head>

<body>

<%
    String policy =
        "{\"expiration\": \"2020-01-01T00:00:00Z\"," + 
          "\"conditions\": [" +  
            "{\"bucket\": \"my-bucket\"}," +  
//          "[\"starts-with\", \"$key\", \"*\"]," + 
            "{\"acl\": \"private\"}," + 
            "{\"success_action_redirect\": \"OpSuccess.jsp\"}," + 
            "[\"starts-with\", \"$Content-Type\", \"\"]," + 
            "[\"content-length-range\", 0, 1048576]" +
            "]" + 
        "}";

        policy.replaceAll("\n","").replaceAll("\r","");

        String encPolicy =  Base64.getEncoder().encodeToString(policy.getBytes("UTF-8"));       


        String awsAccessKeyId = <my id>;
        String awsSecretKey   = <my private key>;


        Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(awsSecretKey.getBytes("UTF-8"), "HmacSHA1"));
        String signature = Base64.getEncoder().encodeToString(hmac.doFinal(policy.getBytes("UTF-8"))).replaceAll("\n", "").replaceAll("\r","");
%>

    <form action="https://s3.amazonaws.com/my-bucket/" method="post" enctype="multipart/form-data">

      <input type="hidden" name="key" value="p_1_L.jpg">
      <input type="hidden" name="AWSAccessKeyId" value="<%= awsAccessKeyId %>"> 
      <input type="hidden" name="acl" value="private"> 
      <input type="hidden" name="success_action_redirect" value="OpSuccess.jsp">
      <input type="hidden" name="policy" value="<%= encPolicy %>" >
      <input type="hidden" name="signature" value="<%= signature %>" >
      <input type="hidden" name="Content-Type" value="image/jpeg">

      File to upload to S3: 
      <input name="file" type="file"> 
      <br> 
      <input type="submit" value="Upload File to S3"> 
    </form> 

 </body>

 </html>

1 个答案:

答案 0 :(得分:0)

经过一番挖掘,我发现了问题。我正在签署该策略的字符串版本而不是base64编码版本...

String signature = Base64.getEncoder().encodeToString(hmac.doFinal(*policy*.getBytes("UTF-8"))).replaceAll("\n", "").replaceAll("\r","");
%>

Should be

String signature = Base64.getEncoder().encodeToString(hmac.doFinal(*encPolicy*.getBytes("UTF-8"))).replaceAll("\n", "").replaceAll("\r","");
%>

in the above example