在Javaweb项目中用MVC模式进行后端管理员RSA加密登录前后端具体代码实现,要求使用MySQL数据库
时间: 2023-05-27 18:05:01 浏览: 64
以下是一个简单的示例,演示如何在Java Web项目中使用MVC模式实现后端管理员RSA加密登录,使用MySQL数据库进行数据存储:
Model:
```java
package model;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
public class RSA {
private static final String ALGORITHM = "RSA";
private static final int KEY_SIZE = 2048;
private PublicKey publicKey;
private PrivateKey privateKey;
public RSA() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public PublicKey getPublicKey() {
return publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
}
```
Controller:
```java
package controller;
import model.RSA;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/")
public String index(Model model) {
RSA rsa = new RSA();
model.addAttribute("publicKey", rsa.getPublicKey());
return "index";
}
@RequestMapping("/login")
public String login(HttpServletRequest request, HttpSession session) {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 进行RSA解密
String decryptedPassword = RSAUtil.decrypt(password, rsa.getPrivateKey());
// 检查用户名和密码是否正确
if (username.equals("admin") && decryptedPassword.equals("admin123")) {
session.setAttribute("username", username);
return "redirect:/dashboard";
} else {
return "redirect:/";
}
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
```
View:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br><br>
<input type="hidden" name="publicKey" value="${publicKey}">
<button type="submit">Login</button>
</form>
</body>
</html>
```
在MySQL数据库中创建一个名为“users”的表,包含以下字段:id(INT)、username(VARCHAR)、password(VARCHAR)和email(VARCHAR)。在表中添加一个管理员用户“admin”,密码为RSA加密后的字符串。
RSA加密和解密的具体实现可以使用第三方库,例如BC库。需要将库添加到项目中的pom.xml文件中,并在代码中使用相应的类和方法。
此示例提供了一个简单的MVC实现,您可以根据实际情况进行修改和扩展。