bn_mp_unpack.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. /* based on gmp's mpz_import.
  6. * see http://gmplib.org/manual/Integer-Import-and-Export.html
  7. */
  8. mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size,
  9. mp_endian endian, size_t nails, const void *op)
  10. {
  11. mp_err err;
  12. size_t odd_nails, nail_bytes, i, j;
  13. unsigned char odd_nail_mask;
  14. mp_zero(rop);
  15. if (endian == MP_NATIVE_ENDIAN) {
  16. MP_GET_ENDIANNESS(endian);
  17. }
  18. odd_nails = (nails % 8u);
  19. odd_nail_mask = 0xff;
  20. for (i = 0; i < odd_nails; ++i) {
  21. odd_nail_mask ^= (unsigned char)(1u << (7u - i));
  22. }
  23. nail_bytes = nails / 8u;
  24. for (i = 0; i < count; ++i) {
  25. for (j = 0; j < (size - nail_bytes); ++j) {
  26. unsigned char byte = *((const unsigned char *)op +
  27. (((order == MP_MSB_FIRST) ? i : ((count - 1u) - i)) * size) +
  28. ((endian == MP_BIG_ENDIAN) ? (j + nail_bytes) : (((size - 1u) - j) - nail_bytes)));
  29. if ((err = mp_mul_2d(rop, (j == 0u) ? (int)(8u - odd_nails) : 8, rop)) != MP_OKAY) {
  30. return err;
  31. }
  32. rop->dp[0] |= (j == 0u) ? (mp_digit)(byte & odd_nail_mask) : (mp_digit)byte;
  33. rop->used += 1;
  34. }
  35. }
  36. mp_clamp(rop);
  37. return MP_OKAY;
  38. }
  39. #endif