libtommath/mp_pack.c

70 lines
1.7 KiB
C
Raw Normal View History

#include "tommath_private.h"
#ifdef MP_PACK_C
2019-04-07 13:29:11 +00:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
2013-01-22 20:29:12 +00:00
/* based on gmp's mpz_export.
* see http://gmplib.org/manual/Integer-Import-and-Export.html
*/
mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
mp_endian endian, size_t nails, const mp_int *op)
2017-08-30 17:07:12 +00:00
{
2019-05-19 15:16:13 +00:00
mp_err err;
size_t odd_nails, nail_bytes, i, j, count;
2019-10-29 07:44:51 +00:00
uint8_t odd_nail_mask;
2017-08-30 03:52:16 +00:00
mp_int t;
count = mp_pack_count(op, nails, size);
if (count > maxcount) {
2019-10-08 19:47:57 +00:00
return MP_BUF;
}
2019-05-19 15:16:13 +00:00
if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
return err;
2017-08-30 03:52:16 +00:00
}
if (endian == MP_NATIVE_ENDIAN) {
MP_GET_ENDIANNESS(endian);
2017-08-30 03:52:16 +00:00
}
2017-10-15 17:57:12 +00:00
odd_nails = (nails % 8u);
2017-08-30 03:52:16 +00:00
odd_nail_mask = 0xff;
for (i = 0u; i < odd_nails; ++i) {
2019-10-29 07:44:51 +00:00
odd_nail_mask ^= (uint8_t)(1u << (7u - i));
2017-08-30 03:52:16 +00:00
}
2017-10-15 17:57:12 +00:00
nail_bytes = nails / 8u;
2017-08-30 03:52:16 +00:00
for (i = 0u; i < count; ++i) {
for (j = 0u; j < size; ++j) {
2019-10-29 07:44:51 +00:00
uint8_t *byte = (uint8_t *)rop +
(((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
2017-08-30 03:52:16 +00:00
if (j >= (size - nail_bytes)) {
*byte = 0;
continue;
}
2019-10-29 07:44:51 +00:00
*byte = (uint8_t)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
2017-08-30 03:52:16 +00:00
2019-05-19 15:16:13 +00:00
if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
2019-05-29 10:23:08 +00:00
goto LBL_ERR;
2017-08-30 03:52:16 +00:00
}
2017-08-30 03:52:16 +00:00
}
}
if (written != NULL) {
*written = count;
2017-08-30 03:52:16 +00:00
}
2019-05-29 10:23:08 +00:00
err = MP_OKAY;
2017-08-30 03:52:16 +00:00
2019-05-29 10:23:08 +00:00
LBL_ERR:
mp_clear(&t);
return err;
2013-01-22 20:29:12 +00:00
}
#endif