在Javaweb项目中用MVC模式进行后端管理员RSA加密登录前后端具体代码实现
时间: 2023-05-28 16:01:55 浏览: 168
下面是基于MVC模式的JavaWeb项目中使用RSA算法进行管理员登录的示例代码:
(1)Model层代码
```java
public class Admin {
private String username;
private String password;
// getters and setters
// 使用RSA算法进行密码加密
public String encryptPassword(String publicKey) throws Exception {
byte[] encryptedBytes = null;
try {
PublicKey publicKeyObj = getPublicKey(publicKey);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKeyObj);
byte[] inputBytes = password.getBytes();
encryptedBytes = cipher.doFinal(inputBytes);
} catch (Exception e) {
e.printStackTrace();
}
return new String(Base64.getEncoder().encode(encryptedBytes));
}
// 获取公钥对象
private PublicKey getPublicKey(String publicKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory;
PublicKey publicKeyObj = null;
keyFactory = KeyFactory.getInstance("RSA");
publicKeyObj = keyFactory.generatePublic(keySpec);
return publicKeyObj;
}
}
```
(2)View层代码
```jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>管理员登录</title>
</head>
<body>
<h1>管理员登录</h1>
<form action="${pageContext.request.contextPath}/admin/login" method="post">
<label>用户名:<input type="text" name="username"></label><br>
<label>密码:<input type="password" name="password"></label><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
(3)Controller层代码
```java
public class AdminController extends HttpServlet {
private AdminService adminService = new AdminService();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
Admin admin = new Admin();
admin.setUsername(username);
admin.setPassword(password);
try {
// 调用Service层方法进行登录验证
boolean loginSuccess = adminService.login(admin);
if (loginSuccess) {
// 登录成功,跳转到管理后台首页
resp.sendRedirect(req.getContextPath() + "/admin/home");
} else {
// 登录失败,返回错误提示信息到前端页面
req.setAttribute("errorMsg", "用户名或密码错误,请重试!");
req.getRequestDispatcher("/WEB-INF/views/admin/login.jsp").forward(req, resp);
}
} catch (Exception e) {
e.printStackTrace();
// 出现异常,返回错误提示信息到前端页面
req.setAttribute("errorMsg", "登录失败,请重试!");
req.getRequestDispatcher("/WEB-INF/views/admin/login.jsp").forward(req, resp);
}
}
}
```
(4)Service层代码
```java
public class AdminService {
// 随机生成RSA公钥和私钥,存储在服务器端
private String publicKey = "";
private String privateKey = "";
public AdminService() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
publicKey = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
privateKey = new String(Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
} catch (Exception e) {
e.printStackTrace();
}
}
// 登录验证
public boolean login(Admin admin) throws Exception {
// 获取加密后的密码
String encrypedPassword = admin.encryptPassword(publicKey);
// 从数据库中查询是否存在该管理员
AdminDao adminDao = new AdminDao();
Admin adminInDB = adminDao.findByUserName(admin.getUsername());
if (adminInDB == null) {
return false; // 用户名不存在,登录失败
}
// 如果密码匹配,则登录成功
if (encrypedPassword.equals(adminInDB.getPassword())) {
return true;
} else {
return false;
}
}
}
```
(5)Dao层代码
```java
public class AdminDao {
// 根据用户名查询管理员
public Admin findByUserName(String username) {
String query = "SELECT * FROM admin WHERE username = ?";
try (Connection conn = DBUtil.getConnection();
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
Admin admin = new Admin();
admin.setUsername(rs.getString("username"));
admin.setPassword(rs.getString("password"));
return admin;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
```
需要注意的是,上述代码中的EncryptUtil工具类,是用于RSA加密操作的工具类,代码实现可以根据具体要求自行完成。此外,为了更好地理解MVC模式的实现逻辑,以上示例代码中未使用任何额外的框架,仅使用了Servlet、JSP和JDBC等基础技术。
阅读全文