MD5(Message-Digest Algorithm 5)是一种广泛使用的密码散列函数,可以产生一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。在Java中,我们可以使用java.security.MessageDigest
类来实现MD5算法。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static String md5(String input) {
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(e);
}
}
public static void main(String[] args) {
String input = "Hello, MD5!";
System.out.println("MD5 hash: " + md5(input));
}
}
import org.apache.commons.codec.digest.DigestUtils;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, MD5!";
String md5Hex = DigestUtils.md5Hex(input);
System.out.println("MD5 hash: " + md5Hex);
}
}
import com.google.common.hash.Hashing;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello, MD5!";
String md5Hash = Hashing.md5()
.hashString(input, java.nio.charset.StandardCharsets.UTF_8)
.toString();
System.out.println("MD5 hash: " + md5Hash);
}
}
虽然MD5曾经广泛使用,但由于以下安全问题,现在已不再推荐用于安全敏感场景:
更安全的替代方案包括:
原因:
解决方案: 确保使用相同的字符编码,例如:
byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
解决方案: 对于大文件,使用分块处理:
public static String md5File(File file) throws IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = new FileInputStream(file);
DigestInputStream dis = new DigestInputStream(is, md)) {
byte[] buffer = new byte[8192];
while (dis.read(buffer) != -1) {
// 自动更新摘要
}
}
byte[] digest = md.digest();
// 转换为十六进制字符串...
}
原因:
解决方案: 使用专门设计的密码哈希函数:
// 使用BCrypt
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
MD5在Java中的性能通常很好,但要注意:
MD5仍然是许多非安全关键场景中的实用工具,但在安全敏感的应用中应使用更现代的哈希算法。