1 /* mdXhl.c * ----------------------------------------------------------------------------
2 * "THE BEER-WARE LICENSE" (Revision 42):
3 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
4 * can do whatever you want with this stuff. If we meet some day, and you think
5 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
6 * ----------------------------------------------------------------------------
7 */
8
9 #include <sys/cdefs.h>
10 __FBSDID("$FreeBSD: src/lib/libmd/mdXhl.c,v 1.19 2006/01/17 15:35:56 phk Exp $");
11
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16
17 #include <errno.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20
21 #include "md5.h"
22
23 char *
MD5End(MD5_CTX * ctx,char * buf)24 MD5End(MD5_CTX *ctx, char *buf)
25 {
26 int i;
27 unsigned char digest[MD5_DIGEST_LENGTH];
28 static const char hex[]="0123456789abcdef";
29
30 if (!buf)
31 buf = malloc(2*MD5_DIGEST_LENGTH + 1);
32 if (!buf)
33 return 0;
34 MD5Final(digest, ctx);
35 for (i = 0; i < MD5_DIGEST_LENGTH; i++) {
36 buf[i+i] = hex[digest[i] >> 4];
37 buf[i+i+1] = hex[digest[i] & 0x0f];
38 }
39 buf[i+i] = '\0';
40 return buf;
41 }
42
43 char *
MD5File(const char * filename,char * buf)44 MD5File(const char *filename, char *buf)
45 {
46 return (MD5FileChunk(filename, buf, 0, 0));
47 }
48
49 char *
MD5FileChunk(const char * filename,char * buf,off_t ofs,off_t len)50 MD5FileChunk(const char *filename, char *buf, off_t ofs, off_t len)
51 {
52 unsigned char buffer[BUFSIZ];
53 MD5_CTX ctx;
54 struct stat stbuf;
55 int f, i, e;
56 off_t n;
57
58 MD5Init(&ctx);
59 f = open(filename, O_RDONLY);
60 if (f < 0)
61 return 0;
62 if (fstat(f, &stbuf) < 0)
63 return 0;
64 if (ofs > stbuf.st_size)
65 ofs = stbuf.st_size;
66 if ((len == 0) || (len > stbuf.st_size - ofs))
67 len = stbuf.st_size - ofs;
68 if (lseek(f, ofs, SEEK_SET) < 0)
69 return 0;
70 n = len;
71 i = 0;
72 while (n > 0) {
73 if (n > sizeof(buffer))
74 i = read(f, buffer, sizeof(buffer));
75 else
76 i = read(f, buffer, n);
77 if (i < 0)
78 break;
79 MD5Update(&ctx, buffer, i);
80 n -= i;
81 }
82 e = errno;
83 close(f);
84 errno = e;
85 if (i < 0)
86 return 0;
87 return (MD5End(&ctx, buf));
88 }
89
90 char *
MD5Data(const void * data,unsigned int len,char * buf)91 MD5Data (const void *data, unsigned int len, char *buf)
92 {
93 MD5_CTX ctx;
94
95 MD5Init(&ctx);
96 MD5Update(&ctx,data,len);
97 return (MD5End(&ctx, buf));
98 }
99