#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include "sha2.h"
void usage(char *prog, char *msg) {
fprintf(stderr, "%s\nUsage:\t%s [options] [<file>]\nOptions:\n\t-256\tGenerate SHA-256 hash\n\t-384\tGenerate SHA-284 hash\n\t-512\tGenerate SHA-512 hash\n\t-ALL\tGenerate all three hashes\n\t-q\tQuiet mode - only output hexadecimal hashes, one per line\n\n", msg, prog);
exit(-1);
}
#define BUFLEN 16384
int main(int argc, char **argv) {
int kl, l, fd, ac;
int quiet = 0, hash = 0;
char *av, *file = (char*)0;
FILE *IN = (FILE*)0;
dtls_sha256_ctx ctx256;
dtls_sha384_ctx ctx384;
dtls_sha512_ctx ctx512;
unsigned char buf[BUFLEN];
dtls_sha256_init(&ctx256);
dtls_sha384_init(&ctx384);
dtls_sha512_init(&ctx512);
fd = fileno(stdin);
ac = 1;
while (ac < argc) {
if (*argv[ac] == '-') {
av = argv[ac] + 1;
if (!strcmp(av, "q")) {
quiet = 1;
} else if (!strcmp(av, "256")) {
hash |= 1;
} else if (!strcmp(av, "384")) {
hash |= 2;
} else if (!strcmp(av, "512")) {
hash |= 4;
} else if (!strcmp(av, "ALL")) {
hash = 7;
} else {
usage(argv[0], "Invalid option.");
}
ac++;
} else {
file = argv[ac++];
if (ac != argc) {
usage(argv[0], "Too many arguments.");
}
if ((IN = fopen(file, "r")) == NULL) {
perror(argv[0]);
exit(-1);
}
fd = fileno(IN);
}
}
if (hash == 0)
hash = 7;
kl = 0;
while ((l = read(fd,buf,BUFLEN)) > 0) {
kl += l;
dtls_sha256_update(&ctx256, (unsigned char*)buf, l);
dtls_sha384_update(&ctx384, (unsigned char*)buf, l);
dtls_sha512_update(&ctx512, (unsigned char*)buf, l);
}
if (file) {
fclose(IN);
}
if (hash & 1) {
dtls_sha256_end(&ctx256, buf);
if (!quiet)
printf("SHA-256 (%s) = ", file);
printf("%s\n", buf);
}
if (hash & 2) {
dtls_sha384_end(&ctx384, buf);
if (!quiet)
printf("SHA-384 (%s) = ", file);
printf("%s\n", buf);
}
if (hash & 4) {
dtls_sha512_end(&ctx512, buf);
if (!quiet)
printf("SHA-512 (%s) = ", file);
printf("%s\n", buf);
}
return 1;
}