代码如下:
1 /** 2 * MD5单向加密,32位,用于加密密码,因为明文密码在信道中传输不安全,明文保存在本地也不安全 3 * 4 * @param str 5 * @return 6 */ 7 public static String md5(String str) { 8 MessageDigest md5 = null; 9 try {10 md5 = MessageDigest.getInstance("MD5");11 } catch (Exception e) {12 e.printStackTrace();13 return "";14 }15 16 char[] charArray = str.toCharArray();17 byte[] byteArray = new byte[charArray.length];18 19 for (int i = 0; i < charArray.length; i++) {20 byteArray[i] = (byte) charArray[i];21 }22 byte[] md5Bytes = md5.digest(byteArray);23 24 StringBuffer hexValue = new StringBuffer();25 for (int i = 0; i < md5Bytes.length; i++) {26 int val = ((int) md5Bytes[i]) & 0xff;27 if (val < 16) {28 hexValue.append("0");29 }30 hexValue.append(Integer.toHexString(val));31 }32 return hexValue.toString();33 }