Skip to content

Instantly share code, notes, and snippets.

@rudchenkos
Last active April 20, 2018 06:37
Show Gist options
  • Save rudchenkos/852a97f6b7e81424f0a2800f5d1269cb to your computer and use it in GitHub Desktop.
Save rudchenkos/852a97f6b7e81424f0a2800f5d1269cb to your computer and use it in GitHub Desktop.
Fast SHA1 calculation on files
/* 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