签名不匹配。使用的签名字符串是 rl

Signature did not match. String to sign used was rl

我正在尝试为 blob 创建 Azure SAS。但是,我收到身份验证失败错误。无论我尝试什么,我都无法构建格式正确的 stringToSign 或签名。

错误说:

“签名不匹配。使用的签名字符串是 rl 2021-03-11T08:08:46Z 2021-03-12T08:08:46Z /blob/{myAccountName}[=29= .txt 2020-02-10 b“

我的 stringToSign 是:

    String stringToSign= "rl\n"+ 
                         "2021-03-11T08:08:46Z" +"\n" + 
                         "2021-03-12T08:08:46Z"+ "\n"+ 
                         "\n"+ 
                         "\n"+ 
                         "\n"+ 
                         "\n"+ 
                         2020-02-10"+ 
                         "\n"+"\n"+"\n"+"\n"+"\n";
     String signature = getHMAC256(key, stringToSign);

我的 SAS 令牌 uri 是:

      String sasToken = "?sp=rl"
                        + "&st=" +  "2021-03-11T08:08:46Z" 
                        + "&se=" +  "2021-03-12T08:08:46Z"
                        + "&sv=" +  "2020-02-10"
                        + "&sr=b"
                        + "&sig=" + URLEncoder.encode(signature, "UTF-8"); 

加密函数为:

  public static String computeHMac256(final String base64Key, final String stringToSign) {
        try {
            byte[] key = Base64.getDecoder().decode(base64Key);
            Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
            hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256"));
            byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8);
            return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes));
        } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
            throw new RuntimeException(ex);
        }
    }  

如何为我的 sas uri 生成格式正确的签名?

根据提供的说明 here,您的 stringToSign 应符合以下结构:

StringToSign = signedPermissions + "\n" +  
               signedStart + "\n" +  
               signedExpiry + "\n" +  
               canonicalizedResource + "\n" +  
               signedIdentifier + "\n" +  
               signedIP + "\n" +  
               signedProtocol + "\n" +  
               signedVersion + "\n" +  
               signedResource + "\n"
               signedSnapshotTime + "\n" +
               rscc + "\n" +  
               rscd + "\n" +  
               rsce + "\n" +  
               rscl + "\n" +  
               rsct

这与您正在做的不一样。本质上你缺少 canonicalizedResourcesignedResource 参数。

请正确构成 stringToSign,您应该不会遇到遇到的错误。我认为它应该是这样的(虽然没有测试):

String stringToSign= "rl\n"+ 
                     "2021-03-11T08:08:46Z" +"\n" + 
                     "2021-03-12T08:08:46Z"+ "\n"+ 
                     "/blob/{myAccountName}/quickstartcontainer/sampleFile2813061026464365578.txt 2020-02-10\n"+ 
                     "\n"+ 
                     "\n"+ 
                     "\n"+ 
                     2020-02-10"+"\n"+ 
                     "b\n"+"\n"+"\n"+"\n"+"\n"+"\n";