mdXhl.c revision 1.3
1/*	$NetBSD: mdXhl.c,v 1.3 1998/11/13 15:48:30 christos 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#include <fcntl.h>
20#include <unistd.h>
21
22#include <errno.h>
23#include <stdio.h>
24#include <stdlib.h>
25
26#define	CONCAT(x,y)	__CONCAT(x,y)
27#define	MDNAME(x)	CONCAT(MDALGORITHM,x)
28
29char *
30MDNAME(End)(ctx, buf)
31	MDNAME(_CTX) *ctx;
32	char *buf;
33{
34	int i;
35	unsigned char digest[16];
36	static const char hex[]="0123456789abcdef";
37
38	if (buf == NULL)
39		buf = malloc(33);
40	if (buf == NULL)
41		return (NULL);
42
43	MDNAME(Final)(digest, ctx);
44
45	for (i = 0; i < 16; i++) {
46		buf[i+i] = hex[(u_int32_t)digest[i] >> 4];
47		buf[i+i+1] = hex[digest[i] & 0x0f];
48	}
49
50	buf[i+i] = '\0';
51	return (buf);
52}
53
54char *
55MDNAME(File)(filename, buf)
56	const char *filename;
57	char *buf;
58{
59	unsigned char buffer[BUFSIZ];
60	MDNAME(_CTX) ctx;
61	int f, i, j;
62
63	MDNAME(Init)(&ctx);
64	f = open(filename, O_RDONLY, 0666);
65	if (f < 0)
66		return NULL;
67
68	while ((i = read(f, buffer, sizeof(buffer))) > 0)
69		MDNAME(Update)(&ctx, buffer, (unsigned int)i);
70
71	j = errno;
72	close(f);
73	errno = j;
74
75	if (i < 0)
76		return NULL;
77
78	return (MDNAME(End)(&ctx, buf));
79}
80
81char *
82MDNAME(Data)(data, len, buf)
83	const unsigned char *data;
84	unsigned int len;
85	char *buf;
86{
87	MDNAME(_CTX) ctx;
88
89	MDNAME(Init)(&ctx);
90	MDNAME(Update)(&ctx, data, len);
91	return (MDNAME(End)(&ctx, buf));
92}
93