Skip to content
Related Articles
Open in App
Not now

Related Articles

Program to generate CAPTCHA and verify user

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 24 Mar, 2023
Improve Article
Save Article
Like Article

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.

CPP




// C++ program to automatically generate CAPTCHA and
// verify user
#include<bits/stdc++.h>
using namespace std;
  
// Returns true if given two strings are same
bool checkCaptcha(string &captcha, string &user_captcha)
{
    return captcha.compare(user_captcha) == 0;
}
  
// Generates a CAPTCHA of given length
string generateCaptcha(int n)
{
    time_t t;
    srand((unsigned)time(&t));
  
    // Characters to be included
    char *chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHI"
                  "JKLMNOPQRSTUVWXYZ0123456789";
  
    // Generate n characters from above set and
    // add these characters to captcha.
    string captcha = "";
    while (n--)
        captcha.push_back(chrs[rand()%62]);
  
    return captcha;
}
  
// Driver code
int main()
{
    // Generate a random CAPTCHA
    string captcha = generateCaptcha(9);
    cout << captcha;
  
    // Ask user to enter a CAPTCHA
    string usr_captcha;
    cout << "\nEnter above CAPTCHA: ";
    cin >> usr_captcha;
  
    // Notify user about matching status
    if (checkCaptcha(captcha, usr_captcha))
        printf("\nCAPTCHA Matched");
    else
        printf("\nCAPTCHA Not Matched");
  
    return 0;
}


Java




// Java pprogram to automatically generate CAPTCHA and
// verify user
import java.util.*;
import java.io.*;
  
class GFG
{
      
    // Returns true if given two strings are same
    static boolean checkCaptcha(String captcha, String user_captcha)
    {
        return captcha.equals(user_captcha);
    }
      
    // Generates a CAPTCHA of given length
    static String generateCaptcha(int n)
    {
        //to generate random integers in the range [0-61]
        Random rand = new Random(62); 
          
        // Characters to be included
        String chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
       
        // Generate n characters from above set and
        // add these characters to captcha.
        String captcha = "";
        while (n-->0){
            int index = (int)(Math.random()*62);
            captcha+=chrs.charAt(index);
        }
            
        return captcha;
    }
      
    // Driver code
    public static void main(String[] args)throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          
        // Generate a random CAPTCHA
        String captcha = generateCaptcha(9);
        System.out.println(captcha);
       
        // Ask user to enter a CAPTCHA
        System.out.println("Enter above CAPTCHA: ");
        String usr_captcha = reader.readLine();
       
        // Notify user about matching status
        if (checkCaptcha(captcha, usr_captcha))
            System.out.println("CAPTCHA Matched");
        else
            System.out.println("CAPTCHA Not Matched");
    }
}
  
// This code is contributed by shruti456rawal


Python3




# Python program to automatically generate CAPTCHA and
# verify user
import random
  
# Returns true if given two strings are same
def checkCaptcha(captcha, user_captcha):
    if captcha == user_captcha:
        return True
    return False
  
# Generates a CAPTCHA of given length
def generateCaptcha(n):
      
    # Characters to be included
    chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
      
    # Generate n characters from above set and
    # add these characters to captcha.
    captcha = ""
    while (n):
        captcha += chrs[random.randint(1, 1000) % 62]
        n -= 1
    return captcha
  
# Driver code
  
# Generate a random CAPTCHA
captcha = generateCaptcha(9)
print(captcha)
  
# Ask user to enter a CAPTCHA
print("Enter above CAPTCHA:")
usr_captcha = input()
  
# Notify user about matching status
if (checkCaptcha(captcha, usr_captcha)):
    print("CAPTCHA Matched")
else:
    print("CAPTCHA Not Matched")
  
# This code is contributed by shubhamsingh10


Javascript




// JavaScript program to automatically generate CAPTCHA and
// verify user
  
// Returns true if given two strings are same
function checkCaptcha(captcha, user_captcha) {
return captcha.localeCompare(user_captcha) == 0;
}
  
// Generates a CAPTCHA of given length
function generateCaptcha(n) {
// Characters to be included
const chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let captcha = "";
for (let i = 0; i < n; i++) {
captcha += chrs[(Math.floor(Math.random() * chrs.length))];
}
return captcha;
}
  
// Driver code
function main() {
// Generate a random CAPTCHA
const captcha = generateCaptcha(9);
console.log(captcha);
  
// Ask user to enter a CAPTCHA
const usr_captcha = prompt("Enter above CAPTCHA:");
  
// Notify user about matching status
if (checkCaptcha(captcha, usr_captcha))
console.log("CAPTCHA Matched");
else
console.log("CAPTCHA Not Matched");
}
  
main();


Output: 
 

CAPTCHA: cF3yl9T4
Enter CAPTCHA: cF3yl9T4
CAPTCHA Matched

Time Complexity: O(n)
Space Complexity: O(1)
This article is contributed by Himanshu Gupta(Bagri). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!