bn_mp_to_ubin.c 877 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_TO_UBIN_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* store in unsigned [big endian] format */
  6. mp_err mp_to_ubin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
  7. {
  8. size_t x, count;
  9. mp_err err;
  10. mp_int t;
  11. count = mp_ubin_size(a);
  12. if (count > maxlen) {
  13. return MP_BUF;
  14. }
  15. if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
  16. return err;
  17. }
  18. for (x = count; x --> 0u;) {
  19. #ifndef MP_8BIT
  20. buf[x] = (unsigned char)(t.dp[0] & 255u);
  21. #else
  22. buf[x] = (unsigned char)(t.dp[0] | ((t.dp[1] & 1u) << 7));
  23. #endif
  24. if ((err = mp_div_2d(&t, 8, &t, NULL)) != MP_OKAY) {
  25. goto LBL_ERR;
  26. }
  27. }
  28. if (written != NULL) {
  29. *written = count;
  30. }
  31. LBL_ERR:
  32. mp_clear(&t);
  33. return err;
  34. }
  35. #endif