话不多说,直接上代码:
默认会对字符串的前2048个字符进行加密,可以根据需要进行调整
package com.ebao.frontsys.tools;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MD5Utils {
private static final int MD5_LENGTH = 1024 * 2;
private static Logger logger = LogManager.getLogger(MD5Utils.class.getName());
public static String generateMD5(String plainText) {
try {
if (null == plainText || plainText.length() == 0)
plainText = "";
plainText = (plainText.length() > MD5_LENGTH) ? plainText
.substring(0, MD5_LENGTH) : plainText;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = plainText.getBytes(Charset.forName("UTF-8"));
md.update(bytes);
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0, j = b.length; offset < j; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
return buf.toString().toLowerCase();
} catch (NoSuchAlgorithmException e) {
logger.debug(ExceptionUtils.getFullStackTrace(e));
return null;
}
}
}