package com.qunzhixinxi.hnqz.admin.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

public class HMACSignProvider {

    public List<String> getMechanismNames() {
        List<String> list = new LinkedList<>();
        list.add("HmacSHA256");
        return list;
    }

    public String sign(String type, String privateKey, String data) throws Exception {
        try {
            SecretKey secretKey = new SecretKeySpec(privateKey.getBytes(StandardCharsets.UTF_8),
                    type);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return Base64.encodeBase64String(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw e;
        }

    }

    public boolean verfy(String type, String publicKey, String data, String sign) throws Exception {
        try {
            SecretKey secretKey = new SecretKeySpec(publicKey.getBytes(StandardCharsets.UTF_8),
                    type);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return Base64.encodeBase64String(mac.doFinal(data.getBytes(StandardCharsets.UTF_8))).equals(sign);
        } catch (Exception e) {
            throw e;
        }
    }
}
