#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

/*
	Compute SHA-512 of file using C
	Author: Tim Pierson, Dartmouth CS60, Fall 2026
		based example from Du: Computer and Internet Security pg 503

	compile on Linux:
		uncomment line 5
		gcc compute_hash.c -o compute_hash -lcrypto	

	run:
	compute_hash plain.txt
	
	will output the SHA-512 hash of the plain.txt file
	to confirm type sha512sum plain.txt on command line and compare hashes
*/

void main(int argc, char *argv[]) {
	SHA512_CTX ctx;
	u_int8_t results[SHA512_DIGEST_LENGTH];
	FILE * fp;
	char * line = NULL;
	size_t len = 0;
	ssize_t read;
	int i;

	//check usage
	if (argc != 2) {
		printf("Usage: compute_hash <filename>");
		exit(EXIT_FAILURE);
	}

	//set up for hashing
	SHA512_Init(&ctx);
	
	//open file for reading
	fp = fopen(argv[1], "r");
	if (fp == NULL)
		exit(EXIT_FAILURE);

	//read lines
	while ((read = getline(&line, &len, fp)) != -1) {
		SHA512_Update(&ctx, line, strlen(line));
	}


	//finalize hashing
	SHA512_Final(results,&ctx);

	//free line variable and close file
	if (line)
		free(line);
	fclose(fp);

	//print results
	for(i=0;i< SHA512_DIGEST_LENGTH;i++) {
		printf("%02x",results[i]);
	}
	printf("\n");	
}