简体   繁体   English

C中的crypt函数中的数据丢失

[英]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. 基于crypt.c的示例,我有以下代码,但是当我运行它时,密码1在第二次调用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. 这样可以解决您消失的密码1。

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()的第二次调用-即使密码相同,这也会导致返回值不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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