1 /* $NetBSD: md5hl.c,v 1.3 2011/11/05 00:17:19 cheusov Exp $ */
2
3 /*
4 * Written by Jason R. Thorpe <thorpej@netbsd.org>, April 29, 1997.
5 * Public domain.
6 */
7
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11
12 #define MDALGORITHM iSCSI_MD5
13
14 /* #include "namespace.h" */
15 #include "iscsi-md5.h"
16
17 #ifndef _DIAGASSERT
18 #define _DIAGASSERT(cond) assert(cond)
19 #endif
20
21 /* $NetBSD: md5hl.c,v 1.3 2011/11/05 00:17:19 cheusov Exp $ */
22
23 /*
24 * ----------------------------------------------------------------------------
25 * "THE BEER-WARE LICENSE" (Revision 42):
26 * <phk@login.dkuug.dk> wrote this file. As long as you retain this notice you
27 * can do whatever you want with this stuff. If we meet some day, and you think
28 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
29 * ----------------------------------------------------------------------------
30 *
31 * from FreeBSD Id: mdXhl.c,v 1.8 1996/10/25 06:48:12 bde Exp
32 */
33
34 /*
35 * Modifed April 29, 1997 by Jason R. Thorpe <thorpej@netbsd.org>
36 */
37
38 #include <assert.h>
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #endif
42 #ifdef HAVE_ERRNO_H
43 #include <errno.h>
44 #endif
45 #include <stdio.h>
46 #include <stdlib.h>
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #define CONCAT(x,y) __CONCAT(x,y)
52 #define MDNAME(x) CONCAT(MDALGORITHM,x)
53
54 char *
MDNAME(End)55 MDNAME(End)(MDNAME(_CTX) *ctx, char *buf)
56 {
57 int i;
58 unsigned char digest[16];
59 static const char hex[]="0123456789abcdef";
60
61 _DIAGASSERT(ctx != 0);
62
63 if (buf == NULL)
64 buf = malloc(33);
65 if (buf == NULL)
66 return (NULL);
67
68 MDNAME(Final)(digest, ctx);
69
70 for (i = 0; i < 16; i++) {
71 buf[i+i] = hex[(uint32_t)digest[i] >> 4];
72 buf[i+i+1] = hex[digest[i] & 0x0f];
73 }
74
75 buf[i+i] = '\0';
76 return (buf);
77 }
78
79 char *
80 MDNAME(File)(filename, buf)
81 const char *filename;
82 char *buf;
83 {
84 unsigned char buffer[BUFSIZ];
85 MDNAME(_CTX) ctx;
86 int f, j;
87 ssize_t i;
88
89 _DIAGASSERT(filename != 0);
90 /* buf may be NULL */
91
92 MDNAME(Init)(&ctx);
93 f = open(filename, O_RDONLY, 0666);
94 if (f < 0)
95 return NULL;
96
97 while ((i = read(f, buffer, sizeof(buffer))) > 0)
98 MDNAME(Update)(&ctx, buffer, (size_t)i);
99
100 j = errno;
101 close(f);
102 errno = j;
103
104 #if 0
105 if (i < 0)
106 return NULL;
107 #endif
108
109 return (MDNAME(End)(&ctx, buf));
110 }
111
112 char *
MDNAME(Data)113 MDNAME(Data)(const uint8_t *data, size_t len, char *buf)
114 {
115 MDNAME(_CTX) ctx;
116
117 _DIAGASSERT(data != 0);
118
119 MDNAME(Init)(&ctx);
120 MDNAME(Update)(&ctx, data, len);
121 return (MDNAME(End)(&ctx, buf));
122 }
123