mdXhl.c revision 1.12
1/*	$NetBSD: mdXhl.c,v 1.12 2014/09/24 07:53:07 he 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#ifndef O_CLOEXEC /* For tools, as in NetBSD 5.2 or earlier... */
46#define O_CLOEXEC 0
47#endif
48
49
50char *
51MDNAME(End)(MDNAME(_CTX) *ctx, char *buf)
52{
53	int i;
54	unsigned char digest[16];
55	static const char hex[]="0123456789abcdef";
56
57	_DIAGASSERT(ctx != 0);
58
59	if (buf == NULL)
60		buf = malloc(33);
61	if (buf == NULL)
62		return (NULL);
63
64	MDNAME(Final)(digest, ctx);
65
66	for (i = 0; i < 16; i++) {
67		buf[i+i] = hex[(u_int32_t)digest[i] >> 4];
68		buf[i+i+1] = hex[digest[i] & 0x0f];
69	}
70
71	buf[i+i] = '\0';
72	return (buf);
73}
74
75char *
76MDNAME(File)(const char *filename, char *buf)
77{
78	unsigned char buffer[BUFSIZ];
79	MDNAME(_CTX) ctx;
80	int f, j;
81	ssize_t i;
82
83	_DIAGASSERT(filename != 0);
84	/* buf may be NULL */
85
86	MDNAME(Init)(&ctx);
87	f = open(filename, O_RDONLY | O_CLOEXEC, 0666);
88	if (f < 0)
89		return NULL;
90
91	while ((i = read(f, buffer, sizeof(buffer))) > 0)
92		MDNAME(Update)(&ctx, buffer, (unsigned int)i);
93
94	j = errno;
95	close(f);
96	errno = j;
97
98	if (i < 0)
99		return NULL;
100
101	return (MDNAME(End)(&ctx, buf));
102}
103
104char *
105MDNAME(Data)(const unsigned char *data, unsigned int len, char *buf)
106{
107	MDNAME(_CTX) ctx;
108
109	_DIAGASSERT(data != 0);
110
111	MDNAME(Init)(&ctx);
112	MDNAME(Update)(&ctx, data, len);
113	return (MDNAME(End)(&ctx, buf));
114}
115