[Spring Boot]登录密码三种加密方式
在Spring Boot中,常见的登录密码加密方式有MD5、SHA-1、SHA-256、BCrypt、Argon2等。以下是使用这些方式的示例代码:
- MD5加密(不推荐使用,存在弱点)
import org.springframework.util.DigestUtils;
public String encryptMD5(String password) {
return DigestUtils.md5DigestAsHex(password.getBytes()).toUpperCase();
}
- SHA-1加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public String encryptSHA1(String password) {
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
byte[] bytes = sha1.digest(password.getBytes());
return bytesToHex(bytes);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
- SHA-256加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public String encryptSHA256(String password) {
try {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] bytes = sha256.digest(password.getBytes());
return bytesToHex(bytes);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
- BCrypt加密(推荐使用,安全且复杂度可调)
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public String encryptBCrypt(String password) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode(password);
}
- Argon2加密(推荐使用,最新安全哈希算法)
import de.mkammerer.argon2.Argon2Argon2ad;
import de.mkammerer.argon2.Argon2Argon2id;
public String encryptArgon2(String password) {
Argon2Argon2id argon2 = new Argon2Argon2id();
return argon2.hash(1, 65536, 2, password.getBytes());
}
注意:在实际应用中,应该根据需求和安全标准选择合适的加密方式,并确保加密的密码在数据库中安全存储,通常使用BCrypt或Argon2等方法。
评论已关闭