md5hl.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* mdXhl.c * ----------------------------------------------------------------------------
  2. * "THE BEER-WARE LICENSE" (Revision 42):
  3. * <[email protected]> wrote this file. As long as you retain this notice you
  4. * can do whatever you want with this stuff. If we meet some day, and you think
  5. * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
  6. * ----------------------------------------------------------------------------
  7. */
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <unistd.h>
  12. #include <errno.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #define LENGTH 16
  16. #include "./md5.h"
  17. char *
  18. MD5End(MD5_CTX *ctx, char *buf)
  19. {
  20. int i;
  21. unsigned char digest[LENGTH];
  22. static const char hex[]="0123456789abcdef";
  23. if (!buf)
  24. buf = malloc(2*LENGTH + 1);
  25. if (!buf)
  26. return 0;
  27. MD5Final(digest, ctx);
  28. for (i = 0; i < LENGTH; i++) {
  29. buf[i+i] = hex[digest[i] >> 4];
  30. buf[i+i+1] = hex[digest[i] & 0x0f];
  31. }
  32. buf[i+i] = '\0';
  33. return buf;
  34. }
  35. char *
  36. MD5File(const char *filename, char *buf)
  37. {
  38. return (MD5FileChunk(filename, buf, 0, 0));
  39. }
  40. char *
  41. MD5FileChunk(const char *filename, char *buf, off_t ofs, off_t len)
  42. {
  43. unsigned char buffer[BUFSIZ];
  44. MD5_CTX ctx;
  45. struct stat stbuf;
  46. int f, i, e;
  47. off_t n;
  48. MD5Init(&ctx);
  49. f = open(filename, O_RDONLY);
  50. if (f < 0)
  51. return 0;
  52. if (fstat(f, &stbuf) < 0)
  53. return 0;
  54. if (ofs > stbuf.st_size)
  55. ofs = stbuf.st_size;
  56. if ((len == 0) || (len > stbuf.st_size - ofs))
  57. len = stbuf.st_size - ofs;
  58. if (lseek(f, ofs, SEEK_SET) < 0)
  59. return 0;
  60. n = len;
  61. i = 0;
  62. while (n > 0) {
  63. if (n > sizeof(buffer))
  64. i = read(f, buffer, sizeof(buffer));
  65. else
  66. i = read(f, buffer, n);
  67. if (i < 0)
  68. break;
  69. MD5Update(&ctx, buffer, i);
  70. n -= i;
  71. }
  72. e = errno;
  73. close(f);
  74. errno = e;
  75. if (i < 0)
  76. return 0;
  77. return (MD5End(&ctx, buf));
  78. }
  79. char *
  80. MD5Data (const void *data, unsigned int len, char *buf)
  81. {
  82. MD5_CTX ctx;
  83. MD5Init(&ctx);
  84. MD5Update(&ctx,data,len);
  85. return (MD5End(&ctx, buf));
  86. }