package com.hcmony.date;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.logging.Logger;
/**
* <h3>Shenjue.java基本描述</h3>
* <p></p>
*
* @author hcmony
* @since V1.0.0, 2018/12/14 16:45
*/
public class MD5Helper {
private static final Logger LOGGER = Logger.getLogger("com.hcmony.date.MD5Helper");
private static final String HEXDIGITS[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
private MD5Helper(){}
/**
*
* @param origin 加密源
* @return
* @throws UnsupportedEncodingException
*/
public static String md5(String origin)throws UnsupportedEncodingException {
return DigestUtils.md5Hex(origin.getBytes("UTF-8"));
}
/**
*
* @param origin 加密源
* @return
*/
public static String md5EncodeUtf8(String origin) {
return md5Encode(origin, "utf-8");
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++){
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0){
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
return HEXDIGITS[d1] + HEXDIGITS[d2];
}
/**
* 返回大写MD5
*
* @param origin
* @param charsetname
* @return
*/
private static String md5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname)){
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
}else {
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
} catch (Exception exception) {
}
return resultString.toUpperCase();
}
/**
* md5加密只获取字母
* @param origin
* @return
* @throws UnsupportedEncodingException
*/
public static String md5OnlyLetter(String origin)throws UnsupportedEncodingException {
String result = md5(origin);
return result.replaceAll("[^a-z^A-Z]", "");
}
/**
* md5加密只获取数字10位
* @param origin
* @return
* @throws UnsupportedEncodingException
*/
public static String md5OnlyNumber(String origin)throws UnsupportedEncodingException {
String result = md5(origin).replaceAll("[^0-9]", "");
if(result.length()>10){
return result.substring(0,10);
}
return StringUtils.leftPad(result,10,"0");
}
/**
* 验证是否是正确的加密方法
* @param source
* @return
* @throws Exception
*/
public static boolean encode(String source)throws Exception{
String source1 = source.substring(22);
String source2 = source.substring(17,22);
LOGGER.info("source is "+source);
LOGGER.info("source1 is "+source1);
LOGGER.info("source2 is "+source2);
if(StringUtils.isNotBlank(source)){
return source1.equals(md5OnlyNumber(source2));
}
return false;
}
}