Monday, November 19, 2012

Captcha for Java

       A CAPTCHA is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text as the one shown on image, but current computer programs can't.
       The term CAPTCHA (for Completely Automated Public Turing Test To Tell Computers and Humans Apart) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University.
       When u create web project sometimes u need captcha with colors of your site. That cases u can create captcha yourself as following:

Create CaptchaMServlet and generate your captcha with Java AWT lib.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  int width    = 137;
  int height    = 33;
  Color bgColor1   = new Color(33, 189, 254); // gradient top-bottom color
  Color bgColor2   = new Color(255, 255, 255); // gradient middle color
  Color textColor  = new Color(255, 153, 0);
  Font font   = new Font("Arial", Font.BOLD, 13);
  Random random  = new Random();
  String captchaStr = RandomStringUtils.randomAlphanumeric(5+random.nextInt(3)); //[5-7]
  
  BufferedImage captchaImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  
  Graphics2D g = captchaImg.createGraphics();
  
  GradientPaint gp = new GradientPaint(0, 0, bgColor1, 0, height/2, bgColor2, true);
  g.setPaint(gp);
  g.fillRect(0, 0, width, height);
  
  g.setColor(textColor);
  g.setFont(font);
  char[] captchaArr = captchaStr.toCharArray();
  int x = 0; 
  int y = 0;
  for (int i=0; i < captchaArr.length; i++) {
   x += 15;
      y = 17 + random.nextInt(5);
      g.drawChars(captchaArr, i, 1, x, y);
  }
  
  float[] dash4 = { 4f, 4f, 1f };
  BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f );
  g.setStroke(bs4);
        g.drawLine(3, height/2, width-3, height/2);
  
        request.getSession().setAttribute("captcha", captchaStr);
        
  response.setContentType("image/png");
  ImageIO.write(captchaImg, "png", response.getOutputStream());
}
Create jsp and write:
<img src="CaptchaMServlet" border=0 id="captchaImg">
<img alt="" src="resource/image/reload.png" onclick="reloadCaptcha()"><br>
<input type="text" name="captchaAnswer">
Now create js file and write reloadCaptcha() function:
function reloadCaptcha(){
   var c_miliseconds = new Date().getTime();
   $("#captchaImg")[0].src = 'CaptchaMServlet?x='+ c_miliseconds;
}
Now when u click on reload.png u will see new one captcha. That is all :)

1 comment:

  1. Cheap Wildcard SSL - Cheap SSL certificates (including wildcard and multi-domain (SAN) SSL certificates) from Comodo, GeoTrust, Thawte and Symantec (VeriSign)

    ReplyDelete