aboutsummaryrefslogtreecommitdiff
path: root/src/libmp/port/mprand.c
blob: fd288f24e2861fc4764591a95041268936190978 (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
#include "os.h"
#include <mp.h>
#include <libsec.h>
#include "dat.h"

mpint*
mprand(int bits, void (*gen)(uchar*, int), mpint *b)
{
	int n, m;
	mpdigit mask;
	uchar *p;

	n = DIGITS(bits);
	if(b == nil)
		b = mpnew(bits);
	else
		mpbits(b, bits);

	p = malloc(n*Dbytes);
	if(p == nil)
		return nil;
	(*gen)(p, n*Dbytes);
	betomp(p, n*Dbytes, b);
	free(p);

	// make sure we don't give too many bits
	m = bits%Dbits;
	n--;
	if(m > 0){
		mask = 1;
		mask <<= m;
		mask--;
		b->p[n] &= mask;
	}

	for(; n >= 0; n--)
		if(b->p[n] != 0)
			break;
	b->top = n+1;
	b->sign = 1;
	return b;
}