Skip to content

Instantly share code, notes, and snippets.

@sm00th
Created September 25, 2013 14:51
Show Gist options
  • Save sm00th/6700763 to your computer and use it in GitHub Desktop.
Save sm00th/6700763 to your computer and use it in GitHub Desktop.
w3 sha256 stuff
#include <stdio.h>
#include <stdint.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <openssl/evp.h>
#define DIGEST_SIZE 32
#define BLOCK_SIZE 1024
int main(int argc, char **argv)
{
struct stat filestat;
int32_t blocks, lblock;
uint64_t fsize;
int fd;
unsigned char ldigest[DIGEST_SIZE];
unsigned char msg[BLOCK_SIZE + DIGEST_SIZE];
unsigned int md_len, i, j;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
return 1;
}
if (stat(argv[1], &filestat) != 0) {
fprintf(stderr, "Failed to stat file '%s'\n", argv[1]);
return 1;
}
fsize = filestat.st_size;
blocks = fsize / BLOCK_SIZE;
lblock = fsize - (blocks++ * BLOCK_SIZE);
printf("File '%s' has size %d\n", argv[1], fsize);
printf("%d blocks to hash, last block is %d bytes\n", blocks, lblock);
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
fprintf(stderr, "Failed to open file '%s'\n", argv[1]);
}
i = 0;
for (i = 0; i < blocks; i++) {
uint32_t offset = fsize - lblock - (i * BLOCK_SIZE);
uint32_t bsize = i == 0 ? lblock : BLOCK_SIZE;
printf("[%d] Digesting block %d (%d/%d)... ", i, blocks, offset, bsize);
if (lseek(fd, offset, SEEK_SET) == -1) {
printf("Failed to seek file\n");
return 1;
};
read(fd, msg, bsize);
if (i != 0) {
memcpy(msg + bsize, ldigest, DIGEST_SIZE);
bsize += DIGEST_SIZE;
}
EVP_Digest(msg, bsize, ldigest, &md_len, EVP_sha256(), NULL);
for(j = 0; j < md_len; j++)
printf("%02x", ldigest[j]);
printf("\n");
}
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment