【发布时间】:2018-05-28 12:35:18
【问题描述】:
我正在尝试创建一个类似 shadowfile 的 txt 文件,并且我正在使用 crypt 来生成哈希。我通过终端询问密码,然后生成一个伪随机盐。我在 crypt 函数中给出了这两个值,但它每次都创建一个不同的哈希值,或者根本没有创建一个不同的哈希值,我无法理解我的代码有什么问题。
#include<stdio.h>
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<ctime>
#include<crypt.h>
#include<unistd.h>
using namespace std;
/*====== READ STRING DYNAMICALLY ======*/
char* readFromTerminal() {
int length = 0; //counts number of characters
char c; //holds last read character
char *input;
input = (char *) malloc(sizeof (char)); //Allocate initial memory
if (input == NULL) //Fail if allocating of memory not possible
{
printf("Could not allocate memory!");
exit(1);
}
while ((c = getchar()) != '\n') //until end of line
{
realloc(input, (sizeof (char))); //allocate more memory
input[length++] = c; //save entered character
}
input[length] = '\0'; //add terminator
return input;
}
/*====== GENERATE PSEUDO RANDOM SALT VALUE ======*/
char* generateSalt() {
const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"; //salt alphanum
int alphanumLength = sizeof (alphanum) - 1; // alphanum lenght
char *salt; //salt string
salt = (char *) malloc(sizeof (char)); //Allocate initial memory
if (salt == NULL) //Fail if allocating of memory not possible
{
printf("Could not allocate memory!");
exit(1);
}
srand(time(NULL));
for (int i = 0; i < 21; i++) {
realloc(salt, (sizeof (char))); //allocate more memory
salt[i] = alphanum[rand() % alphanumLength]; //generate a random character from the alphanum
}
salt[21] = '\0'; //add terminator
return salt;
}
/*====== MAIN ======*/
int main(int argc, char** argv) {
char *username, *password, *salt, *hash;
ofstream myshadow("myshadow.txt", ios::out);
cout << "Enter your username: ";
username = readFromTerminal();
cout << "Enter your password: ";
password = readFromTerminal();
salt = generateSalt();
hash = (char *) malloc(30 * sizeof (char)); //Allocate memory for hash
hash = crypt(password, salt);
myshadow << username << ":" << hash;
return 0;
}
【问题讨论】:
-
为什么这个标签是C
-
现在对你来说不是个大问题
-
每次使用当前时间作为种子 (srand(time(NULL));),所以很明显每次都有不同的哈希值(即每次使用不同的盐)。
-
这很正常。如果你改变盐,哈希值也会改变。
-
当它什么都不生产的时候呢?