Line data Source code
1 : #include "tommath_private.h" 2 : #ifdef BN_MP_PACK_C 3 : /* LibTomMath, multiple-precision integer library -- Tom St Denis */ 4 : /* SPDX-License-Identifier: Unlicense */ 5 : 6 : /* based on gmp's mpz_export. 7 : * see http://gmplib.org/manual/Integer-Import-and-Export.html 8 : */ 9 0 : mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size, 10 : mp_endian endian, size_t nails, const mp_int *op) 11 : { 12 0 : mp_err err; 13 0 : size_t odd_nails, nail_bytes, i, j, count; 14 0 : unsigned char odd_nail_mask; 15 : 16 0 : mp_int t; 17 : 18 0 : count = mp_pack_count(op, nails, size); 19 : 20 0 : if (count > maxcount) { 21 0 : return MP_BUF; 22 : } 23 : 24 0 : if ((err = mp_init_copy(&t, op)) != MP_OKAY) { 25 0 : return err; 26 : } 27 : 28 0 : if (endian == MP_NATIVE_ENDIAN) { 29 0 : MP_GET_ENDIANNESS(endian); 30 : } 31 : 32 0 : odd_nails = (nails % 8u); 33 0 : odd_nail_mask = 0xff; 34 0 : for (i = 0u; i < odd_nails; ++i) { 35 0 : odd_nail_mask ^= (unsigned char)(1u << (7u - i)); 36 : } 37 0 : nail_bytes = nails / 8u; 38 : 39 0 : for (i = 0u; i < count; ++i) { 40 0 : for (j = 0u; j < size; ++j) { 41 0 : unsigned char *byte = (unsigned char *)rop + 42 0 : (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) + 43 0 : ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j)); 44 : 45 0 : if (j >= (size - nail_bytes)) { 46 0 : *byte = 0; 47 0 : continue; 48 : } 49 : 50 0 : *byte = (unsigned char)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL)); 51 : 52 0 : if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) { 53 0 : goto LBL_ERR; 54 : } 55 : 56 : } 57 : } 58 : 59 0 : if (written != NULL) { 60 0 : *written = count; 61 : } 62 0 : err = MP_OKAY; 63 : 64 0 : LBL_ERR: 65 0 : mp_clear(&t); 66 0 : return err; 67 : } 68 : 69 : #endif