Important stuff about the crypt() function in crypt.h under linux

The char* crypt(char*salt, char* str); function is used for one-way encryption with salt. However, the buffer it returns is always the same piece of memory so it may appear to be returning duplicated results.

Solution: Use strcp() or strdup() to make a copy of the result every-time after invokes. Also, remember to free the memory after use.

Example:


char a = crypt(“string1”,”this_is_salt”);
char
b = crypt(“string2”,”this_is_salt”);
printf(“%s”, strcmp(a,b));

The above is a wrong example and will print 0;


char a = strdup(crypt(“string1”,”this_is_salt”));
char
b = strdup(crypt(“string2”,”this_is_salt”));
printf(“%s”, strcmp(a,b));
free(a);free(b);

The above is a correct example and will print a non-0 value;

2017/5/25