繁体   English   中英

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

[英]loss of data in crypt function in C

基于crypt.c的示例,我有以下代码,但是当我运行它时,密码1在第二次调用crypt时被损坏。 谁能发现问题?

在两个请求中输入相同的密码,最后三个字符串的值应相同。

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

#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;
}

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

您的问题是该功能:

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

返回一个临时指针,下次您调用该函数时,该指针将被覆盖。 为了不覆盖先前返回的数据,您想做什么:

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

代替; 这使您可以传入一个包含缓冲区的结构,以保留加密的密码。 有关更多信息,请参见手册页。

这样可以解决您消失的密码1。

另外,这不是正确的:“对两个请求输入相同的密码,最后三个字符串的值都应相同。” 通过使用不同的盐,您将获得不同的加密值。

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

暂无
暂无

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

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