蛮力实施的局限性

Limitation in the implementation of Brute Force

我写了一段代码,可以破解三位数密码。如果密码为 888 或小于该值,则此代码似乎有效。如果密码大于 888,则代码显示以下输出:

Unable to crack password..

我想知道这个限制背后的原因以及这个问题的解决方案。提前致谢。

#include <stdio.h>
#include <string.h>

int main()
{
    char pswd[5];
    char brute[4];
    char crack[4];


    printf("Program to crack a 3 digit numeric password\n ");
    printf("Enter password: ");
    scanf("%s", pswd);
    
    
    int i, j, k;
    int flag = 1;

    for(i = 48; i < 57; ++i)
    {
        for(j = 48; j < 57; ++j)
        {
            for(k = 48; k < 57; ++k)
            {
                crack[0] = i;
                crack[1] = j;
                crack[2] = k;
                crack[3] = 0;


                if(strcmp(crack, pswd) == 0)
                {
                    flag = 0;
                    break;
                }
            }
            
            if(flag == 0) break;
        }
        
        if(flag == 0) break;
    }
    
    
    

    flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");

    return 0;

}

问题是在你的 for-loops 中,数字 57 代表字符“9”,但你添加了一个严格小于意味着你不会使用字符“9”,一个简单的解决方法是只需添加 <='9' 或 <=57,这样您的代码将如下所示:

#include <stdio.h>
#include <string.h>

int main()
{
    char pswd[5];
    char brute[4];
    char crack[4];

    printf("Program to crack a 3 digit numeric password\n ");
    printf("Enter password: ");
    scanf("%s", pswd);
    int i, j, k;
    int flag = 1;

    for(i = '0'; i <= '9'; ++i)
    {
        for(j = '0'; j <= '9'; ++j)
        {
            for(k = '0'; k <= '9'; ++k)
            {
                crack[0] = i;
                crack[1] = j;
                crack[2] = k;
                crack[3] = 0;
                if(strcmp(crack, pswd) == 0)
                {
                    flag = 0;
                    break;
                }
            }
            if(flag == 0) break;
        }
        if(flag == 0) break;
    }
    flag == 0 ? printf("Password cracked successfully.\
Your password is %s", crack) : printf("Unable to crack password..");

    return 0;

}

您也可以将其更改为适用于超过 3 位数字,我的方法没有数组:

#include <stdio.h>

int main()
{
    int pswd,brute = 0;

    printf("Program to crack a positive password\n ");
    do
    {
        printf("Enter password: ");
        scanf("%d", &pswd);
    } while(pswd<0);

    while(brute != pswd)
        brute++;
    printf("The password is %d",brute);
    getchar();
    return 0;
}