· 7 years ago · Jan 24, 2019, 02:56 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 = "Oe8TBDzg4tatdq2cL9ojeEj3U3oWSCSC5fqOHAqaKVg";
14 String method = "POST";
15 String body = "{\"amount\":\"100\"}";
16 String date = "2019-01-09T11:24:40+00:00";
17 String path = "/api/auth/test";
18 String contentType = "application/json";
19
20 // 5173e4d02d8a761679b0165b87d9ee5f
21 String bodyMD5 = body.isEmpty() ? "" : md5hex(body);
22
23 // POST\n5173e4d02d8a761679b0165b87d9ee5f\napplication/json\n2019-01-09T11:24:40+00:00\n/api/auth/test
24 String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);
25
26 // fVYzUdYqZO1ozBeP3KQHFp9/Kno=
27 String signature = hmac(stringToSign, secret);
28
29 System.out.println(signature);
30 }
31
32 private static String md5hex(String str) throws NoSuchAlgorithmException {
33 MessageDigest md5 = MessageDigest.getInstance("MD5");
34 byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
35
36 return hex(bytes);
37 }
38
39 private static String hmac(String str, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
40 SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
41
42 Mac mac = Mac.getInstance("HmacSHA1");
43 mac.init(secretKey);
44 byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
45
46 String base64 = Base64.getEncoder().encodeToString(result);
47
48 return base64;
49 }
50
51 private static String hex(byte[] bytes) {
52 StringBuilder sb = new StringBuilder();
53
54 for (byte b : bytes) {
55 sb.append(String.format("%02x", b));
56 }
57
58 return sb.toString();
59 }
60}