md5.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <md5.h>
  10. static int usage()
  11. {
  12. fprintf(stderr,"md5 file ...\n");
  13. return -1;
  14. }
  15. static int do_md5(const char *path)
  16. {
  17. unsigned int i;
  18. int fd;
  19. MD5_CTX md5_ctx;
  20. unsigned char md5[MD5_DIGEST_LENGTH];
  21. fd = open(path, O_RDONLY);
  22. if (fd < 0) {
  23. fprintf(stderr,"could not open %s, %s\n", path, strerror(errno));
  24. return -1;
  25. }
  26. /* Note that bionic's MD5_* functions return void. */
  27. MD5Init(&md5_ctx);
  28. while (1) {
  29. char buf[4096];
  30. ssize_t rlen;
  31. rlen = read(fd, buf, sizeof(buf));
  32. if (rlen == 0)
  33. break;
  34. else if (rlen < 0) {
  35. (void)close(fd);
  36. fprintf(stderr,"could not read %s, %s\n", path, strerror(errno));
  37. return -1;
  38. }
  39. MD5Update(&md5_ctx, (const void *)buf, rlen);
  40. }
  41. if (close(fd)) {
  42. fprintf(stderr,"could not close %s, %s\n", path, strerror(errno));
  43. return -1;
  44. }
  45. MD5Final(md5, &md5_ctx);
  46. for (i = 0; i < (int)sizeof(md5); i++)
  47. printf("%02x", md5[i]);
  48. printf(" %s\n", path);
  49. return 0;
  50. }
  51. int
  52. main(int argc, char *argv[])
  53. {
  54. int i, ret = 0;
  55. if (argc < 2)
  56. return usage();
  57. /* loop over the file args */
  58. for (i = 1; i < argc; i++) {
  59. if (do_md5(argv[i]))
  60. ret = 1;
  61. }
  62. return ret;
  63. }