加密算法
使用JDK自带MessageDigest
package com.bj58.bic.touchms.util;
import lombok.extern.slf4j.Slf4j;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Slf4j
public class SignUtil {
public static final String sign(String converge) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(converge.getBytes());
String singStr = new BigInteger(1, md.digest()).toString(16);
return lowZeroPadding(singStr);
} catch (NoSuchAlgorithmException e) {
log.error("签名加密出错", e);
}
return "";
}
private static String lowZeroPadding(String singStr) {
if (singStr.length() < 32){
singStr = "0" + singStr;
return lowZeroPadding(singStr);
}
return singStr;
}
}
使用Spring自带的DigestUtils
String md5Str = DigestUtils.md5DigestAsHex("原串".getBytes());
自己定义
public static String md5(String data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.getBytes());
StringBuffer buf = new StringBuffer();
byte[] bits = md.digest();
for(int i=0;i<bits.length;i++){
int a = bits[i];
if(a<0) a+=256;
if(a<16) buf.append("0");
buf.append(Integer.toHexString(a));
}
return buf.toString();
}