3 * bignum operations that are missing from gmp.
6 /* nettle, low-level cryptographics library
8 * Copyright (C) 2001 Niels Möller
10 * The nettle library is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or (at your
13 * option) any later version.
15 * The nettle library is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
18 * License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with the nettle library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
35 /* Two's complement negation means that -x = ~x + 1, ~x = -(x+1),
36 * and we use that x = ~~x = ~(-x-1).
48 /* Including extra sign bit, if needed. Also one byte for zero. */
50 nettle_mpz_sizeinbase_256_s(const mpz_t x
)
53 return 1 + mpz_sizeinbase(x
, 2) / 8;
56 /* We'll output ~~x, so we need as many bits as for ~x */
61 mpz_com(c
, x
); /* Same as c = - x - 1 = |x| + 1 */
62 size
= 1 + mpz_sizeinbase(c
,2) / 8;
70 nettle_mpz_sizeinbase_256_u(const mpz_t x
)
72 return (mpz_sizeinbase(x
,2) + 7) / 8;
76 nettle_mpz_to_octets(unsigned length
, uint8_t *s
,
77 const mpz_t x
, uint8_t sign
)
79 uint8_t *dst
= s
+ length
- 1;
80 unsigned size
= mpz_size(x
);
83 for (i
= 0; i
<size
; i
++)
85 mp_limb_t limb
= mpz_getlimbn(x
, i
);
88 for (j
= 0; length
&& j
< sizeof(mp_limb_t
); j
++)
90 *dst
-- = sign
^ (limb
& 0xff);
97 memset(s
, sign
, length
);
101 nettle_mpz_get_str_256(unsigned length
, uint8_t *s
, const mpz_t x
)
112 assert(nettle_mpz_sizeinbase_256_u(x
) <= length
);
113 nettle_mpz_to_octets(length
, s
, x
, 0);
121 assert(nettle_mpz_sizeinbase_256_u(c
) <= length
);
122 nettle_mpz_to_octets(length
, s
, c
, 0xff);
128 /* Converting from strings */
131 /* Was introduced in GMP-4.1 */
132 # define nettle_mpz_from_octets(x, length, s) \
133 mpz_import((x), (length), 1, 1, 0, 0, (s))
136 nettle_mpz_from_octets(mpz_t x
,
137 unsigned length
, const uint8_t *s
)
143 for (i
= 0; i
< length
; i
++)
145 mpz_mul_2exp(x
, x
, 8);
146 mpz_add_ui(x
, x
, s
[i
]);
152 nettle_mpz_set_str_256_u(mpz_t x
,
153 unsigned length
, const uint8_t *s
)
155 nettle_mpz_from_octets(x
, length
, s
);
159 nettle_mpz_init_set_str_256_u(mpz_t x
,
160 unsigned length
, const uint8_t *s
)
163 nettle_mpz_from_octets(x
, length
, s
);
167 nettle_mpz_set_str_256_s(mpz_t x
,
168 unsigned length
, const uint8_t *s
)
176 nettle_mpz_from_octets(x
, length
, s
);
182 mpz_init_set_ui(t
, 1);
183 mpz_mul_2exp(t
, t
, length
*8);
190 nettle_mpz_init_set_str_256_s(mpz_t x
,
191 unsigned length
, const uint8_t *s
)
194 nettle_mpz_set_str_256_s(x
, length
, s
);