]> git.xonotic.org Git - xonotic/d0_blind_id.git/blob - d0_bignum-tommath.c
Merge branch 'little_update' into 'master'
[xonotic/d0_blind_id.git] / d0_bignum-tommath.c
1 /*
2  * FILE:        d0_bignum-tommath.c
3  * AUTHOR:      Rudolf Polzer - divVerent@xonotic.org
4  * 
5  * Copyright (c) 2010, Rudolf Polzer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the copyright holder nor the names of contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  * 
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Format:commit %H$
33  * $Id$
34  */
35
36 #ifdef WIN32
37 #include <windows.h>
38 #include <wincrypt.h>
39 #endif
40
41 #include "d0_bignum.h"
42
43 #include <string.h>
44 #include <stdlib.h>
45 #include <assert.h>
46
47 // tommath/tomsfastmath distinction
48 #if defined(TOMMATH)
49 # include <tommath.h>
50 # define TM(name) MP_##name
51 # define tm(name) mp_##name
52 #elif defined(TOMSFASTMATH)
53 # include <tfm.h>
54 # define TM(name) FP_##name
55 # define tm(name) fp_##name
56 # define mp_clear
57 #else
58 # error Either TOMMATH or TOMSFASTMATH must be defined.
59 #endif
60
61 struct d0_bignum_s
62 {
63         tm(int) z;
64 };
65
66 static d0_bignum_t temp;
67 static unsigned char numbuf[65536];
68 static void *tempmutex = NULL; // hold this mutex when using temp or numbuf
69
70 #include <stdio.h>
71
72 #ifdef WIN32
73 HCRYPTPROV hCryptProv;
74 #else
75 static FILE *randf;
76 #endif
77
78 void rand_bytes(unsigned char *buf, size_t n)
79 {
80 #ifdef WIN32
81         CryptGenRandom(hCryptProv, n, (PBYTE) buf);
82 #else
83         if(!randf)
84                 return;
85         fread(buf, 1, n, randf);
86 #endif
87 }
88
89 D0_WARN_UNUSED_RESULT D0_BOOL d0_bignum_INITIALIZE(void)
90 {
91         D0_BOOL ret = 1;
92         unsigned char buf[256];
93
94         tempmutex = d0_createmutex();
95         d0_lockmutex(tempmutex);
96
97         d0_bignum_init(&temp);
98 #ifdef WIN32
99         {
100                 if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
101                 {
102                 }
103                 else if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET))
104                 {
105                 }
106                 else
107                 {
108                         fprintf(stderr, "WARNING: could not initialize random number generator (CryptAcquireContext failed)\n");
109                         ret = 0;
110                         hCryptProv = NULL;
111                 }
112         }
113 #else
114         randf = fopen("/dev/urandom", "rb");
115         if(!randf)
116                 randf = fopen("/dev/random", "rb");
117         if(randf)
118         {
119                 setbuf(randf, NULL);
120         }
121         else
122         {
123                 fprintf(stderr, "WARNING: could not initialize random number generator (no random device found)\n");
124                 ret = 0;
125         }
126 #endif
127
128         d0_unlockmutex(tempmutex);
129
130         return ret;
131 }
132
133 void d0_bignum_SHUTDOWN(void)
134 {
135         d0_lockmutex(tempmutex);
136
137         d0_bignum_clear(&temp);
138 #ifdef WIN32
139         if(hCryptProv)
140         {
141                 CryptReleaseContext(hCryptProv, 0);
142                 hCryptProv = NULL;
143         }
144 #endif
145
146         d0_unlockmutex(tempmutex);
147         d0_destroymutex(tempmutex);
148         tempmutex = NULL;
149 }
150
151 D0_BOOL d0_iobuf_write_bignum(d0_iobuf_t *buf, const d0_bignum_t *bignum)
152 {
153         D0_BOOL ret;
154         size_t count = 0;
155
156         d0_lockmutex(tempmutex);
157         numbuf[0] = (tm(iszero)(&bignum->z) ? 0 : (bignum->z.sign == TM(ZPOS)) ? 1 : 3);
158         if((numbuf[0] & 3) != 0) // nonzero
159         {
160                 count = tm(unsigned_bin_size)((tm(int) *) &bignum->z);
161                 if(count > sizeof(numbuf) - 1)
162                 {
163                         d0_unlockmutex(tempmutex);
164                         return 0;
165                 }
166                 tm(to_unsigned_bin)((tm(int) *) &bignum->z, numbuf+1);
167         }
168         ret = d0_iobuf_write_packet(buf, numbuf, count + 1);
169         d0_unlockmutex(tempmutex);
170         return ret;
171 }
172
173 d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum)
174 {
175         size_t count = sizeof(numbuf);
176         d0_lockmutex(tempmutex);
177         if(!d0_iobuf_read_packet(buf, numbuf, &count))
178         {
179                 d0_unlockmutex(tempmutex);
180                 return NULL;
181         }
182         if(count < 1)
183         {
184                 d0_unlockmutex(tempmutex);
185                 return NULL;
186         }
187         if(!bignum)
188                 bignum = d0_bignum_new();
189         if(!bignum)
190         {
191                 d0_unlockmutex(tempmutex);
192                 return NULL;
193         }
194         if(numbuf[0] & 3) // nonzero
195         {
196                 tm(read_unsigned_bin)(&bignum->z, numbuf+1, count-1);
197                 if(numbuf[0] & 2) // negative
198                         bignum->z.sign = TM(NEG);
199         }
200         else // zero
201         {
202                 tm(zero)(&bignum->z);
203         }
204         d0_unlockmutex(tempmutex);
205         return bignum;
206 }
207
208 ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize)
209 {
210         unsigned long bufsize_;
211         unsigned long count;
212         count = tm(unsigned_bin_size)((tm(int) *) &bignum->z);
213         if(count > bufsize)
214                 return -1;
215         if(bufsize > count)
216         {
217                 // pad from left (big endian numbers!)
218                 memset(buf, 0, bufsize - count);
219                 buf += bufsize - count;
220         }
221         tm(to_unsigned_bin)((tm(int) *) &bignum->z, buf);
222         return bufsize;
223 }
224
225 d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize)
226 {
227         size_t count;
228         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
229         tm(read_unsigned_bin)(&bignum->z, (void *) buf, bufsize);
230         return bignum;
231 }
232
233 d0_bignum_t *d0_bignum_new(void)
234 {
235         d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t));
236         tm(init)(&b->z);
237         return b;
238 }
239
240 void d0_bignum_free(d0_bignum_t *a)
241 {
242 #ifdef TOMMATH
243         tm(clear)(&a->z);
244 #endif
245         d0_free(a);
246 }
247
248 void d0_bignum_init(d0_bignum_t *b)
249 {
250         tm(init)(&b->z);
251 }
252
253 void d0_bignum_clear(d0_bignum_t *a)
254 {
255 #ifdef TOMMATH
256         tm(clear)(&a->z);
257 #endif
258 }
259
260 size_t d0_bignum_size(const d0_bignum_t *r)
261 {
262         return tm(count_bits)((tm(int) *) &r->z);
263 }
264
265 int d0_bignum_cmp(const d0_bignum_t *a, const d0_bignum_t *b)
266 {
267         return tm(cmp)((tm(int) *) &a->z, (tm(int) *) &b->z);
268 }
269
270 static d0_bignum_t *d0_bignum_rand_0_to_limit(d0_bignum_t *r, const d0_bignum_t *limit)
271 {
272         size_t n = d0_bignum_size(limit);
273         size_t b = (n + 7) / 8;
274         unsigned char mask = "\xFF\x7F\x3F\x1F\x0F\x07\x03\x01"[8*b - n];
275         assert(b <= sizeof(numbuf));
276         d0_lockmutex(tempmutex);
277         for(;;)
278         {
279                 rand_bytes(numbuf, b);
280                 numbuf[0] &= mask;
281                 r = d0_bignum_import_unsigned(r, numbuf, b);
282                 if(d0_bignum_cmp(r, limit) < 0)
283                 {
284                         d0_unlockmutex(tempmutex);
285                         return r;
286                 }
287         }
288 }
289
290 d0_bignum_t *d0_bignum_rand_range(d0_bignum_t *r, const d0_bignum_t *min, const d0_bignum_t *max)
291 {
292         d0_lockmutex(tempmutex);
293         tm(sub)((tm(int) *) &max->z, (tm(int) *) &min->z, &temp.z);
294         r = d0_bignum_rand_0_to_limit(r, &temp);
295         d0_unlockmutex(tempmutex);
296         tm(add)((tm(int) *) &r->z, (tm(int) *) &min->z, &r->z);
297         return r;
298 }
299
300 d0_bignum_t *d0_bignum_rand_bit_atmost(d0_bignum_t *r, size_t n)
301 {
302         d0_lockmutex(tempmutex);
303         if(!d0_bignum_one(&temp))
304         {
305                 d0_unlockmutex(tempmutex);
306                 return NULL;
307         }
308         if(!d0_bignum_shl(&temp, &temp, n))
309         {
310                 d0_unlockmutex(tempmutex);
311                 return NULL;
312         }
313         r = d0_bignum_rand_0_to_limit(r, &temp);
314         d0_unlockmutex(tempmutex);
315         return r;
316 }
317
318 d0_bignum_t *d0_bignum_rand_bit_exact(d0_bignum_t *r, size_t n)
319 {
320         d0_lockmutex(tempmutex);
321         if(!d0_bignum_one(&temp))
322         {
323                 d0_unlockmutex(tempmutex);
324                 return NULL;
325         }
326         if(!d0_bignum_shl(&temp, &temp, n-1))
327         {
328                 d0_unlockmutex(tempmutex);
329                 return NULL;
330         }
331         r = d0_bignum_rand_0_to_limit(r, &temp);
332         if(!d0_bignum_add(r, r, &temp))
333         {
334                 d0_unlockmutex(tempmutex);
335                 return NULL;
336         }
337         d0_unlockmutex(tempmutex);
338         return r;
339 }
340
341 d0_bignum_t *d0_bignum_zero(d0_bignum_t *r)
342 {
343         if(!r) r = d0_bignum_new(); if(!r) return NULL;
344         tm(zero)(&r->z);
345         return r;
346 }
347
348 d0_bignum_t *d0_bignum_one(d0_bignum_t *r)
349 {
350         return d0_bignum_int(r, 1);
351 }
352
353 d0_bignum_t *d0_bignum_int(d0_bignum_t *r, int n)
354 {
355         if(!r) r = d0_bignum_new(); if(!r) return NULL;
356 #ifdef TOMMATH
357         tm(set_int)(&r->z, n);
358 #else
359         // libtomsfastmath lacks this function
360         if (n < 0)
361                 assert(!"Sorry, importing signed is not implemented");
362         {
363                 unsigned char nbuf[sizeof(n)];
364                 size_t i;
365                 // big endian!
366                 for (i = sizeof(n); i-- > 0; )
367                 {
368                         nbuf[i] = n & 255;
369                         n >>= 8;
370                 }
371                 tm(read_unsigned_bin)(&r->z, nbuf, sizeof(n));
372         }
373 #endif
374
375         return r;
376 }
377
378 d0_bignum_t *d0_bignum_mov(d0_bignum_t *r, const d0_bignum_t *a)
379 {
380         if(r == a)
381                 return r; // trivial
382         if(!r) r = d0_bignum_new(); if(!r) return NULL;
383         tm(copy)((tm(int) *) &a->z, &r->z);
384         return r;
385 }
386
387 d0_bignum_t *d0_bignum_neg(d0_bignum_t *r, const d0_bignum_t *a)
388 {
389         if(!r) r = d0_bignum_new(); if(!r) return NULL;
390         tm(neg)((tm(int) *) &a->z, &r->z);
391         return r;
392 }
393
394 d0_bignum_t *d0_bignum_shl(d0_bignum_t *r, const d0_bignum_t *a, ssize_t n)
395 {
396         if(!r) r = d0_bignum_new(); if(!r) return NULL;
397         if(n > 0)
398                 tm(mul_2d)((tm(int) *) &a->z,  n, &r->z);
399         else if(n < 0)
400                 tm(div_2d)((tm(int) *) &a->z, -n, &r->z, NULL);
401         else
402                 tm(copy)((tm(int) *) &a->z, &r->z);
403         return r;
404 }
405
406 d0_bignum_t *d0_bignum_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
407 {
408         if(!r) r = d0_bignum_new(); if(!r) return NULL;
409         tm(add)((tm(int) *) &a->z, (tm(int) *) &b->z, &r->z);
410         return r;
411 }
412
413 d0_bignum_t *d0_bignum_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
414 {
415         if(!r) r = d0_bignum_new(); if(!r) return NULL;
416         tm(sub)((tm(int) *) &a->z, (tm(int) *) &b->z, &r->z);
417         return r;
418 }
419
420 d0_bignum_t *d0_bignum_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
421 {
422         if(!r) r = d0_bignum_new(); if(!r) return NULL;
423         tm(mul)((tm(int) *) &a->z, (tm(int) *) &b->z, &r->z);
424         return r;
425 }
426
427 d0_bignum_t *d0_bignum_divmod(d0_bignum_t *q, d0_bignum_t *m, const d0_bignum_t *a, const d0_bignum_t *b)
428 {
429         if(!q && !m)
430                 m = d0_bignum_new();
431         if(q)
432                 tm(div)((tm(int) *) &a->z, (tm(int) *) &b->z, &q->z, m ? &m->z : NULL);
433         else
434                 tm(mod)((tm(int) *) &a->z, (tm(int) *) &b->z, &m->z);
435         if(m)
436                 return m;
437         else
438                 return q;
439 }
440
441 d0_bignum_t *d0_bignum_mod_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
442 {
443         if(!r) r = d0_bignum_new(); if(!r) return NULL;
444         tm(addmod)((tm(int) *) &a->z, (tm(int) *) &b->z, (tm(int) *) &m->z, &r->z);
445         return r;
446 }
447
448 d0_bignum_t *d0_bignum_mod_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
449 {
450         if(!r) r = d0_bignum_new(); if(!r) return NULL;
451         tm(submod)((tm(int) *) &a->z, (tm(int) *) &b->z, (tm(int) *) &m->z, &r->z);
452         return r;
453 }
454
455 d0_bignum_t *d0_bignum_mod_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
456 {
457         if(!r) r = d0_bignum_new(); if(!r) return NULL;
458         tm(mulmod)((tm(int) *) &a->z, (tm(int) *) &b->z, (tm(int) *) &m->z, &r->z);
459         return r;
460 }
461
462 d0_bignum_t *d0_bignum_mod_pow(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
463 {
464         if(!r) r = d0_bignum_new(); if(!r) return NULL;
465         tm(exptmod)((tm(int) *) &a->z, (tm(int) *) &b->z, (tm(int) *) &m->z, &r->z);
466         return r;
467 }
468
469 D0_BOOL d0_bignum_mod_inv(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *m)
470 {
471         // here, r MUST be set, as otherwise we cannot return error state!
472         return tm(invmod)((tm(int) *) &a->z, (tm(int) *) &m->z, &r->z) == TM(OKAY);
473 }
474
475 int d0_bignum_isprime(const d0_bignum_t *r, int param)
476 {
477         if(param < 1)
478                 param = 1;
479 #ifdef TOMMATH
480         {
481                 int ret = 0;
482                 tm(prime_is_prime)((tm(int) *) &r->z, param, &ret);
483                 return ret;
484         }
485 #else
486         // this does 8 rabin tests; for param > 8, do more?
487         return tm(isprime)((tm(int) *) &r->z);
488 #endif
489 }
490
491 d0_bignum_t *d0_bignum_gcd(d0_bignum_t *r, d0_bignum_t *s, d0_bignum_t *t, const d0_bignum_t *a, const d0_bignum_t *b)
492 {
493         if(!r) r = d0_bignum_new(); if(!r) return NULL;
494         if(s || t)
495         {
496 #ifdef TOMMATH
497                 tm(exteuclid)((tm(int) *) &a->z, (tm(int) *) &b->z, s ? &s->z : NULL, t ? &t->z : NULL, &r->z);
498 #else
499                 assert(!"Extended gcd not implemented");
500 #endif
501         }
502         else
503                 tm(gcd)((tm(int) *) &a->z, (tm(int) *) &b->z, &r->z);
504         return r;
505 }
506
507 char *d0_bignum_tostring(const d0_bignum_t *x, unsigned int base)
508 {
509         char *str;
510         int sz = 0;
511         tm(radix_size)((tm(int) *) &x->z, base, &sz);
512         str = d0_malloc(sz + 1);
513         tm(toradix)((tm(int) *) &x->z, str, base);
514         return str;
515 }