· 8 years ago · Jan 18, 2018, 02:08 AM
1private JSONObject getAuthenticatedData() throws NoSuchAlgorithmException
2 {
3 try {
4 String timestamp= Instant.now().getEpochSecond()+"";
5 String accessSign = getAccess(timestamp);
6
7 String apiKey = properties.getProperty("key");
8 String passphrase = properties.getProperty("passphrase");
9 System.out.println("$: "+accessSign);
10
11 URL url = new URL("https://" + properties.getProperty("host") + "/accounts");
12 HttpURLConnection con = (HttpURLConnection) url.openConnection();
13 con.setRequestMethod("GET");
14
15 con.setRequestProperty("CB-ACCESS-KEY", apiKey);
16 con.setRequestProperty("CB-ACCESS-SIGN", accessSign);
17 con.setRequestProperty("CB-ACCESS-PASSPHRASE", passphrase);
18 con.setRequestProperty("CB-ACCESS-TIMESTAMP", timestamp);
19 con.setRequestProperty("Content-Type", "application/json");
20
21 con.setConnectTimeout(5000);
22 con.setReadTimeout(5000);
23
24 String status = con.getResponseMessage();
25 System.out.println(status);
26
27 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
28 String inputLine;
29 StringBuffer content = new StringBuffer();
30 while ((inputLine = in.readLine()) != null) {
31 content.append(inputLine);
32 }
33 System.out.println(content);
34 in.close();
35
36 con.disconnect();
37 }catch(Exception e) {
38 e.printStackTrace();
39 }
40
41 return null;
42
43 }
44
45 private String getAccess(String timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
46 String secret = properties.getProperty("secret");
47 String prehash = timestamp+"GET"+"/accounts";
48
49 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
50 byte[] secretDecoded = Base64.getDecoder().decode(secret);
51 SecretKeySpec secret_key = new SecretKeySpec(secretDecoded, "HmacSHA256");
52 sha256_HMAC.init(secret_key);
53
54 return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(prehash.getBytes()));
55 }