1 /* Copyright (c) 2023, Google LLC
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 <openssl/base.h>
16
17 #include <assert.h>
18
19 #include "./spx_util.h"
20
spx_uint64_to_len_bytes(uint8_t * output,size_t out_len,uint64_t input)21 void spx_uint64_to_len_bytes(uint8_t *output, size_t out_len, uint64_t input) {
22 for (size_t i = out_len; i > 0; --i) {
23 output[i - 1] = input & 0xff;
24 input = input >> 8;
25 }
26 }
27
spx_to_uint64(const uint8_t * input,size_t input_len)28 uint64_t spx_to_uint64(const uint8_t *input, size_t input_len) {
29 uint64_t tmp = 0;
30 for (size_t i = 0; i < input_len; ++i) {
31 tmp = 256 * tmp + input[i];
32 }
33 return tmp;
34 }
35
spx_base_b(uint32_t * output,size_t out_len,const uint8_t * input,unsigned int log2_b)36 void spx_base_b(uint32_t *output, size_t out_len, const uint8_t *input,
37 unsigned int log2_b) {
38 int in = 0;
39 uint32_t out = 0;
40 uint32_t bits = 0;
41 uint32_t total = 0;
42 uint32_t base = UINT32_C(1) << log2_b;
43
44 for (out = 0; out < out_len; ++out) {
45 while (bits < log2_b) {
46 total = (total << 8) + input[in];
47 in++;
48 bits = bits + 8;
49 }
50 bits -= log2_b;
51 output[out] = (total >> bits) % base;
52 }
53 }
54