package com.galaxis.manatee.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author zcj
 * @version 0.1
 * @date 2020/1/8 10:36 下午
 */
public class DingTalkRobotUtils {

    /**
     * 给url签名的工具方法
     * @param secret        对应机器人的签名密钥
     * @param timestamp     时间戳
     * @return  完成签名的
     * @throws NoSuchAlgorithmException     算法名不对的异常
     * @throws UnsupportedEncodingException 不支持的编码
     * @throws InvalidKeyException          非法的关键字
     */
    public static String sign(String secret,Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)),StandardCharsets.UTF_8);
    }
}
