xref: /dragonfly/sbin/md5/md5.c (revision 0dace59e)
1 /*
2  * Derived from:
3  *
4  * MDDRIVER.C - test driver for MD2, MD4 and MD5
5  *
6  * $FreeBSD: src/sbin/md5/md5.c,v 1.35 2006/01/17 15:35:57 phk Exp $
7  */
8 
9 /*
10  *  Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990. All
11  *  rights reserved.
12  *
13  *  RSA Data Security, Inc. makes no representations concerning either
14  *  the merchantability of this software or the suitability of this
15  *  software for any particular purpose. It is provided "as is"
16  *  without express or implied warranty of any kind.
17  *
18  *  These notices must be retained in any copies of any part of this
19  *  documentation and/or software.
20  */
21 
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <err.h>
28 #include <sys/mman.h>
29 #include <md5.h>
30 #include <ripemd.h>
31 #include <sha.h>
32 #include <sha256.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <sysexits.h>
39 
40 /*
41  * Length of test block, number of test blocks.
42  */
43 #define TEST_BLOCK_LEN 10000
44 #define TEST_BLOCK_COUNT 100000
45 #define MDTESTCOUNT 8
46 
47 int qflag;
48 int rflag;
49 int sflag;
50 
51 typedef void (DIGEST_Init)(void *);
52 typedef void (DIGEST_Update)(void *, const unsigned char *, size_t);
53 typedef char *(DIGEST_End)(void *, char *);
54 
55 extern const char *MD5TestOutput[MDTESTCOUNT];
56 extern const char *SHA1_TestOutput[MDTESTCOUNT];
57 extern const char *SHA256_TestOutput[MDTESTCOUNT];
58 extern const char *RIPEMD160_TestOutput[MDTESTCOUNT];
59 
60 typedef struct Algorithm_t {
61 	const char *progname;
62 	const char *name;
63 	const char *(*TestOutput)[MDTESTCOUNT];
64 	DIGEST_Init *Init;
65 	DIGEST_Update *Update;
66 	DIGEST_End *End;
67 	char *(*Data)(const void *, unsigned int, char *);
68 	char *(*File)(const char *, char *);
69 } Algorithm_t;
70 
71 static void MD5_Update(MD5_CTX *, const unsigned char *, size_t);
72 static void MDString(Algorithm_t *, const char *);
73 static void MDTimeTrial(Algorithm_t *);
74 static void MDTestSuite(Algorithm_t *);
75 static void MDFilter(Algorithm_t *, int);
76 static void usage(int excode);
77 
78 typedef union {
79 	MD5_CTX md5;
80 	SHA1_CTX sha1;
81 	SHA256_CTX sha256;
82 	RIPEMD160_CTX ripemd160;
83 } DIGEST_CTX;
84 
85 /* max(MD5_DIGEST_LENGTH, SHA_DIGEST_LENGTH,
86 	SHA256_DIGEST_LENGTH, RIPEMD160_DIGEST_LENGTH)*2+1 */
87 #define HEX_DIGEST_LENGTH 65
88 
89 /* algorithm function table */
90 
91 struct Algorithm_t Algorithm[] = {
92 	{ "md5", "MD5", &MD5TestOutput, (DIGEST_Init*)&MD5Init,
93 		(DIGEST_Update*)&MD5_Update, (DIGEST_End*)&MD5End,
94 		&MD5Data, &MD5File },
95 	{ "sha1", "SHA1", &SHA1_TestOutput, (DIGEST_Init*)&SHA1_Init,
96 		(DIGEST_Update*)&SHA1_Update, (DIGEST_End*)&SHA1_End,
97 		&SHA1_Data, &SHA1_File },
98 	{ "sha256", "SHA256", &SHA256_TestOutput, (DIGEST_Init*)&SHA256_Init,
99 		(DIGEST_Update*)&SHA256_Update, (DIGEST_End*)&SHA256_End,
100 		&SHA256_Data, &SHA256_File },
101 	{ "rmd160", "RMD160", &RIPEMD160_TestOutput,
102 		(DIGEST_Init*)&RIPEMD160_Init, (DIGEST_Update*)&RIPEMD160_Update,
103 		(DIGEST_End*)&RIPEMD160_End, &RIPEMD160_Data, &RIPEMD160_File }
104 };
105 
106 static void
107 MD5_Update(MD5_CTX *c, const unsigned char *data, size_t len)
108 {
109 	MD5Update(c, data, len);
110 }
111 
112 /*
113  * There is no need to use a huge mmap, just pick something
114  * reasonable.
115  */
116 #define MAXMMAP	(32*1024*1024)
117 
118 static char *
119 digestfile(const char *fname, char *buf, const Algorithm_t *alg,
120     off_t *beginp, off_t *endp)
121 {
122 	int		 fd;
123 	struct stat	 st;
124 	size_t		 size;
125 	char		*result = NULL;
126 	void		*map;
127 	DIGEST_CTX	 context;
128 	off_t		 end = *endp, begin = *beginp;
129 	size_t		 pagesize;
130 
131 	fd = open(fname, O_RDONLY);
132 	if (fd == -1) {
133 		warn("can't open %s", fname);
134 		return NULL;
135 	}
136 
137 	if (fstat(fd, &st) == -1) {
138 		warn("can't fstat %s after opening", fname);
139 		goto cleanup;
140 	}
141 
142 	/* Non-positive end means, it has to be counted from the back:	*/
143 	if (end <= 0)
144 		end += st.st_size;
145 	/* Negative begin means, it has to be counted from the back:	*/
146 	if (begin < 0)
147 		begin += st.st_size;
148 
149 	if (begin < 0 || end < 0 || begin > st.st_size || end > st.st_size) {
150 		warnx("%s is %jd bytes long, not large enough for the "
151 		    "specified offsets [%jd-%jd]", fname,
152 		    (intmax_t)st.st_size,
153 		    (intmax_t)*beginp, (intmax_t)*endp);
154 		goto cleanup;
155 	}
156 	if (begin > end) {
157 		warnx("%s is %jd bytes long. Begin-offset %jd (%jd) is "
158 		    "larger than end-offset %jd (%jd)",
159 		    fname, (intmax_t)st.st_size,
160 		    (intmax_t)begin, (intmax_t)*beginp,
161 		    (intmax_t)end, (intmax_t)*endp);
162 		goto cleanup;
163 	}
164 
165 	if (*endp <= 0)
166 		*endp = end;
167 	if (*beginp < 0)
168 		*beginp = begin;
169 
170 	pagesize = getpagesize();
171 
172 	alg->Init(&context);
173 
174 	do {
175 		if (end - begin > MAXMMAP)
176 			size = MAXMMAP;
177 		else
178 			size = end - begin;
179 
180 		map = mmap(NULL, size, PROT_READ, MAP_NOCORE, fd, begin);
181 		if (map == MAP_FAILED) {
182 			warn("mmaping of %s between %jd and %jd ",
183 			    fname, (intmax_t)begin, (intmax_t)begin + size);
184 			goto cleanup;
185 		}
186 		/*
187 		 * Try to give kernel a hint. Not that it
188 		 * cares at the time of this writing :-(
189 		 */
190 		if (size > pagesize)
191 			madvise(map, size, MADV_SEQUENTIAL);
192 		alg->Update(&context, map, size);
193 		munmap(map, size);
194 		begin += size;
195 	} while (begin < end);
196 
197 	result = alg->End(&context, buf);
198 
199 cleanup:
200 	close(fd);
201 	return result;
202 }
203 
204 static off_t
205 parseint(const char *arg)
206 {
207 	double	 result; /* Use double to allow things like 0.5Kb */
208 	char	*endp;
209 
210 	result = strtod(arg, &endp);
211 	switch (endp[0]) {
212 	case 'T':
213 	case 't':
214 		result *= 1024;	/* FALLTHROUGH */
215 	case 'M':
216 	case 'm':
217 		result *= 1024;	/* FALLTHROUGH */
218 	case 'K':
219 	case 'k':
220 		endp++;
221 		if (endp[1] == 'b' || endp[1] == 'B')
222 			endp++;
223 		result *= 1024;	/* FALLTHROUGH */
224 	case '\0':
225 		break;
226 	default:
227 		warnx("%c (%d): unrecognized suffix", endp[0], (int)endp[0]);
228 		goto badnumber;
229 	}
230 
231 	if (endp[0] == '\0')
232 		return result;
233 
234 badnumber:
235 	errx(EX_USAGE, "`%s' is not a valid offset.", arg);
236 }
237 
238 /* Main driver.
239 
240 Arguments (may be any combination):
241   -sstring - digests string
242   -t       - runs time trial
243   -x       - runs test script
244   filename - digests file
245   (none)   - digests standard input
246  */
247 int
248 main(int argc, char *argv[])
249 {
250 	int     ch;
251 	char   *p;
252 	char	buf[HEX_DIGEST_LENGTH];
253 	int     failed, useoffsets = 0;
254 	off_t   begin = 0, end = 0; /* To shut compiler warning */
255  	unsigned	digest;
256  	const char*	progname;
257 
258  	if ((progname = strrchr(argv[0], '/')) == NULL)
259  		progname = argv[0];
260  	else
261  		progname++;
262 
263  	for (digest = 0; digest < sizeof(Algorithm)/sizeof(*Algorithm); digest++)
264  		if (strcasecmp(Algorithm[digest].progname, progname) == 0)
265  			break;
266 
267  	if (digest == sizeof(Algorithm)/sizeof(*Algorithm))
268  		digest = 0;
269 
270 	failed = 0;
271 	while ((ch = getopt(argc, argv, "hb:e:pqrs:tx")) != -1) {
272 		switch (ch) {
273 		case 'b':
274 			begin = parseint(optarg);
275 			useoffsets = 1;
276 			break;
277 		case 'e':
278 			end = parseint(optarg);
279 			useoffsets = 1;
280 			break;
281 		case 'p':
282 			MDFilter(&Algorithm[digest], 1);
283 			break;
284 		case 'q':
285 			qflag = 1;
286 			break;
287 		case 'r':
288 			rflag = 1;
289 			break;
290 		case 's':
291 			sflag = 1;
292 			MDString(&Algorithm[digest], optarg);
293 			break;
294 		case 't':
295 			MDTimeTrial(&Algorithm[digest]);
296 			break;
297 		case 'x':
298 			MDTestSuite(&Algorithm[digest]);
299 			break;
300 		case 'h':
301 			usage(EX_OK);
302 		default:
303 			usage(EX_USAGE);
304 		}
305 	}
306 	argc -= optind;
307 	argv += optind;
308 
309 	if (*argv) {
310 		do {
311 			if (useoffsets)
312 				p = digestfile(*argv, buf, Algorithm + digest,
313 				    &begin, &end);
314 			else
315 				p = Algorithm[digest].File(*argv, buf);
316 			if (!p) {
317 				/* digestfile() outputs its own diagnostics */
318 				if (!useoffsets)
319 					warn("%s", *argv);
320 				failed++;
321 			} else {
322 				if (qflag) {
323 					printf("%s\n", p);
324 				} else if (rflag) {
325 					if (useoffsets)
326 						printf("%s %s[%jd-%jd]\n",
327 						       p, *argv,
328 						       (intmax_t)begin,
329 						       (intmax_t)end);
330 					else
331 						printf("%s %s\n",
332 							p, *argv);
333 				} else if (useoffsets) {
334 					printf("%s (%s[%jd-%jd]) = %s\n",
335 					       Algorithm[digest].name, *argv,
336 					       (intmax_t)begin,
337 					       (intmax_t)end,
338 					       p);
339 				} else {
340 					printf("%s (%s) = %s\n",
341 					       Algorithm[digest].name,
342 					       *argv, p);
343 				}
344 			}
345 		} while (*++argv);
346 	} else if (!sflag && (optind == 1 || qflag || rflag))
347 		MDFilter(&Algorithm[digest], 0);
348 
349 	if (failed != 0)
350 		return (EX_NOINPUT);
351 
352 	return (0);
353 }
354 /*
355  * Digests a string and prints the result.
356  */
357 static void
358 MDString(Algorithm_t *alg, const char *string)
359 {
360 	size_t len = strlen(string);
361 	char buf[HEX_DIGEST_LENGTH];
362 
363 	if (qflag)
364 		printf("%s\n", alg->Data(string, len, buf));
365 	else if (rflag)
366 		printf("%s \"%s\"\n", alg->Data(string, len, buf), string);
367 	else
368 		printf("%s (\"%s\") = %s\n", alg->name, string, alg->Data(string, len, buf));
369 }
370 /*
371  * Measures the time to digest TEST_BLOCK_COUNT TEST_BLOCK_LEN-byte blocks.
372  */
373 static void
374 MDTimeTrial(Algorithm_t *alg)
375 {
376 	DIGEST_CTX context;
377 	struct rusage before, after;
378 	struct timeval total;
379 	float seconds;
380 	unsigned char block[TEST_BLOCK_LEN];
381 	unsigned int i;
382 	char   *p, buf[HEX_DIGEST_LENGTH];
383 
384 	printf
385 	    ("%s time trial. Digesting %d %d-byte blocks ...",
386 	    alg->name, TEST_BLOCK_COUNT, TEST_BLOCK_LEN);
387 	fflush(stdout);
388 
389 	/* Initialize block */
390 	for (i = 0; i < TEST_BLOCK_LEN; i++)
391 		block[i] = (unsigned char) (i & 0xff);
392 
393 	/* Start timer */
394 	getrusage(0, &before);
395 
396 	/* Digest blocks */
397 	alg->Init(&context);
398 	for (i = 0; i < TEST_BLOCK_COUNT; i++)
399 		alg->Update(&context, block, TEST_BLOCK_LEN);
400 	p = alg->End(&context, buf);
401 
402 	/* Stop timer */
403 	getrusage(0, &after);
404 	timersub(&after.ru_utime, &before.ru_utime, &total);
405 	seconds = total.tv_sec + (float) total.tv_usec / 1000000;
406 
407 	printf(" done\n");
408 	printf("Digest = %s", p);
409 	printf("\nTime = %f seconds\n", seconds);
410 	printf
411 	    ("Speed = %f bytes/second\n",
412 	    (float) TEST_BLOCK_LEN * (float) TEST_BLOCK_COUNT / seconds);
413 }
414 /*
415  * Digests a reference suite of strings and prints the results.
416  */
417 
418 const char *MDTestInput[MDTESTCOUNT] = {
419 	"",
420 	"a",
421 	"abc",
422 	"message digest",
423 	"abcdefghijklmnopqrstuvwxyz",
424 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
425 	"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
426 	"MD5 has not yet (2001-09-03) been broken, but sufficient attacks have been made \
427 that its security is in some doubt"
428 };
429 
430 const char *MD5TestOutput[MDTESTCOUNT] = {
431 	"d41d8cd98f00b204e9800998ecf8427e",
432 	"0cc175b9c0f1b6a831c399e269772661",
433 	"900150983cd24fb0d6963f7d28e17f72",
434 	"f96b697d7cb7938d525a2f31aaf161d0",
435 	"c3fcd3d76192e4007dfb496cca67e13b",
436 	"d174ab98d277d9f5a5611c2c9f419d9f",
437 	"57edf4a22be3c955ac49da2e2107b67a",
438 	"b50663f41d44d92171cb9976bc118538"
439 };
440 
441 const char *SHA1_TestOutput[MDTESTCOUNT] = {
442 	"da39a3ee5e6b4b0d3255bfef95601890afd80709",
443 	"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8",
444 	"a9993e364706816aba3e25717850c26c9cd0d89d",
445 	"c12252ceda8be8994d5fa0290a47231c1d16aae3",
446 	"32d10c7b8cf96570ca04ce37f2a19d84240d3a89",
447 	"761c457bf73b14d27e9e9265c46f4b4dda11f940",
448 	"50abf5706a150990a08b2c5ea40fa0e585554732",
449 	"18eca4333979c4181199b7b4fab8786d16cf2846"
450 };
451 
452 const char *SHA256_TestOutput[MDTESTCOUNT] = {
453 	"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
454 	"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb",
455 	"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
456 	"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650",
457 	"71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73",
458 	"db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0",
459 	"f371bc4a311f2b009eef952dd83ca80e2b60026c8e935592d0f9c308453c813e",
460 	"e6eae09f10ad4122a0e2a4075761d185a272ebd9f5aa489e998ff2f09cbfdd9f"
461 };
462 
463 const char *RIPEMD160_TestOutput[MDTESTCOUNT] = {
464 	"9c1185a5c5e9fc54612808977ee8f548b2258d31",
465 	"0bdc9d2d256b3ee9daae347be6f4dc835a467ffe",
466 	"8eb208f7e05d987a9b044a8e98c6b087f15a0bfc",
467 	"5d0689ef49d2fae572b881b123a85ffa21595f36",
468 	"f71c27109c692c1b56bbdceb5b9d2865b3708dbc",
469 	"b0e20b6e3116640286ed3a87a5713079b21f5189",
470 	"9b752e45573d4b39f4dbd3323cab82bf63326bfb",
471 	"5feb69c6bf7c29d95715ad55f57d8ac5b2b7dd32"
472 };
473 
474 static void
475 MDTestSuite(Algorithm_t *alg)
476 {
477 	int i;
478 	char buffer[HEX_DIGEST_LENGTH];
479 
480 	printf("%s test suite:\n", alg->name);
481 	for (i = 0; i < MDTESTCOUNT; i++) {
482 		(*alg->Data)(MDTestInput[i], strlen(MDTestInput[i]), buffer);
483 		printf("%s (\"%s\") = %s", alg->name, MDTestInput[i], buffer);
484 		if (strcmp(buffer, (*alg->TestOutput)[i]) == 0)
485 			printf(" - verified correct\n");
486 		else
487 			printf(" - INCORRECT RESULT!\n");
488 	}
489 }
490 
491 /*
492  * Digests the standard input and prints the result.
493  */
494 static void
495 MDFilter(Algorithm_t *alg, int tee)
496 {
497 	DIGEST_CTX context;
498 	unsigned int len;
499 	unsigned char buffer[BUFSIZ];
500 	char buf[HEX_DIGEST_LENGTH];
501 
502 	alg->Init(&context);
503 	while ((len = fread(buffer, 1, BUFSIZ, stdin))) {
504 		if (tee && len != fwrite(buffer, 1, len, stdout))
505 			err(1, "stdout");
506 		alg->Update(&context, buffer, len);
507 	}
508 	printf("%s\n", alg->End(&context, buf));
509 }
510 
511 static void
512 usage(int excode)
513 {
514 	fprintf(stderr, "usage:\n\t%s [-pqrtx] [-b offset] [-e offset] "
515 	    "[-s string] [files ...]\n", getprogname());
516 	exit(excode);
517 }
518