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