package com.dollearn.student.network;
|
import android.util.Base64;
|
import android.util.Log;
|
|
|
import com.dollearn.student.utils.Const;
|
import com.dollearn.student.utils.HMACSHA1;
|
|
import java.security.InvalidKeyException;
|
import java.security.NoSuchAlgorithmException;
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.Comparator;
|
import java.util.List;
|
import java.util.Map;
|
|
import javax.crypto.Mac;
|
import javax.crypto.spec.SecretKeySpec;
|
|
import cn.sinata.util.Base64DES;
|
|
public class SignUtil {
|
|
/*
|
* 不要写成:Cipher cipher = Cipher.getInstance("DES");
|
* 或:Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
|
* 原因是Cipher cipher = Cipher.getInstance("DES");
|
* 与Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
|
* 等同,填充方式错误,加密的时候会得到16长度的字节数组。
|
* 应该写成
|
* Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
|
*/
|
|
/**
|
* 生成签名
|
* @param map
|
* @return
|
*/
|
public static String getSign(Map<String, Object> map) {
|
|
String result = "";
|
try {
|
List<Map.Entry<String, Object>> infoIds = new ArrayList<>(map.entrySet());
|
if (infoIds.size()>0){
|
// 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
|
Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
|
@Override
|
public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
|
return (o1.getKey()).compareTo(o2.getKey());
|
}
|
});
|
// 构造签名键值对的格式
|
StringBuilder sb = new StringBuilder();
|
for (Map.Entry<String, Object> item : infoIds) {
|
if (item.getKey() == null) {
|
item.getKey();
|
}
|
String key = item.getKey();
|
Object val = item.getValue();
|
if (!(val == "" || val == null)) {
|
sb.append(key).append("=").append(val).append("&");
|
}
|
}
|
result = sb.toString();
|
result = result.substring(0,result.length() - 1);
|
Log.e(Const.Tag, "getSign: ====》"+result);
|
}
|
result = Base64DES.INSTANCE.encode(HMACSHA1.HmacSHA1Encrypt(result, Const.APP_KEY));
|
} catch (Exception e) {
|
return null;
|
}
|
return result;
|
}
|
private static final String MAC_NAME = "HmacSHA1";
|
private static final String ENCODING = "UTF-8";
|
public static String genHMAC(String data, String key) {
|
byte[] result = null;
|
try {
|
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
|
SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), MAC_NAME);
|
//生成一个指定 Mac 算法 的 Mac 对象
|
Mac mac = Mac.getInstance(MAC_NAME);
|
//用给定密钥初始化 Mac 对象
|
mac.init(signinKey);
|
//完成 Mac 操作
|
byte[] rawHmac = mac.doFinal(data.getBytes());
|
result = Base64.encode(rawHmac, Base64.DEFAULT);
|
} catch (NoSuchAlgorithmException e) {
|
System.err.println(e.getMessage());
|
} catch (InvalidKeyException e) {
|
System.err.println(e.getMessage());
|
}
|
if (null != result) {
|
return new String(result);
|
} else {
|
return null;
|
}
|
}
|
|
}
|