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