100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 【图片验证码】Java实现图片验证工具类

【图片验证码】Java实现图片验证工具类

时间:2020-11-23 16:26:11

相关推荐

【图片验证码】Java实现图片验证工具类

原理:

图片验证码是一种常见的安全验证技术,它通过在用户访问网站时显示一张图片,要求用户输入图片中的文字或字符,以确认用户的身份。图片验证码的优点在于它可以有效地防止恶意破解,防止机器人程序自动提交表单,从而保护网站免受恶意攻击。

图片验证码的实现原理是,当用户访问网站时,网站会生成一张随机的图片,并要求用户输入图片中的文字或字符,然后将用户输入的文字或字符与图片中的文字或字符进行比较,如果相同,则表示用户身份验证通过,可以继续访问网站,否则则表示用户身份验证失败,无法继续访问网站。

图片验证码是一种常见的安全验证技术,它可以有效防止恶意破解和攻击。它的原理是,在用户登录或注册时,系统会生成一个随机的图片验证码,用户需要输入正确的验证码才能继续操作。出现问题的原因可能是用户输入的验证码不正确,或者系统生成的验证码有误。

解决方法:

1. 如果用户输入的验证码不正确,可以提示用户重新输入正确的验证码;

2. 如果系统生成的验证码有误,可以重新生成一个新的验证码,并让用户重新输入;

3. 可以使用更加安全的验证码,比如动态验证码,可以有效防止恶意破解和攻击。

最近在项目中需要在登录页面添加一个验证码功能防止人机暴力攻击,但是为了避免在项目中到过多的导入依赖,于是就写了一个生成图片验证码的工具类

整体效果如图:

这个验证码包含图片长宽,验证码字符数量等, 不区分大小写

接下来就给大家分析一下怎么使用

工具类如下:

verifyCode方法是根据传递的长度宽度和验证码的宽度,来确定生成的验证码

outputImage方法就是对图片进行一些编辑,调整宽高,绘制干扰线等功能

public class VerifyCodeUtils {//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";private static Random random = new Random();/*** 获取随机验证码及其加密图片** @param w 宽度* @param h 长度* @param size 验证码长度*/public static ValidateCodeDto verifyCode(int w, int h, int size) {//base64编码器//生成的图片验证码的值try {ValidateCodeDto validateCode = new ValidateCodeDto();String uuid = IdUtil.fastSimpleUUID();String code = generateVerifyCode(size).toLowerCase();ByteArrayOutputStream data = new ByteArrayOutputStream();//生成图片outputImage(w, h, data, code);validateCode.setId(uuid);validateCode.setCode(code);validateCode.setContent(data.toByteArray());return validateCode;} catch (IOException e) {throw new RuntimeException(e);}}/*** 使用系统默认字符源生成验证码** @param verifySize 验证码长度* @return*/public static String generateVerifyCode(int verifySize) {return generateVerifyCode(verifySize, VERIFY_CODES);}/*** 使用指定源生成验证码** @param verifySize 验证码长度* @param sources 验证码字符源* @return*/public static String generateVerifyCode(int verifySize, String sources) {if (sources == null || sources.length() == 0) {sources = VERIFY_CODES;}int codesLen = sources.length();Random rand = new Random(System.currentTimeMillis());StringBuilder verifyCode = new StringBuilder(verifySize);for (int i = 0; i < verifySize; i++) {verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));}return verifyCode.toString();}/*** description:指定参数 获取图片验证码输出流* @param w 宽* @param h 高* @param os 输出流* @param code 验证码内容* @return void* @author litong* @date /6/2*/public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {int verifySize = code.length();BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);Random rand = new Random();Graphics2D g2 = image.createGraphics();g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);Color[] colors = new Color[5];Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,Color.PINK, Color.YELLOW};float[] fractions = new float[colors.length];for (int i = 0; i < colors.length; i++) {colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];fractions[i] = rand.nextFloat();}Arrays.sort(fractions);g2.setColor(Color.GRAY);// 设置边框色g2.fillRect(0, 0, w, h);Color c = getRandColor(200, 250);g2.setColor(c);// 设置背景色g2.fillRect(0, 2, w, h - 4);//绘制干扰线Random random = new Random();g2.setColor(getRandColor(160, 200));// 设置线条的颜色for (int i = 0; i < 20; i++) {int x = random.nextInt(w - 1);int y = random.nextInt(h - 1);int xl = random.nextInt(6) + 1;int yl = random.nextInt(12) + 1;g2.drawLine(x, y, x + xl + 40, y + yl + 20);}// 添加噪点float yawpRate = 0.05f;// 噪声率int area = (int) (yawpRate * w * h);for (int i = 0; i < area; i++) {int x = random.nextInt(w);int y = random.nextInt(h);int rgb = getRandomIntColor();image.setRGB(x, y, rgb);}shear(g2, w, h, c);// 使图片扭曲g2.setColor(getRandColor(100, 160));int fontSize = h - 4;Font font = new Font("Algerian", Font.ITALIC, fontSize);g2.setFont(font);char[] chars = code.toCharArray();for (int i = 0; i < verifySize; i++) {AffineTransform affine = new AffineTransform();affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);g2.setTransform(affine);g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);}g2.dispose();ImageIO.write(image, "jpg", os);}private static Color getRandColor(int fc, int bc) {if (fc > 255)fc = 255;if (bc > 255)bc = 255;int r = fc + random.nextInt(bc - fc);int g = fc + random.nextInt(bc - fc);int b = fc + random.nextInt(bc - fc);return new Color(r, g, b);}private static int getRandomIntColor() {int[] rgb = getRandomRgb();int color = 0;for (int c : rgb) {color = color << 8;color = color | c;}return color;}private static int[] getRandomRgb() {int[] rgb = new int[3];for (int i = 0; i < 3; i++) {rgb[i] = random.nextInt(255);}return rgb;}private static void shear(Graphics g, int w1, int h1, Color color) {shearX(g, w1, h1, color);shearY(g, w1, h1, color);}private static void shearX(Graphics g, int w1, int h1, Color color) {int period = random.nextInt(2);boolean borderGap = true;int frames = 1;int phase = random.nextInt(2);for (int i = 0; i < h1; i++) {double d = (double) (period >> 1)* Math.sin((double) i / (double) period+ (6.2831853071795862D * (double) phase)/ (double) frames);g.copyArea(0, i, w1, 1, (int) d, 0);if (borderGap) {g.setColor(color);g.drawLine((int) d, i, 0, i);g.drawLine((int) d + w1, i, w1, i);}}}private static void shearY(Graphics g, int w1, int h1, Color color) {int period = random.nextInt(40) + 10; // 50;boolean borderGap = true;int frames = 20;int phase = 7;for (int i = 0; i < w1; i++) {double d = (double) (period >> 1)* Math.sin((double) i / (double) period+ (6.2831853071795862D * (double) phase)/ (double) frames);g.copyArea(i, 0, 1, h1, 0, (int) d);if (borderGap) {g.setColor(color);g.drawLine(i, (int) d, i, 0);g.drawLine(i, (int) d + h1, i, h1);}}}/*** 获取随机验证码及其加密图片** @param w 宽度* @param h 长度* @param code 验证码内容*/public static String verifyCode(int w, int h, String code) {//base64编码器//输出流:输出图片的ByteArrayOutputStream data = new ByteArrayOutputStream();try {//把code合并到图片,并输出成流到 ByteArrayOutputStreamoutputImage(w, h, data, code);} catch (IOException e) {e.printStackTrace();throw new BusinessException("图片验证码创建失败");}//使用BASE64Encoder编码器把 ByteArrayOutputStream流中的图片内容基于base64编码成字符串,返回return Base64.encode(data.toByteArray());}}

这个工具类已经囊括了所有的生成二维码所需要的方法,大家可以直接复制到项目中,然后调用这个工具类就行了

调用

调用方法就非常之简单了,传递长宽和需要的验证码字符数量就可以得到对应的验证码图片对象了

VerifyCodeUtils.verifyCode(imageWidth, imageHeight, codeCount);

这样就获得了一个验证码的图片和对应的验证码,然后将返回的图片验证码用一个对象存储起来

ValidateCodeDto validateCode = new ValidateCodeDto();String uuid = IdUtil.fastSimpleUUID();String code = generateVerifyCode(size).toLowerCase();ByteArrayOutputStream data = new ByteArrayOutputStream();//生成图片outputImage(w, h, data, code);validateCode.setId(uuid);validateCode.setCode(code);validateCode.setContent(data.toByteArray());

返回了这个对象之后,将对象里面的对应的验证码和唯一id存入缓存,设置过期时间

validateCode = VerifyCodeUtils.verifyCode(imageWidth, imageHeight, codeCount);String id = validateCode.getId();String code = validateCode.getCode();// 将验证码放入缓存,有效期为5分钟validateCodeCache.putWithExpire(id, code, 300);

将验证码图片转换成base64格式返回给前端做显示

我的对象是这样定义的

public class ValidateCodeDto {// 验证码编号private String id;// 验证码内容private byte[] content;//验证码private String code;}

然后前端传递对应的唯一id和验证码信息做比对,就完成了简单的登录验证码验证的功能了

这个是一个相对简单的例子,只是将验证码做出了该有的效果,如果你需要增加一些特定的需求,可以根据上面的代码做一些修改。

注意:

1. 尽量使用更加安全的验证码,比如动态验证码,可以有效防止恶意破解和攻击;

2. 尽量使用复杂的验证码,比如使用大小写字母、数字和特殊字符组合的验证码,可以提高验证码的安全性;

3. 尽量使用更加可靠的验证码,比如使用人机验证,可以有效防止恶意破解和攻击。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。