Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using crypt() from crypt.h

I am doing the week2 pset for CS50. When using the crypt function, the char pointers which point to the ciphertext of any string always point to the last thing I encrypted. For example:

char password[] = "AAAA";
char toCrack[] = "AAzz";
printf("%s\n", password);
printf("%s\n", toCrack);

char *toCrackCiph = crypt(toCrack, "da");
char *passwordCiph = crypt(password, "aa");


printf("%s\n", passwordCiph);
printf("%s\n", toCrackCiph);

toCrackCiph and passwordCiph equal each other, even though their strings are not the same, and neither is the salt.

Am I making a simple pointer error somewhere?

Thanks,

like image 859
Zach LeFevre Avatar asked Mar 10 '23 00:03

Zach LeFevre


1 Answers

(I am not familiar with CS50. I am answering this question under the assumption that crypt is the function crypt(3) from the traditional Unix standard C library.)

crypt is a very old function, from the days before anyone worried about thread-safety in C. Every time you call it, it returns the same pointer, pointing to a static buffer inside the C library. Each call overwrites the result of any previous call.

If you print out the result of the first crypt call before calling it again...

#include <stdio.h>
#include <unistd.h>

int 
main(void)
{
    char password[] = "AAAA";
    char toCrack[] = "AAzz";
    printf("%s\n", password);
    printf("%s\n", toCrack);

    char *toCrackCiph = crypt(toCrack, "da");
    printf("%s\n", toCrackCiph);

    char *passwordCiph = crypt(password, "aa");
    printf("%s\n", passwordCiph);
    return 0;
}

... then you will see two different strings. The output on my computer is

AAAA
AAzz
daeBW5vt16USo
aaI8pRQwCn7N2

Since you are using salt strings that request the old DES-based password hash algorithm, you should get the same thing.

This is a classroom exercise, but I must still point out that the old DES-based password hash can be broken by brute force on any modern computer, so it should never be used for real passwords. You can probably get a better algorithm to be used by specifying a different style of salt string, something like "$5$bpKU3bUSQLwX87z/$".

like image 91
zwol Avatar answered Mar 24 '23 01:03

zwol