public class Md5Util {
/**
* 簽名字符串
* @param text 需要簽名的字符串
* @return 簽名結果
*/
public static String sign(String text) {
return DigestUtils.md5Hex(getContentBytes(text, "UTF-8"));
}
/**
* 簽名字符串並將驗簽結果轉化爲大寫
* @param text 需要簽名的字符串
* @return 簽名結果
*/
public static String signToUpperCase(String text) {
return DigestUtils.md5Hex(getContentBytes(text, "UTF-8")).toUpperCase(Locale.ENGLISH);
}
/**
* 簽名字符串
* @param text 需要簽名的字符串
* @param inputCharset 編碼格式
* @return 簽名結果
*/
public static String sign(String text, String inputCharset) {
return DigestUtils.md5Hex(getContentBytes(text, inputCharset));
}
/**
* 簽名字符串
* @param text 需要簽名的字符串
* @param sign 簽名結果
* @param inputCharset 編碼格式
* @return 簽名結果
*/
public static boolean verify(String text, String sign, String inputCharset) {
String mysign = DigestUtils.md5Hex(getContentBytes(text, inputCharset));
if(mysign.equals(sign)) {
return true;
}else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new CommonException().newInstance("MD5簽名過程中出現錯誤,指定的編碼集不對,您目前指定的編碼集是:{0}",charset);
}
}
}