Path: blob/main/contrib/bearssl/src/rsa/rsa_i31_pub.c
39483 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/*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 + 30) / 31)))3132/* see bearssl_rsa.h */33uint32_t34br_rsa_i31_public(unsigned char *x, size_t xlen,35const br_rsa_public_key *pk)36{37const unsigned char *n;38size_t nlen;39uint32_t tmp[1 + TLEN];40uint32_t *m, *a, *t;41size_t fwlen;42long z;43uint32_t m0i, r;4445/*46* Get the actual length of the modulus, and see if it fits within47* our stack buffer. We also check that the length of x[] is valid.48*/49n = pk->n;50nlen = pk->nlen;51while (nlen > 0 && *n == 0) {52n ++;53nlen --;54}55if (nlen == 0 || nlen > (BR_MAX_RSA_SIZE >> 3) || xlen != nlen) {56return 0;57}58z = (long)nlen << 3;59fwlen = 1;60while (z > 0) {61z -= 31;62fwlen ++;63}64/*65* Round up length to an even number.66*/67fwlen += (fwlen & 1);6869/*70* The modulus gets decoded into m[].71* The value to exponentiate goes into a[].72* The temporaries for modular exponentiation are in t[].73*/74m = tmp;75a = m + fwlen;76t = m + 2 * fwlen;7778/*79* Decode the modulus.80*/81br_i31_decode(m, n, nlen);82m0i = br_i31_ninv31(m[1]);8384/*85* Note: if m[] is even, then m0i == 0. Otherwise, m0i must be86* an odd integer.87*/88r = m0i & 1;8990/*91* Decode x[] into a[]; we also check that its value is proper.92*/93r &= br_i31_decode_mod(a, x, xlen, m);9495/*96* Compute the modular exponentiation.97*/98br_i31_modpow_opt(a, pk->e, pk->elen, m, m0i, t, TLEN - 2 * fwlen);99100/*101* Encode the result.102*/103br_i31_encode(x, xlen, a);104return r;105}106107108