X-Git-Url: http://git.silcnet.org/gitweb/?a=blobdiff_plain;f=lib%2Fsilcmath%2Fmpbin.c;h=02b7e941024cd3f4be9d24101e9402c36accffc6;hb=40f8443d8d3a6577336ee66d18e04d9ac4d956bb;hp=3e8cc6132de94b46626fbd2369aa6d4d9e386148;hpb=3801db8c41948715d6042a80883e30b23a55e22b;p=silc.git diff --git a/lib/silcmath/mpbin.c b/lib/silcmath/mpbin.c index 3e8cc613..02b7e941 100644 --- a/lib/silcmath/mpbin.c +++ b/lib/silcmath/mpbin.c @@ -2,56 +2,80 @@ mpbin.c - Author: Pekka Riikonen + Author: Pekka Riikonen - Copyright (C) 2000 Pekka Riikonen + Copyright (C) 2000 - 2005 Pekka Riikonen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - + the Free Software Foundation; version 2 of the License. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ +/* $Id$ */ -#include "silcincludes.h" +#include "silc.h" /* Encodes MP integer into binary data. Returns allocated data that - must be free'd by the caller. */ + must be free'd by the caller. If `len' is provided the destination + buffer is allocated that large. If zero then the size is approximated. */ -unsigned char *silc_mp_mp2bin(SilcInt *val, unsigned int *ret_len) +unsigned char *silc_mp_mp2bin(SilcMPInt *val, SilcUInt32 len, + SilcUInt32 *ret_len) { int i; - unsigned int size; + SilcUInt32 size; unsigned char *ret; - SilcInt tmp; + SilcMPInt tmp; - size = (silc_mp_sizeinbase(val, 2) + 7) / 8; + size = (len ? len : ((silc_mp_sizeinbase(val, 2) + 7) / 8)); ret = silc_calloc(size, sizeof(*ret)); - silc_mp_init_set(&tmp, val); + silc_mp_init(&tmp); + silc_mp_set(&tmp, val); for (i = size; i > 0; i--) { ret[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff); - silc_mp_fdiv_q_2exp(&tmp, &tmp, 8); + silc_mp_div_2exp(&tmp, &tmp, 8); } - silc_mp_clear(&tmp); + silc_mp_uninit(&tmp); - if (*ret_len) + if (ret_len) *ret_len = size; return ret; } +/* Samve as above but does not allocate any memory. The encoded data is + returned into `dst' and it's length to the `ret_len'. */ + +void silc_mp_mp2bin_noalloc(SilcMPInt *val, unsigned char *dst, + SilcUInt32 dst_len) +{ + int i; + SilcUInt32 size = dst_len; + SilcMPInt tmp; + + silc_mp_init(&tmp); + silc_mp_set(&tmp, val); + + for (i = size; i > 0; i--) { + dst[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff); + silc_mp_div_2exp(&tmp, &tmp, 8); + } + + silc_mp_uninit(&tmp); +} + /* Decodes binary data into MP integer. The integer sent as argument must be initialized. */ -void silc_mp_bin2mp(unsigned char *data, unsigned int len, SilcInt *ret) +void silc_mp_bin2mp(unsigned char *data, SilcUInt32 len, SilcMPInt *ret) { int i;