實現一個簡單的token認證
1.對前臺的請求地址做處理,對請求引數進行排序後,拼入請求地址.
2.在排序後的引數結尾拼入約定的key,進行MD5計算得出一個token拼入請求地址,傳送請求.
3.請求的接收方得到地址,截取出所傳的引數(去掉尾部的token)在結尾拼入約定的key,進行MD5計算得出token與傳過來的token進行比較.
4.下面給出關鍵部分的程式碼
public class HttpUtils{
private static String keyStr = "keyTest";//雙方約定的key
public static String createNewUrl(String oldUrl){
int index = oldUrl.indexOf("?");//返回“?”的索引
String url = oldUrl.subString(0,index+1);//擷取請求路徑+"?"
String addVersionStr = urlParam.substring(index + 1, urlParam.length());//擷取請求引數
String[] strArr = addVersionStr.split("&");//將請求引數分隔成陣列
Arrays.sort(strArr);//對請求引數陣列進行排序
StringBuffer strBuffer = new StringBuffer();
//將請求引數進行重新拼接
for (String str : strArr) {
strBuffer.append(str + "&");
}
String result = strBuffer.substring(0, strBuffer.length() - 1);//得到新的請求引數字串
return url + result + "&token=" + md5(result + "&" + keyStr);//對請求引數進行MD5計算,得出token值一起拼到請求路徑後面
}
/**
* MD5加密
*
* @param string
*/
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
接受方的核心程式碼基本如上,這裡不做累述.
}