Line data Source code
1 : #include "tommath_private.h"
2 : #ifdef BN_MP_UNPACK_C
3 : /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 : /* SPDX-License-Identifier: Unlicense */
5 :
6 : /* based on gmp's mpz_import.
7 : * see http://gmplib.org/manual/Integer-Import-and-Export.html
8 : */
9 0 : mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
10 : mp_endian endian, size_t nails, const void *op)
11 : {
12 : mp_err err;
13 : size_t odd_nails, nail_bytes, i, j;
14 : unsigned char odd_nail_mask;
15 :
16 0 : mp_zero(rop);
17 :
18 0 : if (endian == MP_NATIVE_ENDIAN) {
19 0 : MP_GET_ENDIANNESS(endian);
20 : }
21 :
22 0 : odd_nails = (nails % 8u);
23 0 : odd_nail_mask = 0xff;
24 0 : for (i = 0; i < odd_nails; ++i) {
25 0 : odd_nail_mask ^= (unsigned char)(1u << (7u - i));
26 : }
27 0 : nail_bytes = nails / 8u;
28 :
29 0 : for (i = 0; i < count; ++i) {
30 0 : for (j = 0; j < (size - nail_bytes); ++j) {
31 0 : unsigned char byte = *((const unsigned char *)op +
32 0 : (((order == MP_MSB_FIRST) ? i : ((count - 1u) - i)) * size) +
33 0 : ((endian == MP_BIG_ENDIAN) ? (j + nail_bytes) : (((size - 1u) - j) - nail_bytes)));
34 :
35 0 : if ((err = mp_mul_2d(rop, (j == 0u) ? (int)(8u - odd_nails) : 8, rop)) != MP_OKAY) {
36 0 : return err;
37 : }
38 :
39 0 : rop->dp[0] |= (j == 0u) ? (mp_digit)(byte & odd_nail_mask) : (mp_digit)byte;
40 0 : rop->used += 1;
41 : }
42 : }
43 :
44 0 : mp_clamp(rop);
45 :
46 0 : return MP_OKAY;
47 : }
48 :
49 : #endif
|