aoc/2015/day04/answer02.c
2024-07-05 19:55:39 -04:00

63 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>
int main() {
size_t PUZZLE_SIZE = 8; //puzzle input is 8 characters with no ending newline character
//load input string
FILE *file = fopen("input", "r");
if (file == NULL) {
perror("main: error opening file.");
return -1;
}
char input[256];
while (fgets(input, sizeof(input), file));
if (strlen(input) != PUZZLE_SIZE) {
perror("main: error reading file.");
return -1;
}
printf("puzzle input: %s\n", input);
//initialize MD5 context
//note: ignore gcc's warnings that MD5 is depreciated
MD5_CTX md5_context;
uint8_t md5_hash[MD5_DIGEST_LENGTH];
char md5_string[MD5_DIGEST_LENGTH * 2 + 1]; //32 hexadecimal digits
//each byte needs two characters in hex, plus one for '\0'
char *md5_string_ptr = md5_string;
int32_t chars_written;
int32_t available_space;
int32_t count = -1; //initialize count at -1 so that the first count++ sets it to 0
while (strncmp(md5_string, "000000", 6) != 0) {
count++;
chars_written = snprintf(input + PUZZLE_SIZE, sizeof(input) - strlen(input), "%i", count);
available_space = sizeof(input) - strlen(input);
if (chars_written >= available_space) {
perror("main: buffer overflow.");
return -1;
}
//initialize MD5 context
MD5_Init(&md5_context);
//update context with input (+ count) data
MD5_Update(&md5_context, input, strlen(input));
//finalize MD5 hash
MD5_Final(md5_hash, &md5_context);
for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {
md5_string_ptr += sprintf(md5_string_ptr, "%02x", md5_hash[i]);
}
md5_string_ptr = md5_string; //reset pointer
}
printf("count %i: %s\n", count, md5_string);
return 0;
}