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