Monday, 19 December 2016

Program to generate unique CAPTCHA to verify an user

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a test to determine whether the user is human or not.

CAPTCHA provides a way to block bots from interacting with your site by providing something that's hard for them to read, but easy for people to read.

import java.util.Random;

public class GenerateCaptcha {
      /**
       * Generate Length between 5 and 8.
       * @return return length.
       */
      private static int generateRandomLength() {
            int length = 5 + Math.abs((random.nextInt()%4));
            return length;
      }

      /**
       *  Generate a CAPTCHA String consisting of random
       *  lower case & upper case letters, and numbers.
       */
      private static String generateCaptchaString(int length) {
           
            StringBuffer captchaBuffer = new StringBuffer();
           
            for (int i = 0; i < length; i++) {
                 
                  /** Generate the Random Character between 0 to 61.
                   * NOTE: Take abs value, because there may
                   * be ArrayIndexOutOfBount
                   * Exception for negative number*/
                  int rndCharIdx = Math.abs(random.nextInt()) % 62;
                 
                  char character = characters[rndCharIdx];
                 
                  captchaBuffer.append(character);
            }
            return captchaBuffer.toString();
      }

      private static Character[] characters = {'a','b','c','d','e','f',
            'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u',
            'v','w','x','y','z','A','B','C','D','E','F','G','H','I','J',
            'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y',
            'Z','0','1','2','3','4','5','6','7','8','9'};

      private static Random random= new Random();

      public static void main(String[] args) {

            int rndmCaptchaLen = generateRandomLength();

            String captcha = generateCaptchaString(rndmCaptchaLen);

            System.out.println("Random Captcha #"+captcha);
      }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...