-1

I have been scratching my head quite a lot here and couldn't find a solution. I have written this code in order to crack simple 4 characters passwords (see code below). I can see that the passwords are correctly generated and that every possibility is tested with every combination of letters from A to z but the loop is never ending. Could someone tell me why?

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <crypt.h>


int main(int argc, string argv[])
{
//check number of arguments
if( argc != 2 )
{
    printf("Usage: ./crack hash\n");   
}

char str[5];
char salt[] = "..";
strncpy(salt, argv[1], 2);
string hash = argv[1];
string password = "....";
char pass[5]; 


//brute force loop
for( int i = 65; i < 123; i++)
{
    str[0] = i;
    for( int j = 65; j < 123; j++)
    {
        str[1] = j;
        for( int k = 65; k < 123; k++)
        {
            str[2] = k;
            for( int l = 65; l < 123; l++)
            {
                str[3] = l;
                str[4] = '\0';

                strcpy(pass, str);

                password = crypt(pass, salt);
                if ( hash == password)
                {
                    printf("%s\n", password);
                    break;
                }

                printf("\r%s", pass);
                fflush(stdout);
            }   
        }   
    }
}
}
Tripduc
  • 31
  • 1
  • 11

1 Answers1

2

Change the break in the if in a return to exit all the loops.

Moreover, as pointed out in the comments:

if ( hash == password) should be if(!strcmp(hash,password)) because you want to compare two strings in C.

granmirupa
  • 2,780
  • 16
  • 27
  • Works perfectly, thanks! Just a question, why would hash == password not work? It is still comparing both string no? Do string only compare with a strcmp function? – Tripduc May 03 '17 at 08:57
  • @Tripduc because the fiend that crafted `cs50.h` and typdef-ed `char*` as `string` did you no favors at all. All `hash == password` does is C is compare two `pointers` (i.e. the addresses held within each), not the *content* to which they point *to*. Mere words cannot express how much frustration that hidden `char*` typedef in that header file has caused people new to the language. The proper way to compare terminated strings is C for equivalence is is via a function like `strcmp`. – WhozCraig May 03 '17 at 08:59