summaryrefslogtreecommitdiff
path: root/collect.c
blob: e800edd8c0d410b40455463a18430dbfa03f9efc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
 * Collect various pieces of randomness
 */

static char rcsid[] = "$Header: /home/sater/bridge/bigdeal/RCS/collect.c,v 1.7 2000/08/25 15:55:26 sater Exp $";

#include "types.h"
#include "rmd160.h"
#include "bigdeal.h"
#include <stdio.h>

static dword MDbuf[RMDdwords];		/* Contains state of RIPEMD-160 */
static byte variousbytes[64];
static int vbytesindex;

int nrandombits;			/* Collected bits of randomness */
static int nhashbytes;			/* Number of bytes hashed */

#ifdef BIGDEALX
extern FILE *flog;
#endif

void
collect_start()
/*
 * Set everything to zero, and init the hashing engine
 */
{

	MDinit(MDbuf);
	vbytesindex = 0;
	nhashbytes = 0;
	nrandombits = 0;
}

static void
collect_byte(byte b)
/*
 * Throw another byte into the machine. If it fills up the buffer run the 
 * buffer through the hashing engine
 */
{
	dword X[16];
	int i;
	byte *bp;

	nhashbytes++;
	variousbytes[vbytesindex++] = b;
	if (vbytesindex == 64) {
		bp = variousbytes;
		for (i=0; i<16; i++) {
			X[i] = BYTES_TO_DWORD(bp);
			bp += 4;
		}
		compress(MDbuf, X);
		vbytesindex = 0;
#ifdef BIGDEALX
		if (flog)
			fprintf(flog, "compressed another 64 bytes\n");
#endif
	}
}

void
collect_more(byte *bp, int nbytes, int entropybits)
/*
 * Throw a bunch of information into the machine.
 * The user supplies a hopefully pessimistic estimate of the entropy
 */
{

	nrandombits += entropybits;
#ifdef BIGDEALX
	if (flog) {
		int i;

		fprintf(flog, "collect_more(");
		for (i=0; i < nbytes; i++)
			fprintf(flog, "%02x", bp[i]);
		fprintf(flog, ", %d, %d) -> %d\n", nbytes, entropybits, nrandombits);
	}
#endif
	while(nbytes > 0) {
		collect_byte(*bp);
		nbytes--;
		bp++;
	}
}

void
collect_finish(byte *hash)
/*
 * Halt the hashing engine
 * Extract the result into hash[]
 */
{
	int i;

	MDfinish(MDbuf, variousbytes, nhashbytes, 0);
#ifdef BIGDEALX
	if (flog)
		fprintf(flog, "collected %d random bits, from %d bytes of data\n",
			nrandombits, nhashbytes);

#endif
	for (i=0; i<RMDbytes; i+=4) {
		hash[i]   =  MDbuf[i>>2];         /* implicit cast to byte  */
		hash[i+1] = (MDbuf[i>>2] >>  8);  /*  extracts the 8 least  */
		hash[i+2] = (MDbuf[i>>2] >> 16);  /*  significant bits.     */
		hash[i+3] = (MDbuf[i>>2] >> 24);
	}
}