Repository navigation
Expand file tree
/
Copy pathdpssastoken.java
More file actions
73 lines (61 loc) · 2.47 KB
/
Copy pathdpssastoken.java
File metadata and controls
73 lines (61 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package azure;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Base64.Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class dpssastoken {
public String GetderivedKey(String device_id,String scope_id,String dpskey) {
String derivedKey = "";
String stringToSign = "";
try {
stringToSign = URLEncoder.encode(device_id, "UTF-8");
derivedKey = getHMAC256(dpskey, stringToSign);
System.out.println("Derived Key: " + derivedKey);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return derivedKey;
}
public String GenerateSasToken(String resourceUri, String keyName, String key) {
long epoch = System.currentTimeMillis()/1000L;
int week = 60*60*24*364; //year
String expiry = Long.toString(epoch + week);
String sasToken = null;
try {
String stringToSign = URLEncoder.encode(resourceUri, "UTF-8") + "\n" + expiry;
String signature = getHMAC256(key, stringToSign);
sasToken = "SharedAccessSignature sr=" + URLEncoder.encode(resourceUri, "UTF-8") +"&sig=" +
URLEncoder.encode(signature, "UTF-8") + "&se=" + expiry+ "&skn=" + keyName;
System.out.println("sasToken: " + sasToken);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return sasToken;
}
public static String getHMAC256(String key, String input) {
Mac sha256_HMAC = null;
String hash = null;
try {
sha256_HMAC = Mac.getInstance("HmacSHA256");
// SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "HmacSHA256");
sha256_HMAC.init(secretKey);
Encoder encoder = Base64.getEncoder();
hash = new String(encoder.encode(sha256_HMAC.doFinal(input.getBytes("UTF-8"))));
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return hash;
}
}