#include "sha-2/sha-256.h" #include #include #include #include #include #include #include #include #include void print_hash(uint8_t *hash){ for(int i = 0; i < 32; i++) printf("%02x", hash[i]); puts(""); } // Return true if they're the same char compare_hashes(uint8_t *a, uint8_t *b){ for(int i = 0; i < 32; i++) if(a[i] != b[i]) return 0; return 1; } double timediff(struct timeval* start, struct timeval* end) { double s_diff = end->tv_sec - start->tv_sec; double us_diff = end->tv_usec - start->tv_usec; s_diff += us_diff / 1000000; return s_diff; } struct range { char* data; size_t start_idx; size_t end_idx; uint8_t *target_hash; }; char done = 0; void *check_range(void *p){ struct range *r = p; char *savepoint; uint8_t current_hash[32]; char* word; word = strtok_r(r->data + r->start_idx, "\n", &savepoint); while(!done && word && word < (r->data + r->end_idx)) { calc_sha_256(current_hash, word, strlen(word)); if(compare_hashes(current_hash, r->target_hash)) { printf("The word was %s\n", word); done = 1; break; } word = strtok_r(0, "\n", &savepoint); } } int main(){ int fd = open("/usr/share/dict/american-english", O_RDONLY); struct stat stats; fstat(fd, &stats); printf("File size is %d bytes\n", stats.st_size); char *ro_data = mmap(0, stats.st_size, PROT_READ, MAP_SHARED, fd, 0); char *file_data = malloc(stats.st_size); memcpy(file_data, ro_data, stats.st_size); munmap(file_data, stats.st_size); close(fd); char *target_as_string = "4ea511963388132dd56b3b23fdfa1a25b952a8fe958afc7938622a33156bebf3"; uint8_t target_hash[32]; for(int i = 0; i < 32; i++){ char byte[5] = "0x"; byte[4] = 0; memcpy(byte + 2, target_as_string + 2*i, 2); /* * This part was broke at the end of class * I changed to using strtol, as Aiden suggested * It does exactly what I hoped atoi would do */ target_hash[i] = strtol(byte, 0, 0); } print_hash(target_hash); struct timeval start, end; gettimeofday(&start, NULL); int thread_count = 8; pthread_t threads[thread_count]; struct range parameters[thread_count]; for(int i = 0; i < thread_count; i++){ parameters[i].data = file_data; parameters[i].target_hash = target_hash; parameters[i].start_idx = i * (stats.st_size / thread_count); parameters[i].end_idx = (i+1) * (stats.st_size / thread_count); pthread_create(&threads[i], 0, check_range, ¶meters[i]); } for(int i = 0; i < thread_count; i++){ pthread_join(threads[i], 0); } gettimeofday(&end, NULL); printf("Password Finding Time: %lf\n", timediff(&start, &end)); return 0; }