43 lines
941 B
C
43 lines
941 B
C
#define _GNU_SOURCE
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
#include <crypt.h>
|
|
|
|
void generate_salt(char *salt_buffer)
|
|
{
|
|
const char *charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
|
|
salt_buffer[0] = '$';
|
|
salt_buffer[1] = '6'; // SHA-512
|
|
salt_buffer[2] = '$';
|
|
|
|
srand(time(NULL));
|
|
for (int i = 3; i < 19; i++) {
|
|
salt_buffer[i] = charset[rand() % 64];
|
|
}
|
|
salt_buffer[19] = '$';
|
|
salt_buffer[20] = '\0';
|
|
}
|
|
|
|
char* hash_password(const char *password)
|
|
{
|
|
struct crypt_data data;
|
|
data.initialized = 0;
|
|
|
|
char salt[21];
|
|
generate_salt(salt);
|
|
|
|
char *hash = crypt_r(password, salt, &data);
|
|
return hash ? strdup(hash) : NULL;
|
|
}
|
|
|
|
int verify_password(const char *password, const char *stored_hash)
|
|
{
|
|
struct crypt_data data;
|
|
data.initialized = 0;
|
|
|
|
char *calculated = crypt_r(password, stored_hash, &data);
|
|
|
|
return (calculated && strcmp(calculated, stored_hash) == 0);
|
|
}
|