41663337e8b42dcea82518641bf376fe61ca12ff
1 /* some multiprecision utilities
2 * Copyright (C) 1998-2001 D. Hugh Redelmeier.
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>.
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
18 #include <asn1/asn1.h>
20 #include "constants.h"
25 /* Convert MP_INT to network form (binary octets, big-endian).
26 * We do the malloc; caller must eventually do free.
29 mpz_to_n(const MP_INT
*mp
, size_t bytes
)
36 r
.ptr
= malloc(r
.len
);
43 for (i
= r
.len
-1; i
>= 0; i
--)
45 r
.ptr
[i
] = mpz_mdivmod_ui(&temp2
, NULL
, &temp1
, 1 << BITS_PER_BYTE
);
46 mpz_set(&temp1
, &temp2
);
49 passert(mpz_sgn(&temp1
) == 0); /* we must have done all the bits */
56 /* Convert network form (binary bytes, big-endian) to MP_INT.
57 * The *mp must not be previously mpz_inited.
60 n_to_mpz(MP_INT
*mp
, const u_char
*nbytes
, size_t nlen
)
64 mpz_init_set_ui(mp
, 0);
66 for (i
= 0; i
!= nlen
; i
++)
68 mpz_mul_ui(mp
, mp
, 1 << BITS_PER_BYTE
);
69 mpz_add_ui(mp
, mp
, nbytes
[i
]);
74 * convert a MP integer into a DER coded ASN.1 object
77 asn1_integer_from_mpz(const mpz_t value
)
79 size_t bits
= mpz_sizeinbase(value
, 2); /* size in bits */
80 size_t size
= 1 + bits
/ BITS_PER_BYTE
; /* size in bytes */
81 chunk_t n
= mpz_to_n(value
, size
);
83 return asn1_wrap(ASN1_INTEGER
, "m", n
);