package com.uas.eis.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Util { /** * MD5加密 * @param message * @return */ public static String getEncryption(String message){ String result = ""; if(message != null){ try { MessageDigest md = MessageDigest.getInstance("MD5"); //指定加密方式 //加密 byte[] bytes = md.digest(message.getBytes()); for(int i = 0; i < bytes.length; i++){ // 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位 String str = Integer.toHexString(bytes[i] & 0xFF); if(str.length() == 1){ str += "F"; } result += str; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } public static String encodeByMD5(String originString) { if (originString != null) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] results = md.digest(originString.getBytes()); String resultString = byteArrayToHexString(results); return resultString.toUpperCase(); } catch (Exception ex) { ex.printStackTrace(); } } return null; } public static String byteArrayToHexString(byte[] bArr) { StringBuffer sb = new StringBuffer(bArr.length); String sTmp; for (int i = 0; i < bArr.length; i++) { sTmp = Integer.toHexString(0xFF & bArr[i]); if (sTmp.length() < 2){ sb.append(0); } sb.append(sTmp.toUpperCase()); } return sb.toString(); } /** * hex字符串转byte数组 * @param inHex 待转换的Hex字符串 * @return 转换后的byte数组结果 */ public static byte[] hexToByteArray(String inHex){ int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1){ //奇数 hexlen++; result = new byte[(hexlen/2)]; inHex="0"+inHex; }else { //偶数 result = new byte[(hexlen/2)]; } int j=0; for (int i = 0; i < hexlen; i+=2){ result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16); j++; } return result; } }