groovy 3.0.7
代码实现
实现方式1
import java.security.MessageDigest; public class MD5Utils { public final static String MD5(String s) { char[] hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; // 十六进制的字符 try { byte[] byteData = s.getBytes("utf-8"); // 获取待加密字符的字节表示 MessageDigest md5 = MessageDigest.getInstance("MD5"); //指定加密方式,获取加密对象 byte[] digest = md5.digest(byteData); // 加密 StringBuffer sb = new StringBuffer(); // 处理成十六进制的字符串(通常) for (byte b : digest) { sb.append(hexChars[(b >> 4) & 15]); sb.append(hexChars[b & 15]); } return new String(sb); } catch (Exception e) { e.printStackTrace(); return null; } } } String md5Str = MD5Utils.MD5("2023, hello, mr授客"); // 获取32位小写md5值 println(md5Str); // 52d4eb68f09f4a8eae0b0b02adc748f3 md5Str = md5Str.substring(8, 24); // 获取16位小写md5值 println(md5Str); // f09f4a8eae0b0b02
说明:如果在JAVA中运行,则需要修改
char[] hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; // 十六进制的字符
为
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; // 十六进制的字符
实现方式2
import java.security.MessageDigest; public class MD5Utils { public final static String MD5(String s) { char[] hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; try { byte[] byteData = s.getBytes("utf-8"); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(byteData); return new BigInteger(1, digest).toString(16); } catch (Exception e) { e.printStackTrace(); return null; } } } String md5Str = MD5Utils.MD5("2023, hello, mr授客"); // 获取32位小写md5值 println(md5Str); // 52d4eb68f09f4a8eae0b0b02adc748f3 md5Str = md5Str.substring(8, 24); // 获取16位小写md5值 println(md5Str); // f09f4a8eae0b0b02
实现方式3
import java.security.MessageDigest; public class MD5Utils { public final static String MD5(String s) { char[] hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; // 十六进制的字符 try { byte[] byteData = s.getBytes("utf-8"); MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(byteData); return new BigInteger(1, digest).toString(16); } catch (Exception e) { e.printStackTrace(); return null; } } } String md5Str = MD5Utils.MD5("2023, hello, mr授客"); // 获取32位小写md5值 println(md5Str); // 52d4eb68f09f4a8eae0b0b02adc748f3 md5Str = md5Str.substring(8, 24); // 获取16位小写md5值 println(md5Str); // f09f4a8eae0b0b02