package com.sfnt.ldk.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HmacSHA256Util {
	private static final String ALGORITHM_NAME = "HmacSHA256";
	
	private HmacSHA256Util() {
		throw new IllegalStateException("HmacSHA256Util class");
	}
	
	public static byte[] hmacSHA256(byte[] key, byte[] content) throws Exception {
		Mac hmacSha256 = Mac.getInstance(ALGORITHM_NAME);
		hmacSha256.init(new SecretKeySpec(key, 0, key.length, ALGORITHM_NAME));
		return hmacSha256.doFinal(content);
	}

	public static String byteArrayToHexString(byte[] a) {
		StringBuilder sb = new StringBuilder(a.length * 2);
		for (byte b : a)
			sb.append(String.format("%02x", b));
		return sb.toString();
	}

	public static String hmacSHA256(String secret, String message) throws Exception {
		String hash = "";
		Mac hmacSha256 = Mac.getInstance(ALGORITHM_NAME);
		SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), ALGORITHM_NAME);
		hmacSha256.init(secretKey);
		byte[] bytes = hmacSha256.doFinal(message.getBytes());
		hash = byteArrayToHexString(bytes);
		return hash;
	}
}