package org.example.util; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @program: demo * @description: * @create: 2024-07-29 11:22 **/ public class MD5Util { // 使用MD5算法对密码进行加密 public static String encrypt(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(password.getBytes()); BigInteger no = new BigInteger(1, messageDigest); StringBuilder hashText = new StringBuilder(no.toString(16)); while (hashText.length() < 32) { hashText.insert(0, "0"); } return hashText.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } // 校验输入的密码和加密后的密码是否匹配 public static boolean verify(String inputPassword, String hashedPassword) { String hashedInputPassword = encrypt(inputPassword); return hashedInputPassword.equals(hashedPassword); } // 示例用法 public static void main(String[] args) { String originalPassword = "myPassword123"; String hashedPassword = encrypt(originalPassword); // 模拟校验过程 String inputPassword = "myPassword123"; if (verify(inputPassword, hashedPassword)) { System.out.println("Password Matched!"); } else { System.out.println("Password Not Matched!"); } } }