在Javaweb项目中用MVC模式进行后端管理员RSA加密登录验证的具体代码实现
时间: 2023-06-01 19:01:32 浏览: 113
基于mvc模式的登录验证
3星 · 编辑精心推荐
1. 创建一个Controller类来处理登录请求和验证:
```java
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private AdminService adminService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, Model model) {
String username = request.getParameter("username");
String password = request.getParameter("password");
Admin admin = adminService.getAdminByUsername(username);
if(admin == null) {
model.addAttribute("error", "用户名不存在");
return "admin/login";
}
String decryptPassword = RSAUtils.decrypt(password, admin.getPrivateKey());
if(!decryptPassword.equals(admin.getPassword())) {
model.addAttribute("error", "密码错误");
return "admin/login";
}
request.getSession().setAttribute("admin", admin);
return "redirect:/admin/index";
}
}
```
2. 创建一个Service类来处理业务逻辑:
```java
@Service
public class AdminService {
@Autowired
private AdminMapper adminMapper;
public Admin getAdminByUsername(String username) {
return adminMapper.getAdminByUsername(username);
}
}
```
3. 创建一个Mapper类来实现数据库操作:
```java
public interface AdminMapper {
@Select("SELECT * FROM admin WHERE username = #{username}")
@Results({
@Result(property = "privateKey", column = "private_key"),
@Result(property = "createTime", column = "create_time")
})
Admin getAdminByUsername(String username);
}
```
4. 创建一个工具类来实现RSA加密和解密:
```java
public class RSAUtils {
private static final String CHARSET = "UTF-8";
private static final String RSA_ALGORITHM = "RSA";
public static String decrypt(String encryptedData, String privateKey) {
try {
byte[] data = Base64.decodeBase64(encryptedData);
byte[] keyBytes = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > 128) {
cache = cipher.doFinal(data, offSet, 128);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * 128;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData, CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密失败", e);
}
}
}
```
5. 在前端页面中使用RSA加密密码并提交表单:
```html
<form method="post" action="${pageContext.request.contextPath}/admin/login">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
</div>
<button type="submit" class="btn btn-primary">登录</button>
</form>
<script src="${pageContext.request.contextPath}/static/js/jsencrypt.min.js"></script>
<script>
var encrypt = new JSEncrypt();
encrypt.setPublicKey("-----BEGIN PUBLIC KEY-----\n" +
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDm1pmZC9JcLH1geQvYzK0b8Z0P\n" +
"4v4zWtj8X9O9JL5pCvKDrWojJ8QI5c5q3q5K5z5MzGKU6iXD3lNJYU6VWU1LJz1K\n" +
"z7VWmZ8n9PbTowKj/1rFzrLHaA1xVjKwH2s7NzgPZ0XbJyTjKvJg7yWHT+JG0xKj\n" +
"okZuFXzjXV6UJq6G+QIDAQAB\n" +
"-----END PUBLIC KEY-----");
$("#password").on("input propertychange", function() {
var password = $(this).val();
var encryptedPassword = encrypt.encrypt(password);
$(this).val(encryptedPassword);
});
</script>
```
注意:在使用RSA加密和解密的过程中,需要使用相同的密钥对。在这里,我们使用JSEncrypt生成公钥,并将其传递给前端。后端的私钥保存在数据库中,用于解密密码。
阅读全文