]> git.ipfire.org Git - people/ms/strongswan.git/blob - programs/pluto/mp_defs.c
- import of strongswan-2.7.0
[people/ms/strongswan.git] / programs / pluto / mp_defs.c
1 /* some multiprecision utilities
2 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 *
14 * RCSID $Id: mp_defs.c,v 1.1 2006/01/05 12:37:11 as Exp $
15 */
16
17 #include <freeswan.h>
18
19 #include "constants.h"
20 #include "defs.h"
21 #include "mp_defs.h"
22 #include "log.h"
23
24 /* Convert MP_INT to network form (binary octets, big-endian).
25 * We do the malloc; caller must eventually do free.
26 */
27 chunk_t
28 mpz_to_n(const MP_INT *mp, size_t bytes)
29 {
30 chunk_t r;
31 MP_INT temp1, temp2;
32 int i;
33
34 r.len = bytes;
35 r.ptr = alloc_bytes(r.len, "host representation of large integer");
36
37 mpz_init(&temp1);
38 mpz_init(&temp2);
39
40 mpz_set(&temp1, mp);
41
42 for (i = r.len-1; i >= 0; i--)
43 {
44 r.ptr[i] = mpz_mdivmod_ui(&temp2, NULL, &temp1, 1 << BITS_PER_BYTE);
45 mpz_set(&temp1, &temp2);
46 }
47
48 passert(mpz_sgn(&temp1) == 0); /* we must have done all the bits */
49 mpz_clear(&temp1);
50 mpz_clear(&temp2);
51
52 return r;
53 }
54
55 /* Convert network form (binary bytes, big-endian) to MP_INT.
56 * The *mp must not be previously mpz_inited.
57 */
58 void
59 n_to_mpz(MP_INT *mp, const u_char *nbytes, size_t nlen)
60 {
61 size_t i;
62
63 mpz_init_set_ui(mp, 0);
64
65 for (i = 0; i != nlen; i++)
66 {
67 mpz_mul_ui(mp, mp, 1 << BITS_PER_BYTE);
68 mpz_add_ui(mp, mp, nbytes[i]);
69 }
70 }