· 6 years ago · Jul 16, 2019, 05:14 PM
1import java.nio.charset.StandardCharsets;
2import java.security.InvalidKeyException;
3import java.security.MessageDigest;
4import java.security.NoSuchAlgorithmException;
5import java.security.NoSuchAlgorithmException;
6import java.util.Base64;
7
8import javax.crypto.Mac;
9import javax.crypto.spec.SecretKeySpec;
10
11class Main {
12 public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
13 String secret = "..."; // Your API Secret
14 String method = "GET";
15 String body = "";
16 String date = "2019-01-09T11:24:40+00:00"; // timestamp
17 String path = "/api/rates/BTCEUR";
18 String contentType = "application/json";
19
20 String bodyMD5 = body.isEmpty() ? "" : md5hex(body);
21
22 String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);
23
24 String signature = hmac(stringToSign, secret);
25
26 System.out.println(signature);
27 }
28
29 private static String md5hex(String str) throws NoSuchAlgorithmException {
30 MessageDigest md5 = MessageDigest.getInstance("MD5");
31 byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
32
33 return hex(bytes);
34 }
35
36 private static String hmac(String str, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
37 SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
38
39 Mac mac = Mac.getInstance("HmacSHA1");
40 mac.init(secretKey);
41 byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
42
43 String base64 = Base64.getEncoder().encodeToString(result);
44
45 return base64;
46 }
47
48 private static String hex(byte[] bytes) {
49 StringBuilder sb = new StringBuilder();
50
51 for (byte b : bytes) {
52 sb.append(String.format("%02x", b));
53 }
54
55 return sb.toString();
56 }
57}