Path: blob/main/contrib/bearssl/src/rsa/rsa_i15_modulus.c
39488 views
/*1* Copyright (c) 2018 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 bearssl_rsa.h */27size_t28br_rsa_i15_compute_modulus(void *n, const br_rsa_private_key *sk)29{30uint16_t tmp[4 * (((BR_MAX_RSA_SIZE / 2) + 14) / 15) + 5];31uint16_t *t, *p, *q;32const unsigned char *pbuf, *qbuf;33size_t nlen, plen, qlen, tlen;3435/*36* Compute actual byte and lengths for p and q.37*/38pbuf = sk->p;39plen = sk->plen;40while (plen > 0 && *pbuf == 0) {41pbuf ++;42plen --;43}44qbuf = sk->q;45qlen = sk->qlen;46while (qlen > 0 && *qbuf == 0) {47qbuf ++;48qlen --;49}5051t = tmp;52tlen = (sizeof tmp) / (sizeof tmp[0]);5354/*55* Decode p.56*/57if ((15 * tlen) < (plen << 3) + 15) {58return 0;59}60br_i15_decode(t, pbuf, plen);61p = t;62plen = (p[0] + 31) >> 4;63t += plen;64tlen -= plen;6566/*67* Decode q.68*/69if ((15 * tlen) < (qlen << 3) + 15) {70return 0;71}72br_i15_decode(t, qbuf, qlen);73q = t;74qlen = (q[0] + 31) >> 4;75t += qlen;76tlen -= qlen;7778/*79* Computation can proceed only if we have enough room for the80* modulus.81*/82if (tlen < (plen + qlen + 1)) {83return 0;84}8586/*87* Private key already contains the modulus bit length, from which88* we can infer the output length. Even if n is NULL, we still had89* to decode p and q to make sure that the product can be computed.90*/91nlen = (sk->n_bitlen + 7) >> 3;92if (n != NULL) {93br_i15_zero(t, p[0]);94br_i15_mulacc(t, p, q);95br_i15_encode(n, nlen, t);96}97return nlen;98}99100101