| Scott Anderson | d0455c9 | 2012-01-11 18:13:26 -0800 | [diff] [blame] | 1 | #include <errno.h> | 
|  | 2 | #include <fcntl.h> | 
|  | 3 | #include <stdio.h> | 
|  | 4 | #include <unistd.h> | 
|  | 5 | #include <sys/stat.h> | 
|  | 6 | #include <sys/types.h> | 
| Elliott Hughes | 7fc4712 | 2014-06-07 21:53:04 -0700 | [diff] [blame] | 7 | #include <openssl/md5.h> | 
| Scott Anderson | d0455c9 | 2012-01-11 18:13:26 -0800 | [diff] [blame] | 8 |  | 
|  | 9 | static int usage() | 
|  | 10 | { | 
|  | 11 | fprintf(stderr,"md5 file ...\n"); | 
|  | 12 | return -1; | 
|  | 13 | } | 
|  | 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 |  | 
|  | 22 | fd = open(path, O_RDONLY); | 
|  | 23 | if (fd < 0) { | 
|  | 24 | fprintf(stderr,"could not open %s, %s\n", path, strerror(errno)); | 
|  | 25 | return -1; | 
|  | 26 | } | 
|  | 27 |  | 
| Scott Anderson | d0455c9 | 2012-01-11 18:13:26 -0800 | [diff] [blame] | 28 | MD5_Init(&md5_ctx); | 
|  | 29 |  | 
|  | 30 | while (1) { | 
|  | 31 | char buf[4096]; | 
|  | 32 | ssize_t rlen; | 
|  | 33 | rlen = read(fd, buf, sizeof(buf)); | 
|  | 34 | if (rlen == 0) | 
|  | 35 | break; | 
|  | 36 | else if (rlen < 0) { | 
|  | 37 | (void)close(fd); | 
|  | 38 | fprintf(stderr,"could not read %s, %s\n", path, strerror(errno)); | 
|  | 39 | return -1; | 
|  | 40 | } | 
|  | 41 | MD5_Update(&md5_ctx, buf, rlen); | 
|  | 42 | } | 
|  | 43 | if (close(fd)) { | 
|  | 44 | fprintf(stderr,"could not close %s, %s\n", path, strerror(errno)); | 
|  | 45 | return -1; | 
|  | 46 | } | 
|  | 47 |  | 
|  | 48 | MD5_Final(md5, &md5_ctx); | 
|  | 49 |  | 
|  | 50 | for (i = 0; i < (int)sizeof(md5); i++) | 
|  | 51 | printf("%02x", md5[i]); | 
|  | 52 | printf("  %s\n", path); | 
|  | 53 |  | 
|  | 54 | return 0; | 
|  | 55 | } | 
|  | 56 |  | 
|  | 57 | int md5_main(int argc, char *argv[]) | 
|  | 58 | { | 
|  | 59 | int i, ret = 0; | 
|  | 60 |  | 
|  | 61 | if (argc < 2) | 
|  | 62 | return usage(); | 
|  | 63 |  | 
|  | 64 | /* loop over the file args */ | 
|  | 65 | for (i = 1; i < argc; i++) { | 
|  | 66 | if (do_md5(argv[i])) | 
|  | 67 | ret = 1; | 
|  | 68 | } | 
|  | 69 |  | 
|  | 70 | return ret; | 
|  | 71 | } |