MD5Util.java
2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.xly.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具类
*/
public class MD5Util {
/**
* 将字符串进行MD5加密
* @param input 输入字符串
* @return MD5加密后的32位小写字符串
*/
public static String encrypt(String input) {
if (input == null || input.isEmpty()) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
// 将字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5加密失败", e);
}
}
/**
* 将字符串进行MD5加密(大写)
* @param input 输入字符串
* @return MD5加密后的32位大写字符串
*/
public static String encryptToUpperCase(String input) {
String result = encrypt(input);
return result != null ? result.toUpperCase() : null;
}
/**
* 验证字符串与MD5值是否匹配
* @param input 输入字符串
* @param md5 MD5值
* @return 是否匹配
*/
public static boolean verify(String input, String md5) {
String encrypted = encrypt(input);
return encrypted != null && encrypted.equalsIgnoreCase(md5);
}
/**
* 获取文件的MD5值
* @param bytes 文件字节数组
* @return 文件MD5值
*/
public static String getFileMD5(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(bytes);
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("文件MD5计算失败", e);
}
}
/**
* MD5加盐加密
* @param input 输入字符串
* @param salt 盐值
* @return 加盐后的MD5值
*/
public static String encryptWithSalt(String input, String salt) {
return encrypt(input + salt);
}
/**
* 双重MD5加密
* @param input 输入字符串
* @return 双重MD5加密结果
*/
public static String doubleEncrypt(String input) {
String first = encrypt(input);
return encrypt(first);
}
}