xref: /freebsd/lib/libmd/mdXhl.c (revision 7f3dea244c40159a41ab22da77a434d7c5b5e85a)
1 /* mdXhl.c
2  * ----------------------------------------------------------------------------
3  * "THE BEER-WARE LICENSE" (Revision 42):
4  * <phk@login.dkuug.dk> wrote this file.  As long as you retain this notice you
5  * can do whatever you want with this stuff. If we meet some day, and you think
6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7  * ----------------------------------------------------------------------------
8  *
9  * $FreeBSD$
10  *
11  */
12 
13 #include <sys/types.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 "mdX.h"
22 
23 char *
24 MDXEnd(MDX_CTX *ctx, char *buf)
25 {
26     int i;
27     unsigned char digest[LENGTH];
28     static const char hex[]="0123456789abcdef";
29 
30     if (!buf)
31         buf = malloc(2*LENGTH + 1);
32     if (!buf)
33 	return 0;
34     MDXFinal(digest, ctx);
35     for (i = 0; i < 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 *
44 MDXFile(const char *filename, char *buf)
45 {
46     unsigned char buffer[BUFSIZ];
47     MDX_CTX ctx;
48     int f,i,j;
49 
50     MDXInit(&ctx);
51     f = open(filename,O_RDONLY);
52     if (f < 0) return 0;
53     while ((i = read(f,buffer,sizeof buffer)) > 0) {
54 	MDXUpdate(&ctx,buffer,i);
55     }
56     j = errno;
57     close(f);
58     errno = j;
59     if (i < 0) return 0;
60     return MDXEnd(&ctx, buf);
61 }
62 
63 char *
64 MDXData (const unsigned char *data, unsigned int len, char *buf)
65 {
66     MDX_CTX ctx;
67 
68     MDXInit(&ctx);
69     MDXUpdate(&ctx,data,len);
70     return MDXEnd(&ctx, buf);
71 }
72