一个简单的签名方法
2016-10-19 本文已影响6人
BigB
public class SignUtil {
private static String privateKey = "xxx" ;
public static void main(String[] args) throws Exception {
Map<String,String> data = new HashMap<String,String>();
//用户名
String username = "HelloKittyNMB";
//访问时间
String time = String.valueOf(System.currentTimeMillis());
data.put("username", username);
data.put("time", time);
String sign = getSign(data);
}
/**
* 获取用户接口数据的签名
*
* @param data
* @return
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static String getSign(Map<String ,String> data) throws NoSuchAlgorithmException, UnsupportedEncodingException{
String[] keys=new String[data.size()];
int i=0;
for(Map.Entry<String, String> entry:data.entrySet()){
keys[i]=entry.getKey();
i++;
}
Arrays.sort(keys);
StringBuffer sb=new StringBuffer();
for(String key :keys){
sb.append(key);
sb.append("=");
sb.append(data.get(key));
sb.append("&");
}
sb.append(privateKey);
byte[] b=MessageDigest.getInstance("MD5").digest(sb.toString().getBytes("UTF-8"));//和教育用户接口为UTF-8编码
sb=new StringBuffer();
for(int j : b){
j=j & 0xff;
if(j<16)sb.append("0");
sb.append(Integer.toHexString(j));
}
return sb.toString();
}
}