1

I'm trying to get crack.c to print out the key used in the crypt() function if the output from crypt() is the same as the user-inputted hash. To test this out, I've pre-generated a hash to use in testing. crypt("a", "AA") returns the hash AAa6CzJlsalyo.

My code is:

#define _XOPEN_SOURCE
#include <stdio.h>
#include <cs50.h>
#include <unistd.h>
#include <string.h>

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

    string cracked = " ",
           keyrange = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    char salt[] = "  ";

    salt[0] = argv[1][0];
    salt[1] = argv[1][1];

    char onelen[] = "A";

    for(int i = 0, n = strlen(keyrange); i < n; i++)
    {
        onelen[0] = keyrange[i];
        cracked = crypt(onelen, salt);
        printf("key: %s | salt: %s | hash: %s\n", onelen, salt, cracked); //used for debugging purposes
        if(cracked == argv[1])
        {
            break;
        }
    }

    printf("%s\n", onelen);
}

It works when I run it, it checks for every possible combination with a specific salt. My problem is that the for loop does not terminate when the condition cracked == argv[1] is true.

What am I doing wrong?

1 Answer 1

2

The var cracked is essentially a pointer, holding the address of the start of a string. if(cracked == argv[1]) is comparing a string's address to the address of argv[1], another string.

Next, strings cannot be compared with the == operator, although addresses can. You should get to know the strcmp() function and it's cousins. They will be most helpful to you.

Finally, string cracked = " ", is problematic. This sets the length of the allocated space for the cracked string to 2 - one for the space and one for \0, the end of string marker. If you try to write something longer into it, it will overwrite whatever follows in physical memory, often without generating an error.

As a side note, if you want to put a single char in a var, as appears to be the case with onelen, an array is not necessary. You can declare a var as a char and char onelen = 'A'; Note the single quotes.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .