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