简体   繁体   中英

crypt_r() example?

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.

EDIT Example, as requested:

struct crypt_data data;
data.initialized = 0;

char *enc = crypt_r(key, salt, &data);
printf("EncryptedL %s\n", enc);

The whole point of the _r versions of GNU functions is to make them reentrant (and threadsafe in this case); eliminating the internal static buffers the non-_r versions use and return pointers to.

The char* returned is pointing into the data structure you allocated and passed in.

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM