package com.ruoyi.system.utils.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Util { // 将字节数组转换为十六进制字符串 private static String bytesToHex(byte[] bytes) { StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } // 计算字符串的MD5值,返回十六进制字符串 public static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(message.getBytes()); return bytesToHex(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); // 不应该发生,因为"MD5"是一个标准的算法名称 } } public static void main(String[] args) { String originalString = "Hello, World!"; String md5Result = md5Hex(originalString); System.out.println("Original: " + originalString); System.out.println("MD5: " + md5Result); } }