1 /* $NetBSD: mdXhl.c,v 1.10 2012/06/25 22:32:44 abs 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 * Modified April 29, 1997 by Jason R. Thorpe <thorpej@NetBSD.org> 16 */ 17 18 #if HAVE_NBTOOL_CONFIG_H 19 #include "nbtool_config.h" 20 #endif 21 22 #define CONCAT(x,y) __CONCAT(x,y) 23 #define MDNAME(x) CONCAT(MDALGORITHM,x) 24 25 #if !defined(_KERNEL) && defined(__weak_alias) && !defined(HAVE_NBTOOL_CONFIG_H) 26 #define WA(a,b) __weak_alias(a,b) 27 WA(MDNAME(End),CONCAT(_,MDNAME(End))) 28 WA(MDNAME(File),CONCAT(_,MDNAME(File))) 29 WA(MDNAME(Data),CONCAT(_,MDNAME(Data))) 30 #undef WA 31 #endif 32 33 #include "namespace.h" 34 35 #include <sys/types.h> 36 37 #include MDINCLUDE 38 #include <assert.h> 39 #include <fcntl.h> 40 #include <errno.h> 41 #include <stdio.h> 42 #include <stdlib.h> 43 #include <unistd.h> 44 45 46 47 char * 48 MDNAME(End)(MDNAME(_CTX) *ctx, char *buf) 49 { 50 int i; 51 unsigned char digest[16]; 52 static const char hex[]="0123456789abcdef"; 53 54 _DIAGASSERT(ctx != 0); 55 56 if (buf == NULL) 57 buf = malloc(33); 58 if (buf == NULL) 59 return (NULL); 60 61 MDNAME(Final)(digest, ctx); 62 63 for (i = 0; i < 16; i++) { 64 buf[i+i] = hex[(u_int32_t)digest[i] >> 4]; 65 buf[i+i+1] = hex[digest[i] & 0x0f]; 66 } 67 68 buf[i+i] = '\0'; 69 return (buf); 70 } 71 72 char * 73 MDNAME(File)(const char *filename, char *buf) 74 { 75 unsigned char buffer[BUFSIZ]; 76 MDNAME(_CTX) ctx; 77 int f, j; 78 ssize_t i; 79 80 _DIAGASSERT(filename != 0); 81 /* buf may be NULL */ 82 83 MDNAME(Init)(&ctx); 84 f = open(filename, O_RDONLY, 0666); 85 if (f < 0) 86 return NULL; 87 88 while ((i = read(f, buffer, sizeof(buffer))) > 0) 89 MDNAME(Update)(&ctx, buffer, (unsigned int)i); 90 91 j = errno; 92 close(f); 93 errno = j; 94 95 if (i < 0) 96 return NULL; 97 98 return (MDNAME(End)(&ctx, buf)); 99 } 100 101 char * 102 MDNAME(Data)(const unsigned char *data, unsigned int len, char *buf) 103 { 104 MDNAME(_CTX) ctx; 105 106 _DIAGASSERT(data != 0); 107 108 MDNAME(Init)(&ctx); 109 MDNAME(Update)(&ctx, data, len); 110 return (MDNAME(End)(&ctx, buf)); 111 } 112