Guest User

Untitled

a guest
Jul 16th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.nio.charset.StandardCharsets;
  2. import java.security.InvalidKeyException;
  3. import java.security.MessageDigest;
  4. import java.security.NoSuchAlgorithmException;
  5. import java.security.NoSuchAlgorithmException;
  6. import java.util.Base64;
  7.  
  8. import javax.crypto.Mac;
  9. import javax.crypto.spec.SecretKeySpec;
  10.  
  11. class 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. }
Advertisement
Add Comment
Please, Sign In to add comment