md5sum.c (975B)
1 #include <u.h> 2 #include <libc.h> 3 #include <bio.h> 4 #include <libsec.h> 5 6 static int 7 digestfmt(Fmt *fmt) 8 { 9 char buf[MD5dlen*2+1]; 10 uchar *p; 11 int i; 12 13 p = va_arg(fmt->args, uchar*); 14 for(i=0; i<MD5dlen; i++) 15 sprint(buf+2*i, "%.2ux", p[i]); 16 return fmtstrcpy(fmt, buf); 17 } 18 19 static void 20 sum(int fd, char *name) 21 { 22 int n; 23 uchar buf[8192], digest[MD5dlen]; 24 DigestState *s; 25 26 s = md5(nil, 0, nil, nil); 27 while((n = read(fd, buf, sizeof buf)) > 0) 28 md5(buf, n, nil, s); 29 md5(nil, 0, digest, s); 30 if(name == nil) 31 print("%M\n", digest); 32 else 33 print("%M\t%s\n", digest, name); 34 } 35 36 void 37 main(int argc, char *argv[]) 38 { 39 int i, fd; 40 41 ARGBEGIN{ 42 default: 43 fprint(2, "usage: md5sum [file...]\n"); 44 exits("usage"); 45 }ARGEND 46 47 fmtinstall('M', digestfmt); 48 49 if(argc == 0) 50 sum(0, nil); 51 else for(i = 0; i < argc; i++){ 52 fd = open(argv[i], OREAD); 53 if(fd < 0){ 54 fprint(2, "md5sum: can't open %s: %r\n", argv[i]); 55 continue; 56 } 57 sum(fd, argv[i]); 58 close(fd); 59 } 60 exits(nil); 61 }