1 package Util; 2 3 import java.security.MessageDigest; 4 import java.security.NoSuchAlgorithmException; 5 6 import sun.security.provider.MD5; 7 8 public class MD5Util { 9 private static final char[] hexDigest = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};10 11 /**12 * MD5加密算法13 * @param content14 * @return15 */16 public static String md5(String content)17 {18 try {19 //1. 返回实现指定摘要算法的 MessageDigest 对象20 MessageDigest md = MessageDigest.getInstance("MD5");21 22 //2.获取待加密字符串的byte数组23 byte[] bytes = content.getBytes();24 25 //3.使用指定的 byte 数组更新摘要26 md.update(bytes);27 28 //4.加密: 通过执行诸如填充之类的最终操作完成哈希计算29 byte[] newBytes = md.digest(); //得到长度为16的字节数组30 31 //5.将长度为16的byte数组表示为32位十六进制数字32 /*byte a = -81;33 System.out.println(Integer.toBinaryString(a)); //111111111111111111111111 1010 1111 字节有效位8位34 System.out.println(Integer.toBinaryString(a >>> 4 & 0xf));//111111111111111111111111 1010 无符号右移四位,与0xf做与运算,去24个135 System.out.println(Integer.toBinaryString(a & 0xf));//111136 */ 37 //System.out.println(Integer.toHexString(a >>> 4 & 0xf));38 //System.out.println(Integer.toHexString(a & 0xf));39 40 char[] result = new char[newBytes.length * 2];//定义存储十六进制数结果的字符数组41 int k = 0;42 for (int i = 0; i < newBytes.length; i++) {43 byte c = newBytes[i];44 result[k++] = hexDigest[c >>> 4 & 0xf];//高四位45 result[k++] = hexDigest[c & 0xf]; //低四位46 }47 48 return new String(result);49 50 } catch (NoSuchAlgorithmException e) {51 e.printStackTrace();52 }53 return "";54 }55 }
将此类封装进工具包中,需要加密时即可取出使用