首先先要创建一个CaptchaController的类,可以在下面的代码中看到
在getCaptcha的方法里面写好了生成随机的4位小写字母或数字的验证码,然后通过BufferedImage类变为图片,顺便加上了干扰线。之后把图片转为Base64编码方便传给前端
为了安全我写了encrypt方法把4位验证码加密了一下,和图片放在了Mapli传给了前端,后面的verifyCaptcha是对前端输入的内容和我们生成的验证码进行比较,并返回状态码。
package cn.kmbeast.controller;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
private static final String ALGORITHM = "AES";
private static final String SECRET_KEY = "1234567890123456"; // 16字节的密钥
@GetMapping("/get")
public Map getCaptcha(HttpServletResponse response) throws Exception {
System.out.println("验证码已生成");
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
// 生成随机4位验证码(字母+数字)
String code = RandomStringUtils.randomAlphanumeric(4).toLowerCase();
// 加密验证码
String encryptedCode = encrypt(code);
// 生成图片
int width = 100, height = 40;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 设置背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 绘制干扰线
g.setColor(Color.GRAY);
for (int i = 0; i < 10; i++) {
int x1 = (int) (Math.random() * width);
int y1 = (int) (Math.random() * height);
int x2 = (int) (Math.random() * width);
int y2 = (int) (Math.random() * height);
g.drawLine(x1, y1, x2, y2);
}
// 绘制验证码
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 30));
g.drawString(code, 15, 30);
g.dispose();
// 将图片转换为Base64编码
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
ImageIO.write(image, "PNG", baos);
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
Map result = new HashMap<>();
result.put("image", base64Image);
result.put("encryptedCode", encryptedCode);
return result;
}
@PostMapping("/verify")
public Map verifyCaptcha(@RequestBody Map requestBody) {
Map result = new HashMap<>();
String inputCode = requestBody.get("code");
String encryptedCode = requestBody.get("encryptedCode");
try {
// 解密验证码
String decryptedCode = decrypt(encryptedCode);
if (!decryptedCode.equalsIgnoreCase(inputCode)) {
result.put("code", 500);
result.put("msg", "验证码错误");
} else {
result.put("code", 200);
result.put("msg", "验证码验证通过");
}
} catch (Exception e) {
result.put("code", 500);
result.put("msg", "验证码验证出错");
}
return result;
}
// 加密方法
private String encrypt(String data) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密方法
private String decrypt(String encryptedData) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
}
在网页要渲染的样式
逻辑处理
//在data里加入
data() {
return {
captchaImage: '', // 新增:用于存储验证码图片的 Base64 编码
encryptedCode: '' // 新增:用于存储加密的验证码
}
},methods: {
// 刷新验证码
async refreshCaptcha() {
try {
const { data } = await request.get(`http://localhost:8088/api/online-travel-sys/v1.0/captcha/get`);
this.captchaImage = `data:image/png;base64,${data.image}`;
this.encryptedCode = data.encryptedCode;
this.code = ''; // 刷新验证码时清空输入框
} catch (error) {
console.error('获取验证码出错:', error);
}
},
async login() {
if (!this.act || !this.pwd) {
this.$swal.fire({
title: '填写校验',
text: '账号或密码不能为空',
icon: 'error',
showConfirmButton: false,
timer: DELAY_TIME,
});
return;
}
if (!this.code) {
this.$swal.fire({
title: '填写校验',
text: '验证码不能为空',
icon: 'error',
showConfirmButton: false,
timer: DELAY_TIME,
});
return;
}
// 先验证验证码是否正确
try {
const { data } = await request.post(`http://localhost:8088/api/online-travel-sys/v1.0/captcha/verify`, { code: this.code, encryptedCode: this.encryptedCode });
if (data.code !== 200) {
this.$swal.fire({
title: '验证码错误',
text: data.msg,
icon: 'error',
showConfirmButton: false,
timer: DELAY_TIME,
});
this.refreshCaptcha(); // 刷新验证码
return;
}
} catch (error) {
console.error('验证码验证请求错误:', error);
this.$message.error('验证码验证出错,请重试!');
this.refreshCaptcha(); // 刷新验证码
return;
}
}
完整的前端代码
立即登录
没有账号?点此注册
结果展示