package in.gov.digilocker.uidai.web.validator;

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

import org.springframework.stereotype.Component;

@Component
public class HMacAlgorithm {
	public String hmacSha1(String KEY, String VALUE) {
		return hmacSha(KEY, VALUE, "HmacSHA1");
	}

	public String hmacSha256(String KEY, String VALUE) {
		return hmacSha(KEY, VALUE, "HmacSHA256");
	}

	private static String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
		try {
			SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
			Mac mac = Mac.getInstance(SHA_TYPE);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));

			byte[] hexArray = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97, 98, 99, 100, 101, 102 };

			byte[] hexChars = new byte[rawHmac.length * 2];
			for (int j = 0; j < rawHmac.length; j++) {
				int v = rawHmac[j] & 0xFF;
				hexChars[(j * 2)] = hexArray[(v >>> 4)];
				hexChars[(j * 2 + 1)] = hexArray[(v & 0xF)];
			}
			return new String(hexChars);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
}
