java Md5加密打包之后一直匹配失败
背景:lz使用md5做签名校验数据完整性,本地测试没有任何问题,但是打包之后进入测试,后端校验签名的时候,一直无法与前端带有签名匹配。反复报错。
因为lz之前也没做过直接从网上抄过来的代码。代码如下:
public static String encrypt(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
byte [] byteInput = s.getBytes();
//获取MD5摘要算法的MessageDigest对象
try {
MessageDigest mdInst = MessageDigest.getInstance("md5");
//使用指定的字节更新摘要
mdInst.update(byteInput);
//获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j *2]; //char占两个字节
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf]; //右移四位,高四位清空 取低四位的值
}
return new String(str);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
原因:String转字节的时候没有指定编码导致的,简单修改如下部分即可解决
try {
byteInput = s.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}