📜  生成验证码并验证用户的程序

📅  最后修改于: 2021-05-04 12:11:16             🧑  作者: Mango

CAPTCHA(完全自动化的公共Turing测试,告诉计算机和人类分开了)是一种确定用户是否为人类的测试。
因此,任务是每次都生成唯一的验证码,并通过要求用户输入自动生成的相同验证码并用生成的验证码检查用户输入来判断用户是否为人类。
例子:

CAPTCHA: x9Pm72se
Input: x9Pm62es
Output: CAPTCHA Not Matched

CAPTCHA: cF3yl9T4
Input: cF3yl9T4
Output: CAPTCHA Matched

生成验证码的字符集存储在包含(az,AZ,0-9)的字符数组chrs []中,因此chrs []的大小为62。
为了每次生成唯一的验证码,请使用rand()函数(rand()%62)生成一个随机数,该函数生成一个介于0到61之间的随机数,并将生成的随机数作为字符数组chrs []的索引从而生成一个新的captcha []字符,并且此循环运行n次(CAPTCHA的长度)次,以生成给定长度的CAPTCHA。

CPP
// C++ program to automatically generate CAPTCHA and
// verify user
#include
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;
}


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


输出:

CAPTCHA: cF3yl9T4
Enter CAPTCHA: cF3yl9T4
CAPTCHA Matched