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