Created
March 14, 2017 17:44
-
-
Save gut/9622d4535a9e3f9ea3b0ded2762d4b28 to your computer and use it in GitHub Desktop.
Nettle's sha256 usage example
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <sys/stat.h> | |
#include "rsa.h" | |
static uint8_t * hash_sha_256 (const struct nettle_hash *hash, const char *s, | |
const size_t len) { | |
void *ctx = malloc (hash->context_size); | |
uint8_t *digest = malloc (hash->digest_size); | |
hash->init (ctx); | |
hash->update (ctx, len, (const uint8_t *) s); | |
hash->digest (ctx, hash->digest_size, digest); | |
free (ctx); | |
return digest; | |
} | |
int main (int argc, char **argv) { | |
char* input = "abc"; | |
struct stat st; | |
st.st_size = strlen(input); | |
if (argc > 1) { | |
// get file as an argument | |
char *filename = argv[1]; | |
FILE *file = fopen(filename, "r"); | |
if (file == NULL) { | |
fprintf(stderr, "Error opening %s. %s\n", argv[1], | |
strerror(errno)); | |
return errno; | |
} | |
// Get file size | |
if (stat(argv[1], &st) != 0) { | |
fprintf(stderr, "Cannot determine size of %s: %s\n", argv[1], | |
strerror(errno)); | |
fclose(file); | |
return errno; | |
} | |
input = (char *) calloc(st.st_size, sizeof(unsigned char)); | |
if (input == NULL) { | |
fprintf(stderr, "%s\n.", strerror(errno)); | |
return errno; | |
} | |
if (fread(input, sizeof(char), st.st_size, file) != (size_t)st.st_size) { | |
fprintf(stderr, "Read error on file %s. %s\n", argv[1], | |
strerror(errno)); | |
fclose(file); | |
return errno; | |
} | |
fclose(file); | |
} | |
uint8_t* hash = hash_sha_256 (&nettle_sha256, input, st.st_size); | |
for (size_t i=0; i < nettle_sha256.digest_size; i++) | |
printf("%02x", hash[i]); | |
printf("\n"); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment