package com.xhpc.evcs.encryption;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class HMAC {

    public static void main(String[] args) throws Exception {

        System.out.println(hmacDigest("MA005DBW1ywyEEd5aKPJOTraAY/gXB45odqp5Axj1BXk+4tvClkdXyWpD/EfoC1w7mCwkCICPseWumr" +
                "iDz4CJW2GKaTdaVmmx5GDa+LlLMJvcFEgXgJZDypWLeRW4ijOjsQ+MrXafhaDfd5zMPYyhEXNhe4UXzK/70vCRNOCltcM" +
                "+iXsZJcHBFna0mk5" +
                "Dl8/o0WZF3tym20211117191615987", "wAeYIVQUwd0iGZsV", "HmacMD5"/*"HmacSHA1"*/));
    }

    public static String hmacDigest(String operatorID, String data, String timestamp, String seq, String keyString) {

        return hmacDigest(operatorID + data + timestamp + seq, keyString, "HmacMD5");
    }

    public static String hmacDigest(String msg, String keyString) {

        return hmacDigest(msg, keyString, "HmacMD5");
    }

    public static String hmacDigest(String msg, String keyString, String algo) {

        String digest = null;
        try {
            SecretKeySpec key = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), algo);
            Mac mac = Mac.getInstance(algo);
            mac.init(key);

            byte[] bytes = mac.doFinal(msg.getBytes(StandardCharsets.US_ASCII));

            StringBuffer hash = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toHexString(0xFF & bytes[i]);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            digest = hash.toString().toUpperCase();
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            e.printStackTrace();//todo remove pod
            log.error(e.getMessage());
        }
        return digest;
    }

}
