-
Notifications
You must be signed in to change notification settings - Fork 1
/
sample.java
62 lines (47 loc) · 1.95 KB
/
sample.java
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.parser.JSONParser;
class sample {
public static byte[] base64_url_decode(String input) throws IOException {
return new Base64(true).decode(input);
}
public static Map parse_signed_request(String input, String secret) throws Exception {
return parse_signed_request(input, secret, 3600);
}
public static Map parse_signed_request(String input, String secret, int max_age) throws Exception {
String[] split = input.split("[.]", 2);
String encoded_sig = split[0];
String encoded_envelope = split[1];
JSONParser parser = new JSONParser();
Map envelope = (Map) parser.parse(new String(base64_url_decode(encoded_envelope)));
String algorithm = (String) envelope.get("algorithm");
if (!algorithm.equals("HMAC-SHA256")) {
throw new Exception("Invalid request. (Unsupported algorithm.)");
}
if (((Long) envelope.get("issued_at")) < System.currentTimeMillis() / 1000 - max_age) {
throw new Exception("Invalid request. (Too old.)");
}
byte[] key = secret.getBytes();
SecretKey hmacKey = new SecretKeySpec(key, "HMACSHA256");
Mac mac = Mac.getInstance("HMACSHA256");
mac.init(hmacKey);
byte[] digest = mac.doFinal(encoded_envelope.getBytes());
if (!Arrays.equals(base64_url_decode(encoded_sig), digest)) {
throw new Exception("Invalid request. (Invalid signature.)");
}
return envelope;
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String input = in.readLine();
String secret = "13750c9911fec5865d01f3bd00bdf4db";
System.out.println(parse_signed_request(input, secret));
}
}