Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypt_r() example?

Tags:

c

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()?

like image 795
Qiang Xu Avatar asked Nov 22 '25 23:11

Qiang Xu


2 Answers

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.

EDIT Example, as requested:

struct crypt_data data;
data.initialized = 0;

char *enc = crypt_r(key, salt, &data);
printf("EncryptedL %s\n", enc);
like image 70
cnicutar Avatar answered Nov 25 '25 17:11

cnicutar


#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
like image 33
pmg Avatar answered Nov 25 '25 16:11

pmg