You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.zsz.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5 工具类,用于对字符串进行 MD5 加密。
* 该类为 final 类,不可被继承,且所有方法均为静态方法,方便直接调用。
*/
public final class MD5 {
/**
* 对输入的字符串进行 MD5 加密
* @param strSrc 待加密的原始字符串
* @return 加密后的十六进制字符串,如果加密过程中出现异常则抛出 RuntimeException
*/
public static String encrypt(String strSrc) {
try {
// 定义十六进制字符数组,用于将字节转换为十六进制表示
char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
// 将输入的字符串转换为字节数组
byte[] bytes = strSrc.getBytes();
// 获取 MD5 算法的 MessageDigest 实例
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用输入的字节数组更新摘要
md.update(bytes);
// 完成哈希计算,得到加密后的字节数组
bytes = md.digest();
// 获取加密后字节数组的长度
int j = bytes.length;
// 创建一个字符数组,长度为字节数组长度的两倍,用于存储十六进制表示
char[] chars = new char[j * 2];
// 用于记录字符数组的索引
int k = 0;
// 遍历加密后的字节数组
for (int i = 0; i < bytes.length; i++) {
// 获取当前字节
byte b = bytes[i];
// 将字节的高 4 位转换为十六进制字符并存储到字符数组中
chars[k++] = hexChars[b >>> 4 & 0xf];
// 将字节的低 4 位转换为十六进制字符并存储到字符数组中
chars[k++] = hexChars[b & 0xf];
}
// 将字符数组转换为字符串并返回
return new String(chars);
} catch (NoSuchAlgorithmException e) {
// 打印异常堆栈信息
e.printStackTrace();
// 抛出运行时异常,提示 MD5 加密出错
throw new RuntimeException("MD5加密出错+" + e);
}
}
/**
* 主方法,用于测试 MD5 加密功能
* @param args 命令行参数
*/
public static void main(String[] args) {
// 对字符串 "123456" 进行加密
String encrypt = encrypt("123456");
// 打印加密后的字符串
System.out.println(encrypt);
}
}