java生成CAPTCHA验证码并逐步优化

本文详细介绍了一种使用纯Java实现的CAPTCHA验证码方案,包括验证码的生成过程、随机字符串生成、背景设置、干扰线绘制、验证码字符显示及图片扭曲等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纯Java实现CAPTCHA验证码,验证码被机器破解由易到难。

图片如下:

 eazy:     

normal: 

hard:      

very hard:    

1.指明验证码的宽和高,以及画板和画笔

// 验证码图片的宽度。
		int width = 70;
		// 验证码图片的高度。
		int height = 30;
		
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics g=image.getGraphics();		
		// 随机操作對象
	    Random random=new Random();

2.生成随机字符串(验证码)

String s ="";
         for(int i=0;i<4;i++){
        	 s=getRandomCode(0, 4, null);
             System.out.println(s);
         }



	/**
	 * 生成随机字符串
	 * @param type 类型  0:大小写+数字  1:大小写  2:数字
	 * @param length 长度
	 * @param exChars 排除的字符
	 * @return
	 */
	public static String getRandomCode(int type,int length,String exChars){
		StringBuffer sb=new StringBuffer();
		Random random=new Random();
		int i=0;
		switch (type) {
		case 0:
			while(i<length){
                int t=random.nextInt(123);
                if((t>=97||(t>=65&&t<=90)||(t>=48&&t<=57))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		case 1:
			while(i<length){
                int t=random.nextInt(123);
                if((t>=97||(t>=65&&t<=90))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		case 2:
			while(i<length){
                int t=random.nextInt(123);
                if(((t>=48&&t<=57))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		default:
			break;
		}	
		return sb.toString();
		
	}

3.设置背景颜色、字体以及边框

// 设定图像背景色(因为是做背景,所以偏淡)
         Color color=getRandomColor(200, 250);
 		g.setColor(color);
 		g.fillRect(0, 0, width, height);
 		
 		// 创建字体,字体的大小应该根据图片的高度来定。
		Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
		// 设置字体。
		g.setFont(font);
		
            // 画边框。
	    g.setColor(Color.BLACK);
	    g.drawRect(0, 0, width - 1, height - 1);

4.随机生成多条干扰线,加大攻击难度。

// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
		g.setColor(getRandomColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}	

其中getRandomColor():

// 给定范围获得随机颜色
	public static Color getRandomColor(int fc, int bc) {
			Random random = new Random();
			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);
		}

5.按位写入验证码,分顺序分布和随机分布。

// 写入验证码。
		for (int i = 0; i < s.length(); i++) {	
			String strRand = s.charAt(i)+"";
			// 生成随机颜色
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));

			//等间隔出现 
			//g.drawString(strRand, 15*i + 6 , 24);
			
			//随机位置出现
			g.drawString(strRand, (int) (15*i+Math.random()*10) , (int) (Math.random()*10+20));
			

			
		}

6.再进行扭曲图片。

//扭曲图片
		shearX(g, width, height, color);
        shearY(g, width, height, color);
//延水平方向扭曲图片
	private static void shearX(Graphics g, int w1, int h1, Color color) {
	     Random random=new Random();
	     int period = 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 
            		 + (2.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) {
        Random random=new Random();
        int period = random.nextInt(5) + 10; // 35;
 
        boolean borderGap = true;
        int frames = 20;
        int phase = random.nextInt(2);
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                            + (2.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);
            }
 
        }
 
    }

6.图像生效,并以文件形式输出。

// 图象生效
		g.dispose();
		output(image);
        

其中 output(image) 输出jpg文件 :

//将图片输出成文件
	public static void output(BufferedImage image) {
		//String randomCode = getRandomCode(0, 4, null);
		try {
			File file = new File("d:/test_captcha.jpg");
			ImageIO.write(image, "jpg", file);
		} catch (IOException e) {
			// TODO: handle exception
			System.out.println("保存失敗");
			e.printStackTrace();
		}
		
	}

文章多处参考自:https://www.cnblogs.com/maixiaodou/p/7305729.html









### 如何在Java项目中实现和使用Captcha验证码 #### 实现校验验证码的功能 为了确保用户提交的信息安全可靠,在实际业务逻辑中,通常会加入验证码机制来防止恶意攻击。当接收到用户请求时,服务器端需从Session对象中取出之前存储的验证码字符串,将其与用户输入的内容进行比较。如果两者不匹配,则返回错误提示给客户端。 ```java // 校验验证码是否正确 String captcha = (String) request.getSession().getAttribute("captcha"); if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) { return RespBean.error("验证码错误,请重新输入"); } ``` [^1] #### 创建发送中文类型的图形验证码 对于希望提供更友好用户体验的应用程序来说,可以考虑采用带有汉字字符集的图像形式作为验证手段之一。下面这段代码展示了如何利用`ChineseCaptcha`类创建一个宽度为130像素高度为48像素大小的中文风格验证码图片实例,通过HTTP响应输出流直接传送给浏览器显示出来。 ```java @RequestMapping("/hello") public void hello(HttpServletResponse response) throws IOException { // 中文类型 ChineseCaptcha captcha = new ChineseCaptcha(130, 48); // 获取验证码文本内容以便后续对比检验 String text = captcha.text(); System.out.println("验证码为:" + text); // 将生成好的验证码图象数据写入到HttpServletResponse对象里去 captcha.out(response.getOutputStream()); } ``` [^2] #### 验证滑块式交互型验证码的有效性 除了传统的纯文字或图案组合外,还有一种基于拖拽动作完成身份认证过程的方法——即所谓的“滑块”验证码。这里给出了一种具体的解决方案框架:借助于第三方库`aj-captcha`所提供的工具函数来进行最终的结果判定工作。具体而言就是先构建好相应的验证器实体;再依据实际情况传递必要的参数进去调用其内部定义好的接口方法即可得知当前操作是否合法合规。 ```java import com.github.ajanthan.captcha.SliderCaptchaVerifier; public class SliderCaptchaExample { public static void main(String[] args) { // 假设此处已存在用于表示待测目标位置偏移量等信息的相关变量声明语句... SliderCaptchaVerifier verifier = new SliderCaptchaVerifier(); boolean isVerified = verifier.verify(imagePath, sliderImagePath, sliderToken, offsetX); if (isVerified) { System.out.println("滑动操作验证成功!"); } else { System.out.println("滑动操作验证失败!"); } } } ``` [^4]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值