java实现参数名ASCII字典序排序并MD5加密

package com.example.demo_java8_new_characteristic.test;


import org.apache.commons.lang.StringUtils;

import java.security.MessageDigest;
import java.util.*;

public class MD5Utils {

    /**
     * sign 签名 (参数名按ASCII码从小到大排序(字典序)+key+MD5+转大写签名)
     * @param map
     * @return
     */
    public static String encodeSign(SortedMap map, String key){
        if(StringUtils.isEmpty(key)){
            throw new RuntimeException("签名key不能为空");
        }
        Set> entries = map.entrySet();
        Iterator> iterator = entries.iterator();
        List values =new ArrayList();

        while(iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String k = String.valueOf(entry.getKey());
            String v = String.valueOf(entry.getValue());
            if (StringUtils.isNotEmpty(v) && entry.getValue() !=null && !"sign".equals(k) && !"key".equals(k)) {
                values.add(k + "=" + v);
            }
        }
        values.add("key="+ key);
        String sign = StringUtils.join(values, "&");
        return encodeByMD5(sign).toUpperCase();
    }
    /**
     * 通过MD5加密
     *
     * @param algorithmStr
     * @return String
     */
    public static String encodeByMD5(String algorithmStr) {
        if (algorithmStr==null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("md5");
            messageDigest.update(algorithmStr.getBytes("utf-8"));
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private static String getFormattedText(byte[] digest){
        StringBuffer buffer = new StringBuffer();
        //把每一个byte,做一个与运算,0xff
        for (byte b :
                digest) {
            int number=b & 0xff;//加盐
            String str = Integer.toHexString(number);
            if (str.length() == 1){
                buffer.append("0");
            }
            buffer.append(str);
        }
        //标准的md5加密后的结果
        return buffer.toString();
    }


    public static void main(String[] args) {

        TreeMap stringStringTreeMap = new TreeMap<>();
        stringStringTreeMap.put("cardAccNum","2");
        stringStringTreeMap.put("liquidationDate","20170101");
        stringStringTreeMap.put("amount","100.00");
        stringStringTreeMap.put("sourceChannel","1");
        stringStringTreeMap.put("serialNum","29199388433");
        stringStringTreeMap.put("eWalletId","1");
        stringStringTreeMap.put("accNum","2");

        String s = MD5Utils.encodeSign(stringStringTreeMap, "123456");
        System.out.println(s);
        System.out.println(s.equals("322C77067A392E9A8960CDEBCE147B5E"));
    }
}

 

你可能感兴趣的:(MD5,签名,MD5,java)