下面是一个示例代码,演示了如何使用 BCrypt 生成哈希和盐,并将其与 MySQL 数据库中存储的哈希值进行比较。
import org.mindrot.jbcrypt.BCrypt;
import java.sql.*;
public class BCryptExample {
// 生成哈希和盐
public static String generateHash(String password) {
String salt = BCrypt.gensalt();
return BCrypt.hashpw(password, salt);
}
// 比较哈希值
public static boolean compareHash(String password, String hashedPassword) {
return BCrypt.checkpw(password, hashedPassword);
}
public static void main(String[] args) {
try {
// 连接到 MySQL 数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
Connection connection = DriverManager.getConnection(url, username, password);
// 查询用户名的哈希值
String selectQuery = "SELECT password FROM users WHERE username = ?";
PreparedStatement statement = connection.prepareStatement(selectQuery);
statement.setString(1, "myusername");
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String hashedPassword = resultSet.getString("password");
// 比较用户输入的密码和数据库中的哈希值
String userPassword = "mypassword";
boolean isMatch = compareHash(userPassword, hashedPassword);
if (isMatch) {
System.out.println("密码匹配");
} else {
System.out.println("密码不匹配");
}
} else {
System.out.println("用户不存在");
}
// 关闭连接
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
请注意,上述示例假设您已经安装了 BCrypt 库(org.mindrot.jbcrypt.BCrypt),并且已经创建了一个名为 users
的表,其中包含 username
和 password
列。您需要根据自己的数据库设置进行相应的更改。
下一篇:bcrypt生成盐函数