微信支付签名

import cn.hutool.crypto.SecureUtil;
import com.dtyunxi.exchange.api.IFunctionAuthService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * 不要使用,这只是 一个示例
 */
@Component
public class WechatPayCustomFunctionSignAuth implements IFunctionAuthService {
    private static final Logger log = LoggerFactory.getLogger(WechatPayCustomFunctionSignAuth.class);

    @Override
    public void modifyRequest(Map<String, Object> channelContext, Map<String, String> urlParams, Map<String, String> headers, Map<String, Object> body) {
        //String sign = getSignData(channelContext, body);
        String apiKey = channelContext.get("apiKey").toString();
        try {
            String sign = sign(body, apiKey);
            body.put("sign", sign);
        } catch (Exception ex) {

        }
    }

// md5签名方法
    private String getSignData(Map bodyMap, String apiKey) {
        //String apiKey = channelContext.get("apiKey").toString();
        Map<String, String> body = bodyMap instanceof TreeMap ? bodyMap : new TreeMap<>(bodyMap);
        if (body.containsKey("sign")) {
            body.remove("sign");
        }

        List<String> listArray = new ArrayList<>();
        for (Map.Entry<String, String> entry : body.entrySet()) {
            String key = entry.getKey();
            listArray.add(key + "=" + entry.getValue().toString());
        }

        String data = StringUtils.join(listArray, "&") + "&key=" + apiKey;

        return SecureUtil.md5(data).toUpperCase();
    }

    /**
     * HmacSHA256类型签名
     *
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String sign(Map<String, Object> map, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        Map<String, String> params = new HashMap<String, String>();
        Set<String> set = map.keySet();
        for (String string : set) {
            if (!map.get(string).equals("")) {
                params.put(string, String.valueOf(map.get(string)));
            }
        }

        String string1 = createSign(params);
        String stringSignTemp = string1 + "&key=" + key;
        //return DigestUtils.sha256Hex(stringSignTemp).toUpperCase();
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        //  utf-8 : 解决中文加密不一致问题,必须指定编码格式

        return byteArrayToHexString(sha256_HMAC.doFinal(stringSignTemp.getBytes("utf-8"))).toUpperCase();
    }


    /**
     * 构造package
     *
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String createSign(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key.toString()).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            temp.append(valueString);
        }
        return temp.toString();
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}

 

posted @ 2023-08-07 19:14  zslm___  阅读(37)  评论(0编辑  收藏  举报