# 密码加密
可选
MD5
或者SHA-256
package example.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class PasswordHashing {
public static String hashPassword(String password, String algorithm) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashedBytes = digest.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashedBytes) {
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("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
String password = "123";
System.out.println("MD5: " + hashPassword(password, "MD5"));
System.out.println("SHA-256: " + hashPassword(password, "SHA-256"));
}
}
示例结果如下:
MD5: 202cb962ac59075b964b07152d234b70
SHA-256: a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3