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/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <unistd.h>
13
14 #include <errno.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17
18 #define LENGTH 16
19
20 #include "./md5.h"
21
22 char *
MD5End(MD5_CTX * ctx,char * buf)23 MD5End(MD5_CTX *ctx, char *buf)
24 {
25 int i;
26 unsigned char digest[LENGTH];
27 static const char hex[]="0123456789abcdef";
28
29 if (!buf)
30 buf = malloc(2*LENGTH + 1);
31 if (!buf)
32 return 0;
33 MD5Final(digest, ctx);
34 for (i = 0; i < LENGTH; i++) {
35 buf[i+i] = hex[digest[i] >> 4];
36 buf[i+i+1] = hex[digest[i] & 0x0f];
37 }
38 buf[i+i] = '\0';
39 return buf;
40 }
41
42 char *
MD5File(const char * filename,char * buf)43 MD5File(const char *filename, char *buf)
44 {
45 return (MD5FileChunk(filename, buf, 0, 0));
46 }
47
48 char *
MD5FileChunk(const char * filename,char * buf,off_t ofs,off_t len)49 MD5FileChunk(const char *filename, char *buf, off_t ofs, off_t len)
50 {
51 unsigned char buffer[BUFSIZ];
52 MD5_CTX ctx;
53 struct stat stbuf;
54 int f, i, e;
55 off_t n;
56
57 MD5Init(&ctx);
58 f = open(filename, O_RDONLY);
59 if (f < 0)
60 return 0;
61 if (fstat(f, &stbuf) < 0)
62 return 0;
63 if (ofs > stbuf.st_size)
64 ofs = stbuf.st_size;
65 if ((len == 0) || (len > stbuf.st_size - ofs))
66 len = stbuf.st_size - ofs;
67 if (lseek(f, ofs, SEEK_SET) < 0)
68 return 0;
69 n = len;
70 i = 0;
71 while (n > 0) {
72 if (n > sizeof(buffer))
73 i = read(f, buffer, sizeof(buffer));
74 else
75 i = read(f, buffer, n);
76 if (i < 0)
77 break;
78 MD5Update(&ctx, buffer, i);
79 n -= i;
80 }
81 e = errno;
82 close(f);
83 errno = e;
84 if (i < 0)
85 return 0;
86 return (MD5End(&ctx, buf));
87 }
88
89 char *
MD5Data(const void * data,unsigned int len,char * buf)90 MD5Data (const void *data, unsigned int len, char *buf)
91 {
92 MD5_CTX ctx;
93
94 MD5Init(&ctx);
95 MD5Update(&ctx,data,len);
96 return (MD5End(&ctx, buf));
97 }
98