Add crypt.[ch] and update md5sum and sha1sum

Factor out the code from md5sum and sha1sum into a util function.

Use FILE * instead of a file descriptor.  This will make it a bit
easier/more consistent when we implement support for the -c option.
This commit is contained in:
sin
2013-07-07 15:29:45 +01:00
committed by David Galos
parent 48e6870bb7
commit 9ac01f59be
9 changed files with 98 additions and 83 deletions

View File

@@ -1,15 +1,18 @@
/* See LICENSE file for copyright and license details. */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "util.h"
#include "crypt.h"
#include "sha1.h"
static void sha1sum(int fd, const char *f);
struct sha1 s;
struct crypt_ops sha1_ops = {
sha1_init,
sha1_update,
sha1_sum,
&s,
};
static void
usage(void)
@@ -20,7 +23,8 @@ usage(void)
int
main(int argc, char *argv[])
{
int fd;
FILE *fp;
uint8_t md[SHA1_DIGEST_LENGTH];
ARGBEGIN {
default:
@@ -28,40 +32,18 @@ main(int argc, char *argv[])
} ARGEND;
if (argc == 0) {
sha1sum(STDIN_FILENO, "<stdin>");
cryptsum(&sha1_ops, stdin, "<stdin>", md);
mdprint(md, "<stdin>", sizeof(md));
} else {
for (; argc > 0; argc--) {
if ((fd = open(*argv, O_RDONLY)) < 0)
eprintf("open %s:", *argv);
sha1sum(fd, *argv);
close(fd);
if ((fp = fopen(*argv, "r")) == NULL)
eprintf("fopen %s:", *argv);
cryptsum(&sha1_ops, fp, *argv, md);
mdprint(md, *argv, sizeof(md));
fclose(fp);
argv++;
}
}
return 0;
}
static void
sha1sum(int fd, const char *f)
{
unsigned char buf[BUFSIZ];
unsigned char digest[SHA1_DIGEST_LENGTH];
struct sha1 s;
ssize_t n;
int i;
sha1_init(&s);
while ((n = read(fd, buf, sizeof buf)) > 0)
sha1_update(&s, buf, n);
if (n < 0) {
eprintf("%s: read error:", f);
return;
}
sha1_sum(&s, digest);
for (i = 0; i < sizeof(digest); i++)
printf("%02x", digest[i]);
printf(" %s\n", f);
}