Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.nio.charset.StandardCharsets;
- import java.security.InvalidKeyException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.security.NoSuchAlgorithmException;
- import java.util.Base64;
- import javax.crypto.Mac;
- import javax.crypto.spec.SecretKeySpec;
- class Main {
- public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
- String secret = "..."; // Your API Secret
- String method = "GET";
- String body = "";
- String date = "2019-01-09T11:24:40+00:00"; // timestamp
- String path = "/api/rates/BTCEUR";
- String contentType = "application/json";
- String bodyMD5 = body.isEmpty() ? "" : md5hex(body);
- String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);
- String signature = hmac(stringToSign, secret);
- System.out.println(signature);
- }
- private static String md5hex(String str) throws NoSuchAlgorithmException {
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- byte[] bytes = md5.digest(str.getBytes(StandardCharsets.UTF_8));
- return hex(bytes);
- }
- private static String hmac(String str, String secret) throws InvalidKeyException, NoSuchAlgorithmException {
- SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
- Mac mac = Mac.getInstance("HmacSHA1");
- mac.init(secretKey);
- byte[] result = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
- String base64 = Base64.getEncoder().encodeToString(result);
- return base64;
- }
- private static String hex(byte[] bytes) {
- StringBuilder sb = new StringBuilder();
- for (byte b : bytes) {
- sb.append(String.format("%02x", b));
- }
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment