package com.tcl.ah.security;

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

public class HmacSha256 {
    public static String encrypt(String message,String secret){
        return encrypt(message,secret.getBytes());
    }
    public static String encrypt(String message,byte[] secret){
        return encrypt(message.getBytes(),secret);
    }
    public static String encrypt(byte[] message,byte[] secret){
        final String algorithm="HmacSHA256";
        try {
            Mac sha256_HMAC = Mac.getInstance(algorithm);
            SecretKeySpec secret_key = new SecretKeySpec(secret, algorithm);
            sha256_HMAC.init(secret_key);

            String hash = byteArrayToHexString(sha256_HMAC.doFinal(message));
            return hash;
        }
        catch (Exception e){
            System.out.println("Error");
        }
        return null ;
    }

    public static byte[] encrypt2(byte[] message,byte[] secret){
        final String algorithm="HmacSHA256";
        try {
            Mac sha256_HMAC = Mac.getInstance(algorithm);
            SecretKeySpec secret_key = new SecretKeySpec(secret, algorithm);
            sha256_HMAC.init(secret_key);
            return sha256_HMAC.doFinal(message);
        }
        catch (Exception e){
            System.out.println("Error");
        }
        return null ;
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}
