VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-generate-captcha-verify-user/

⇱ Program to generate CAPTCHA and verify user - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to generate CAPTCHA and verify user

Last Updated : 3 Apr, 2023

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.
So, the task is to generate unique CAPTCHA every time and to tell whether the user is human or not by asking user to enter the same CAPTCHA as generated automatically and checking the user input with the generated CAPTCHA.
Examples: 

CAPTCHA: x9Pm72se
Input: x9Pm62es
Output: CAPTCHA Not Matched

CAPTCHA: cF3yl9T4
Input: cF3yl9T4
Output: CAPTCHA Matched

The set of characters to generate CAPTCHA are stored in a character array chrs[] which contains (a-z, A-Z, 0-9), therefore size of chrs[] is 62. 
To generate a unique CAPTCHA every time, a random number is generated using rand() function (rand()%62) which generates a random number between 0 to 61 and the generated random number is taken as index to the character array chrs[] thus generates a new character of captcha[] and this loop runs n (length of CAPTCHA) times to generate CAPTCHA of given length.

Algorithm:

  1. First declare and define the checkCaptcha() function that takes two string parameters and returns a boolean value.
  2. Within the checkCaptcha() function, compare the two string parameters using the compare() function and return true if they are the same; otherwise, return false.
  3. Declare and define the generateCaptcha() function that takes an integer parameter and returns a string value.
  4. Within the generateCaptcha() function, initialize a time variable using the time() function and seed the random number generator using the srand() function.
  5. Declare a character array containing all the characters to be included in the CAPTCHA and assign it to a char pointer variable.
  6. Generate a random CAPTCHA string of the specified length by repeatedly appending random characters from the character array to a string variable using the push_back() function.
  7. Return the generated CAPTCHA string.
  8. Within the main() function, declare a string variable named captcha and call the generateCaptcha() function with a length of 9 to generate a random CAPTCHA string.
  9. Print the generated CAPTCHA string on the console. 
     

Output: 

CAPTCHA: cF3yl9T4
Enter CAPTCHA: cF3yl9T4
CAPTCHA Matched

Time Complexity: O(n)
Space Complexity: O(1)

Comment
Article Tags:
Article Tags: