1 /*	$Id$ */
2 /*
3  * Copyright (c) 2019 Kristaps Dzonsons <kristaps@bsd.lv>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include "config.h"
18 
19 #include <sys/types.h>
20 #include COMPAT_ENDIAN_H
21 
22 #include <assert.h>
23 #include <assert.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 
27 #include "extern.h"
28 #include "md4.h"
29 
30 /*
31  * A fast 32-bit hash.
32  * Described in Tridgell's "Efficient Algorithms for Sorting and
33  * Synchronization" thesis and the "Rolling checksum" document.
34  */
35 uint32_t
hash_fast(const void * buf,size_t len)36 hash_fast(const void *buf, size_t len)
37 {
38 	size_t			 i = 0;
39 	uint32_t		 a = 0, /* part of a(k, l) */
40 				 b = 0; /* b(k, l) */
41 	const signed char	*dat = buf;
42 
43 	if (len > 4)
44 		for ( ; i < len - 4; i += 4) {
45 			b += 4 * (a + dat[i]) +
46 			    3 * dat[i + 1] +
47 			    2 * dat[i + 2] +
48 			    dat[i + 3];
49 			a += dat[i + 0] +
50 			    dat[i + 1] +
51 			    dat[i + 2] +
52 			    dat[i + 3];
53 		}
54 
55 	for ( ; i < len; i++) {
56 		a += dat[i];
57 		b += a;
58 	}
59 
60 	/* s(k, l) = (eps % M) + 2^16 b(k, l) % M */
61 
62 	return (a & 0xffff) + (b << 16);
63 }
64 
65 /*
66  * Slow MD4-based hash with trailing seed.
67  */
68 void
hash_slow(const void * buf,size_t len,unsigned char * md,const struct sess * sess)69 hash_slow(const void *buf, size_t len,
70 	unsigned char *md, const struct sess *sess)
71 {
72 	MD4_CTX		 ctx;
73 	int32_t		 seed = htole32(sess->seed);
74 
75 	MD4_Init(&ctx);
76 	MD4_Update(&ctx, buf, len);
77 	MD4_Update(&ctx, (unsigned char *)&seed, sizeof(int32_t));
78 	MD4_Final(md, &ctx);
79 }
80 
81 /*
82  * Hash an entire file.
83  * This is similar to hash_slow() except the seed is hashed at the end
84  * of the sequence, not the beginning.
85  */
86 void
hash_file(const void * buf,size_t len,unsigned char * md,const struct sess * sess)87 hash_file(const void *buf, size_t len,
88 	unsigned char *md, const struct sess *sess)
89 {
90 	MD4_CTX		 ctx;
91 	int32_t		 seed = htole32(sess->seed);
92 
93 	MD4_Init(&ctx);
94 	MD4_Update(&ctx, (unsigned char *)&seed, sizeof(int32_t));
95 	MD4_Update(&ctx, buf, len);
96 	MD4_Final(md, &ctx);
97 }
98