I am trying to create an Azure SAS to a blob. However, I am getting authentication failed error. Whatever I try, I am not able to construct a well formed stringToSign or signiture.
The error says:
"Signature did not match. String to sign used was rl 2021-03-11T08:08:46Z 2021-03-12T08:08:46Z /blob/{myAccountName}/quickstartcontainer/sampleFile2813061026464365578.txt 2020-02-10 b "
My stringToSign is :
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);
My SAS token uri is :
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");
The encryption function is:
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);
}
}
How can I generate a well formed signiture for my sas uri?
According to the instructions provided
here
, yourstringToSign
should conform to the following structure:Which is not the same as what you're doing. Essentially you're missing
canonicalizedResource
andsignedResource
parameters.Please form your
stringToSign
properly and you should not get the error you're encountering. I think it should be something like (not tested though):