Last active
August 10, 2018 20:02
-
-
Save oconnor663/b6ba1e1a01b493590c39e473b9606f43 to your computer and use it in GitHub Desktop.
libsodium 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 <sodium.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#define BUFSIZE 65536 | |
#define HASHSIZE 32 | |
int main() { | |
if (sodium_init() == -1) { | |
return 1; | |
} | |
crypto_generichash_state state; | |
crypto_generichash_init(&state, NULL, 0, HASHSIZE); | |
unsigned char buf[BUFSIZE]; | |
ssize_t n; | |
while ((n = read(STDIN_FILENO, buf, BUFSIZE))) { | |
crypto_generichash_update(&state, buf, n); | |
} | |
unsigned char hash[HASHSIZE]; | |
crypto_generichash_final(&state, hash, HASHSIZE); | |
char hex[2 * HASHSIZE + 1]; | |
sodium_bin2hex(hex, sizeof hex, hash, sizeof hash); | |
printf("%s\n", hex); | |
} |
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 <sodium.h> | |
#include <stdio.h> | |
#include <time.h> | |
#include <unistd.h> | |
#define BUFSIZE 65536 | |
#define HASHSIZE 32 | |
#define INPUT_LEN 1000000000 | |
void print_time(struct timespec tstart, struct timespec tend, char *name) { | |
double diff = ((double)tend.tv_sec + 1.0e-9 * tend.tv_nsec) - | |
((double)tstart.tv_sec + 1.0e-9 * tstart.tv_nsec); | |
printf("%.7fs %s\n", diff, name); | |
} | |
int main() { | |
struct timespec tstart, tend; | |
clock_gettime(CLOCK_MONOTONIC, &tstart); | |
if (sodium_init() == -1) { | |
return 1; | |
} | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
print_time(tstart, tend, "init"); | |
clock_gettime(CLOCK_MONOTONIC, &tstart); | |
unsigned char *input = calloc(INPUT_LEN, 1); | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
print_time(tstart, tend, "calloc"); | |
clock_gettime(CLOCK_MONOTONIC, &tstart); | |
for (int i = 0; i < INPUT_LEN; i++) { | |
if (input[i] != 0) { | |
printf("PANIC!\n"); | |
} | |
} | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
print_time(tstart, tend, "read"); | |
clock_gettime(CLOCK_MONOTONIC, &tstart); | |
unsigned char hash[HASHSIZE]; | |
crypto_generichash(hash, HASHSIZE, input, INPUT_LEN, NULL, 0); | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
print_time(tstart, tend, "hash"); | |
char hex[2 * HASHSIZE + 1]; | |
sodium_bin2hex(hex, sizeof hex, hash, sizeof hash); | |
printf("%s\n", hex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment