d9aff6b16b021b5762a31d3885c90c44b843028c
[crypto.git] / lib / silcmath / mpbin.c
1 /*
2
3   mpbin.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2000 - 2005 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silccrypto.h"
21
22 /* Encodes MP integer into binary data. Returns allocated data that
23    must be free'd by the caller. If `len' is provided the destination
24    buffer is allocated that large. If zero then the size is approximated. */
25
26 unsigned char *silc_mp_mp2bin(SilcMPInt *val, SilcUInt32 len,
27                               SilcUInt32 *ret_len)
28 {
29   SilcUInt32 size;
30   unsigned char *ret;
31
32   size = (len ? len : ((silc_mp_sizeinbase(val, 2) + 7) / 8));
33   ret = silc_calloc(size, sizeof(*ret));
34   if (!ret)
35     return NULL;
36
37   silc_mp_mp2bin_noalloc(val, ret, size);
38
39   if (ret_len)
40     *ret_len = size;
41
42   return ret;
43 }
44
45 /* Samve as above but does not allocate any memory.  The encoded data is
46    returned into `dst' and it's length to the `ret_len'. */
47
48 void silc_mp_mp2bin_noalloc(SilcMPInt *val, unsigned char *dst,
49                             SilcUInt32 dst_len)
50 {
51   int i;
52   SilcUInt32 size = dst_len;
53   SilcMPInt tmp;
54
55   silc_mp_init(&tmp);
56   silc_mp_set(&tmp, val);
57
58   for (i = size; i > 0; i--) {
59     dst[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
60     silc_mp_div_2exp(&tmp, &tmp, 8);
61   }
62
63   silc_mp_uninit(&tmp);
64 }
65
66 /* Decodes binary data into MP integer. The integer sent as argument
67    must be initialized. */
68
69 void silc_mp_bin2mp(unsigned char *data, SilcUInt32 len, SilcMPInt *ret)
70 {
71   int i;
72
73   silc_mp_set_ui(ret, 0);
74
75   for (i = 0; i < len; i++) {
76     silc_mp_mul_2exp(ret, ret, 8);
77     silc_mp_add_ui(ret, ret, data[i]);
78   }
79 }