Path: blob/main/contrib/bearssl/src/int/i32_decred.c
39488 views
/*1* Copyright (c) 2016 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_i32_decode_reduce(uint32_t *x,29const void *src, size_t len, const uint32_t *m)30{31uint32_t m_bitlen;32size_t mblen, k, q;33const unsigned char *buf;3435m_bitlen = m[0];3637/*38* Special case for an invalid modulus.39*/40if (m_bitlen == 0) {41x[0] = 0;42return;43}4445/*46* Clear the destination.47*/48br_i32_zero(x, m_bitlen);4950/*51* First decode directly as many bytes as possible without52* reduction, taking care to leave a number of bytes which53* is a multiple of 4.54*/55mblen = (m_bitlen + 7) >> 3;56k = mblen - 1;5758/*59* Up to k bytes can be safely decoded.60*/61if (k >= len) {62br_i32_decode(x, src, len);63x[0] = m_bitlen;64return;65}6667/*68* We want to first inject some bytes with direct decoding,69* then extra bytes by whole 32-bit words. First compute70* the size that should be injected that way.71*/72buf = src;73q = (len - k + 3) & ~(size_t)3;7475/*76* It may happen that this is more than what we already have77* (by at most 3 bytes). Such a case may happen only with78* a very short modulus. In that case, we must process the first79* bytes "manually".80*/81if (q > len) {82int i;83uint32_t w;8485w = 0;86for (i = 0; i < 4; i ++) {87w <<= 8;88if (q <= len) {89w |= buf[len - q];90}91q --;92}93br_i32_muladd_small(x, w, m);94} else {95br_i32_decode(x, buf, len - q);96x[0] = m_bitlen;97}9899/*100* At that point, we have exactly q bytes to inject, and q is101* a multiple of 4.102*/103for (k = len - q; k < len; k += 4) {104br_i32_muladd_small(x, br_dec32be(buf + k), m);105}106}107108109