Reputation: 13
Following is my code. But it always throw an error for signature did not match. Not sure what is wrong with it? With Same URL if signature generated from azure portal, resource loads fine.
String accessKey = "<API KEy from azure portal>";`your text`
String accountName = "<My account name>";
String signedPermissions = "rwdlacupiy";
String signedService = "bfqt";
String signedResType = "o";
String signedIp = "";
String protocol = "https";
String AZURE_API_VERSION = "2021-12-02";
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, -2);
String start = fmt.format(cal.getTime());
cal.add(Calendar.DATE, 4);
String expiry1 = fmt.format(cal.getTime());
String stringToSign = ACCOUNT_NAME + "\n" +
signedPermissions + "\n" +
signedService + "\n" +
signedResType + "\n" +
start + "\n" +
expiry1 + "\n" +
signedIp + "\n" +
protocol + "\n" +
AZURE_API_VERSION+"\n";
//System.out.println("string to sign "+ stringToSign);
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(accessKey), "HmacSHA256");
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
sha256HMAC.init(secretKey);
String signature =
Base64.getEncoder().encodeToString(sha256HMAC.doFinal(stringToSign.getBytes("UTF-8")));
//System.out.println("signature "+URLEncoder.encode(signature, "UTF-8"));
String sasToken = "sv=" + AZURE_API_VERSION +
"&ss=" + signedService +
"&srt=" + signedResType +
"&sp=" + signedPermissions +
"&se=" + URLEncoder.encode(expiry1, "UTF-8") +
"&st=" + URLEncoder.encode(start, "UTF-8") +
"&spr=" + protocol +
"&sig=" + URLEncoder.encode(signature, "UTF-8") ;
//System.out.println("sasToken1 "+sasToken);
String resourceUrl="https://<accountName >.file.core.windows.net/<My resource path>"; // this is file resource
URL url;
try {
url = new URL(resourceUrl+"?"+sasToken);
InputStream in =url.openStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}`
Error is always 403 on the resource URL and if I place the URL in browser it is always Signature did not match. String to sign used was rwdlacupiy bfqt o 2023-03-08T02:23:43Z 2023-03-12T01:23:43Z
https 2021-12-02
I tried above steps and not sure what is wrong. ACCESS key is copied from azure portal. IF I generate SAS token from azure portal signature works but not with the program.
Upvotes: 1
Views: 656
Reputation: 136346
Considering you are using REST API version 2021-12-02
, your stringToSign
should be constructed using the following logic:
StringToSign = accountname + "\n" +
signedpermissions + "\n" +
signedservice + "\n" +
signedresourcetype + "\n" +
signedstart + "\n" +
signedexpiry + "\n" +
signedIP + "\n" +
signedProtocol + "\n" +
signedversion + "\n" +
signedEncryptionScope + "\n"
Please note signedEncryptionScope
in the string to sign.
Upvotes: 0