简体   繁体   中英

loss of data in crypt function in C

Based on the crypt.c example I have the following code, but when I run it password1 gets corrupted during the second call to crypt. Can anyone spot the problem?

Entering the same password to both requests should result in the same value for all three strings at the end.

================================================

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <crypt.h>
#define _XOPEN_SOURCE
#include <unistd.h>

/*
cc calc1.c -ocalc1 -lcrypt
*/

int main(void) {
    unsigned long seed[2];
    char salt[] = "$1$zhodFRlE$";
    char *password2,*password1,*temp1;
    int i,ok;
    printf("%s is Salt\n",salt);

    password1 = crypt(getpass("Password1 :"), salt);

    printf("Crypt Password1: %s\n",password1);
    temp1 = strdup(password1);
    printf("Crypt temp1: %s\n",temp1);

    password2 = crypt(getpass("Password2 :"),temp1);

    printf("Crypt Password1: %s\n",password1);
    printf("Crypt temp1: %s\n",temp1);
    printf("Crypt Password2: %s\n",password2);
    return 0;
}

================================================================

Your problem is that this function:

char *crypt(const char *key, const char *salt);

returns a temporary pointer that will be overwritten the next time you call that function. What you want to do in order to not overwrite the previously returned data:

char *crypt_r(const char *key, const char *salt,
                 struct crypt_data *data);

instead; this allows you to pass in a structure that includes a buffer to keep the encrypted password. See the man page for crypt for more information.

That will take care of your disappearing password1.

Separately, this is not true: "Entering the same password to both requests should result in the same value for all three strings at the end." By using a different salt, you'll get a different encrypted value.

您将不同的盐值传递给对crypt()的第二次调用-即使密码相同,这也会导致返回值不同。

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