Creating a signature. Code samples

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 = "Oe8TBDzg4tatdq2cL9ojeEj3U3oWSCSC5fqOHAqaKVg";
    String method = "POST";
    String body = "{\"amount\":\"100\"}";
    String date = "2019-01-09T11:24:40+00:00";
    String path = "/api/auth/test";
    String contentType = "application/json";

    // 5173e4d02d8a761679b0165b87d9ee5f
    String bodyMD5 = body.isEmpty() ? "" : md5hex(body);

    // POST\n5173e4d02d8a761679b0165b87d9ee5f\napplication/json\n2019-01-09T11:24:40+00:00\n/api/auth/test
    String stringToSign = String.join("\n", method, bodyMD5, contentType, date, path);

    // fVYzUdYqZO1ozBeP3KQHFp9/Kno=
    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();
  }
}

Last updated