]> de.git.xonotic.org Git - xonotic/d0_blind_id.git/blob - d0_bignum-openssl.c
add .gitignore
[xonotic/d0_blind_id.git] / d0_bignum-openssl.c
1 /*
2  * FILE:        d0_bignum-openssl.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 openssl (http://www.openssl.org), which is
37  * under the OpenSSL License. You may have to abide to its terms too if you use
38  * this file.
39  * To alternatively link to GMP, provide the option --without-openssl to
40  * ./configure.
41  */
42
43 #include "d0_bignum.h"
44
45 #include <assert.h>
46 #include <string.h>
47 #include <openssl/bn.h>
48 #include <openssl/crypto.h>
49
50 // for stupid OpenSSL versions in Mac OS X
51 #ifndef BN_is_negative
52 #define BN_is_negative(a) ((a)->neg != 0)
53 #define BN_set_negative(a,n) ((a)->neg = ((n) && !BN_is_zero(a)))
54 #endif
55
56 struct d0_bignum_s
57 {
58         BIGNUM z;
59 };
60
61 static d0_bignum_t temp;
62 static BN_CTX *ctx;
63 static unsigned char numbuf[65536];
64 static void *tempmutex = NULL; // hold this mutex when using ctx or temp or numbuf
65
66 #include <time.h>
67 #include <stdio.h>
68
69 static void **locks;
70
71 void locking_function(int mode, int l, const char *file, int line)
72 {
73         void *m = locks[l];
74         if(mode & CRYPTO_LOCK)
75                 d0_lockmutex(m);
76         else
77                 d0_unlockmutex(m);
78 }
79
80 typedef struct CRYPTO_dynlock_value
81 {
82         void *m;
83 };
84
85 struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
86 {
87         return (struct CRYPTO_dynlock_value *) d0_createmutex();
88 }
89
90 void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
91 {
92         void *m = (void *) l;
93         if(mode & CRYPTO_LOCK)
94                 d0_lockmutex(m);
95         else
96                 d0_unlockmutex(m);
97 }
98
99 void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
100 {
101         void *m = (void *) l;
102         d0_destroymutex(l);
103 }
104
105 D0_WARN_UNUSED_RESULT D0_BOOL d0_bignum_INITIALIZE(void)
106 {
107         FILE *f;
108         D0_BOOL ret = 1;
109         unsigned char buf[256];
110         int i, n;
111
112         tempmutex = d0_createmutex();
113         d0_lockmutex(tempmutex);
114
115         n = CRYPTO_num_locks();
116         locks = d0_malloc(n * sizeof(*locks));
117         for(i = 0; i < n; ++i)
118                 locks[i] = d0_createmutex();
119
120         CRYPTO_set_locking_callback(locking_function);
121         CRYPTO_set_dynlock_create_callback(dyn_create_function);
122         CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
123         CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
124
125         ctx = BN_CTX_new();
126         d0_bignum_init(&temp);
127
128 #ifdef WIN32
129         {
130                 HCRYPTPROV hCryptProv;
131                 if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
132                 {
133                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
134                         {
135                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
136                                 ret = 0;
137                         }
138                         CryptReleaseContext(hCryptProv, 0);
139                 }
140                 else if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET))
141                 {
142                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
143                         {
144                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
145                                 ret = 0;
146                         }
147                         CryptReleaseContext(hCryptProv, 0);
148                 }
149                 else
150                 {
151                         fprintf(stderr, "WARNING: could not initialize random number generator (CryptAcquireContext failed)\n");
152                         ret = 0;
153                 }
154         }
155 #else
156         f = fopen("/dev/urandom", "rb");
157         if(!f)
158                 f = fopen("/dev/random", "rb");
159         if(f)
160         {
161                 setbuf(f, NULL);
162                 if(fread(buf, sizeof(buf), 1, f) != 1)
163                 {
164                         fprintf(stderr, "WARNING: could not initialize random number generator (read from random device failed)\n");
165                         ret = 0;
166                 }
167                 fclose(f);
168         }
169         else
170         {
171                 fprintf(stderr, "WARNING: could not initialize random number generator (no random device found)\n");
172                 ret = 0;
173         }
174 #endif
175         RAND_add(buf, sizeof(buf), sizeof(buf));
176
177         d0_unlockmutex(tempmutex);
178
179         return 1;
180         // FIXME initialize the RNG on Windows on UNIX it is done right already
181 }
182
183 void d0_bignum_SHUTDOWN(void)
184 {
185         int i, n;
186
187         d0_lockmutex(tempmutex);
188
189         d0_bignum_clear(&temp);
190         BN_CTX_free(ctx);
191         ctx = NULL;
192
193         n = CRYPTO_num_locks();
194         for(i = 0; i < n; ++i)
195                 d0_destroymutex(locks[i]);
196         d0_free(locks);
197
198         d0_unlockmutex(tempmutex);
199         d0_destroymutex(tempmutex);
200         tempmutex = NULL;
201 }
202
203 D0_BOOL d0_iobuf_write_bignum(d0_iobuf_t *buf, const d0_bignum_t *bignum)
204 {
205         D0_BOOL ret;
206         size_t count = 0;
207
208         d0_lockmutex(tempmutex);
209         numbuf[0] = BN_is_zero(&bignum->z) ? 0 : BN_is_negative(&bignum->z) ? 3 : 1;
210         if((numbuf[0] & 3) != 0) // nonzero
211         {
212                 count = BN_num_bytes(&bignum->z);
213                 if(count > sizeof(numbuf) - 1)
214                 {
215                         d0_unlockmutex(tempmutex);
216                         return 0;
217                 }
218                 BN_bn2bin(&bignum->z, numbuf+1);
219         }
220         ret = d0_iobuf_write_packet(buf, numbuf, count + 1);
221         d0_unlockmutex(tempmutex);
222         return ret;
223 }
224
225 d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum)
226 {
227         size_t count = sizeof(numbuf);
228
229         d0_lockmutex(tempmutex);
230         if(!d0_iobuf_read_packet(buf, numbuf, &count))
231         {
232                 d0_unlockmutex(tempmutex);
233                 return NULL;
234         }
235         if(count < 1)
236         {
237                 d0_unlockmutex(tempmutex);
238                 return NULL;
239         }
240         if(!bignum)
241                 bignum = d0_bignum_new();
242         if(!bignum)
243         {
244                 d0_unlockmutex(tempmutex);
245                 return NULL;
246         }
247         if(numbuf[0] & 3) // nonzero
248         {
249                 BN_bin2bn(numbuf+1, count-1, &bignum->z);
250                 if(numbuf[0] & 2) // negative
251                         BN_set_negative(&bignum->z, 1);
252         }
253         else // zero
254         {
255                 BN_zero(&bignum->z);
256         }
257         d0_unlockmutex(tempmutex);
258         return bignum;
259 }
260
261 ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize)
262 {
263         size_t count;
264         count = BN_num_bytes(&bignum->z);
265         if(count > bufsize)
266                 return -1;
267         if(bufsize > count)
268         {
269                 // pad from left (big endian numbers!)
270                 memset(buf, 0, bufsize - count);
271                 buf += bufsize - count;
272         }
273         BN_bn2bin(&bignum->z, buf);
274         return bufsize;
275 }
276
277 d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize)
278 {
279         size_t count;
280         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
281         BN_bin2bn(buf, bufsize, &bignum->z);
282         return bignum;
283 }
284
285 d0_bignum_t *d0_bignum_new(void)
286 {
287         d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t));
288         BN_init(&b->z);
289         return b;
290 }
291
292 void d0_bignum_free(d0_bignum_t *a)
293 {
294         BN_free(&a->z);
295         d0_free(a);
296 }
297
298 void d0_bignum_init(d0_bignum_t *b)
299 {
300         BN_init(&b->z);
301 }
302
303 void d0_bignum_clear(d0_bignum_t *a)
304 {
305         BN_free(&a->z);
306 }
307
308 size_t d0_bignum_size(const d0_bignum_t *r)
309 {
310         return BN_num_bits(&r->z);
311 }
312
313 int d0_bignum_cmp(const d0_bignum_t *a, const d0_bignum_t *b)
314 {
315         return BN_cmp(&a->z, &b->z);
316 }
317
318 d0_bignum_t *d0_bignum_rand_range(d0_bignum_t *r, const d0_bignum_t *min, const d0_bignum_t *max)
319 {
320         if(!r) r = d0_bignum_new(); if(!r) return NULL;
321         d0_lockmutex(tempmutex);
322         BN_sub(&temp.z, &max->z, &min->z);
323         BN_rand_range(&r->z, &temp.z);
324         d0_unlockmutex(tempmutex);
325         BN_add(&r->z, &r->z, &min->z);
326         return r;
327 }
328
329 d0_bignum_t *d0_bignum_rand_bit_atmost(d0_bignum_t *r, size_t n)
330 {
331         if(!r) r = d0_bignum_new(); if(!r) return NULL;
332         BN_rand(&r->z, n, -1, 0);
333         return r;
334 }
335
336 d0_bignum_t *d0_bignum_rand_bit_exact(d0_bignum_t *r, size_t n)
337 {
338         if(!r) r = d0_bignum_new(); if(!r) return NULL;
339         BN_rand(&r->z, n, 0, 0);
340         return r;
341 }
342
343 d0_bignum_t *d0_bignum_zero(d0_bignum_t *r)
344 {
345         if(!r) r = d0_bignum_new(); if(!r) return NULL;
346         BN_zero(&r->z);
347         return r;
348 }
349
350 d0_bignum_t *d0_bignum_one(d0_bignum_t *r)
351 {
352         if(!r) r = d0_bignum_new(); if(!r) return NULL;
353         BN_one(&r->z);
354         return r;
355 }
356
357 d0_bignum_t *d0_bignum_int(d0_bignum_t *r, int n)
358 {
359         if(!r) r = d0_bignum_new(); if(!r) return NULL;
360         BN_set_word(&r->z, n);
361         return r;
362 }
363
364 d0_bignum_t *d0_bignum_mov(d0_bignum_t *r, const d0_bignum_t *a)
365 {
366         if(r == a)
367                 return r; // trivial
368         if(!r) r = d0_bignum_new(); if(!r) return NULL;
369         BN_copy(&r->z, &a->z);
370         return r;
371 }
372
373 d0_bignum_t *d0_bignum_neg(d0_bignum_t *r, const d0_bignum_t *a)
374 {
375         if(!r) r = d0_bignum_new(); if(!r) return NULL;
376         if(r != a)
377                 BN_copy(&r->z, &a->z);
378         BN_set_negative(&r->z, !BN_is_negative(&r->z));
379         return r;
380 }
381
382 d0_bignum_t *d0_bignum_shl(d0_bignum_t *r, const d0_bignum_t *a, ssize_t n)
383 {
384         if(!r) r = d0_bignum_new(); if(!r) return NULL;
385         if(n > 0)
386                 BN_lshift(&r->z, &a->z, n);
387         else if(n < 0)
388                 BN_rshift(&r->z, &a->z, -n);
389         else if(r != a)
390                 BN_copy(&r->z, &a->z);
391         return r;
392 }
393
394 d0_bignum_t *d0_bignum_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
395 {
396         if(!r) r = d0_bignum_new(); if(!r) return NULL;
397         BN_add(&r->z, &a->z, &b->z);
398         return r;
399 }
400
401 d0_bignum_t *d0_bignum_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
402 {
403         if(!r) r = d0_bignum_new(); if(!r) return NULL;
404         BN_sub(&r->z, &a->z, &b->z);
405         return r;
406 }
407
408 d0_bignum_t *d0_bignum_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
409 {
410         if(!r) r = d0_bignum_new(); if(!r) return NULL;
411         d0_lockmutex(tempmutex);
412         BN_mul(&r->z, &a->z, &b->z, ctx);
413         d0_unlockmutex(tempmutex);
414         return r;
415 }
416
417 d0_bignum_t *d0_bignum_divmod(d0_bignum_t *q, d0_bignum_t *m, const d0_bignum_t *a, const d0_bignum_t *b)
418 {
419         if(!q && !m)
420                 m = d0_bignum_new();
421         d0_lockmutex(tempmutex);
422         if(q)
423         {
424                 if(m)
425                         BN_div(&q->z, &m->z, &a->z, &b->z, ctx);
426                 else
427                         BN_div(&q->z, NULL, &a->z, &b->z, ctx);
428                 assert(!"I know this code is broken (rounds towards zero), need handle negative correctly");
429         }
430         else
431                 BN_nnmod(&m->z, &a->z, &b->z, ctx);
432         d0_unlockmutex(tempmutex);
433         if(m)
434                 return m;
435         else
436                 return q;
437 }
438
439 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)
440 {
441         if(!r) r = d0_bignum_new(); if(!r) return NULL;
442         d0_lockmutex(tempmutex);
443         BN_mod_add(&r->z, &a->z, &b->z, &m->z, ctx);
444         d0_unlockmutex(tempmutex);
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         d0_lockmutex(tempmutex);
452         BN_mod_sub(&r->z, &a->z, &b->z, &m->z, ctx);
453         d0_unlockmutex(tempmutex);
454         return r;
455 }
456
457 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)
458 {
459         if(!r) r = d0_bignum_new(); if(!r) return NULL;
460         d0_lockmutex(tempmutex);
461         BN_mod_mul(&r->z, &a->z, &b->z, &m->z, ctx);
462         d0_unlockmutex(tempmutex);
463         return r;
464 }
465
466 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)
467 {
468         if(!r) r = d0_bignum_new(); if(!r) return NULL;
469         d0_lockmutex(tempmutex);
470         BN_mod_exp(&r->z, &a->z, &b->z, &m->z, ctx);
471         d0_unlockmutex(tempmutex);
472         return r;
473 }
474
475 D0_BOOL d0_bignum_mod_inv(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *m)
476 {
477         // here, r MUST be set, as otherwise we cannot return error state!
478         int ret;
479         d0_lockmutex(tempmutex);
480         ret = !!BN_mod_inverse(&r->z, &a->z, &m->z, ctx);
481         d0_unlockmutex(tempmutex);
482         return ret;
483 }
484
485 int d0_bignum_isprime(const d0_bignum_t *r, int param)
486 {
487         int ret;
488         d0_lockmutex(tempmutex);
489         if(param <= 0)
490                 ret = BN_is_prime_fasttest(&r->z, 1, NULL, ctx, NULL, 1);
491         else
492                 ret = BN_is_prime(&r->z, param, NULL, ctx, NULL);
493         d0_unlockmutex(tempmutex);
494         return ret;
495 }
496
497 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)
498 {
499         if(!r) r = d0_bignum_new(); if(!r) return NULL;
500         if(s)
501                 assert(!"Extended gcd not implemented");
502         else if(t)
503                 assert(!"Extended gcd not implemented");
504         else
505         {
506                 d0_lockmutex(tempmutex);
507                 BN_gcd(&r->z, &a->z, &b->z, ctx);
508                 d0_unlockmutex(tempmutex);
509         }
510         return r;
511 }
512
513 char *d0_bignum_tostring(const d0_bignum_t *x, unsigned int base)
514 {
515         char *s = NULL;
516         char *s2;
517         size_t n;
518         if(base == 10)
519                 s = BN_bn2dec(&x->z);
520         else if(base == 16)
521                 s = BN_bn2hex(&x->z);
522         else
523                 assert(!"Other bases not implemented");
524         n = strlen(s) + 1;
525         s2 = d0_malloc(n);
526         memcpy(s2, s, n);
527         OPENSSL_free(s);
528         return s2;
529 }