I have left some debug statements in my code so it should be easy to understand my problem. (these statements have comment DEBUG)
I have manually ran crypt with salt 50 and password A.
I have restricted my set of available characters to A (rather than all upper and lower case characters) and set password length to 1 (rather than 5.)
For some reason which I'm struggling to understand, the string "A" created by my program isn't equivalent to the string "A" when entered manually.
I'm fairly happy that my recursion generates all combinations of lower/upper case letters over password length 5.
define _XOPEN_SOURCE 700
#import <stdio.h>
#import <math.h>
#import <string.h>
#import <cs50.h>
#import <stdlib.h>
#import <ctype.h>
#import <unistd.h>
bool crack_pwrd(string guess, string salt, string hashed)
{
string hashed_pwrd_guess = crypt(guess, salt);
//DEBUG: print statements
printf("guess is: %s\n",guess);
printf("hased password for guess is: %s\n",hashed_pwrd_guess);
//compare hashed password provided vs hashed password from guess if same return 1
if(strcmp(hashed_pwrd_guess, hashed) == 0)
{
return(1);
}
else
{
return(0);
}
}
string recur_crack(int counter, char guess[],string salt, string hashed, string alphabet, int pwrd_len)
{
//recursion will call until password exceeds password length
if(counter <= pwrd_len)
{
counter++;
for(int i=0; i<strlen(alphabet); i++)
{
//defines the guess//brute force through all options via recursion
guess[counter-1]=alphabet[i];
guess[counter]='\0';
//check if guess returns the same hashed password as input, returns guess and exits if correct
bool guess_correct = crack_pwrd(guess,salt,hashed);
if(guess_correct == 1)
{
return(guess);
exit(1);
}
//recursive call
recur_crack(counter, guess, salt, hashed, alphabet, pwrd_len);
}
}
return(0);
}
int main(int argc, string argv[])
{
string hashed = argv[1];
//checks if user entered exactly one keyword argument
if (argc==1 || argc>2)
{
printf("Argument count error\n");
exit(1);
}
//extract salt from hashed password
char salt[3];
strncpy(salt, hashed, 2);
salt[2] = '\0';
//DEBUG: manually check hashed password for letter A
string test=crypt("A", salt);
printf("hashed password for A is: %s\n",test);
int j = 1;
char guess[j];
string alphabet = "A";
//"ABCDEFGHIJKLMNOPQRSTUVWXUZabcdefghijklmnopqrstuvwxyz";
int pwrd_len=1;
//5
string password = recur_crack(j,guess,salt,hashed,alphabet,pwrd_len);
printf("%s",password);
}