X-Git-Url: http://de.git.xonotic.org/?p=xonotic%2Fd0_blind_id.git;a=blobdiff_plain;f=d0_bignum-gmp.c;h=6a2f703e2d69796903fd198d95e2de6f25bfd05e;hp=a66096dff4b910835e52ae3b9ac1131030a7653f;hb=587bbd752e2037d8c1488a51d99c99f29a660f0d;hpb=698fe0ac106c840671df6668946135e7c8ef4963 diff --git a/d0_bignum-gmp.c b/d0_bignum-gmp.c index a66096d..6a2f703 100644 --- a/d0_bignum-gmp.c +++ b/d0_bignum-gmp.c @@ -20,6 +20,8 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "d0_bignum.h" #include +#include +#include struct d0_bignum_s { @@ -31,13 +33,15 @@ static d0_bignum_t temp; #include #include -void d0_bignum_INITIALIZE() +void d0_bignum_INITIALIZE(void) { FILE *f; d0_bignum_init(&temp); gmp_randinit_mt(RANDSTATE); gmp_randseed_ui(RANDSTATE, time(NULL)); - f = fopen("/dev/random", "rb"); + f = fopen("/dev/urandom", "rb"); + if(!f) + f = fopen("/dev/random", "rb"); if(f) { unsigned char buf[256]; @@ -51,7 +55,7 @@ void d0_bignum_INITIALIZE() } } -void d0_bignum_SHUTDOWN() +void d0_bignum_SHUTDOWN(void) { d0_bignum_clear(&temp); gmp_randclear(RANDSTATE); @@ -94,7 +98,55 @@ d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum) return bignum; } -d0_bignum_t *d0_bignum_new() +ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize) +{ + size_t count; + count = (mpz_sizeinbase(bignum->z, 2) + 7) / 8; + if(count > bufsize) + return -1; + if(bufsize > count) + { + // pad from left (big endian numbers!) + memset(buf, 0, bufsize - count); + buf += bufsize - count; + } + bufsize = count; + mpz_export(buf, &bufsize, 1, 1, 0, 0, bignum->z); + if(bufsize > count) + { + // REALLY BAD + // mpz_sizeinbase lied to us + // buffer overflow + // there is no sane way whatsoever to handle this + abort(); + } + if(bufsize < count) + { + // BAD + // mpz_sizeinbase lied to us + // move the number + if(bufsize == 0) + { + memset(buf, 0, count); + } + else + { + memmove(buf + count - bufsize, buf, bufsize); + memset(buf, 0, count - bufsize); + } + } + return bufsize; +} + +d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize) +{ + size_t count; + if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL; + mpz_import(bignum->z, bufsize, 1, 1, 0, 0, buf); + return bignum; +} + +d0_bignum_t *d0_bignum_new(void) { d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t)); mpz_init(b->z);