1 /* Copyright (c) 2014, Intel Corporation.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include "ecp_nistz.h"
16
17 #if defined(__GNUC__)
18 #pragma GCC diagnostic ignored "-Wconversion"
19 #endif
20
21 /* Fills |str| with the bytewise little-endian encoding of |scalar|, where
22 * |scalar| has |num_limbs| limbs. |str| is padded with zeros at the end up
23 * to |str_len| bytes. Actually, |str_len| must be exactly one byte more than
24 * needed to encode |num_limbs| losslessly, so that there is an extra byte at
25 * the end. The extra byte is useful because the caller will be breaking |str|
26 * up into windows of a number of bits (5 or 7) that isn't divisible by 8, and
27 * so it is useful for it to be able to read an extra zero byte. */
gfp_little_endian_bytes_from_scalar(uint8_t str[],size_t str_len,const Limb scalar[],size_t num_limbs)28 void gfp_little_endian_bytes_from_scalar(uint8_t str[], size_t str_len,
29 const Limb scalar[],
30 size_t num_limbs) {
31 debug_assert_nonsecret(str_len == (num_limbs * sizeof(Limb)) + 1);
32
33 size_t i;
34 for (i = 0; i < num_limbs * sizeof(Limb); i += sizeof(Limb)) {
35 Limb d = scalar[i / sizeof(Limb)];
36
37 str[i + 0] = d & 0xff;
38 str[i + 1] = (d >> 8) & 0xff;
39 str[i + 2] = (d >> 16) & 0xff;
40 str[i + 3] = (d >>= 24) & 0xff;
41 if (sizeof(Limb) == 8) {
42 d >>= 8;
43 str[i + 4] = d & 0xff;
44 str[i + 5] = (d >> 8) & 0xff;
45 str[i + 6] = (d >> 16) & 0xff;
46 str[i + 7] = (d >> 24) & 0xff;
47 }
48 }
49 for (; i < str_len; i++) {
50 str[i] = 0;
51 }
52 }
53