接口安全--http数字签名

原文:https://blog.csdn.net/u011521890/article/details/55506716

 

import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import java.util.Comparator;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;

public class SignUtils {
    
    /**
     * 参数签名加密
     * @param parameters
     * @param secret
     * @return
     */
    public static String signRequest(TreeMap<String,String> parameters,String secret,String charset){

        TreeMap<String, String> treeMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        treeMap = (TreeMap<String, String>) parameters;
        System.out.println("升序排序结果:"+treeMap);
        StringBuffer sb = new StringBuffer();
        //把map中的集合拼接成字符串
        for(Map.Entry<String, String> entry:treeMap.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            sb.append(key).append("=").append(value).append("&");
        }
        sb.append("key").append("=").append(secret);
        System.out.println("拼接后的字符:"+sb.toString());
        //进行MD5加密
        String sign = DigestUtils.md5Hex(getContentBytes(sb.toString(), charset));
        System.out.println("加密后的签名:"+sign);
        return sign;
    }
     /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException 
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }
    
    public static String getShortUUID(int num) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        TreeMap<String,String> treeMap = new TreeMap<String, String>();
        treeMap.put("appKey", "hh");
        treeMap.put("username", "1335288");
        treeMap.put("password", "435rewt32423ewt4325terw");
        treeMap.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
        treeMap.put("nonceStr", getShortUUID(8));
        String key = "密钥";
        signRequest(treeMap, key, "utf-8");
    }
}

 

posted @ 2018-03-27 10:48  这个名字想了很久~  阅读(881)  评论(0编辑  收藏  举报