mdXhl.c revision 1.4
1/*	$NetBSD: mdXhl.c,v 1.4 1999/09/16 11:45:10 lukem Exp $	*/
2
3/*
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 * ----------------------------------------------------------------------------
10 *
11 * from FreeBSD Id: mdXhl.c,v 1.8 1996/10/25 06:48:12 bde Exp
12 */
13
14/*
15 * Modifed April 29, 1997 by Jason R. Thorpe <thorpej@netbsd.org>
16 */
17
18#include <sys/types.h>
19
20#include <assert.h>
21#include <fcntl.h>
22#include <errno.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <unistd.h>
26
27#define	CONCAT(x,y)	__CONCAT(x,y)
28#define	MDNAME(x)	CONCAT(MDALGORITHM,x)
29
30char *
31MDNAME(End)(ctx, buf)
32	MDNAME(_CTX) *ctx;
33	char *buf;
34{
35	int i;
36	unsigned char digest[16];
37	static const char hex[]="0123456789abcdef";
38
39	_DIAGASSERT(ctx != 0);
40#ifdef _DIAGNOSTIC
41	if (ctx == 0)
42		return (NULL);
43#endif
44
45	if (buf == NULL)
46		buf = malloc(33);
47	if (buf == NULL)
48		return (NULL);
49
50	MDNAME(Final)(digest, ctx);
51
52	for (i = 0; i < 16; i++) {
53		buf[i+i] = hex[(u_int32_t)digest[i] >> 4];
54		buf[i+i+1] = hex[digest[i] & 0x0f];
55	}
56
57	buf[i+i] = '\0';
58	return (buf);
59}
60
61char *
62MDNAME(File)(filename, buf)
63	const char *filename;
64	char *buf;
65{
66	unsigned char buffer[BUFSIZ];
67	MDNAME(_CTX) ctx;
68	int f, i, j;
69
70	_DIAGASSERT(filename != 0);
71	/* buf may be NULL */
72#ifdef _DIAGNOSTIC
73	if (filename == 0 || *filename == '\0')
74		return (NULL);
75#endif
76
77	MDNAME(Init)(&ctx);
78	f = open(filename, O_RDONLY, 0666);
79	if (f < 0)
80		return NULL;
81
82	while ((i = read(f, buffer, sizeof(buffer))) > 0)
83		MDNAME(Update)(&ctx, buffer, (unsigned int)i);
84
85	j = errno;
86	close(f);
87	errno = j;
88
89	if (i < 0)
90		return NULL;
91
92	return (MDNAME(End)(&ctx, buf));
93}
94
95char *
96MDNAME(Data)(data, len, buf)
97	const unsigned char *data;
98	unsigned int len;
99	char *buf;
100{
101	MDNAME(_CTX) ctx;
102
103	_DIAGASSERT(data != 0);
104#ifdef _DIAGNOSTIC
105	if (data == 0)
106		return (NULL);
107#endif
108
109	MDNAME(Init)(&ctx);
110	MDNAME(Update)(&ctx, data, len);
111	return (MDNAME(End)(&ctx, buf));
112}
113