package com.ruoyi.web.controller.api.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; public class MD5Util { private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray(); /** * 计算字符串MD5 */ public static String md5(String input) { if (input == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8)); return bytesToHex(digest); } catch (Exception e) { throw new RuntimeException("MD5计算失败", e); } } /** * 计算文件MD5 */ public static String md5(File file) { if (file == null || !file.exists()) return null; try (FileInputStream fis = new FileInputStream(file)) { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[8192]; int length; while ((length = fis.read(buffer)) != -1) { md.update(buffer, 0, length); } return bytesToHex(md.digest()); } catch (Exception e) { throw new RuntimeException("文件MD5计算失败", e); } } /** * 字节数组转十六进制字符串 */ private static String bytesToHex(byte[] bytes) { if (bytes == null) return null; StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte b : bytes) { sb.append(HEX_CHARS[(b >> 4) & 0x0F]); sb.append(HEX_CHARS[b & 0x0F]); } return sb.toString(); } /** * 验证MD5 */ public static boolean verify(String input, String md5) { return md5(input).equalsIgnoreCase(md5); } public static boolean verify(File file, String md5) { return md5(file).equalsIgnoreCase(md5); } }