Could anyone here give me an example on how to use the function crypt_r()?
From man page, it is unclear that the returned char * string is pointing to a block of memory allocated (in the heap) inside the function itself, or is still pointing to a static memory, like crypt()?
From the GNU manual:
The crypt_r function does the same thing as crypt, but takes an extra parameter which includes space for its result (among other things), so it can be reentrant. data->initialized must be cleared to zero before the first time crypt_r is called.
Kernel.org gives more details:
crypt_r() is a reentrant version of crypt(). The structure pointed to by data is used to store result data and bookkeeping information. Other than allocating it, the only thing that the caller should do with this structure is to set data->initialized to zero before the first call to crypt_r().
Both crypt and crypt_r return a pointer to the encrypted password. Naturally, if you use crypt_r that memory will be somewhere in the crypt_data you passed.
struct crypt_data data;
data.initialized = 0;
char *enc = crypt_r(key, salt, &data);
printf("EncryptedL %s\n", enc);
#define _GNU_SOURCE
#include <crypt.h>
#include <stdio.h>
int main(void) {
struct crypt_data data[1] = {0};
char *res;
res = crypt_r("password", "QX", data);
printf("return value from crypt_r was %s\n", res);
return 0;
}
Compiled with gcc version 4.6.2 on my system
gcc crypttest.c -lcrypt
the result is
return value from crypt_r was QXZx61KdaYegc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With