md5sum.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. #include <libsec.h>
  13. static int
  14. digestfmt(Fmt *fmt)
  15. {
  16. char buf[MD5dlen*2+1];
  17. uint8_t *p;
  18. int i;
  19. p = va_arg(fmt->args, uint8_t*);
  20. for(i=0; i<MD5dlen; i++)
  21. sprint(buf+2*i, "%.2x", p[i]);
  22. return fmtstrcpy(fmt, buf);
  23. }
  24. static void
  25. sum(int fd, char *name)
  26. {
  27. int n;
  28. uint8_t buf[8192], digest[MD5dlen];
  29. DigestState *s;
  30. s = md5(nil, 0, nil, nil);
  31. while((n = read(fd, buf, sizeof buf)) > 0)
  32. md5(buf, n, nil, s);
  33. if(n < 0){
  34. fprint(2, "reading %s: %r\n", name ? name : "stdin");
  35. return;
  36. }
  37. md5(nil, 0, digest, s);
  38. if(name == nil)
  39. print("%M\n", digest);
  40. else
  41. print("%M\t%s\n", digest, name);
  42. }
  43. void
  44. main(int argc, char *argv[])
  45. {
  46. int i, fd;
  47. ARGBEGIN{
  48. default:
  49. fprint(2, "usage: md5sum [file...]\n");
  50. exits("usage");
  51. }ARGEND
  52. fmtinstall('M', digestfmt);
  53. if(argc == 0)
  54. sum(0, nil);
  55. else for(i = 0; i < argc; i++){
  56. fd = open(argv[i], OREAD);
  57. if(fd < 0){
  58. fprint(2, "md5sum: can't open %s: %r\n", argv[i]);
  59. continue;
  60. }
  61. sum(fd, argv[i]);
  62. close(fd);
  63. }
  64. exits(nil);
  65. }