Can't understand why my code is not working. Tried 2 different loops to arrive at the solution but the first one does not arrive at anything and keeps on going:
#include <stdio.h>
//#include <cs50.h>
#include <string.h>
//#include <ctype.h>
#include <stdlib.h>
#define _XOPEN_SOURCE
char *crypt(const char *key, const char *salt);
int main(int argc, char *argv[])
{
// check single command-line argument: a hashed password
if (argc != 2)
{
printf("Missing or invalid command-line argument. Usage: ./crack hash\n");
return 1;
}
char key[5];
char salt[2];
char alphabet[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','\0'};
strncpy(salt,argv[1],2);
while (strcmp(argv[1], crypt(key, salt)) != 0)
{
for (int i = 0, n = strlen(alphabet); i < n; i++)
{
key[0] = alphabet[i];
for (int j = 0; j < n; j++)
{
key[1] = alphabet[j];
for (int k = 0; k < n; k++)
{
key[2] = alphabet[k];
for (int l = 0; l < n ; l++)
{
key[3] = alphabet[l];
}
}
}
}
}
printf("%s\n", key);
return 0;
}
while the second one only solve hash for rolf password, but none of the others:
#include <stdio.h>
//#include <cs50.h>
#include <string.h>
//#include <ctype.h>
#include <stdlib.h>
#define _XOPEN_SOURCE
char *crypt(const char *key, const char *salt);
int main(int argc, char *argv[])
{
// check single command-line argument: a hashed password
if (argc != 2)
{
printf("Missing or invalid command-line argument. Usage: ./crack hash\n");
return 1;
}
char key[5];
char salt[3];
char alphabet[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
strncpy(salt,argv[1],2);
for (int i = 0, n = strlen(alphabet); i < n; i++)
{
key[0] = alphabet[i];
for (int j = 0; j < n; j++)
{
key[1] = alphabet[j];
for (int k = 0; k < n; k++)
{
key[2] = alphabet[k];
for (int l = 0; l < n ; l++)
{
key[3] = alphabet[l];
if (strcmp(argv[1],crypt(key,salt)) == 0)
{
printf("%s\n", key);
return(0);
}
}
}
}
}
}
I suppose there is a problem with the length of the defined array, or maybe with the elements of arrays ("\0" maybe?!). Or possibly something else, or more than one thing! Any help would be greatly appreciated!
Thanks!