X-Git-Url: https://git.xonotic.org/?a=blobdiff_plain;f=d0_bignum-gmp.c;h=30d630103d6a026671b42cf98000371ce3e8b443;hb=1e6764b3137ab0e1ecbbe5fdf0108d3c91357489;hp=93bf0f72154d3c5c5da75de81c58344eb7794434;hpb=0fc918f0db9a3fa9a674934eca1926d983a3d6ce;p=xonotic%2Fd0_blind_id.git diff --git a/d0_bignum-gmp.c b/d0_bignum-gmp.c index 93bf0f7..30d6301 100644 --- a/d0_bignum-gmp.c +++ b/d0_bignum-gmp.c @@ -20,6 +20,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "d0_bignum.h" #include +#include struct d0_bignum_s { @@ -37,7 +38,9 @@ void d0_bignum_INITIALIZE(void) 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]; @@ -94,6 +97,54 @@ d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum) return bignum; } +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));