Java使用MD5加盐对密码进行加密处理,附注册和登录加密解密处理
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class PasswordHelper {
private static final String MD5 = "MD5";
private static final String HEX_NUMS_STR = "0123456789ABCDEF";
private static final int COUNT_BITS = 128;
public static void main(String[] args) {
// 测试注册
String password = "user_password";
String salt = register(password);
System.out.println("注册生成的盐值:" + salt);
String encryptedPassword = encrypt(password, salt);
System.out.println("注册生成的密码:" + encryptedPassword);
// 测试登录
boolean loginSuccess = login(password, salt, encryptedPassword);
System.out.println("登录结果:" + (loginSuccess ? "成功" : "失败"));
}
public static String register(String password) {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[COUNT_BITS / 8];
random.nextBytes(salt);
return encryptToHex(salt);
}
public static String encrypt(String password, String salt) {
return md5(password + salt, MD5);
}
public static boolean login(String password, String salt, String encryptedPassword) {
String encryptedPasswordFromDb = encrypt(password, salt);
return encryptedPasswordFromDb.equals(encryptedPassword);
}
private static String md5(String input, String algorithm) {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
byte[] inputByteArray = input.getBytes();
messageDigest.update(inputByteArray);
byte[] resultByteArray = messageDigest.digest();
return encryptToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static String encryptToHex(byte[] input) {
StringBuilder hexBuilder = new StringBuilder();
for (byte b : input) {
hexBuilder.append(byteToHex(b));
}
return hexBuilder.toString();
}
private static String byteToHex(byte b) {
int val = b & 0xff;
return HEX_NUMS_STR.charAt(val >> 4) + "" + HEX_NUMS_STR.charAt(val & 0x0f);
}
}
这段代码提供了一个简单的密码加盐和验证流程。register
方法生成盐值,encrypt
方法使用盐值对密码进行加密,而login
方法则用于验证登录信息。这里使用MD5作为散列函数,并将其输出转化为十六进制字符串。注意,在实际应用中应该使用更安全的加密算
评论已关闭