本文目录导读:

我来为你提供Java中实现MD5和SHA加密算法的完整案例。
使用Java内置的MessageDigest类
MD5加密示例
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static String md5Encrypt(String input) {
try {
// 创建MD5摘要对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算MD5值
byte[] digest = md.digest(input.getBytes());
// 将字节数组转换为16进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
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);
}
}
public static void main(String[] args) {
String text = "Hello World";
System.out.println("原始文本: " + text);
System.out.println("MD5加密: " + md5Encrypt(text));
// 验证
String hash1 = md5Encrypt("Hello World");
String hash2 = md5Encrypt("Hello World");
System.out.println("两次加密结果相同: " + hash1.equals(hash2));
}
}
SHA-256加密示例
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAExample {
public static String sha256Encrypt(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256算法不存在", e);
}
}
public static String sha512Encrypt(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
byte[] digest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-512算法不存在", e);
}
}
public static void main(String[] args) {
String text = "Hello World";
System.out.println("原始文本: " + text);
System.out.println("SHA-256: " + sha256Encrypt(text));
System.out.println("SHA-512: " + sha512Encrypt(text));
}
}
使用Apache Commons Codec库
首先添加Maven依赖:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
import org.apache.commons.codec.digest.DigestUtils;
public class CommonsCodecExample {
public static void main(String[] args) {
String text = "Hello World";
// MD5
String md5Hex = DigestUtils.md5Hex(text);
System.out.println("MD5: " + md5Hex);
// SHA-256
String sha256Hex = DigestUtils.sha256Hex(text);
System.out.println("SHA-256: " + sha256Hex);
// SHA-512
String sha512Hex = DigestUtils.sha512Hex(text);
System.out.println("SHA-512: " + sha512Hex);
}
}
带盐值的SHA加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class SaltedHashExample {
// 生成随机盐值
public static byte[] generateSalt() {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return salt;
}
// 带盐值的SHA-256加密
public static String sha256WithSalt(String password, byte[] salt) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt); // 添加盐值
byte[] hashedPassword = md.digest(password.getBytes());
// 将盐值和哈希值合并存储
byte[] combined = new byte[salt.length + hashedPassword.length];
System.arraycopy(salt, 0, combined, 0, salt.length);
System.arraycopy(hashedPassword, 0, combined, salt.length, hashedPassword.length);
return Base64.getEncoder().encodeToString(combined);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256算法不存在", e);
}
}
// 验证密码
public static boolean verifyPassword(String password, String storedHash) {
try {
// 解码存储的哈希值
byte[] combined = Base64.getDecoder().decode(storedHash);
// 提取盐值(前16字节)
byte[] salt = new byte[16];
System.arraycopy(combined, 0, salt, 0, 16);
// 计算密码的哈希值
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
byte[] hashedPassword = md.digest(password.getBytes());
// 比较哈希值
for (int i = 0; i < hashedPassword.length; i++) {
if (hashedPassword[i] != combined[i + 16]) {
return false;
}
}
return true;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256算法不存在", e);
}
}
public static void main(String[] args) {
String password = "myPassword123";
byte[] salt = generateSalt();
String hashedPassword = sha256WithSalt(password, salt);
System.out.println("密码哈希值: " + hashedPassword);
// 验证密码
boolean isMatch = verifyPassword("myPassword123", hashedPassword);
System.out.println("密码验证结果: " + isMatch);
boolean isNotMatch = verifyPassword("wrongPassword", hashedPassword);
System.out.println("错误密码验证结果: " + isNotMatch);
}
}
完整的工具类
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtils {
// 支持的算法类型
public enum Algorithm {
MD5("MD5"),
SHA1("SHA-1"),
SHA256("SHA-256"),
SHA512("SHA-512");
private final String algorithm;
Algorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getAlgorithm() {
return algorithm;
}
}
// 通用加密方法
public static String hash(String input, Algorithm algorithm) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm.getAlgorithm());
byte[] digest = md.digest(input.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(algorithm.getAlgorithm() + "算法不存在", e);
}
}
// 便捷方法
public static String md5(String input) {
return hash(input, Algorithm.MD5);
}
public static String sha256(String input) {
return hash(input, Algorithm.SHA256);
}
public static String sha512(String input) {
return hash(input, Algorithm.SHA512);
}
public static void main(String[] args) {
String text = "Hello World";
System.out.println("MD5: " + md5(text));
System.out.println("SHA-256: " + sha256(text));
System.out.println("SHA-512: " + sha512(text));
// 通用方法
System.out.println("通用SHA-1: " + hash(text, Algorithm.SHA1));
}
}
注意事项
- MD5安全性: MD5已被证实存在碰撞问题,不建议用于安全敏感场景
- SHA-256推荐: 对于大多数场景,推荐使用SHA-256
- 加盐: 存储密码时一定要加盐,防止彩虹表攻击
- 迭代哈希: 对于密码存储,建议使用PBKDF2、bcrypt或scrypt等专门的密码哈希算法
- 编码问题: 注意字符串编码,建议使用
getBytes("UTF-8")而不是默认编码
这些示例涵盖了Java中MD5和SHA加密的基本用法,你可以根据实际需求选择合适的实现方式。