Path: blob/main/contrib/bearssl/src/int/i15_decred.c
39483 views
/*1* Copyright (c) 2017 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "inner.h"2526/* see inner.h */27void28br_i15_decode_reduce(uint16_t *x,29const void *src, size_t len, const uint16_t *m)30{31uint32_t m_ebitlen, m_rbitlen;32size_t mblen, k;33const unsigned char *buf;34uint32_t acc;35int acc_len;3637/*38* Get the encoded bit length.39*/40m_ebitlen = m[0];4142/*43* Special case for an invalid (null) modulus.44*/45if (m_ebitlen == 0) {46x[0] = 0;47return;48}4950/*51* Clear the destination.52*/53br_i15_zero(x, m_ebitlen);5455/*56* First decode directly as many bytes as possible. This requires57* computing the actual bit length.58*/59m_rbitlen = m_ebitlen >> 4;60m_rbitlen = (m_ebitlen & 15) + (m_rbitlen << 4) - m_rbitlen;61mblen = (m_rbitlen + 7) >> 3;62k = mblen - 1;63if (k >= len) {64br_i15_decode(x, src, len);65x[0] = m_ebitlen;66return;67}68buf = src;69br_i15_decode(x, buf, k);70x[0] = m_ebitlen;7172/*73* Input remaining bytes, using 15-bit words.74*/75acc = 0;76acc_len = 0;77while (k < len) {78uint32_t v;7980v = buf[k ++];81acc = (acc << 8) | v;82acc_len += 8;83if (acc_len >= 15) {84br_i15_muladd_small(x, acc >> (acc_len - 15), m);85acc_len -= 15;86acc &= ~((uint32_t)-1 << acc_len);87}88}8990/*91* We may have some bits accumulated. We then perform a shift to92* be able to inject these bits as a full 15-bit word.93*/94if (acc_len != 0) {95acc = (acc | (x[1] << acc_len)) & 0x7FFF;96br_i15_rshift(x, 15 - acc_len);97br_i15_muladd_small(x, acc, m);98}99}100101102