Last active
April 20, 2018 06:37
-
-
Save rudchenkos/852a97f6b7e81424f0a2800f5d1269cb to your computer and use it in GitHub Desktop.
Fast SHA1 calculation on files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* cc -Wpedantic sha1sum.c -osha1sum $(shell pkg-config --cflags --libs libcrypto) */ | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <sys/mman.h> | |
#include <openssl/sha.h> | |
#include <stdio.h> | |
int main(int args, char* argv[]) { | |
int fd = open(argv[1], O_RDONLY); | |
if (fd == -1) { | |
perror(argv[1]); | |
return 1; | |
} | |
struct stat st; | |
fstat(fd, &st); | |
printf("File size: %lld\n", st.st_size); | |
SHA_CTX ctx; | |
SHA1_Init(&ctx); | |
unsigned char *data = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); | |
if (!data) { | |
perror("mmap"); | |
return 1; | |
} | |
SHA1_Update(&ctx, data, st.st_size); | |
close(fd); | |
unsigned char md[SHA_DIGEST_LENGTH]; | |
SHA1_Final(md, &ctx); | |
for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { | |
printf("%.02x", md[i]); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment