ISV签名生成策略

    在开发阿里软件的ISV应用时,进行签名是到处都要用到的,这里对官方提供的jar中的签名类进行了优化,虽然改动很小,但已能通用了。
以下是对jar包中的 Signature 类进行了改造
package com.alisoft.sip.sdk.isv;

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

/**
 * 服务请求辅助类
 * @author wenchu.cenwc
 *
 */
public class SignatureUtil{

    /**
     * 签名方法
     * @param params
     * @param secret
     * @return
     */
    //免登录签名
	@SuppressWarnings("unchecked")
    public static String signature(Map params,String secret){
        return sign(params,Constants.PARAMETER_SIGN,secret);
    }
	//适用于其它情况的签名,进行了重载
	@SuppressWarnings("unchecked")
	public static String signature(Map params,String sign,String cret){
		return sign(params,sign,cret);
	}
    //签名方法
    @SuppressWarnings("unchecked")
	private static String sign(Map params,String sign,String cret){
    	String result = null;
        
        params.remove(sign);

        try{
            Map treeMap = new TreeMap();
            treeMap.putAll(params);

            Iterator iter = treeMap.keySet().iterator();

            StringBuffer orgin = new StringBuffer(cret);

            while(iter.hasNext())
            {
                String name = (String)iter.next();
                orgin.append(name).append(params.get(name));
            }

            MessageDigest md = MessageDigest.getInstance("MD5");
            result = byte2hex(md.digest(orgin.toString().getBytes("GBK")));
        }catch(Exception ex){
            throw new java.lang.RuntimeException("sign error !");
        }
        return result;
    }

    /**
     *
     * 二行制转字符串
     *
     * @param b
     *
     * @return
     *
     */
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }
}

你可能感兴趣的:(java,Security)