Path: blob/main/contrib/bearssl/src/rsa/rsa_i15_pub.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/*27* As a strict minimum, we need four buffers that can hold a28* modular integer.29*/30#define TLEN (4 * (2 + ((BR_MAX_RSA_SIZE + 14) / 15)))3132/* see bearssl_rsa.h */33uint32_t34br_rsa_i15_public(unsigned char *x, size_t xlen,35const br_rsa_public_key *pk)36{37const unsigned char *n;38size_t nlen;39uint16_t tmp[1 + TLEN];40uint16_t *m, *a, *t;41size_t fwlen;42long z;43uint16_t m0i;44uint32_t r;4546/*47* Get the actual length of the modulus, and see if it fits within48* our stack buffer. We also check that the length of x[] is valid.49*/50n = pk->n;51nlen = pk->nlen;52while (nlen > 0 && *n == 0) {53n ++;54nlen --;55}56if (nlen == 0 || nlen > (BR_MAX_RSA_SIZE >> 3) || xlen != nlen) {57return 0;58}59z = (long)nlen << 3;60fwlen = 1;61while (z > 0) {62z -= 15;63fwlen ++;64}65/*66* Round up length to an even number.67*/68fwlen += (fwlen & 1);6970/*71* The modulus gets decoded into m[].72* The value to exponentiate goes into a[].73* The temporaries for modular exponentiations are in t[].74*75* We want the first value word of each integer to be aligned76* on a 32-bit boundary.77*/78m = tmp;79if (((uintptr_t)m & 2) == 0) {80m ++;81}82a = m + fwlen;83t = m + 2 * fwlen;8485/*86* Decode the modulus.87*/88br_i15_decode(m, n, nlen);89m0i = br_i15_ninv15(m[1]);9091/*92* Note: if m[] is even, then m0i == 0. Otherwise, m0i must be93* an odd integer.94*/95r = m0i & 1;9697/*98* Decode x[] into a[]; we also check that its value is proper.99*/100r &= br_i15_decode_mod(a, x, xlen, m);101102/*103* Compute the modular exponentiation.104*/105br_i15_modpow_opt(a, pk->e, pk->elen, m, m0i, t, TLEN - 2 * fwlen);106107/*108* Encode the result.109*/110br_i15_encode(x, xlen, a);111return r;112}113114115