home *** CD-ROM | disk | FTP | other *** search
/ minnie.tuhs.org / unixen.tar / unixen / misc / md5 / md5hl.c < prev   
Encoding:
C/C++ Source or Header  |  1998-04-13  |  1.5 KB  |  72 lines

  1. /* md5hl.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.  * $Id: md5hl.c,v 1.8.2.1 1998/02/18 02:24:05 jkh Exp $
  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 "md5.h"
  22.  
  23. char *
  24. MD5End(MD5_CTX *ctx, char *buf)
  25. {
  26.     int i;
  27.     unsigned char digest[16];
  28.     static const char hex[]="0123456789abcdef";
  29.  
  30.     if (!buf)
  31.         buf = malloc(33);
  32.     if (!buf)
  33.     return 0;
  34.     MD5Final(digest,ctx);
  35.     for (i=0;i<16;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. MD5File (const char *filename, char *buf)
  45. {
  46.     unsigned char buffer[BUFSIZ];
  47.     MD5_CTX ctx;
  48.     int f,i,j;
  49.  
  50.     MD5Init(&ctx);
  51.     f = open(filename,O_RDONLY);
  52.     if (f < 0) return 0;
  53.     while ((i = read(f,buffer,sizeof buffer)) > 0) {
  54.     MD5Update(&ctx,buffer,i);
  55.     }
  56.     j = errno;
  57.     close(f);
  58.     errno = j;
  59.     if (i < 0) return 0;
  60.     return MD5End(&ctx, buf);
  61. }
  62.  
  63. char *
  64. MD5Data (const unsigned char *data, unsigned int len, char *buf)
  65. {
  66.     MD5_CTX ctx;
  67.  
  68.     MD5Init(&ctx);
  69.     MD5Update(&ctx,data,len);
  70.     return MD5End(&ctx, buf);
  71. }
  72.