package com.gk.hotwork.Domain.Utils;
|
|
import com.gk.hotwork.Domain.Exception.BusinessException;
|
import org.apache.commons.lang3.StringUtils;
|
import org.apache.log4j.Logger;
|
|
import java.nio.ByteBuffer;
|
import java.nio.CharBuffer;
|
import java.nio.charset.Charset;
|
import java.security.MessageDigest;
|
|
public class MD5Utils {
|
|
private static Logger logger = Logger.getLogger(MD5Utils.class);
|
private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
|
'f' };
|
private static final String MD5 = "MD5";
|
private static final Charset CHARSET = Charset.forName("UTF-8");
|
|
public static char[] HexEncode(byte[] bytes) {
|
final int nBytes = bytes.length;
|
char[] result = new char[2 * nBytes];
|
|
int j = 0;
|
for (int i = 0; i < nBytes; i++) {
|
result[j++] = HEX[(0xF0 & bytes[i]) >>> 4];
|
result[j++] = HEX[(0x0F & bytes[i])];
|
}
|
|
return result;
|
}
|
|
public static byte[] Utf8Encode(CharSequence string) {
|
try {
|
ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));
|
byte[] bytesCopy = new byte[bytes.limit()];
|
System.arraycopy(bytes.array(), 0, bytesCopy, 0, bytes.limit());
|
|
return bytesCopy;
|
} catch (Exception e) {
|
logger.error(e.getMessage(), e);
|
throw new BusinessException("字符转码失败。");
|
}
|
}
|
|
public static String encode(String data) {
|
try {
|
if (StringUtils.isEmpty(data)) {
|
data = "";
|
}
|
MessageDigest messageDigest = MessageDigest.getInstance(MD5);
|
byte[] digest = messageDigest.digest(Utf8Encode(data));
|
return new String(HexEncode(digest));
|
} catch (Exception e) {
|
logger.error(e.getMessage(), e);
|
throw new BusinessException("字符转码失败。");
|
}
|
}
|
|
}
|