Java - MD5加密实现详解
发布时间:2020-12-15 07:24:58 所属栏目:Java 来源:网络整理
导读:实现代码: public class Main { public static void main(String[] args) throws Exception { System.out.println(stringToMD5( "hello world!" )); } public static String stringToMD5(String str) throws NoSuchAlgorithmException,UnsupportedEncodingE
实现代码: public class Main { public static void main(String[] args) throws Exception { System.out.println(stringToMD5("hello world!")); } public static String stringToMD5(String str) throws NoSuchAlgorithmException,UnsupportedEncodingException { // 返回实现MD5算法的 MessageDigest对象 MessageDigest md = MessageDigest.getInstance("MD5"); // 使用UTF-8字符集将此String编码到byte序列 byte[] byte_arr = str.getBytes("UTF-8"); // digest(byte[])方法通过执行填充等最终操作来完成哈希计算,计算结果为一个byte数组,接下来将这个数组转换为16进制的字符串 return bytesToHexString(md.digest(byte_arr)); } public static String bytesToHexString(byte[] byte_arr) { StringBuffer res_sb = new StringBuffer(); String temp; for (byte b : byte_arr) { // 将byte数组中的每一个字节先转换为int然后与十六进制下的FF进行按位与运算 // Integer.toHexString的参数是int,如果不进行上述运算,那么当一个byte会转换成int时,对于负数,会做位扩展, // 例如:一个byte类型的-1(即0xFF),会被转换成int 类型的-1(即0xFFFFFFFF) temp = Integer.toHexString((int)b & 0xFF); // 如果运算后的结果不足两位补上最高位0 if (temp.length() < 2) { res_sb.append("0"); } res_sb.append(temp.toUpperCase()); } return res_sb.toString(); } } ? 参考: 1)toHexString(b[n] & 0XFF)为什么要和0XFF做与运算 2)Java bytesToHexString 解析 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读