基于crypt.c示例我有以下代码,但是当我运行它时,在第二次调用crypt时,password1被破坏了。谁能发现问题?
为两个请求输入相同的密码应该在结尾处为所有三个字符串生成相同的值。
=============================================== =
#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;
}
=============================================== =================
答案 0 :(得分:1)
你的问题是这个功能:
char *crypt(const char *key, const char *salt);
返回一个临时指针,下次调用该函数时将覆盖该指针。您想要做什么,以便不覆盖以前返回的数据:
char *crypt_r(const char *key, const char *salt,
struct crypt_data *data);
代替;这允许您传入包含缓冲区的结构以保留加密密码。有关更多信息,请参阅crypt的手册页。
这将照顾你消失的密码1。
另外,情况并非如此:“为两个请求输入相同的密码应该会导致最后三个字符串的值相同。”通过使用不同的盐,您将获得不同的加密值。
答案 1 :(得分:0)
您将另一个salt值传递给第二次调用crypt() - 即使密码相同,也会导致不同的返回值。