一、MD5加密
封装Md5
public class Md5 { //十六进制下数字到字符的映射数组 private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /**把inputString加密*/ public static String md5Str(String inputStr){ return encrypt(inputStr); } public static String encrypt(String inputStr) { byte[] inStrBytes = inputStr.getBytes(); try { //创建具有指定算法名称的信息摘要 MessageDigest MD = MessageDigest.getInstance("MD5"); //使用指定的字节数组对摘要进行最后更新,然后完成摘要计算 MD.update(inStrBytes); byte[] mdByte = MD.digest(); char[] str = new char[mdByte.length * 2]; int k = 0; for(int i=0;i<mdByte.length;i++) { byte temp = mdByte[i]; str[k++] = hexDigits[temp >>> 4 & 0xf]; str[k++] = hexDigits[temp & 0xf]; } return new String(str); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }
二、一般 请求参数+secret 进行加密,故再次进行封装,并返回【请求参数+secret 】MD5加密后的字符串(32位)
import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.TreeMap; public class SJS { //entrance /** * 对请求参数进行加密 * @param requestParams 请求参数 * @param secret 根秘钥 * @return * @throws Exception */ public String getSJSInfo(TreeMap<String, Object> requestParams, String secret) throws Exception { return sjsSi(buildParamStr(requestParams), secret); } //调用MD5封装方法进行加密【入参+secret】 private String sjsSi(String signStr, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { return Md5.md5Str(signStr+secret); } //将入参(格式key=value)与&进行拼接,并返回 public String buildParamStr(TreeMap<String, Object> requestParams) { StringBuilder retStr = new StringBuilder(); for(String key: requestParams.keySet()) { if (retStr.length()==0) { retStr.append(key+"="+String.valueOf(requestParams.get(key))); } else { retStr.append("&"+key+"="+String.valueOf(requestParams.get(key))); } } return retStr.toString(); } }