]> git.xonotic.org Git - xonotic/d0_blind_id.git/blob - d0_bignum-gmp.c
Merge branch 'little_update' into 'master'
[xonotic/d0_blind_id.git] / d0_bignum-gmp.c
1 /*
2  * FILE:        d0_bignum-gmp.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 /* NOTE: this file links against libgmp (http://gmplib.org), which is under the
37  * Lesser General Public License 2.1 or later. You may have to abide to its
38  * terms too if you use this file.
39  * To alternatively link to OpenSSL, provide the option --with-openssl to
40  * ./configure.
41  */
42
43 #ifdef WIN32
44 #include <windows.h>
45 #include <wincrypt.h>
46 #endif
47
48 #include "d0_bignum.h"
49
50 #include <gmp.h>
51 #include <string.h>
52 #include <stdlib.h>
53
54 struct d0_bignum_s
55 {
56         mpz_t z;
57 };
58
59 static gmp_randstate_t RANDSTATE;
60 static d0_bignum_t temp;
61 static unsigned char numbuf[65536];
62 static void *tempmutex = NULL; // hold this mutex when using RANDSTATE or temp or numbuf
63
64 #include <time.h>
65 #include <stdio.h>
66
67 static void *allocate_function (size_t alloc_size)
68 {
69         return d0_malloc(alloc_size);
70 }
71 static void *reallocate_function (void *ptr, size_t old_size, size_t new_size)
72 {
73         void *data;
74         if(old_size == new_size)
75                 return ptr;
76         data = d0_malloc(new_size);
77         if(ptr && data)
78                 memcpy(data, ptr, (old_size < new_size) ? old_size : new_size);
79         d0_free(ptr);
80         return data;
81 }
82 void deallocate_function (void *ptr, size_t size)
83 {
84         d0_free(ptr);
85 }
86
87 D0_WARN_UNUSED_RESULT D0_BOOL d0_bignum_INITIALIZE(void)
88 {
89         FILE *f;
90         D0_BOOL ret = 1;
91         unsigned char buf[256];
92
93         tempmutex = d0_createmutex();
94         d0_lockmutex(tempmutex);
95
96         mp_set_memory_functions(allocate_function, reallocate_function, deallocate_function);
97
98         d0_bignum_init(&temp);
99         gmp_randinit_mt(RANDSTATE);
100         gmp_randseed_ui(RANDSTATE, time(NULL));
101         * (time_t *) (&buf[0]) = time(0); // if everything else fails, we use the current time + uninitialized data
102 #ifdef WIN32
103         {
104                 HCRYPTPROV hCryptProv;
105                 if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
106                 {
107                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
108                         {
109                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
110                                 ret = 0;
111                         }
112                         CryptReleaseContext(hCryptProv, 0);
113                 }
114                 else if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET))
115                 {
116                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
117                         {
118                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
119                                 ret = 0;
120                         }
121                         CryptReleaseContext(hCryptProv, 0);
122                 }
123                 else
124                 {
125                         fprintf(stderr, "WARNING: could not initialize random number generator (CryptAcquireContext failed)\n");
126                         ret = 0;
127                 }
128         }
129 #else
130         f = fopen("/dev/urandom", "rb");
131         if(!f)
132                 f = fopen("/dev/random", "rb");
133         if(f)
134         {
135                 setbuf(f, NULL);
136                 if(fread(buf, sizeof(buf), 1, f) != 1)
137                 {
138                         fprintf(stderr, "WARNING: could not initialize random number generator (read from random device failed)\n");
139                         ret = 0;
140                 }
141                 fclose(f);
142         }
143         else
144         {
145                 fprintf(stderr, "WARNING: could not initialize random number generator (no random device found)\n");
146                 ret = 0;
147         }
148 #endif
149
150         mpz_import(temp.z, sizeof(buf), 1, 1, 0, 0, buf);
151         gmp_randseed(RANDSTATE, temp.z);
152
153         d0_unlockmutex(tempmutex);
154
155         return ret;
156 }
157
158 void d0_bignum_SHUTDOWN(void)
159 {
160         d0_lockmutex(tempmutex);
161
162         d0_bignum_clear(&temp);
163         gmp_randclear(RANDSTATE);
164
165         d0_unlockmutex(tempmutex);
166         d0_destroymutex(tempmutex);
167         tempmutex = NULL;
168 }
169
170 D0_BOOL d0_iobuf_write_bignum(d0_iobuf_t *buf, const d0_bignum_t *bignum)
171 {
172         D0_BOOL ret;
173         size_t count = 0;
174
175         d0_lockmutex(tempmutex);
176         numbuf[0] = mpz_sgn(bignum->z) & 3;
177         if((numbuf[0] & 3) != 0) // nonzero
178         {
179                 count = (mpz_sizeinbase(bignum->z, 2) + 7) / 8;
180                 if(count > sizeof(numbuf) - 1)
181                 {
182                         d0_unlockmutex(tempmutex);
183                         return 0;
184                 }
185                 mpz_export(numbuf+1, &count, 1, 1, 0, 0, bignum->z);
186         }
187         ret = d0_iobuf_write_packet(buf, numbuf, count + 1);
188         d0_unlockmutex(tempmutex);
189         return ret;
190 }
191
192 d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum)
193 {
194         size_t count = sizeof(numbuf);
195
196         d0_lockmutex(tempmutex);
197         if(!d0_iobuf_read_packet(buf, numbuf, &count))
198         {
199                 d0_unlockmutex(tempmutex);
200                 return NULL;
201         }
202         if(count < 1)
203         {
204                 d0_unlockmutex(tempmutex);
205                 return NULL;
206         }
207         if(!bignum)
208                 bignum = d0_bignum_new();
209         if(!bignum)
210         {
211                 d0_unlockmutex(tempmutex);
212                 return NULL;
213         }
214         if(numbuf[0] & 3) // nonzero
215         {
216                 mpz_import(bignum->z, count-1, 1, 1, 0, 0, numbuf+1);
217                 if(numbuf[0] & 2) // negative
218                         mpz_neg(bignum->z, bignum->z);
219         }
220         else // zero
221         {
222                 mpz_set_ui(bignum->z, 0);
223         }
224         d0_unlockmutex(tempmutex);
225         return bignum;
226 }
227
228 ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize)
229 {
230         size_t count;
231         count = (mpz_sizeinbase(bignum->z, 2) + 7) / 8;
232         if(count > bufsize)
233                 return -1;
234         if(bufsize > count)
235         {
236                 // pad from left (big endian numbers!)
237                 memset(buf, 0, bufsize - count);
238                 buf += bufsize - count;
239         }
240         bufsize = count;
241         mpz_export(buf, &bufsize, 1, 1, 0, 0, bignum->z);
242         if(bufsize > count)
243         {
244                 // REALLY BAD
245                 // mpz_sizeinbase lied to us
246                 // buffer overflow
247                 // there is no sane way whatsoever to handle this
248                 abort();
249         }
250         if(bufsize < count)
251         {
252                 // BAD
253                 // mpz_sizeinbase lied to us
254                 // move the number
255                 if(count == 0)
256                 {
257                         memset(buf, 0, count);
258                 }
259                 else
260                 {
261                         memmove(buf + count - bufsize, buf, bufsize);
262                         memset(buf, 0, count - bufsize);
263                 }
264         }
265         return bufsize;
266 }
267
268 d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize)
269 {
270         size_t count;
271         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
272         mpz_import(bignum->z, bufsize, 1, 1, 0, 0, buf);
273         return bignum;
274 }
275
276 d0_bignum_t *d0_bignum_new(void)
277 {
278         d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t));
279         mpz_init(b->z);
280         return b;
281 }
282
283 void d0_bignum_free(d0_bignum_t *a)
284 {
285         mpz_clear(a->z);
286         d0_free(a);
287 }
288
289 void d0_bignum_init(d0_bignum_t *b)
290 {
291         mpz_init(b->z);
292 }
293
294 void d0_bignum_clear(d0_bignum_t *a)
295 {
296         mpz_clear(a->z);
297 }
298
299 size_t d0_bignum_size(const d0_bignum_t *r)
300 {
301         return mpz_sizeinbase(r->z, 2);
302 }
303
304 int d0_bignum_cmp(const d0_bignum_t *a, const d0_bignum_t *b)
305 {
306         return mpz_cmp(a->z, b->z);
307 }
308
309 d0_bignum_t *d0_bignum_rand_range(d0_bignum_t *r, const d0_bignum_t *min, const d0_bignum_t *max)
310 {
311         if(!r) r = d0_bignum_new(); if(!r) return NULL;
312         d0_lockmutex(tempmutex);
313         mpz_sub(temp.z, max->z, min->z);
314         mpz_urandomm(r->z, RANDSTATE, temp.z);
315         d0_unlockmutex(tempmutex);
316         mpz_add(r->z, r->z, min->z);
317         return r;
318 }
319
320 d0_bignum_t *d0_bignum_rand_bit_atmost(d0_bignum_t *r, size_t n)
321 {
322         if(!r) r = d0_bignum_new(); if(!r) return NULL;
323         d0_lockmutex(tempmutex);
324         mpz_urandomb(r->z, RANDSTATE, n);
325         d0_unlockmutex(tempmutex);
326         return r;
327 }
328
329 d0_bignum_t *d0_bignum_rand_bit_exact(d0_bignum_t *r, size_t n)
330 {
331         if(!r) r = d0_bignum_new(); if(!r) return NULL;
332         d0_lockmutex(tempmutex);
333         mpz_urandomb(r->z, RANDSTATE, n-1);
334         d0_unlockmutex(tempmutex);
335         mpz_setbit(r->z, n-1);
336         return r;
337 }
338
339 d0_bignum_t *d0_bignum_zero(d0_bignum_t *r)
340 {
341         return d0_bignum_int(r, 0);
342 }
343
344 d0_bignum_t *d0_bignum_one(d0_bignum_t *r)
345 {
346         return d0_bignum_int(r, 1);
347 }
348
349 d0_bignum_t *d0_bignum_int(d0_bignum_t *r, int n)
350 {
351         if(!r) r = d0_bignum_new(); if(!r) return NULL;
352         mpz_set_si(r->z, n);
353         return r;
354 }
355
356 d0_bignum_t *d0_bignum_mov(d0_bignum_t *r, const d0_bignum_t *a)
357 {
358         if(r == a)
359                 return r; // trivial
360         if(!r) r = d0_bignum_new(); if(!r) return NULL;
361         mpz_set(r->z, a->z);
362         return r;
363 }
364
365 d0_bignum_t *d0_bignum_neg(d0_bignum_t *r, const d0_bignum_t *a)
366 {
367         if(!r) r = d0_bignum_new(); if(!r) return NULL;
368         mpz_neg(r->z, a->z);
369         return r;
370 }
371
372 d0_bignum_t *d0_bignum_shl(d0_bignum_t *r, const d0_bignum_t *a, ssize_t n)
373 {
374         if(!r) r = d0_bignum_new(); if(!r) return NULL;
375         if(n > 0)
376                 mpz_mul_2exp(r->z, a->z, n);
377         else if(n < 0)
378                 mpz_fdiv_q_2exp(r->z, a->z, -n);
379         else
380                 mpz_set(r->z, a->z);
381         return r;
382 }
383
384 d0_bignum_t *d0_bignum_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
385 {
386         if(!r) r = d0_bignum_new(); if(!r) return NULL;
387         mpz_add(r->z, a->z, b->z);
388         return r;
389 }
390
391 d0_bignum_t *d0_bignum_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
392 {
393         if(!r) r = d0_bignum_new(); if(!r) return NULL;
394         mpz_sub(r->z, a->z, b->z);
395         return r;
396 }
397
398 d0_bignum_t *d0_bignum_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
399 {
400         if(!r) r = d0_bignum_new(); if(!r) return NULL;
401         mpz_mul(r->z, a->z, b->z);
402         return r;
403 }
404
405 d0_bignum_t *d0_bignum_divmod(d0_bignum_t *q, d0_bignum_t *m, const d0_bignum_t *a, const d0_bignum_t *b)
406 {
407         if(!q && !m)
408                 m = d0_bignum_new();
409         if(q)
410                 if(m)
411                         mpz_fdiv_qr(q->z, m->z, a->z, b->z);
412                 else
413                         mpz_fdiv_q(q->z, a->z, b->z);
414         else
415                 mpz_fdiv_r(m->z, a->z, b->z);
416         if(m)
417                 return m;
418         else
419                 return q;
420 }
421
422 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)
423 {
424         r = d0_bignum_add(r, a, b);
425         mpz_fdiv_r(r->z, r->z, m->z);
426         return r;
427 }
428
429 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)
430 {
431         r = d0_bignum_sub(r, a, b);
432         mpz_fdiv_r(r->z, r->z, m->z);
433         return r;
434 }
435
436 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)
437 {
438         r = d0_bignum_mul(r, a, b);
439         mpz_fdiv_r(r->z, r->z, m->z);
440         return r;
441 }
442
443 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)
444 {
445         if(!r) r = d0_bignum_new(); if(!r) return NULL;
446         mpz_powm(r->z, a->z, b->z, m->z);
447         return r;
448 }
449
450 D0_BOOL d0_bignum_mod_inv(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *m)
451 {
452         // here, r MUST be set, as otherwise we cannot return error state!
453         return mpz_invert(r->z, a->z, m->z);
454 }
455
456 int d0_bignum_isprime(const d0_bignum_t *r, int param)
457 {
458         return mpz_probab_prime_p(r->z, param);
459 }
460
461 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)
462 {
463         if(!r) r = d0_bignum_new(); if(!r) return NULL;
464         if(s)
465                 mpz_gcdext(r->z, s->z, t ? t->z : NULL, a->z, b->z);
466         else if(t)
467                 mpz_gcdext(r->z, t->z, NULL, b->z, a->z);
468         else
469                 mpz_gcd(r->z, a->z, b->z);
470         return r;
471 }
472
473 char *d0_bignum_tostring(const d0_bignum_t *x, unsigned int base)
474 {
475         return mpz_get_str(NULL, base, x->z); // this allocates!
476 }