New SILC PKCS API, enabling support for other public keys/certs.
[silc.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 /* $Id$ */
20
21 #include "silc.h"
22
23 /* Encodes MP integer into binary data. Returns allocated data that
24    must be free'd by the caller. If `len' is provided the destination
25    buffer is allocated that large. If zero then the size is approximated. */
26
27 unsigned char *silc_mp_mp2bin(SilcMPInt *val, SilcUInt32 len,
28                               SilcUInt32 *ret_len)
29 {
30   int i;
31   SilcUInt32 size;
32   unsigned char *ret;
33   SilcMPInt tmp;
34
35   size = (len ? len : ((silc_mp_sizeinbase(val, 2) + 7) / 8));
36   ret = silc_calloc(size, sizeof(*ret));
37   if (!ret)
38     return NULL;
39
40   silc_mp_init(&tmp);
41   silc_mp_set(&tmp, val);
42
43   for (i = size; i > 0; i--) {
44     ret[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
45     silc_mp_div_2exp(&tmp, &tmp, 8);
46   }
47
48   silc_mp_uninit(&tmp);
49
50   if (ret_len)
51     *ret_len = size;
52
53   return ret;
54 }
55
56 /* Samve as above but does not allocate any memory.  The encoded data is
57    returned into `dst' and it's length to the `ret_len'. */
58
59 void silc_mp_mp2bin_noalloc(SilcMPInt *val, unsigned char *dst,
60                             SilcUInt32 dst_len)
61 {
62   int i;
63   SilcUInt32 size = dst_len;
64   SilcMPInt tmp;
65
66   silc_mp_init(&tmp);
67   silc_mp_set(&tmp, val);
68
69   for (i = size; i > 0; i--) {
70     dst[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
71     silc_mp_div_2exp(&tmp, &tmp, 8);
72   }
73
74   silc_mp_uninit(&tmp);
75 }
76
77 /* Decodes binary data into MP integer. The integer sent as argument
78    must be initialized. */
79
80 void silc_mp_bin2mp(unsigned char *data, SilcUInt32 len, SilcMPInt *ret)
81 {
82   int i;
83
84   silc_mp_set_ui(ret, 0);
85
86   for (i = 0; i < len; i++) {
87     silc_mp_mul_2exp(ret, ret, 8);
88     silc_mp_add_ui(ret, ret, data[i]);
89   }
90 }