bn_mp_pack.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. /* based on gmp's mpz_export.
  6. * see http://gmplib.org/manual/Integer-Import-and-Export.html
  7. */
  8. mp_err mp_pack(void *rop, size_t maxcount, size_t *written, mp_order order, size_t size,
  9. mp_endian endian, size_t nails, const mp_int *op)
  10. {
  11. mp_err err;
  12. size_t odd_nails, nail_bytes, i, j, count;
  13. unsigned char odd_nail_mask;
  14. mp_int t;
  15. count = mp_pack_count(op, nails, size);
  16. if (count > maxcount) {
  17. return MP_BUF;
  18. }
  19. if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
  20. return err;
  21. }
  22. if (endian == MP_NATIVE_ENDIAN) {
  23. MP_GET_ENDIANNESS(endian);
  24. }
  25. odd_nails = (nails % 8u);
  26. odd_nail_mask = 0xff;
  27. for (i = 0u; i < odd_nails; ++i) {
  28. odd_nail_mask ^= (unsigned char)(1u << (7u - i));
  29. }
  30. nail_bytes = nails / 8u;
  31. for (i = 0u; i < count; ++i) {
  32. for (j = 0u; j < size; ++j) {
  33. unsigned char *byte = (unsigned char *)rop +
  34. (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
  35. ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
  36. if (j >= (size - nail_bytes)) {
  37. *byte = 0;
  38. continue;
  39. }
  40. *byte = (unsigned char)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
  41. if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
  42. goto LBL_ERR;
  43. }
  44. }
  45. }
  46. if (written != NULL) {
  47. *written = count;
  48. }
  49. err = MP_OKAY;
  50. LBL_ERR:
  51. mp_clear(&t);
  52. return err;
  53. }
  54. #endif