jinlin
2024-02-23 1772fc5e211f9e9e0ab4cdc6c29b436aac178c2a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
 
package com.zt.security.service;
 
import com.wf.captcha.ArithmeticCaptcha;
import com.zt.common.utils.CacheUtils;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * 验证码
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class CaptchaService {
 
    /**
     * 图片验证码
     */
    public void create(HttpServletResponse response, String uuid) throws IOException {
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
 
        // 生成验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(150, 40);
        captcha.setLen(2);
        captcha.getArithmeticString();
        captcha.out(response.getOutputStream());
 
        // 保存到缓存
        CacheUtils.put("captchaCache", uuid, captcha.text());
    }
 
    /**
     * 验证码效验
     *
     * @param uuid
     *            uuid
     * @param code
     *            验证码
     * @return true:成功 false:失败
     */
    public boolean validate(String uuid, String code) {
        // 获取验证码
        String captcha = (String) CacheUtils.get("captchaCache", uuid);
 
        // 效验成功
        if (code.equalsIgnoreCase(captcha)) {
            return true;
        }
 
        return false;
    }
}