Java MD5 String md5Signature(TreeMap params, String secret)

Here you can find the source of md5Signature(TreeMap params, String secret)

Description

md Signature

License

Apache License

Declaration

public static String md5Signature(TreeMap<String, String> params, String secret) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class Main {

    public static String md5Signature(TreeMap<String, String> params, String secret) {
        String result = null;//from  w  ww .  ja va  2  s. com
        StringBuffer orgin = null;
        try {
            orgin = getBeforeSign(params, new StringBuffer(secret));
        } catch (UnsupportedEncodingException e1) {
            throw new java.lang.RuntimeException("sign encode error !");
        }
        if (orgin == null)
            return result;
        orgin.append(secret);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            result = bytes2Hex(md.digest(orgin.toString().getBytes("utf-8")));
        } catch (Exception e) {
            throw new java.lang.RuntimeException("sign error !");
        }
        return result;
    }

    private static StringBuffer getBeforeSign(TreeMap<String, String> params, StringBuffer orgin)
            throws UnsupportedEncodingException {
        if (params == null)
            return null;
        Map<String, String> treeMap = new TreeMap<String, String>();
        treeMap.putAll(params);
        Iterator<String> iter = treeMap.keySet().iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next();
            String value = params.get(name);
            name = URLEncoder.encode(name, "utf-8");
            value = URLEncoder.encode(value, "utf-8");
            orgin.append(name).append(value);
        }
        return orgin;
    }

    private static String bytes2Hex(byte[] byteArray) {
        StringBuffer strBuf = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (byteArray[i] >= 0 && byteArray[i] < 16) {
                strBuf.append("0");
            }
            strBuf.append(Integer.toHexString(byteArray[i] & 0xFF));
        }
        return strBuf.toString();
    }
}

Related

  1. md5hex(String source)
  2. md5Hex(String str)
  3. md5raw(String data)
  4. md5Representation(String data)
  5. md5Signature(TreeMap params, String secret)
  6. md5String(String input)
  7. md5String(String key)
  8. md5String(String paramString)
  9. md5String(String s)