comparison libtommath/bn_mp_pack.c @ 1733:d529a52b2f7c coverity coverity

merge coverity from main
author Matt Johnston <matt@ucc.asn.au>
date Fri, 26 Jun 2020 21:07:34 +0800
parents 1051e4eea25a
children
comparison
equal deleted inserted replaced
1643:b59623a64678 1733:d529a52b2f7c
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 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 mp_err err;
13 size_t odd_nails, nail_bytes, i, j, count;
14 unsigned char odd_nail_mask;
15
16 mp_int t;
17
18 count = mp_pack_count(op, nails, size);
19
20 if (count > maxcount) {
21 return MP_BUF;
22 }
23
24 if ((err = mp_init_copy(&t, op)) != MP_OKAY) {
25 return err;
26 }
27
28 if (endian == MP_NATIVE_ENDIAN) {
29 MP_GET_ENDIANNESS(endian);
30 }
31
32 odd_nails = (nails % 8u);
33 odd_nail_mask = 0xff;
34 for (i = 0u; i < odd_nails; ++i) {
35 odd_nail_mask ^= (unsigned char)(1u << (7u - i));
36 }
37 nail_bytes = nails / 8u;
38
39 for (i = 0u; i < count; ++i) {
40 for (j = 0u; j < size; ++j) {
41 unsigned char *byte = (unsigned char *)rop +
42 (((order == MP_LSB_FIRST) ? i : ((count - 1u) - i)) * size) +
43 ((endian == MP_LITTLE_ENDIAN) ? j : ((size - 1u) - j));
44
45 if (j >= (size - nail_bytes)) {
46 *byte = 0;
47 continue;
48 }
49
50 *byte = (unsigned char)((j == ((size - nail_bytes) - 1u)) ? (t.dp[0] & odd_nail_mask) : (t.dp[0] & 0xFFuL));
51
52 if ((err = mp_div_2d(&t, (j == ((size - nail_bytes) - 1u)) ? (int)(8u - odd_nails) : 8, &t, NULL)) != MP_OKAY) {
53 goto LBL_ERR;
54 }
55
56 }
57 }
58
59 if (written != NULL) {
60 *written = count;
61 }
62 err = MP_OKAY;
63
64 LBL_ERR:
65 mp_clear(&t);
66 return err;
67 }
68
69 #endif