Newer
Older
br-data-forwarding / src / main / java / com / casic / util / aep / Signature.java
package com.casic.util.aep;

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

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;

public class Signature {

    public Signature() {
    }

    /**
     * 签名
     * 使用AppKey、AppSecretKey、timestamp、MasterAPIKey和业务数据进行签名
     * @param secret AppSecretKey
     * @param application AppKey
     * @param timestamp 时间戳
     * @param masterKey 产品的MasterAPIKey
     * @param body 业务数据
     * @return 返回的签名数据
     * @throws Exception 抛出的需要处理的异常
     */
    public static String sign(String secret, String application, String timestamp, String masterKey, byte[] body) throws Exception {
        if (secret == null) {
            throw new Exception("Secret cannot be null");
        } else if (application == null) {
            throw new Exception("Application cannot be null");
        } else if (timestamp == null) {
            throw new Exception("Timestamp cannot be null");
        } else if (masterKey == null) {
            throw new Exception("MasterAPIKey cannot be null");
        }

        StringBuilder sb = new StringBuilder();
        sb.append("application").append(":").append(application).append("\n");
        sb.append("timestamp").append(":").append(timestamp).append("\n");
        sb.append("MasterKey").append(":").append(masterKey).append("\n");

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        outStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));
        if (body != null && body.length > 0) {
            outStream.write(body);
            outStream.write("\n".getBytes(StandardCharsets.UTF_8));
        }

        return new String(Base64.encodeBase64(encryptHMAC(secret, outStream.toByteArray())));
    }

    public static byte[] encryptHMAC(String secret, byte[] data) {
        byte[] bytes = null;

        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSha1");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data);
        } catch (Exception var5) {
            var5.printStackTrace(System.err);
        }

        return bytes;
    }
}