#define _GNU_SOURCE
#include <assert.h>
#include <crypt.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dictionary_words.h"
#include "thread_pool.h"
const char HASH_START[] = "$6$";
const size_t SALT_LENGTH = 20;
const size_t HASH_LENGTH = 106;
const size_t NUM_THREADS = 16;
static size_t hash_count = 0;
static char **hashes = NULL;
static inline bool hashes_match(const char *password, const char *hash) {
char salt[SALT_LENGTH + 1];
memcpy(salt, hash, sizeof(char[SALT_LENGTH]));
salt[SALT_LENGTH] = '\0';
struct crypt_data data;
memset(&data, 0, sizeof(data));
char *hashed = crypt_r(password, salt, &data);
char *hashed_hash = &hashed[SALT_LENGTH];
const char *hash_hash = &hash[SALT_LENGTH];
return memcmp(hashed_hash, hash_hash, sizeof(char[HASH_LENGTH - SALT_LENGTH])) == 0;
}
typedef struct word_array {
size_t len;
size_t word_size;
char **words;
} word_array_t;
word_array_t word_variants(char *word) {
size_t word_length = strlen(word);
size_t word_variant_count = (word_length + 1) * 10;
size_t word_length_with_null_term = word_length + 1;
char **variants = calloc(word_variant_count, sizeof(char *));
for (size_t i = 0; i < 10; i++) {
for (size_t j = 0; j <= word_length; j++) {
char *result_word = calloc(word_length_with_null_term + 1, sizeof(char));
strncpy(result_word, word, j);
char number[2];
sprintf(number, "%lu", i);
strncpy(&result_word[j], number, 1);
strncpy(&result_word[j + 1], &word[j], word_length - j);
variants[(i * (word_length + 1)) + j] = result_word;
}
}
word_array_t variants_array = {.len = word_variant_count,
.word_size = word_length_with_null_term + 1,
.words = variants};
return variants_array;
}
void free_variants(word_array_t variants) {
for (size_t i = 0; i < variants.len; i++) {
free(variants.words[i]);
}
free(variants.words);
}
void check_word_variants(void *dictionary_word) {
char *word = (char *) dictionary_word;
word_array_t variants = word_variants(word);
for (size_t i = 0; i < variants.len; i++) {
for (size_t j = 0; j < hash_count; j++) {
if (hashes_match(variants.words[i], hashes[j])) {
printf("%s\n", variants.words[i]);
}
}
}
free_variants(variants);
return;
}
int main(void) {
char *line = NULL;
size_t line_capacity = 0;
while (getline(&line, &line_capacity, stdin) > 0 && line[0] != '\n') {
size_t line_length = strlen(line);
assert(line_length == HASH_LENGTH ||
(line_length == HASH_LENGTH + 1 && line[HASH_LENGTH] == '\n'));
assert(memcmp(line, HASH_START, sizeof(HASH_START) - sizeof(char)) == 0);
hashes = realloc(hashes, sizeof(char * [hash_count + 1]));
assert(hashes != NULL);
char *hash = malloc(sizeof(char[HASH_LENGTH + 1]));
assert(hash != NULL);
memcpy(hash, line, sizeof(char[HASH_LENGTH]));
hash[HASH_LENGTH] = '\0';
hashes[hash_count++] = hash;
}
free(line);
thread_pool_t *pool = thread_pool_init(30);
for (size_t i = 0; i < NUM_DICTIONARY_WORDS; i++) {
thread_pool_add_work(pool, check_word_variants, (void *) DICTIONARY[i]);
}
thread_pool_finish(pool);
}