xref: /inferno-os/libsec/port/egencrypt.c (revision 37da2899f40661e3e9631e497da8dc59b971cbd0)
1 #include "os.h"
2 #include <mp.h>
3 #include <libsec.h>
4 
5 mpint*
egencrypt(EGpub * pub,mpint * in,mpint * out)6 egencrypt(EGpub *pub, mpint *in, mpint *out)
7 {
8 	mpint *m, *k, *gamma, *delta, *pm1;
9 	mpint *p = pub->p, *alpha = pub->alpha;
10 	int plen = mpsignif(p);
11 	int shift = ((plen+Dbits)/Dbits)*Dbits;
12 	// in libcrypt version, (int)(LENGTH(pub->p)*sizeof(NumType)*CHARBITS);
13 
14 	if(out == nil)
15 		out = mpnew(0);
16 	pm1 = mpnew(0);
17 	m = mpnew(0);
18 	gamma = mpnew(0);
19 	delta = mpnew(0);
20 	mpmod(in, p, m);
21 	while(1){
22 		k = mprand(plen, genrandom, nil);
23 		if((mpcmp(mpone, k) <= 0) && (mpcmp(k, pm1) < 0))
24 			break;
25 	}
26 	mpexp(alpha, k, p, gamma);
27 	mpexp(pub->key, k, p, delta);
28 	mpmul(m, delta, delta);
29 	mpmod(delta, p, delta);
30 	mpleft(gamma, shift, out);
31 	mpadd(delta, out, out);
32 	mpfree(pm1);
33 	mpfree(m);
34 	mpfree(k);
35 	mpfree(gamma);
36 	mpfree(delta);
37 	return out;
38 }
39