All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.anjiplus.open.sdk.utils.SignUtils Maven / Gradle / Ivy

There is a newer version: 1.0.15.RELEASE
Show newest version
package com.anjiplus.open.sdk.utils;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Map;

/**
 * 验证签名,防止数据被篡改
 * @author lr
 */
public class SignUtils {

    private final static String SIGN_PARAM="sign";
    private final static String CHARSET_UTF8 = "UTF-8";
    private final static String TYPE = "HmacMD5";
    private final static String SLAT = "OPEN_P@SS1234";

    /**
     * 请求生成生产签名
     * @param params 参数
     * @param secret 私钥
     * @return 秘钥
     */
    public static String generateSign(Map params, String secret){
        // 第一步:检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步:把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        for (String key : keys) {
            //跳过参数"sign",sign不参与签名
            if(StringUtils.equals(SIGN_PARAM,key)) {
                continue;
            }
            Object value = params.get(key);
            if (value !=null && !"".equals(value)) {
                query.append(key).append(value);
            }
        }
        //加盐值
        query.append(SLAT);

        // 第三步:使用HMAC加密
        byte[] bytes = encryptHMAC(query.toString(), secret);
        if(bytes == null) {
            return null;
        }
        // 第四步:把二进制转化为大写的十六进制(正确签名应该为32大写字符串,此方法需要时使用)
        return byte2hex(bytes);
    }

    /**
     * 加密
     * @param data 加密数据
     * @param secret 秘钥
     * @return 加密的字节
     */
    public static byte[] encryptHMAC(String data, String secret){
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), TYPE);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes(CHARSET_UTF8));
        } catch (GeneralSecurityException gse) {
            return null;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
        return bytes;
    }

    /**
     * 转16进制
     * @param bytes 字节数组
     * @return 返回16进制
     */
    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy