summaryrefslogtreecommitdiff
path: root/src/pluto/mp_defs.c
blob: 7ad8967512b0196639312c3d95f1e807519abeb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* some multiprecision utilities
 * Copyright (C) 1998-2001  D. Hugh Redelmeier.
 *
 * 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.  See <http://www.fsf.org/copyleft/gpl.txt>.
 *
 * 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.
 *
 * RCSID $Id: mp_defs.c,v 1.1 2006/01/05 12:37:11 as Exp $
 */

#include <freeswan.h>

#include "constants.h"
#include "defs.h"
#include "mp_defs.h"
#include "log.h"

/* Convert MP_INT to network form (binary octets, big-endian).
 * We do the malloc; caller must eventually do free.
 */
chunk_t
mpz_to_n(const MP_INT *mp, size_t bytes)
{
    chunk_t r;
    MP_INT temp1, temp2;
    int i;

    r.len = bytes;
    r.ptr = alloc_bytes(r.len, "host representation of large integer");

    mpz_init(&temp1);
    mpz_init(&temp2);

    mpz_set(&temp1, mp);

    for (i = r.len-1; i >= 0; i--)
    {
	r.ptr[i] = mpz_mdivmod_ui(&temp2, NULL, &temp1, 1 << BITS_PER_BYTE);
	mpz_set(&temp1, &temp2);
    }

    passert(mpz_sgn(&temp1) == 0);	/* we must have done all the bits */
    mpz_clear(&temp1);
    mpz_clear(&temp2);

    return r;
}

/* Convert network form (binary bytes, big-endian) to MP_INT.
 * The *mp must not be previously mpz_inited.
 */
void
n_to_mpz(MP_INT *mp, const u_char *nbytes, size_t nlen)
{
    size_t i;

    mpz_init_set_ui(mp, 0);

    for (i = 0; i != nlen; i++)
    {
	mpz_mul_ui(mp, mp, 1 << BITS_PER_BYTE);
	mpz_add_ui(mp, mp, nbytes[i]);
    }
}