图型验证码的生成和验证

1.生成图型验证码

package com.beauty.common.util.schema;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 生成随机验证码
 * @author raoBo
 * @version 2021-04-19
 */
@SuppressWarnings("serial")
public class ValidateCodeServlet extends HttpServlet {

	public static final String VALIDATE_CODE = "validateCode";

	private int w = 70;
	private int h = 26;

	public ValidateCodeServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public static boolean validate(HttpServletRequest request, String validateCode){
		String code = (String)request.getSession().getAttribute(VALIDATE_CODE);
		return validateCode.toUpperCase().equals(code);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String validateCode = request.getParameter(VALIDATE_CODE); // AJAX验证,成功返回true
		if (StringUtils.isNotBlank(validateCode)){
			response.getOutputStream().print(validate(request, validateCode)?"true":"false");
		}else{
			this.doPost(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		createImage(request,response);
	}

	private void createImage(HttpServletRequest request,
                             HttpServletResponse response) throws IOException {

		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		/*
		 * 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
		 */
		String width = request.getParameter("width");
		String height = request.getParameter("height");
		if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
			w = NumberUtils.toInt(width);
			h = NumberUtils.toInt(height);
		}

		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
		createBackground(g);

		/*
		 * 生成字符
		 */
		String s = createCharacter(g);
		request.getSession().setAttribute(VALIDATE_CODE, s);

		g.dispose();
		OutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		out.close();

	}

	private Color getRandColor(int fc,int bc) {
		int f = fc;
		int b = bc;
		Random random=new Random();
        if(f>255) {
        	f=255;
        }
        if(b>255) {
        	b=255;
        }
        return new Color(f+random.nextInt(b-f),f+random.nextInt(b-f),f+random.nextInt(b-f));
	}

	public void createBackground(Graphics g) {
		// 填充背景
		g.setColor(getRandColor(220,250));
		g.fillRect(0, 0, w, h);
//		// 加入干扰线条
//		for (int i = 0; i < 8; i++) {
//			g.setColor(getRandColor(40,150));
//			Random random = new Random();
//			int x = random.nextInt(w);
//			int y = random.nextInt(h);
//			int x1 = random.nextInt(w);
//			int y1 = random.nextInt(h);
//			g.drawLine(x, y, x1, y1);
//		}
	}

	private String createCharacter(Graphics g) {
		char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
				'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
		String[] fontTypes = {"Arial","Arial Black","AvantGarde Bk BT","Calibri"};
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
			g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26));
			g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
//			g.drawString(r, i*w/4, h-5);
			s.append(r);
		}
		return s.toString();
	}


	public static String createCharacterText(){
		char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
				'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
			s.append(r);
		}
		return s.toString();
	}

	public  BufferedImage createImage(String text)
	{
		/*
		 * 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
		 */

		BufferedImage image = new BufferedImage(70, 26, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
		createBackground(g);

		/*
		 *字符串加入
		 */
		String[] fontTypes = {"Arial","Arial Black","AvantGarde Bk BT","Calibri"};
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		int length = text.length();
		for (int i = 0; i < length; i++) {
			String r = text.substring(i,i+1);
			g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26));
			g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
		}
		g.dispose();
		return image;
	}
}

2.Base64Util 工具类

package com.beauty.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Base64编码工具类
 *
 * @author raoBo
 * @date 2021/4/19
 */
public class Base64Util {
    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    public static String encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);

        int end = len - 3;
        int i = start;
        int n = 0;

        while (i <= end) {
            int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);

            i += 3;

            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }

        if (i == start + len - 2) {
            int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = (((int) data[i]) & 0x0ff) << 16;

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }

        return buf.toString();
    }

    private static int decode(char c) {
        if (c >= 'A' && c <= 'Z')
            return ((int) c) - 65;
        else if (c >= 'a' && c <= 'z')
            return ((int) c) - 97 + 26;
        else if (c >= '0' && c <= '9')
            return ((int) c) - 48 + 26 + 26;
        else
            switch (c) {
                case '+':
                    return 62;
                case '/':
                    return 63;
                case '=':
                    return 0;
                default:
                    throw new RuntimeException("unexpected code: " + c);
            }
    }

    /**
     * Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned.
     */

    public static byte[] decode(String s) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            decode(s, bos);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        byte[] decodedBytes = bos.toByteArray();
        try {
            bos.close();
            bos = null;
        } catch (IOException ex) {
            System.err.println("Error while decoding BASE64: " + ex.toString());
        }
        return decodedBytes;
    }

    private static void decode(String s, OutputStream os) throws IOException {
        int i = 0;

        int len = s.length();

        while (true) {
            while (i < len && s.charAt(i) <= ' ')
                i++;

            if (i == len)
                break;

            int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3)));

            os.write((tri >> 16) & 255);
            if (s.charAt(i + 2) == '=')
                break;
            os.write((tri >> 8) & 255);
            if (s.charAt(i + 3) == '=')
                break;
            os.write(tri & 255);

            i += 4;
        }
    }
}

3.生成和验证

public class SchemaUtil {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 生成图形验证码
     * @param deviceId 前端唯一标识
     * @param scene 场景:注册  登录 修改手机号 验证邮箱
     * @return
     */
    public String imgCaptcha(String deviceId,String scene){
        String captcha = ValidateCodeServlet.createCharacterText();
        log.info("--imgCaptcha--生成验证码:{}",captcha);
        ValidateCodeServlet codeServlet = new ValidateCodeServlet();
        BufferedImage bufferedImage = codeServlet.createImage(captcha);
        try{
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", out);
            String key = deviceId + "_" + scene;
            redisUtil.set(key,captcha,60*5);
            log.info("--imgCaptcha--生成图型成功:{}",captcha);
            return Base64Util.encode(out.toByteArray());
        }catch (Exception e){
            log.error("--imgCaptcha--生成图型验证码失败",e);
            e.printStackTrace();
        }
        throw new BizException("生成图型验证码失败", ResultCodeConstant.GENERATING_GRAPH_ERROR);
    }

    /**
     * 图型验证码code
     * @param deviceId 前端唯一标识
     * @param scene 场景:注册  登录 修改手机号 验证邮箱
     * @param code 用户输入验证码
     * @return
     */
    public boolean verificationCode(String deviceId,String scene,String code){
        String key = deviceId + "_" + scene;
        if (!redisUtil.hasKey(key)){
            return false;
        }
        String captcha = (String) redisUtil.get(key);
        if (StringUtils.equalsIgnoreCase(captcha,code)){
            return true;
        }
        return false;
    }

这里场景可以有很多种,自己定义。唯一标识码可以后端生成,返回给前端进行使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

痕0712

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值