Saturday, 15 October 2016

Captcha Example for Java

Requirement is to authenticate a  rest service via captha alphanumeric text image to protect against robot site crawlers.

1) Create a alphanumeric string and add it to the application session.
2) Create a service to generate an image and send it as the bytestream.
3) Validate the string and the image text and authorize the user request.


       

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.lang.RandomStringUtils;


public class Captcha {

    public static void main(String[] args) throws IOException {

          System.out.println("CAPTCHA START");
          BufferedImage image = new BufferedImage(200, 50,
          BufferedImage.TYPE_INT_RGB);
          Graphics2D graphics2D = image.createGraphics();
          Map map = new HashMap();
          Color c = new Color(0.6662f, 0.4569f, 0.3232f);
          GradientPaint gp = new GradientPaint(30, 30, c, 15, 25,Color.white, true);
          graphics2D.setPaint(gp);
          Font font=new Font("Verdana", Font.CENTER_BASELINE , 26);
          graphics2D.setFont(font);
          graphics2D.drawString( RandomStringUtils.randomAlphanumeric(7),2,20);
          graphics2D.dispose();
          File outputfile = new File("capctha.png");
          ImageIO.write(image, "jpeg", outputfile);
          System.out.println("CAPTCHA END" +outputfile.getAbsolutePath());
    }
}

       
 

No comments:

Post a Comment

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...