Fixup fromcvs/togit conversion
[minix-pkgsrc.git] / pkgtools / digest / files / sha1hl.c
blob3e148c1e8ec1e5777733333b63e3a4e48cff299d
1 /* $NetBSD: sha1hl.c,v 1.7 2007/09/21 18:44:37 joerg Exp $ */
3 /* sha1hl.c
4 * ----------------------------------------------------------------------------
5 * "THE BEER-WARE LICENSE" (Revision 42):
6 * <phk@login.dkuug.dk> wrote this file. As long as you retain this notice you
7 * can do whatever you want with this stuff. If we meet some day, and you think
8 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
9 * ----------------------------------------------------------------------------
12 /* #include "namespace.h" */
14 #ifdef HAVE_CONFIG_H
15 #include <config.h>
16 #endif
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
21 #ifdef HAVE_SYS_FILE_H
22 #include <sys/file.h>
23 #endif
24 #include <sys/uio.h>
26 #include <assert.h>
27 #include <errno.h>
28 #include <sha1.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
35 #if defined(LIBC_SCCS) && !defined(lint)
36 __RCSID("$NetBSD: sha1hl.c,v 1.7 2007/09/21 18:44:37 joerg Exp $");
37 #endif /* LIBC_SCCS and not lint */
39 #ifndef _DIAGASSERT
40 #define _DIAGASSERT(cond) assert(cond)
41 #endif
43 /* ARGSUSED */
44 char *
45 SHA1End(SHA1_CTX *ctx, char *buf)
47 int i;
48 char *p = buf;
49 uint8_t digest[20];
50 static const char hex[]="0123456789abcdef";
52 _DIAGASSERT(ctx != NULL);
53 /* buf may be NULL */
55 if (p == NULL && (p = malloc(41)) == NULL)
56 return 0;
58 SHA1Final(digest,ctx);
59 for (i = 0; i < 20; i++) {
60 p[i + i] = hex[((uint32_t)digest[i]) >> 4];
61 p[i + i + 1] = hex[digest[i] & 0x0f];
63 p[i + i] = '\0';
64 return(p);
67 char *
68 SHA1File(char *filename, char *buf)
70 uint8_t buffer[BUFSIZ];
71 SHA1_CTX ctx;
72 int fd, oerrno;
73 ssize_t num;
75 _DIAGASSERT(filename != NULL);
76 /* XXX: buf may be NULL ? */
78 SHA1Init(&ctx);
80 if ((fd = open(filename,O_RDONLY)) < 0)
81 return(0);
83 while ((num = read(fd, buffer, sizeof(buffer))) > 0)
84 SHA1Update(&ctx, buffer, (size_t)num);
86 oerrno = errno;
87 close(fd);
88 errno = oerrno;
89 return(num < 0 ? 0 : SHA1End(&ctx, buf));
92 char *
93 SHA1Data(const uint8_t *data, size_t len, char *buf)
95 SHA1_CTX ctx;
97 _DIAGASSERT(data != NULL);
98 /* XXX: buf may be NULL ? */
100 SHA1Init(&ctx);
101 SHA1Update(&ctx, data, len);
102 return(SHA1End(&ctx, buf));