java 验证码工具_Java源码ImageVerifyUtils验证码工具类

这是一个Java编写的ImageVerifyUtils类,用于生成和验证验证码。类中包含了生成指定宽度和高度的验证码图片,并将验证码保存到HttpSession中,以及校验输入的验证码是否与生成时一致的功能。验证码包含干扰线和干扰点,确保安全性。
摘要由CSDN通过智能技术生成

应用于验证码校验与生成,一个简单的验证码生成类。

功能结合了,生成验证码,及验证码校验,需要传入http session。

直接上源码:

package com.mymvc.system.utils;

import com.mymvc.system.exception.IllegalValidateException;

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.logging.Logger;

/**

* image verify class.

*

* ImageVerifyUtils verify = new ImageVerifyUtils();

* verify.make(response, request.getSession());

*

* verify.check(request.getSession(),code); => true or throw new Exception.

*/

public class ImageVerifyUtils {

private static final Logger log = Logger.getLogger(ImageVerifyUtils.class.getName());

private String KEY_SESSION_VERIFY = "key_session_image_verify";

private String KEY_SESSION_DATETIME = "key_session_time_verify";

private Long expireIn = 300000L;

private String hash = "hash";

// private String raw = "qwertyupkijhgfdsazxcvbnmABCDEFGHJKLMNPQRSTUVWXYZ1234567890";

private String raw = "1234567890";

public ImageVerifyUtils() {

}

public void make(HttpServletResponse response, HttpSession session) throws Exception {

this.make(response, session, 120, 40);

}

public void make(HttpServletResponse response, HttpSession session, int width, int height) throws Exception {

this.make(response, session, width, height, 4);

}

/**

* make a image verify

* @param response output to browser.

* @param session http session,use it to save verify code.

* @param width default is 120px

* @param height default is 40px

* @param num the verify code.

* @throws Exception

*/

public void make(HttpServletResponse response, HttpSession session, int width, int height, int num) throws Exception {

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

int r = this.getRandom(200, 255);

int g = this.getRandom(200, 255);

int b = this.getRandom(200, 255);

Graphics2D g2d = (Graphics2D) image.getGraphics();

g2d.setColor(new Color(r, g, b));

g2d.fillRect(0, 0, width, height);

g2d.setStroke(new BasicStroke(1.5f));

for (int i = 0; i < 5; i++) {

r = this.getRandom(50, 200);

g = this.getRandom(50, 200);

b = this.getRandom(50, 200);

g2d.setColor(new Color(r, g, b));

g2d.drawLine(getRandom(0, width), getRandom(0, height), getRandom(0, width), getRandom(0, height));

}

int fontSize = (width - 26) / num;

r = this.getRandom(0, 180);

g = this.getRandom(0, 180);

b = this.getRandom(0, 180);

g2d.setColor(new Color(r, g, b));

g2d.setFont(new Font(null, Font.PLAIN, fontSize));

List codes = this.getVerifyString(num);

String code = "";

int __x = (width - fontSize * num) / 2;

for (int i = 0; i < codes.size(); i++) {

code += codes.get(i);

if (i == 0) {

g2d.drawString(codes.get(i), __x, getRandom(20, height));

} else {

g2d.drawString(codes.get(i), fontSize * i + __x, getRandom(20, height));

}

}

log.info(">>code:" + code);

//绘制干扰点

g2d.setStroke(new BasicStroke(2.6f));

for (int i = 0; i < 10; i++) {

r = this.getRandom(100, 255);

g = this.getRandom(100, 255);

b = this.getRandom(100, 255);

g2d.setColor(new Color(r, g, b));

int x = getRandom(0, width);

int y = getRandom(0, height);

g2d.drawLine(x, y, x + 2, y + 2);

}

session.setAttribute(KEY_SESSION_VERIFY, Md5Utils.md5(code.toLowerCase() + hash).toUpperCase());

session.setAttribute(KEY_SESSION_DATETIME, System.currentTimeMillis() + expireIn);

response.setContentType("image/jpeg");

OutputStream ops = response.getOutputStream();

ImageIO.write(image, "jpeg", ops);

ops.close();

}

/**

* check the code valid or invalid.

* @param session Http session

* @param verifyCode code string

* @return true or throws.

* @throws IllegalValidateException

*/

public boolean check(HttpSession session, String verifyCode) throws IllegalValidateException {

if (verifyCode == null) {

throw new IllegalValidateException("请输入验证码");

}

Long makeTime = (Long) session.getAttribute(KEY_SESSION_DATETIME);

if (makeTime == null) {

throw new IllegalValidateException("验证码不存在");

}

if (makeTime.longValue() < System.currentTimeMillis()) {

throw new IllegalValidateException("验证码已过期");

}

String source = (String) session.getAttribute(KEY_SESSION_VERIFY);

if (source == null) {

throw new IllegalValidateException("验证码不存在");

}

String now = Md5Utils.md5(verifyCode.toLowerCase() + hash).toUpperCase();

if (now.equals(source)) {

session.removeAttribute(KEY_SESSION_DATETIME);

session.removeAttribute(KEY_SESSION_VERIFY);

return true;

}

throw new IllegalValidateException("验证码错误");

}

/**

* get verify code.

* @param num the code length,default is 4.

* @return

*/

private List getVerifyString(int num) {

if (num <= 0) {

num = 4;

}

List res = new ArrayList<>();

Random r = new Random();

for (int i = 0; i < num; i++) {

res.add(String.valueOf(raw.charAt(r.nextInt(raw.length()))));

}

return res;

}

/**

* get number by random.

* @param min min number

* @param max max number

* @return between min to max.

*/

private int getRandom(int min, int max) {

Random random = new Random();

return random.nextInt(max) % (max - min + 1) + min;

}

}

使用方法(生成):

ImageVerifyUtils verify = new ImageVerifyUtils();

try {

verify.make(response, request.getSession());

} catch (Exception e) {

e.printStackTrace();

}

校验:

ImageVerifyUtils verify = new ImageVerifyUtils();

try {

String code = request.getParameter("code");

verify.check(request.getSession(),code);

} catch (IllegalValidateException e) {

e.printStackTrace();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值