security/nss/lib/freebl/rsa.c

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/security/nss/lib/freebl/rsa.c	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,1547 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +/*
     1.9 + * RSA key generation, public key op, private key op.
    1.10 + */
    1.11 +#ifdef FREEBL_NO_DEPEND
    1.12 +#include "stubs.h"
    1.13 +#endif
    1.14 +
    1.15 +#include "secerr.h"
    1.16 +
    1.17 +#include "prclist.h"
    1.18 +#include "nssilock.h"
    1.19 +#include "prinit.h"
    1.20 +#include "blapi.h"
    1.21 +#include "mpi.h"
    1.22 +#include "mpprime.h"
    1.23 +#include "mplogic.h"
    1.24 +#include "secmpi.h"
    1.25 +#include "secitem.h"
    1.26 +#include "blapii.h"
    1.27 +
    1.28 +/*
    1.29 +** Number of times to attempt to generate a prime (p or q) from a random
    1.30 +** seed (the seed changes for each iteration).
    1.31 +*/
    1.32 +#define MAX_PRIME_GEN_ATTEMPTS 10
    1.33 +/*
    1.34 +** Number of times to attempt to generate a key.  The primes p and q change
    1.35 +** for each attempt.
    1.36 +*/
    1.37 +#define MAX_KEY_GEN_ATTEMPTS 10
    1.38 +
    1.39 +/* Blinding Parameters max cache size  */
    1.40 +#define RSA_BLINDING_PARAMS_MAX_CACHE_SIZE 20
    1.41 +
    1.42 +/* exponent should not be greater than modulus */
    1.43 +#define BAD_RSA_KEY_SIZE(modLen, expLen) \
    1.44 +    ((expLen) > (modLen) || (modLen) > RSA_MAX_MODULUS_BITS/8 || \
    1.45 +    (expLen) > RSA_MAX_EXPONENT_BITS/8)
    1.46 +
    1.47 +struct blindingParamsStr;
    1.48 +typedef struct blindingParamsStr blindingParams;
    1.49 +
    1.50 +struct blindingParamsStr {
    1.51 +    blindingParams *next;
    1.52 +    mp_int         f, g;             /* blinding parameter                 */
    1.53 +    int            counter;          /* number of remaining uses of (f, g) */
    1.54 +};
    1.55 +
    1.56 +/*
    1.57 +** RSABlindingParamsStr
    1.58 +**
    1.59 +** For discussion of Paul Kocher's timing attack against an RSA private key
    1.60 +** operation, see http://www.cryptography.com/timingattack/paper.html.  The 
    1.61 +** countermeasure to this attack, known as blinding, is also discussed in 
    1.62 +** the Handbook of Applied Cryptography, 11.118-11.119.
    1.63 +*/
    1.64 +struct RSABlindingParamsStr
    1.65 +{
    1.66 +    /* Blinding-specific parameters */
    1.67 +    PRCList   link;                  /* link to list of structs            */
    1.68 +    SECItem   modulus;               /* list element "key"                 */
    1.69 +    blindingParams *free, *bp;       /* Blinding parameters queue          */
    1.70 +    blindingParams array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE];
    1.71 +};
    1.72 +typedef struct RSABlindingParamsStr RSABlindingParams;
    1.73 +
    1.74 +/*
    1.75 +** RSABlindingParamsListStr
    1.76 +**
    1.77 +** List of key-specific blinding params.  The arena holds the volatile pool
    1.78 +** of memory for each entry and the list itself.  The lock is for list
    1.79 +** operations, in this case insertions and iterations, as well as control
    1.80 +** of the counter for each set of blinding parameters.
    1.81 +*/
    1.82 +struct RSABlindingParamsListStr
    1.83 +{
    1.84 +    PZLock  *lock;   /* Lock for the list   */
    1.85 +    PRCondVar *cVar; /* Condidtion Variable */
    1.86 +    int  waitCount;  /* Number of threads waiting on cVar */
    1.87 +    PRCList  head;   /* Pointer to the list */
    1.88 +};
    1.89 +
    1.90 +/*
    1.91 +** The master blinding params list.
    1.92 +*/
    1.93 +static struct RSABlindingParamsListStr blindingParamsList = { 0 };
    1.94 +
    1.95 +/* Number of times to reuse (f, g).  Suggested by Paul Kocher */
    1.96 +#define RSA_BLINDING_PARAMS_MAX_REUSE 50
    1.97 +
    1.98 +/* Global, allows optional use of blinding.  On by default. */
    1.99 +/* Cannot be changed at the moment, due to thread-safety issues. */
   1.100 +static PRBool nssRSAUseBlinding = PR_TRUE;
   1.101 +
   1.102 +static SECStatus
   1.103 +rsa_build_from_primes(const mp_int *p, const mp_int *q,
   1.104 +		mp_int *e, PRBool needPublicExponent,
   1.105 +		mp_int *d, PRBool needPrivateExponent,
   1.106 +		RSAPrivateKey *key, unsigned int keySizeInBits)
   1.107 +{
   1.108 +    mp_int n, phi;
   1.109 +    mp_int psub1, qsub1, tmp;
   1.110 +    mp_err   err = MP_OKAY;
   1.111 +    SECStatus rv = SECSuccess;
   1.112 +    MP_DIGITS(&n)     = 0;
   1.113 +    MP_DIGITS(&phi)   = 0;
   1.114 +    MP_DIGITS(&psub1) = 0;
   1.115 +    MP_DIGITS(&qsub1) = 0;
   1.116 +    MP_DIGITS(&tmp)   = 0;
   1.117 +    CHECK_MPI_OK( mp_init(&n)     );
   1.118 +    CHECK_MPI_OK( mp_init(&phi)   );
   1.119 +    CHECK_MPI_OK( mp_init(&psub1) );
   1.120 +    CHECK_MPI_OK( mp_init(&qsub1) );
   1.121 +    CHECK_MPI_OK( mp_init(&tmp)   );
   1.122 +    /* p and q must be distinct. */
   1.123 +    if (mp_cmp(p, q) == 0) {
   1.124 +	PORT_SetError(SEC_ERROR_NEED_RANDOM);
   1.125 +	rv = SECFailure;
   1.126 +	goto cleanup;
   1.127 +    }
   1.128 +    /* 1.  Compute n = p*q */
   1.129 +    CHECK_MPI_OK( mp_mul(p, q, &n) );
   1.130 +    /*     verify that the modulus has the desired number of bits */
   1.131 +    if ((unsigned)mpl_significant_bits(&n) != keySizeInBits) {
   1.132 +	PORT_SetError(SEC_ERROR_NEED_RANDOM);
   1.133 +	rv = SECFailure;
   1.134 +	goto cleanup;
   1.135 +    }
   1.136 +
   1.137 +    /* at least one exponent must be given */
   1.138 +    PORT_Assert(!(needPublicExponent && needPrivateExponent));
   1.139 +
   1.140 +    /* 2.  Compute phi = (p-1)*(q-1) */
   1.141 +    CHECK_MPI_OK( mp_sub_d(p, 1, &psub1) );
   1.142 +    CHECK_MPI_OK( mp_sub_d(q, 1, &qsub1) );
   1.143 +    if (needPublicExponent || needPrivateExponent) {
   1.144 +	CHECK_MPI_OK( mp_mul(&psub1, &qsub1, &phi) );
   1.145 +	/* 3.  Compute d = e**-1 mod(phi) */
   1.146 +	/*     or      e = d**-1 mod(phi) as necessary */
   1.147 +	if (needPublicExponent) {
   1.148 +	    err = mp_invmod(d, &phi, e);
   1.149 +	} else {
   1.150 +	    err = mp_invmod(e, &phi, d);
   1.151 +	}
   1.152 +    } else {
   1.153 +	err = MP_OKAY;
   1.154 +    }
   1.155 +    /*     Verify that phi(n) and e have no common divisors */
   1.156 +    if (err != MP_OKAY) {
   1.157 +	if (err == MP_UNDEF) {
   1.158 +	    PORT_SetError(SEC_ERROR_NEED_RANDOM);
   1.159 +	    err = MP_OKAY; /* to keep PORT_SetError from being called again */
   1.160 +	    rv = SECFailure;
   1.161 +	}
   1.162 +	goto cleanup;
   1.163 +    }
   1.164 +
   1.165 +    /* 4.  Compute exponent1 = d mod (p-1) */
   1.166 +    CHECK_MPI_OK( mp_mod(d, &psub1, &tmp) );
   1.167 +    MPINT_TO_SECITEM(&tmp, &key->exponent1, key->arena);
   1.168 +    /* 5.  Compute exponent2 = d mod (q-1) */
   1.169 +    CHECK_MPI_OK( mp_mod(d, &qsub1, &tmp) );
   1.170 +    MPINT_TO_SECITEM(&tmp, &key->exponent2, key->arena);
   1.171 +    /* 6.  Compute coefficient = q**-1 mod p */
   1.172 +    CHECK_MPI_OK( mp_invmod(q, p, &tmp) );
   1.173 +    MPINT_TO_SECITEM(&tmp, &key->coefficient, key->arena);
   1.174 +
   1.175 +    /* copy our calculated results, overwrite what is there */
   1.176 +    key->modulus.data = NULL;
   1.177 +    MPINT_TO_SECITEM(&n, &key->modulus, key->arena);
   1.178 +    key->privateExponent.data = NULL;
   1.179 +    MPINT_TO_SECITEM(d, &key->privateExponent, key->arena);
   1.180 +    key->publicExponent.data = NULL;
   1.181 +    MPINT_TO_SECITEM(e, &key->publicExponent, key->arena);
   1.182 +    key->prime1.data = NULL;
   1.183 +    MPINT_TO_SECITEM(p, &key->prime1, key->arena);
   1.184 +    key->prime2.data = NULL;
   1.185 +    MPINT_TO_SECITEM(q, &key->prime2, key->arena);
   1.186 +cleanup:
   1.187 +    mp_clear(&n);
   1.188 +    mp_clear(&phi);
   1.189 +    mp_clear(&psub1);
   1.190 +    mp_clear(&qsub1);
   1.191 +    mp_clear(&tmp);
   1.192 +    if (err) {
   1.193 +	MP_TO_SEC_ERROR(err);
   1.194 +	rv = SECFailure;
   1.195 +    }
   1.196 +    return rv;
   1.197 +}
   1.198 +static SECStatus
   1.199 +generate_prime(mp_int *prime, int primeLen)
   1.200 +{
   1.201 +    mp_err   err = MP_OKAY;
   1.202 +    SECStatus rv = SECSuccess;
   1.203 +    unsigned long counter = 0;
   1.204 +    int piter;
   1.205 +    unsigned char *pb = NULL;
   1.206 +    pb = PORT_Alloc(primeLen);
   1.207 +    if (!pb) {
   1.208 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
   1.209 +	goto cleanup;
   1.210 +    }
   1.211 +    for (piter = 0; piter < MAX_PRIME_GEN_ATTEMPTS; piter++) {
   1.212 +	CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(pb, primeLen) );
   1.213 +	pb[0]          |= 0xC0; /* set two high-order bits */
   1.214 +	pb[primeLen-1] |= 0x01; /* set low-order bit       */
   1.215 +	CHECK_MPI_OK( mp_read_unsigned_octets(prime, pb, primeLen) );
   1.216 +	err = mpp_make_prime(prime, primeLen * 8, PR_FALSE, &counter);
   1.217 +	if (err != MP_NO)
   1.218 +	    goto cleanup;
   1.219 +	/* keep going while err == MP_NO */
   1.220 +    }
   1.221 +cleanup:
   1.222 +    if (pb)
   1.223 +	PORT_ZFree(pb, primeLen);
   1.224 +    if (err) {
   1.225 +	MP_TO_SEC_ERROR(err);
   1.226 +	rv = SECFailure;
   1.227 +    }
   1.228 +    return rv;
   1.229 +}
   1.230 +
   1.231 +/*
   1.232 +** Generate and return a new RSA public and private key.
   1.233 +**	Both keys are encoded in a single RSAPrivateKey structure.
   1.234 +**	"cx" is the random number generator context
   1.235 +**	"keySizeInBits" is the size of the key to be generated, in bits.
   1.236 +**	   512, 1024, etc.
   1.237 +**	"publicExponent" when not NULL is a pointer to some data that
   1.238 +**	   represents the public exponent to use. The data is a byte
   1.239 +**	   encoded integer, in "big endian" order.
   1.240 +*/
   1.241 +RSAPrivateKey *
   1.242 +RSA_NewKey(int keySizeInBits, SECItem *publicExponent)
   1.243 +{
   1.244 +    unsigned int primeLen;
   1.245 +    mp_int p, q, e, d;
   1.246 +    int kiter;
   1.247 +    mp_err   err = MP_OKAY;
   1.248 +    SECStatus rv = SECSuccess;
   1.249 +    int prerr = 0;
   1.250 +    RSAPrivateKey *key = NULL;
   1.251 +    PLArenaPool *arena = NULL;
   1.252 +    /* Require key size to be a multiple of 16 bits. */
   1.253 +    if (!publicExponent || keySizeInBits % 16 != 0 ||
   1.254 +	    BAD_RSA_KEY_SIZE(keySizeInBits/8, publicExponent->len)) {
   1.255 +	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1.256 +	return NULL;
   1.257 +    }
   1.258 +    /* 1. Allocate arena & key */
   1.259 +    arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
   1.260 +    if (!arena) {
   1.261 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
   1.262 +	return NULL;
   1.263 +    }
   1.264 +    key = PORT_ArenaZNew(arena, RSAPrivateKey);
   1.265 +    if (!key) {
   1.266 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
   1.267 +	PORT_FreeArena(arena, PR_TRUE);
   1.268 +	return NULL;
   1.269 +    }
   1.270 +    key->arena = arena;
   1.271 +    /* length of primes p and q (in bytes) */
   1.272 +    primeLen = keySizeInBits / (2 * PR_BITS_PER_BYTE);
   1.273 +    MP_DIGITS(&p) = 0;
   1.274 +    MP_DIGITS(&q) = 0;
   1.275 +    MP_DIGITS(&e) = 0;
   1.276 +    MP_DIGITS(&d) = 0;
   1.277 +    CHECK_MPI_OK( mp_init(&p) );
   1.278 +    CHECK_MPI_OK( mp_init(&q) );
   1.279 +    CHECK_MPI_OK( mp_init(&e) );
   1.280 +    CHECK_MPI_OK( mp_init(&d) );
   1.281 +    /* 2.  Set the version number (PKCS1 v1.5 says it should be zero) */
   1.282 +    SECITEM_AllocItem(arena, &key->version, 1);
   1.283 +    key->version.data[0] = 0;
   1.284 +    /* 3.  Set the public exponent */
   1.285 +    SECITEM_TO_MPINT(*publicExponent, &e);
   1.286 +    kiter = 0;
   1.287 +    do {
   1.288 +	prerr = 0;
   1.289 +	PORT_SetError(0);
   1.290 +	CHECK_SEC_OK( generate_prime(&p, primeLen) );
   1.291 +	CHECK_SEC_OK( generate_prime(&q, primeLen) );
   1.292 +	/* Assure p > q */
   1.293 +	/* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any
   1.294 +	 * implementation optimization that requires p > q. We can remove
   1.295 +	 * this code in the future.
   1.296 +	 */
   1.297 +	if (mp_cmp(&p, &q) < 0)
   1.298 +	    mp_exch(&p, &q);
   1.299 +	/* Attempt to use these primes to generate a key */
   1.300 +	rv = rsa_build_from_primes(&p, &q, 
   1.301 +			&e, PR_FALSE,  /* needPublicExponent=false */
   1.302 +			&d, PR_TRUE,   /* needPrivateExponent=true */
   1.303 +			key, keySizeInBits);
   1.304 +	if (rv == SECSuccess)
   1.305 +	    break; /* generated two good primes */
   1.306 +	prerr = PORT_GetError();
   1.307 +	kiter++;
   1.308 +	/* loop until have primes */
   1.309 +    } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS);
   1.310 +    if (prerr)
   1.311 +	goto cleanup;
   1.312 +cleanup:
   1.313 +    mp_clear(&p);
   1.314 +    mp_clear(&q);
   1.315 +    mp_clear(&e);
   1.316 +    mp_clear(&d);
   1.317 +    if (err) {
   1.318 +	MP_TO_SEC_ERROR(err);
   1.319 +	rv = SECFailure;
   1.320 +    }
   1.321 +    if (rv && arena) {
   1.322 +	PORT_FreeArena(arena, PR_TRUE);
   1.323 +	key = NULL;
   1.324 +    }
   1.325 +    return key;
   1.326 +}
   1.327 +
   1.328 +mp_err
   1.329 +rsa_is_prime(mp_int *p) {
   1.330 +    int res;
   1.331 +
   1.332 +    /* run a Fermat test */
   1.333 +    res = mpp_fermat(p, 2);
   1.334 +    if (res != MP_OKAY) {
   1.335 +	return res;
   1.336 +    }
   1.337 +
   1.338 +    /* If that passed, run some Miller-Rabin tests */
   1.339 +    res = mpp_pprime(p, 2);
   1.340 +    return res;
   1.341 +}
   1.342 +
   1.343 +/*
   1.344 + * Try to find the two primes based on 2 exponents plus either a prime
   1.345 + *   or a modulus.
   1.346 + *
   1.347 + * In: e, d and either p or n (depending on the setting of hasModulus).
   1.348 + * Out: p,q.
   1.349 + * 
   1.350 + * Step 1, Since d = e**-1 mod phi, we know that d*e == 1 mod phi, or
   1.351 + *	d*e = 1+k*phi, or d*e-1 = k*phi. since d is less than phi and e is
   1.352 + *	usually less than d, then k must be an integer between e-1 and 1 
   1.353 + *	(probably on the order of e).
   1.354 + * Step 1a, If we were passed just a prime, we can divide k*phi by that
   1.355 + *      prime-1 and get k*(q-1). This will reduce the size of our division
   1.356 + *      through the rest of the loop.
   1.357 + * Step 2, Loop through the values k=e-1 to 1 looking for k. k should be on
   1.358 + *	the order or e, and e is typically small. This may take a while for
   1.359 + *	a large random e. We are looking for a k that divides kphi
   1.360 + *	evenly. Once we find a k that divides kphi evenly, we assume it 
   1.361 + *	is the true k. It's possible this k is not the 'true' k but has 
   1.362 + *	swapped factors of p-1 and/or q-1. Because of this, we 
   1.363 + *	tentatively continue Steps 3-6 inside this loop, and may return looking
   1.364 + *	for another k on failure.
   1.365 + * Step 3, Calculate are tentative phi=kphi/k. Note: real phi is (p-1)*(q-1).
   1.366 + * Step 4a, if we have a prime, kphi is already k*(q-1), so phi is or tenative
   1.367 + *      q-1. q = phi+1. If k is correct, q should be the right length and 
   1.368 + *      prime.
   1.369 + * Step 4b, It's possible q-1 and k could have swapped factors. We now have a
   1.370 + * 	possible solution that meets our criteria. It may not be the only 
   1.371 + *      solution, however, so we keep looking. If we find more than one, 
   1.372 + *      we will fail since we cannot determine which is the correct
   1.373 + *      solution, and returning the wrong modulus will compromise both
   1.374 + *      moduli. If no other solution is found, we return the unique solution.
   1.375 + * Step 5a, If we have the modulus (n=pq), then use the following formula to 
   1.376 + * 	calculate  s=(p+q): , phi = (p-1)(q-1) = pq  -p-q +1 = n-s+1. so
   1.377 + *	s=n-phi+1.
   1.378 + * Step 5b, Use n=pq and s=p+q to solve for p and q as follows:
   1.379 + *	since q=s-p, then n=p*(s-p)= sp - p^2, rearranging p^2-s*p+n = 0.
   1.380 + *	from the quadratic equation we have p=1/2*(s+sqrt(s*s-4*n)) and
   1.381 + *	q=1/2*(s-sqrt(s*s-4*n)) if s*s-4*n is a perfect square, we are DONE.
   1.382 + *	If it is not, continue in our look looking for another k. NOTE: the
   1.383 + *	code actually distributes the 1/2 and results in the equations:
   1.384 + *	sqrt = sqrt(s/2*s/2-n), p=s/2+sqrt, q=s/2-sqrt. The algebra saves us
   1.385 + *	and extra divide by 2 and a multiply by 4.
   1.386 + * 
   1.387 + * This will return p & q. q may be larger than p in the case that p was given
   1.388 + * and it was the smaller prime.
   1.389 + */
   1.390 +static mp_err
   1.391 +rsa_get_primes_from_exponents(mp_int *e, mp_int *d, mp_int *p, mp_int *q,
   1.392 +			      mp_int *n, PRBool hasModulus, 
   1.393 +			      unsigned int keySizeInBits)
   1.394 +{
   1.395 +    mp_int kphi; /* k*phi */
   1.396 +    mp_int k;    /* current guess at 'k' */
   1.397 +    mp_int phi;  /* (p-1)(q-1) */
   1.398 +    mp_int s;    /* p+q/2 (s/2 in the algebra) */
   1.399 +    mp_int r;    /* remainder */
   1.400 +    mp_int tmp; /* p-1 if p is given, n+1 is modulus is given */
   1.401 +    mp_int sqrt; /* sqrt(s/2*s/2-n) */
   1.402 +    mp_err err = MP_OKAY;
   1.403 +    unsigned int order_k;
   1.404 +
   1.405 +    MP_DIGITS(&kphi) = 0;
   1.406 +    MP_DIGITS(&phi) = 0;
   1.407 +    MP_DIGITS(&s) = 0;
   1.408 +    MP_DIGITS(&k) = 0;
   1.409 +    MP_DIGITS(&r) = 0;
   1.410 +    MP_DIGITS(&tmp) = 0;
   1.411 +    MP_DIGITS(&sqrt) = 0;
   1.412 +    CHECK_MPI_OK( mp_init(&kphi) );
   1.413 +    CHECK_MPI_OK( mp_init(&phi) );
   1.414 +    CHECK_MPI_OK( mp_init(&s) );
   1.415 +    CHECK_MPI_OK( mp_init(&k) );
   1.416 +    CHECK_MPI_OK( mp_init(&r) );
   1.417 +    CHECK_MPI_OK( mp_init(&tmp) );
   1.418 +    CHECK_MPI_OK( mp_init(&sqrt) );
   1.419 +
   1.420 +    /* our algorithm looks for a factor k whose maximum size is dependent
   1.421 +     * on the size of our smallest exponent, which had better be the public
   1.422 +     * exponent (if it's the private, the key is vulnerable to a brute force
   1.423 +     * attack).
   1.424 +     * 
   1.425 +     * since our factor search is linear, we need to limit the maximum
   1.426 +     * size of the public key. this should not be a problem normally, since 
   1.427 +     * public keys are usually small. 
   1.428 +     *
   1.429 +     * if we want to handle larger public key sizes, we should have
   1.430 +     * a version which tries to 'completely' factor k*phi (where completely
   1.431 +     * means 'factor into primes, or composites with which are products of
   1.432 +     * large primes). Once we have all the factors, we can sort them out and
   1.433 +     * try different combinations to form our phi. The risk is if (p-1)/2,
   1.434 +     * (q-1)/2, and k are all large primes. In any case if the public key
   1.435 +     * is small (order of 20 some bits), then a linear search for k is 
   1.436 +     * manageable.
   1.437 +     */
   1.438 +    if (mpl_significant_bits(e) > 23) {
   1.439 +	err=MP_RANGE;
   1.440 +	goto cleanup;
   1.441 +    }
   1.442 +
   1.443 +    /* calculate k*phi = e*d - 1 */
   1.444 +    CHECK_MPI_OK( mp_mul(e, d, &kphi) );
   1.445 +    CHECK_MPI_OK( mp_sub_d(&kphi, 1, &kphi) );
   1.446 +
   1.447 +
   1.448 +    /* kphi is (e*d)-1, which is the same as k*(p-1)(q-1)
   1.449 +     * d < (p-1)(q-1), therefor k must be less than e-1
   1.450 +     * We can narrow down k even more, though. Since p and q are odd and both 
   1.451 +     * have their high bit set, then we know that phi must be on order of 
   1.452 +     * keySizeBits.
   1.453 +     */
   1.454 +    order_k = (unsigned)mpl_significant_bits(&kphi) - keySizeInBits;
   1.455 +
   1.456 +    /* for (k=kinit; order(k) >= order_k; k--) { */
   1.457 +    /* k=kinit: k can't be bigger than  kphi/2^(keySizeInBits -1) */
   1.458 +    CHECK_MPI_OK( mp_2expt(&k,keySizeInBits-1) );
   1.459 +    CHECK_MPI_OK( mp_div(&kphi, &k, &k, NULL));
   1.460 +    if (mp_cmp(&k,e) >= 0) {
   1.461 +	/* also can't be bigger then e-1 */
   1.462 +        CHECK_MPI_OK( mp_sub_d(e, 1, &k) );
   1.463 +    }
   1.464 +
   1.465 +    /* calculate our temp value */
   1.466 +    /* This saves recalculating this value when the k guess is wrong, which
   1.467 +     * is reasonably frequent. */
   1.468 +    /* for the modulus case, tmp = n+1 (used to calculate p+q = tmp - phi) */
   1.469 +    /* for the prime case, tmp = p-1 (used to calculate q-1= phi/tmp) */
   1.470 +    if (hasModulus) {
   1.471 +	CHECK_MPI_OK( mp_add_d(n, 1, &tmp) );
   1.472 +    } else {
   1.473 +	CHECK_MPI_OK( mp_sub_d(p, 1, &tmp) );
   1.474 +	CHECK_MPI_OK(mp_div(&kphi,&tmp,&kphi,&r));
   1.475 +	if (mp_cmp_z(&r) != 0) {
   1.476 +	    /* p-1 doesn't divide kphi, some parameter wasn't correct */
   1.477 +	    err=MP_RANGE;
   1.478 +	    goto cleanup;
   1.479 +	}
   1.480 +	mp_zero(q);
   1.481 +	/* kphi is now k*(q-1) */
   1.482 +    }
   1.483 +
   1.484 +    /* rest of the for loop */
   1.485 +    for (; (err == MP_OKAY) && (mpl_significant_bits(&k) >= order_k); 
   1.486 +						err = mp_sub_d(&k, 1, &k)) {
   1.487 +	/* looking for k as a factor of kphi */
   1.488 +	CHECK_MPI_OK(mp_div(&kphi,&k,&phi,&r));
   1.489 +	if (mp_cmp_z(&r) != 0) {
   1.490 +	    /* not a factor, try the next one */
   1.491 +	    continue;
   1.492 +	}
   1.493 +	/* we have a possible phi, see if it works */
   1.494 +	if (!hasModulus) {
   1.495 +	    if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits/2) {
   1.496 +		/* phi is not the right size */
   1.497 +		continue;
   1.498 +	    }
   1.499 +	    /* phi should be divisible by 2, since
   1.500 +	     * q is odd and phi=(q-1). */
   1.501 +	    if (mpp_divis_d(&phi,2) == MP_NO) {
   1.502 +		/* phi is not divisible by 4 */
   1.503 +		continue;
   1.504 +	    }
   1.505 +	    /* we now have a candidate for the second prime */
   1.506 +	    CHECK_MPI_OK(mp_add_d(&phi, 1, &tmp));
   1.507 +	    
   1.508 +	    /* check to make sure it is prime */
   1.509 +	    err = rsa_is_prime(&tmp);
   1.510 +	    if (err != MP_OKAY) {
   1.511 +		if (err == MP_NO) {
   1.512 +		    /* No, then we still have the wrong phi */
   1.513 +		    err = MP_OKAY;
   1.514 +        	    continue;
   1.515 +		}
   1.516 +		goto cleanup;
   1.517 +	    }
   1.518 +	    /*
   1.519 +	     * It is possible that we have the wrong phi if 
   1.520 +	     * k_guess*(q_guess-1) = k*(q-1) (k and q-1 have swapped factors).
   1.521 +	     * since our q_quess is prime, however. We have found a valid
   1.522 +	     * rsa key because:
   1.523 +	     *   q is the correct order of magnitude.
   1.524 +	     *   phi = (p-1)(q-1) where p and q are both primes.
   1.525 +	     *   e*d mod phi = 1.
   1.526 +	     * There is no way to know from the info given if this is the 
   1.527 +	     * original key. We never want to return the wrong key because if
   1.528 +	     * two moduli with the same factor is known, then euclid's gcd
   1.529 +	     * algorithm can be used to find that factor. Even though the 
   1.530 +	     * caller didn't pass the original modulus, it doesn't mean the
   1.531 +	     * modulus wasn't known or isn't available somewhere. So to be safe
   1.532 +	     * if we can't be sure we have the right q, we don't return any.
   1.533 +	     * 
   1.534 +	     * So to make sure we continue looking for other valid q's. If none
   1.535 +	     * are found, then we can safely return this one, otherwise we just
   1.536 +	     * fail */
   1.537 +	    if (mp_cmp_z(q) != 0) {
   1.538 +		/* this is the second valid q, don't return either, 
   1.539 +		 * just fail */
   1.540 +		err = MP_RANGE;
   1.541 +		break;
   1.542 +	    }
   1.543 +	    /* we only have one q so far, save it and if no others are found,
   1.544 +	     * it's safe to return it */
   1.545 +	    CHECK_MPI_OK(mp_copy(&tmp, q));
   1.546 +	    continue;
   1.547 +	}
   1.548 +	/* test our tentative phi */
   1.549 +	/* phi should be the correct order */
   1.550 +	if ((unsigned)mpl_significant_bits(&phi) != keySizeInBits) {
   1.551 +	    /* phi is not the right size */
   1.552 +	    continue;
   1.553 +	}
   1.554 +	/* phi should be divisible by 4, since
   1.555 +	 * p and q are odd and phi=(p-1)(q-1). */
   1.556 +	if (mpp_divis_d(&phi,4) == MP_NO) {
   1.557 +	    /* phi is not divisible by 4 */
   1.558 +	    continue;
   1.559 +	}
   1.560 +	/* n was given, calculate s/2=(p+q)/2 */
   1.561 +	CHECK_MPI_OK( mp_sub(&tmp, &phi, &s) );
   1.562 +	CHECK_MPI_OK( mp_div_2(&s, &s) );
   1.563 +
   1.564 +	/* calculate sqrt(s/2*s/2-n) */
   1.565 +	CHECK_MPI_OK(mp_sqr(&s,&sqrt));
   1.566 +	CHECK_MPI_OK(mp_sub(&sqrt,n,&r));  /* r as a tmp */
   1.567 +	CHECK_MPI_OK(mp_sqrt(&r,&sqrt));
   1.568 +	/* make sure it's a perfect square */
   1.569 +	/* r is our original value we took the square root of */
   1.570 +	/* q is the square of our tentative square root. They should be equal*/
   1.571 +	CHECK_MPI_OK(mp_sqr(&sqrt,q)); /* q as a tmp */
   1.572 +	if (mp_cmp(&r,q) != 0) {
   1.573 +	    /* sigh according to the doc, mp_sqrt could return sqrt-1 */
   1.574 +	   CHECK_MPI_OK(mp_add_d(&sqrt,1,&sqrt));
   1.575 +	   CHECK_MPI_OK(mp_sqr(&sqrt,q));
   1.576 +	   if (mp_cmp(&r,q) != 0) {
   1.577 +		/* s*s-n not a perfect square, this phi isn't valid, find 			 * another.*/
   1.578 +		continue;
   1.579 +	    }
   1.580 +	}
   1.581 +
   1.582 +	/* NOTE: In this case we know we have the one and only answer.
   1.583 +	 * "Why?", you ask. Because:
   1.584 +	 *    1) n is a composite of two large primes (or it wasn't a
   1.585 +	 *       valid RSA modulus).
   1.586 +	 *    2) If we know any number such that x^2-n is a perfect square 
   1.587 +	 *       and x is not (n+1)/2, then we can calculate 2 non-trivial
   1.588 +	 *       factors of n.
   1.589 +	 *    3) Since we know that n has only 2 non-trivial prime factors, 
   1.590 +	 *       we know the two factors we have are the only possible factors.
   1.591 +	 */
   1.592 +
   1.593 +	/* Now we are home free to calculate p and q */
   1.594 +	/* p = s/2 + sqrt, q= s/2 - sqrt */
   1.595 +	CHECK_MPI_OK(mp_add(&s,&sqrt,p));
   1.596 +	CHECK_MPI_OK(mp_sub(&s,&sqrt,q));
   1.597 +	break;
   1.598 +    }
   1.599 +    if ((unsigned)mpl_significant_bits(&k) < order_k) {
   1.600 +	if (hasModulus || (mp_cmp_z(q) == 0)) {
   1.601 +	    /* If we get here, something was wrong with the parameters we 
   1.602 +	     * were given */
   1.603 +	    err = MP_RANGE; 
   1.604 +	}
   1.605 +    }
   1.606 +cleanup:
   1.607 +    mp_clear(&kphi);
   1.608 +    mp_clear(&phi);
   1.609 +    mp_clear(&s);
   1.610 +    mp_clear(&k);
   1.611 +    mp_clear(&r);
   1.612 +    mp_clear(&tmp);
   1.613 +    mp_clear(&sqrt);
   1.614 +    return err;
   1.615 +}
   1.616 +     
   1.617 +/*
   1.618 + * take a private key with only a few elements and fill out the missing pieces.
   1.619 + *
   1.620 + * All the entries will be overwritten with data allocated out of the arena
   1.621 + * If no arena is supplied, one will be created.
   1.622 + *
   1.623 + * The following fields must be supplied in order for this function
   1.624 + * to succeed:
   1.625 + *   one of either publicExponent or privateExponent
   1.626 + *   two more of the following 5 parameters.
   1.627 + *      modulus (n)
   1.628 + *      prime1  (p)
   1.629 + *      prime2  (q)
   1.630 + *      publicExponent (e)
   1.631 + *      privateExponent (d)
   1.632 + *
   1.633 + * NOTE: if only the publicExponent, privateExponent, and one prime is given,
   1.634 + * then there may be more than one RSA key that matches that combination.
   1.635 + *
   1.636 + * All parameters will be replaced in the key structure with new parameters
   1.637 + * Allocated out of the arena. There is no attempt to free the old structures.
   1.638 + * Prime1 will always be greater than prime2 (even if the caller supplies the
   1.639 + * smaller prime as prime1 or the larger prime as prime2). The parameters are
   1.640 + * not overwritten on failure.
   1.641 + *
   1.642 + *  How it works:
   1.643 + *     We can generate all the parameters from:
   1.644 + *        one of the exponents, plus the two primes. (rsa_build_key_from_primes) *
   1.645 + *     If we are given one of the exponents and both primes, we are done.
   1.646 + *     If we are given one of the exponents, the modulus and one prime, we 
   1.647 + *        caclulate the second prime by dividing the modulus by the given 
   1.648 + *        prime, giving us and exponent and 2 primes.
   1.649 + *     If we are given 2 exponents and either the modulus or one of the primes
   1.650 + *        we calculate k*phi = d*e-1, where k is an integer less than d which 
   1.651 + *        divides d*e-1. We find factor k so we can isolate phi.
   1.652 + *            phi = (p-1)(q-1)
   1.653 + *       If one of the primes are given, we can use phi to find the other prime
   1.654 + *        as follows: q = (phi/(p-1)) + 1. We now have 2 primes and an 
   1.655 + *        exponent. (NOTE: if more then one prime meets this condition, the
   1.656 + *        operation will fail. See comments elsewhere in this file about this).
   1.657 + *       If the modulus is given, then we can calculate the sum of the primes
   1.658 + *        as follows: s := (p+q), phi = (p-1)(q-1) = pq -p - q +1, pq = n ->
   1.659 + *        phi = n - s + 1, s = n - phi +1.  Now that we have s = p+q and n=pq,
   1.660 + *	  we can solve our 2 equations and 2 unknowns as follows: q=s-p ->
   1.661 + *        n=p*(s-p)= sp -p^2 -> p^2-sp+n = 0. Using the quadratic to solve for
   1.662 + *        p, p=1/2*(s+ sqrt(s*s-4*n)) [q=1/2*(s-sqrt(s*s-4*n)]. We again have
   1.663 + *        2 primes and an exponent.
   1.664 + *
   1.665 + */
   1.666 +SECStatus
   1.667 +RSA_PopulatePrivateKey(RSAPrivateKey *key)
   1.668 +{
   1.669 +    PLArenaPool *arena = NULL;
   1.670 +    PRBool needPublicExponent = PR_TRUE;
   1.671 +    PRBool needPrivateExponent = PR_TRUE;
   1.672 +    PRBool hasModulus = PR_FALSE;
   1.673 +    unsigned int keySizeInBits = 0;
   1.674 +    int prime_count = 0;
   1.675 +    /* standard RSA nominclature */
   1.676 +    mp_int p, q, e, d, n;
   1.677 +    /* remainder */
   1.678 +    mp_int r;
   1.679 +    mp_err err = 0;
   1.680 +    SECStatus rv = SECFailure;
   1.681 +
   1.682 +    MP_DIGITS(&p) = 0;
   1.683 +    MP_DIGITS(&q) = 0;
   1.684 +    MP_DIGITS(&e) = 0;
   1.685 +    MP_DIGITS(&d) = 0;
   1.686 +    MP_DIGITS(&n) = 0;
   1.687 +    MP_DIGITS(&r) = 0;
   1.688 +    CHECK_MPI_OK( mp_init(&p) );
   1.689 +    CHECK_MPI_OK( mp_init(&q) );
   1.690 +    CHECK_MPI_OK( mp_init(&e) );
   1.691 +    CHECK_MPI_OK( mp_init(&d) );
   1.692 +    CHECK_MPI_OK( mp_init(&n) );
   1.693 +    CHECK_MPI_OK( mp_init(&r) );
   1.694 + 
   1.695 +    /* if the key didn't already have an arena, create one. */
   1.696 +    if (key->arena == NULL) {
   1.697 +	arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
   1.698 +	if (!arena) {
   1.699 +	    goto cleanup;
   1.700 +	}
   1.701 +	key->arena = arena;
   1.702 +    }
   1.703 +
   1.704 +    /* load up the known exponents */
   1.705 +    if (key->publicExponent.data) {
   1.706 +        SECITEM_TO_MPINT(key->publicExponent, &e);
   1.707 +	needPublicExponent = PR_FALSE;
   1.708 +    } 
   1.709 +    if (key->privateExponent.data) {
   1.710 +        SECITEM_TO_MPINT(key->privateExponent, &d);
   1.711 +	needPrivateExponent = PR_FALSE;
   1.712 +    }
   1.713 +    if (needPrivateExponent && needPublicExponent) {
   1.714 +	/* Not enough information, we need at least one exponent */
   1.715 +	err = MP_BADARG;
   1.716 +	goto cleanup;
   1.717 +    }
   1.718 +
   1.719 +    /* load up the known primes. If only one prime is given, it will be
   1.720 +     * assigned 'p'. Once we have both primes, well make sure p is the larger.
   1.721 +     * The value prime_count tells us howe many we have acquired.
   1.722 +     */
   1.723 +    if (key->prime1.data) {
   1.724 +	int primeLen = key->prime1.len;
   1.725 +	if (key->prime1.data[0] == 0) {
   1.726 +	   primeLen--;
   1.727 +	}
   1.728 +	keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
   1.729 +        SECITEM_TO_MPINT(key->prime1, &p);
   1.730 +	prime_count++;
   1.731 +    }
   1.732 +    if (key->prime2.data) {
   1.733 +	int primeLen = key->prime2.len;
   1.734 +	if (key->prime2.data[0] == 0) {
   1.735 +	   primeLen--;
   1.736 +	}
   1.737 +	keySizeInBits = primeLen * 2 * PR_BITS_PER_BYTE;
   1.738 +        SECITEM_TO_MPINT(key->prime2, prime_count ? &q : &p);
   1.739 +	prime_count++;
   1.740 +    }
   1.741 +    /* load up the modulus */
   1.742 +    if (key->modulus.data) {
   1.743 +	int modLen = key->modulus.len;
   1.744 +	if (key->modulus.data[0] == 0) {
   1.745 +	   modLen--;
   1.746 +	}
   1.747 +	keySizeInBits = modLen * PR_BITS_PER_BYTE;
   1.748 +	SECITEM_TO_MPINT(key->modulus, &n);
   1.749 +	hasModulus = PR_TRUE;
   1.750 +    }
   1.751 +    /* if we have the modulus and one prime, calculate the second. */
   1.752 +    if ((prime_count == 1) && (hasModulus)) {
   1.753 +	mp_div(&n,&p,&q,&r);
   1.754 +	if (mp_cmp_z(&r) != 0) {
   1.755 +	   /* p is not a factor or n, fail */
   1.756 +	   err = MP_BADARG;
   1.757 +	   goto cleanup;
   1.758 +	}
   1.759 +	prime_count++;
   1.760 +    }
   1.761 +
   1.762 +    /* If we didn't have enough primes try to calculate the primes from
   1.763 +     * the exponents */
   1.764 +    if (prime_count < 2) {
   1.765 +	/* if we don't have at least 2 primes at this point, then we need both
   1.766 +	 * exponents and one prime or a modulus*/
   1.767 +	if (!needPublicExponent && !needPrivateExponent &&
   1.768 +		((prime_count > 0) || hasModulus)) {
   1.769 +	    CHECK_MPI_OK(rsa_get_primes_from_exponents(&e,&d,&p,&q,
   1.770 +			&n,hasModulus,keySizeInBits));
   1.771 +	} else {
   1.772 +	    /* not enough given parameters to get both primes */
   1.773 +	    err = MP_BADARG;
   1.774 +	    goto cleanup;
   1.775 +	}
   1.776 +     }
   1.777 +
   1.778 +     /* Assure p > q */
   1.779 +     /* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any
   1.780 +      * implementation optimization that requires p > q. We can remove
   1.781 +      * this code in the future.
   1.782 +      */
   1.783 +     if (mp_cmp(&p, &q) < 0)
   1.784 +	mp_exch(&p, &q);
   1.785 +
   1.786 +     /* we now have our 2 primes and at least one exponent, we can fill
   1.787 +      * in the key */
   1.788 +     rv = rsa_build_from_primes(&p, &q, 
   1.789 +			&e, needPublicExponent,
   1.790 +			&d, needPrivateExponent,
   1.791 +			key, keySizeInBits);
   1.792 +cleanup:
   1.793 +    mp_clear(&p);
   1.794 +    mp_clear(&q);
   1.795 +    mp_clear(&e);
   1.796 +    mp_clear(&d);
   1.797 +    mp_clear(&n);
   1.798 +    mp_clear(&r);
   1.799 +    if (err) {
   1.800 +	MP_TO_SEC_ERROR(err);
   1.801 +	rv = SECFailure;
   1.802 +    }
   1.803 +    if (rv && arena) {
   1.804 +	PORT_FreeArena(arena, PR_TRUE);
   1.805 +	key->arena = NULL;
   1.806 +    }
   1.807 +    return rv;
   1.808 +}
   1.809 +
   1.810 +static unsigned int
   1.811 +rsa_modulusLen(SECItem *modulus)
   1.812 +{
   1.813 +    unsigned char byteZero = modulus->data[0];
   1.814 +    unsigned int modLen = modulus->len - !byteZero;
   1.815 +    return modLen;
   1.816 +}
   1.817 +
   1.818 +/*
   1.819 +** Perform a raw public-key operation 
   1.820 +**	Length of input and output buffers are equal to key's modulus len.
   1.821 +*/
   1.822 +SECStatus 
   1.823 +RSA_PublicKeyOp(RSAPublicKey  *key, 
   1.824 +                unsigned char *output, 
   1.825 +                const unsigned char *input)
   1.826 +{
   1.827 +    unsigned int modLen, expLen, offset;
   1.828 +    mp_int n, e, m, c;
   1.829 +    mp_err err   = MP_OKAY;
   1.830 +    SECStatus rv = SECSuccess;
   1.831 +    if (!key || !output || !input) {
   1.832 +	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   1.833 +	return SECFailure;
   1.834 +    }
   1.835 +    MP_DIGITS(&n) = 0;
   1.836 +    MP_DIGITS(&e) = 0;
   1.837 +    MP_DIGITS(&m) = 0;
   1.838 +    MP_DIGITS(&c) = 0;
   1.839 +    CHECK_MPI_OK( mp_init(&n) );
   1.840 +    CHECK_MPI_OK( mp_init(&e) );
   1.841 +    CHECK_MPI_OK( mp_init(&m) );
   1.842 +    CHECK_MPI_OK( mp_init(&c) );
   1.843 +    modLen = rsa_modulusLen(&key->modulus);
   1.844 +    expLen = rsa_modulusLen(&key->publicExponent);
   1.845 +    /* 1.  Obtain public key (n, e) */
   1.846 +    if (BAD_RSA_KEY_SIZE(modLen, expLen)) {
   1.847 +    	PORT_SetError(SEC_ERROR_INVALID_KEY);
   1.848 +	rv = SECFailure;
   1.849 +	goto cleanup;
   1.850 +    }
   1.851 +    SECITEM_TO_MPINT(key->modulus, &n);
   1.852 +    SECITEM_TO_MPINT(key->publicExponent, &e);
   1.853 +    if (e.used > n.used) {
   1.854 +	/* exponent should not be greater than modulus */
   1.855 +    	PORT_SetError(SEC_ERROR_INVALID_KEY);
   1.856 +	rv = SECFailure;
   1.857 +	goto cleanup;
   1.858 +    }
   1.859 +    /* 2. check input out of range (needs to be in range [0..n-1]) */
   1.860 +    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
   1.861 +    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
   1.862 +        PORT_SetError(SEC_ERROR_INPUT_LEN);
   1.863 +        rv = SECFailure;
   1.864 +        goto cleanup;
   1.865 +    }
   1.866 +    /* 2 bis.  Represent message as integer in range [0..n-1] */
   1.867 +    CHECK_MPI_OK( mp_read_unsigned_octets(&m, input, modLen) );
   1.868 +    /* 3.  Compute c = m**e mod n */
   1.869 +#ifdef USE_MPI_EXPT_D
   1.870 +    /* XXX see which is faster */
   1.871 +    if (MP_USED(&e) == 1) {
   1.872 +	CHECK_MPI_OK( mp_exptmod_d(&m, MP_DIGIT(&e, 0), &n, &c) );
   1.873 +    } else
   1.874 +#endif
   1.875 +    CHECK_MPI_OK( mp_exptmod(&m, &e, &n, &c) );
   1.876 +    /* 4.  result c is ciphertext */
   1.877 +    err = mp_to_fixlen_octets(&c, output, modLen);
   1.878 +    if (err >= 0) err = MP_OKAY;
   1.879 +cleanup:
   1.880 +    mp_clear(&n);
   1.881 +    mp_clear(&e);
   1.882 +    mp_clear(&m);
   1.883 +    mp_clear(&c);
   1.884 +    if (err) {
   1.885 +	MP_TO_SEC_ERROR(err);
   1.886 +	rv = SECFailure;
   1.887 +    }
   1.888 +    return rv;
   1.889 +}
   1.890 +
   1.891 +/*
   1.892 +**  RSA Private key operation (no CRT).
   1.893 +*/
   1.894 +static SECStatus 
   1.895 +rsa_PrivateKeyOpNoCRT(RSAPrivateKey *key, mp_int *m, mp_int *c, mp_int *n,
   1.896 +                      unsigned int modLen)
   1.897 +{
   1.898 +    mp_int d;
   1.899 +    mp_err   err = MP_OKAY;
   1.900 +    SECStatus rv = SECSuccess;
   1.901 +    MP_DIGITS(&d) = 0;
   1.902 +    CHECK_MPI_OK( mp_init(&d) );
   1.903 +    SECITEM_TO_MPINT(key->privateExponent, &d);
   1.904 +    /* 1. m = c**d mod n */
   1.905 +    CHECK_MPI_OK( mp_exptmod(c, &d, n, m) );
   1.906 +cleanup:
   1.907 +    mp_clear(&d);
   1.908 +    if (err) {
   1.909 +	MP_TO_SEC_ERROR(err);
   1.910 +	rv = SECFailure;
   1.911 +    }
   1.912 +    return rv;
   1.913 +}
   1.914 +
   1.915 +/*
   1.916 +**  RSA Private key operation using CRT.
   1.917 +*/
   1.918 +static SECStatus 
   1.919 +rsa_PrivateKeyOpCRTNoCheck(RSAPrivateKey *key, mp_int *m, mp_int *c)
   1.920 +{
   1.921 +    mp_int p, q, d_p, d_q, qInv;
   1.922 +    mp_int m1, m2, h, ctmp;
   1.923 +    mp_err   err = MP_OKAY;
   1.924 +    SECStatus rv = SECSuccess;
   1.925 +    MP_DIGITS(&p)    = 0;
   1.926 +    MP_DIGITS(&q)    = 0;
   1.927 +    MP_DIGITS(&d_p)  = 0;
   1.928 +    MP_DIGITS(&d_q)  = 0;
   1.929 +    MP_DIGITS(&qInv) = 0;
   1.930 +    MP_DIGITS(&m1)   = 0;
   1.931 +    MP_DIGITS(&m2)   = 0;
   1.932 +    MP_DIGITS(&h)    = 0;
   1.933 +    MP_DIGITS(&ctmp) = 0;
   1.934 +    CHECK_MPI_OK( mp_init(&p)    );
   1.935 +    CHECK_MPI_OK( mp_init(&q)    );
   1.936 +    CHECK_MPI_OK( mp_init(&d_p)  );
   1.937 +    CHECK_MPI_OK( mp_init(&d_q)  );
   1.938 +    CHECK_MPI_OK( mp_init(&qInv) );
   1.939 +    CHECK_MPI_OK( mp_init(&m1)   );
   1.940 +    CHECK_MPI_OK( mp_init(&m2)   );
   1.941 +    CHECK_MPI_OK( mp_init(&h)    );
   1.942 +    CHECK_MPI_OK( mp_init(&ctmp) );
   1.943 +    /* copy private key parameters into mp integers */
   1.944 +    SECITEM_TO_MPINT(key->prime1,      &p);    /* p */
   1.945 +    SECITEM_TO_MPINT(key->prime2,      &q);    /* q */
   1.946 +    SECITEM_TO_MPINT(key->exponent1,   &d_p);  /* d_p  = d mod (p-1) */
   1.947 +    SECITEM_TO_MPINT(key->exponent2,   &d_q);  /* d_q  = d mod (q-1) */
   1.948 +    SECITEM_TO_MPINT(key->coefficient, &qInv); /* qInv = q**-1 mod p */
   1.949 +    /* 1. m1 = c**d_p mod p */
   1.950 +    CHECK_MPI_OK( mp_mod(c, &p, &ctmp) );
   1.951 +    CHECK_MPI_OK( mp_exptmod(&ctmp, &d_p, &p, &m1) );
   1.952 +    /* 2. m2 = c**d_q mod q */
   1.953 +    CHECK_MPI_OK( mp_mod(c, &q, &ctmp) );
   1.954 +    CHECK_MPI_OK( mp_exptmod(&ctmp, &d_q, &q, &m2) );
   1.955 +    /* 3.  h = (m1 - m2) * qInv mod p */
   1.956 +    CHECK_MPI_OK( mp_submod(&m1, &m2, &p, &h) );
   1.957 +    CHECK_MPI_OK( mp_mulmod(&h, &qInv, &p, &h)  );
   1.958 +    /* 4.  m = m2 + h * q */
   1.959 +    CHECK_MPI_OK( mp_mul(&h, &q, m) );
   1.960 +    CHECK_MPI_OK( mp_add(m, &m2, m) );
   1.961 +cleanup:
   1.962 +    mp_clear(&p);
   1.963 +    mp_clear(&q);
   1.964 +    mp_clear(&d_p);
   1.965 +    mp_clear(&d_q);
   1.966 +    mp_clear(&qInv);
   1.967 +    mp_clear(&m1);
   1.968 +    mp_clear(&m2);
   1.969 +    mp_clear(&h);
   1.970 +    mp_clear(&ctmp);
   1.971 +    if (err) {
   1.972 +	MP_TO_SEC_ERROR(err);
   1.973 +	rv = SECFailure;
   1.974 +    }
   1.975 +    return rv;
   1.976 +}
   1.977 +
   1.978 +/*
   1.979 +** An attack against RSA CRT was described by Boneh, DeMillo, and Lipton in:
   1.980 +** "On the Importance of Eliminating Errors in Cryptographic Computations",
   1.981 +** http://theory.stanford.edu/~dabo/papers/faults.ps.gz
   1.982 +**
   1.983 +** As a defense against the attack, carry out the private key operation, 
   1.984 +** followed up with a public key operation to invert the result.  
   1.985 +** Verify that result against the input.
   1.986 +*/
   1.987 +static SECStatus 
   1.988 +rsa_PrivateKeyOpCRTCheckedPubKey(RSAPrivateKey *key, mp_int *m, mp_int *c)
   1.989 +{
   1.990 +    mp_int n, e, v;
   1.991 +    mp_err   err = MP_OKAY;
   1.992 +    SECStatus rv = SECSuccess;
   1.993 +    MP_DIGITS(&n) = 0;
   1.994 +    MP_DIGITS(&e) = 0;
   1.995 +    MP_DIGITS(&v) = 0;
   1.996 +    CHECK_MPI_OK( mp_init(&n) );
   1.997 +    CHECK_MPI_OK( mp_init(&e) );
   1.998 +    CHECK_MPI_OK( mp_init(&v) );
   1.999 +    CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, m, c) );
  1.1000 +    SECITEM_TO_MPINT(key->modulus,        &n);
  1.1001 +    SECITEM_TO_MPINT(key->publicExponent, &e);
  1.1002 +    /* Perform a public key operation v = m ** e mod n */
  1.1003 +    CHECK_MPI_OK( mp_exptmod(m, &e, &n, &v) );
  1.1004 +    if (mp_cmp(&v, c) != 0) {
  1.1005 +	rv = SECFailure;
  1.1006 +    }
  1.1007 +cleanup:
  1.1008 +    mp_clear(&n);
  1.1009 +    mp_clear(&e);
  1.1010 +    mp_clear(&v);
  1.1011 +    if (err) {
  1.1012 +	MP_TO_SEC_ERROR(err);
  1.1013 +	rv = SECFailure;
  1.1014 +    }
  1.1015 +    return rv;
  1.1016 +}
  1.1017 +
  1.1018 +static PRCallOnceType coBPInit = { 0, 0, 0 };
  1.1019 +static PRStatus 
  1.1020 +init_blinding_params_list(void)
  1.1021 +{
  1.1022 +    blindingParamsList.lock = PZ_NewLock(nssILockOther);
  1.1023 +    if (!blindingParamsList.lock) {
  1.1024 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
  1.1025 +	return PR_FAILURE;
  1.1026 +    }
  1.1027 +    blindingParamsList.cVar = PR_NewCondVar( blindingParamsList.lock );
  1.1028 +    if (!blindingParamsList.cVar) {
  1.1029 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
  1.1030 +	return PR_FAILURE;
  1.1031 +    }
  1.1032 +    blindingParamsList.waitCount = 0;
  1.1033 +    PR_INIT_CLIST(&blindingParamsList.head);
  1.1034 +    return PR_SUCCESS;
  1.1035 +}
  1.1036 +
  1.1037 +static SECStatus
  1.1038 +generate_blinding_params(RSAPrivateKey *key, mp_int* f, mp_int* g, mp_int *n, 
  1.1039 +                         unsigned int modLen)
  1.1040 +{
  1.1041 +    SECStatus rv = SECSuccess;
  1.1042 +    mp_int e, k;
  1.1043 +    mp_err err = MP_OKAY;
  1.1044 +    unsigned char *kb = NULL;
  1.1045 +
  1.1046 +    MP_DIGITS(&e) = 0;
  1.1047 +    MP_DIGITS(&k) = 0;
  1.1048 +    CHECK_MPI_OK( mp_init(&e) );
  1.1049 +    CHECK_MPI_OK( mp_init(&k) );
  1.1050 +    SECITEM_TO_MPINT(key->publicExponent, &e);
  1.1051 +    /* generate random k < n */
  1.1052 +    kb = PORT_Alloc(modLen);
  1.1053 +    if (!kb) {
  1.1054 +	PORT_SetError(SEC_ERROR_NO_MEMORY);
  1.1055 +	goto cleanup;
  1.1056 +    }
  1.1057 +    CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(kb, modLen) );
  1.1058 +    CHECK_MPI_OK( mp_read_unsigned_octets(&k, kb, modLen) );
  1.1059 +    /* k < n */
  1.1060 +    CHECK_MPI_OK( mp_mod(&k, n, &k) );
  1.1061 +    /* f = k**e mod n */
  1.1062 +    CHECK_MPI_OK( mp_exptmod(&k, &e, n, f) );
  1.1063 +    /* g = k**-1 mod n */
  1.1064 +    CHECK_MPI_OK( mp_invmod(&k, n, g) );
  1.1065 +cleanup:
  1.1066 +    if (kb)
  1.1067 +	PORT_ZFree(kb, modLen);
  1.1068 +    mp_clear(&k);
  1.1069 +    mp_clear(&e);
  1.1070 +    if (err) {
  1.1071 +	MP_TO_SEC_ERROR(err);
  1.1072 +	rv = SECFailure;
  1.1073 +    }
  1.1074 +    return rv;
  1.1075 +}
  1.1076 +
  1.1077 +static SECStatus
  1.1078 +init_blinding_params(RSABlindingParams *rsabp, RSAPrivateKey *key,
  1.1079 +                     mp_int *n, unsigned int modLen)
  1.1080 +{
  1.1081 +    blindingParams * bp = rsabp->array;
  1.1082 +    int i = 0;
  1.1083 +
  1.1084 +    /* Initialize the list pointer for the element */
  1.1085 +    PR_INIT_CLIST(&rsabp->link);
  1.1086 +    for (i = 0; i < RSA_BLINDING_PARAMS_MAX_CACHE_SIZE; ++i, ++bp) {
  1.1087 +    	bp->next = bp + 1;
  1.1088 +	MP_DIGITS(&bp->f) = 0;
  1.1089 +	MP_DIGITS(&bp->g) = 0;
  1.1090 +	bp->counter = 0;
  1.1091 +    }
  1.1092 +    /* The last bp->next value was initialized with out
  1.1093 +     * of rsabp->array pointer and must be set to NULL 
  1.1094 +     */ 
  1.1095 +    rsabp->array[RSA_BLINDING_PARAMS_MAX_CACHE_SIZE - 1].next = NULL;
  1.1096 +    
  1.1097 +    bp          = rsabp->array;
  1.1098 +    rsabp->bp   = NULL;
  1.1099 +    rsabp->free = bp;
  1.1100 +
  1.1101 +    /* List elements are keyed using the modulus */
  1.1102 +    SECITEM_CopyItem(NULL, &rsabp->modulus, &key->modulus);
  1.1103 +
  1.1104 +    return SECSuccess;
  1.1105 +}
  1.1106 +
  1.1107 +static SECStatus
  1.1108 +get_blinding_params(RSAPrivateKey *key, mp_int *n, unsigned int modLen,
  1.1109 +                    mp_int *f, mp_int *g)
  1.1110 +{
  1.1111 +    RSABlindingParams *rsabp           = NULL;
  1.1112 +    blindingParams    *bpUnlinked      = NULL;
  1.1113 +    blindingParams    *bp;
  1.1114 +    PRCList           *el;
  1.1115 +    SECStatus          rv              = SECSuccess;
  1.1116 +    mp_err             err             = MP_OKAY;
  1.1117 +    int                cmp             = -1;
  1.1118 +    PRBool             holdingLock     = PR_FALSE;
  1.1119 +
  1.1120 +    do {
  1.1121 +	if (blindingParamsList.lock == NULL) {
  1.1122 +	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
  1.1123 +	    return SECFailure;
  1.1124 +	}
  1.1125 +	/* Acquire the list lock */
  1.1126 +	PZ_Lock(blindingParamsList.lock);
  1.1127 +	holdingLock = PR_TRUE;
  1.1128 +
  1.1129 +	/* Walk the list looking for the private key */
  1.1130 +	for (el = PR_NEXT_LINK(&blindingParamsList.head);
  1.1131 +	     el != &blindingParamsList.head;
  1.1132 +	     el = PR_NEXT_LINK(el)) {
  1.1133 +	    rsabp = (RSABlindingParams *)el;
  1.1134 +	    cmp = SECITEM_CompareItem(&rsabp->modulus, &key->modulus);
  1.1135 +	    if (cmp >= 0) {
  1.1136 +		/* The key is found or not in the list. */
  1.1137 +		break;
  1.1138 +	    }
  1.1139 +	}
  1.1140 +
  1.1141 +	if (cmp) {
  1.1142 +	    /* At this point, the key is not in the list.  el should point to 
  1.1143 +	    ** the list element before which this key should be inserted. 
  1.1144 +	    */
  1.1145 +	    rsabp = PORT_ZNew(RSABlindingParams);
  1.1146 +	    if (!rsabp) {
  1.1147 +		PORT_SetError(SEC_ERROR_NO_MEMORY);
  1.1148 +		goto cleanup;
  1.1149 +	    }
  1.1150 +
  1.1151 +	    rv = init_blinding_params(rsabp, key, n, modLen);
  1.1152 +	    if (rv != SECSuccess) {
  1.1153 +		PORT_ZFree(rsabp, sizeof(RSABlindingParams));
  1.1154 +		goto cleanup;
  1.1155 +	    }
  1.1156 +
  1.1157 +	    /* Insert the new element into the list
  1.1158 +	    ** If inserting in the middle of the list, el points to the link
  1.1159 +	    ** to insert before.  Otherwise, the link needs to be appended to
  1.1160 +	    ** the end of the list, which is the same as inserting before the
  1.1161 +	    ** head (since el would have looped back to the head).
  1.1162 +	    */
  1.1163 +	    PR_INSERT_BEFORE(&rsabp->link, el);
  1.1164 +	}
  1.1165 +
  1.1166 +	/* We've found (or created) the RSAblindingParams struct for this key.
  1.1167 +	 * Now, search its list of ready blinding params for a usable one.
  1.1168 +	 */
  1.1169 +	while (0 != (bp = rsabp->bp)) {
  1.1170 +	    if (--(bp->counter) > 0) {
  1.1171 +		/* Found a match and there are still remaining uses left */
  1.1172 +		/* Return the parameters */
  1.1173 +		CHECK_MPI_OK( mp_copy(&bp->f, f) );
  1.1174 +		CHECK_MPI_OK( mp_copy(&bp->g, g) );
  1.1175 +
  1.1176 +		PZ_Unlock(blindingParamsList.lock); 
  1.1177 +		return SECSuccess;
  1.1178 +	    }
  1.1179 +	    /* exhausted this one, give its values to caller, and
  1.1180 +	     * then retire it.
  1.1181 +	     */
  1.1182 +	    mp_exch(&bp->f, f);
  1.1183 +	    mp_exch(&bp->g, g);
  1.1184 +	    mp_clear( &bp->f );
  1.1185 +	    mp_clear( &bp->g );
  1.1186 +	    bp->counter = 0;
  1.1187 +	    /* Move to free list */
  1.1188 +	    rsabp->bp   = bp->next;
  1.1189 +	    bp->next    = rsabp->free;
  1.1190 +	    rsabp->free = bp;
  1.1191 +	    /* In case there're threads waiting for new blinding
  1.1192 +	     * value - notify 1 thread the value is ready
  1.1193 +	     */
  1.1194 +	    if (blindingParamsList.waitCount > 0) {
  1.1195 +		PR_NotifyCondVar( blindingParamsList.cVar );
  1.1196 +		blindingParamsList.waitCount--;
  1.1197 +	    }
  1.1198 +	    PZ_Unlock(blindingParamsList.lock); 
  1.1199 +	    return SECSuccess;
  1.1200 +	}
  1.1201 +	/* We did not find a usable set of blinding params.  Can we make one? */
  1.1202 +	/* Find a free bp struct. */
  1.1203 +	if ((bp = rsabp->free) != NULL) {
  1.1204 +	    /* unlink this bp */
  1.1205 +	    rsabp->free  = bp->next;
  1.1206 +	    bp->next     = NULL;
  1.1207 +	    bpUnlinked   = bp;  /* In case we fail */
  1.1208 +
  1.1209 +	    PZ_Unlock(blindingParamsList.lock); 
  1.1210 +	    holdingLock = PR_FALSE;
  1.1211 +	    /* generate blinding parameter values for the current thread */
  1.1212 +	    CHECK_SEC_OK( generate_blinding_params(key, f, g, n, modLen ) );
  1.1213 +
  1.1214 +	    /* put the blinding parameter values into cache */
  1.1215 +	    CHECK_MPI_OK( mp_init( &bp->f) );
  1.1216 +	    CHECK_MPI_OK( mp_init( &bp->g) );
  1.1217 +	    CHECK_MPI_OK( mp_copy( f, &bp->f) );
  1.1218 +	    CHECK_MPI_OK( mp_copy( g, &bp->g) );
  1.1219 +
  1.1220 +	    /* Put this at head of queue of usable params. */
  1.1221 +	    PZ_Lock(blindingParamsList.lock);
  1.1222 +	    holdingLock = PR_TRUE;
  1.1223 +	    /* initialize RSABlindingParamsStr */
  1.1224 +	    bp->counter = RSA_BLINDING_PARAMS_MAX_REUSE;
  1.1225 +	    bp->next    = rsabp->bp;
  1.1226 +	    rsabp->bp   = bp;
  1.1227 +	    bpUnlinked  = NULL;
  1.1228 +	    /* In case there're threads waiting for new blinding value
  1.1229 +	     * just notify them the value is ready
  1.1230 +	     */
  1.1231 +	    if (blindingParamsList.waitCount > 0) {
  1.1232 +		PR_NotifyAllCondVar( blindingParamsList.cVar );
  1.1233 +		blindingParamsList.waitCount = 0;
  1.1234 +	    }
  1.1235 +	    PZ_Unlock(blindingParamsList.lock);
  1.1236 +	    return SECSuccess;
  1.1237 +	}
  1.1238 +	/* Here, there are no usable blinding parameters available,
  1.1239 +	 * and no free bp blocks, presumably because they're all 
  1.1240 +	 * actively having parameters generated for them.
  1.1241 +	 * So, we need to wait here and not eat up CPU until some 
  1.1242 +	 * change happens. 
  1.1243 +	 */
  1.1244 +	blindingParamsList.waitCount++;
  1.1245 +	PR_WaitCondVar( blindingParamsList.cVar, PR_INTERVAL_NO_TIMEOUT );
  1.1246 +	PZ_Unlock(blindingParamsList.lock); 
  1.1247 +	holdingLock = PR_FALSE;
  1.1248 +    } while (1);
  1.1249 +
  1.1250 +cleanup:
  1.1251 +    /* It is possible to reach this after the lock is already released.  */
  1.1252 +    if (bpUnlinked) {
  1.1253 +	if (!holdingLock) {
  1.1254 +	    PZ_Lock(blindingParamsList.lock);
  1.1255 +	    holdingLock = PR_TRUE;
  1.1256 +	}
  1.1257 +	bp = bpUnlinked;
  1.1258 +	mp_clear( &bp->f );
  1.1259 +	mp_clear( &bp->g );
  1.1260 +	bp->counter = 0;
  1.1261 +    	/* Must put the unlinked bp back on the free list */
  1.1262 +	bp->next    = rsabp->free;
  1.1263 +	rsabp->free = bp;
  1.1264 +    }
  1.1265 +    if (holdingLock) {
  1.1266 +	PZ_Unlock(blindingParamsList.lock);
  1.1267 +	holdingLock = PR_FALSE;
  1.1268 +    }
  1.1269 +    if (err) {
  1.1270 +	MP_TO_SEC_ERROR(err);
  1.1271 +    }
  1.1272 +    return SECFailure;
  1.1273 +}
  1.1274 +
  1.1275 +/*
  1.1276 +** Perform a raw private-key operation 
  1.1277 +**	Length of input and output buffers are equal to key's modulus len.
  1.1278 +*/
  1.1279 +static SECStatus 
  1.1280 +rsa_PrivateKeyOp(RSAPrivateKey *key, 
  1.1281 +                 unsigned char *output, 
  1.1282 +                 const unsigned char *input,
  1.1283 +                 PRBool check)
  1.1284 +{
  1.1285 +    unsigned int modLen;
  1.1286 +    unsigned int offset;
  1.1287 +    SECStatus rv = SECSuccess;
  1.1288 +    mp_err err;
  1.1289 +    mp_int n, c, m;
  1.1290 +    mp_int f, g;
  1.1291 +    if (!key || !output || !input) {
  1.1292 +	PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1.1293 +	return SECFailure;
  1.1294 +    }
  1.1295 +    /* check input out of range (needs to be in range [0..n-1]) */
  1.1296 +    modLen = rsa_modulusLen(&key->modulus);
  1.1297 +    offset = (key->modulus.data[0] == 0) ? 1 : 0; /* may be leading 0 */
  1.1298 +    if (memcmp(input, key->modulus.data + offset, modLen) >= 0) {
  1.1299 +	PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1.1300 +	return SECFailure;
  1.1301 +    }
  1.1302 +    MP_DIGITS(&n) = 0;
  1.1303 +    MP_DIGITS(&c) = 0;
  1.1304 +    MP_DIGITS(&m) = 0;
  1.1305 +    MP_DIGITS(&f) = 0;
  1.1306 +    MP_DIGITS(&g) = 0;
  1.1307 +    CHECK_MPI_OK( mp_init(&n) );
  1.1308 +    CHECK_MPI_OK( mp_init(&c) );
  1.1309 +    CHECK_MPI_OK( mp_init(&m) );
  1.1310 +    CHECK_MPI_OK( mp_init(&f) );
  1.1311 +    CHECK_MPI_OK( mp_init(&g) );
  1.1312 +    SECITEM_TO_MPINT(key->modulus, &n);
  1.1313 +    OCTETS_TO_MPINT(input, &c, modLen);
  1.1314 +    /* If blinding, compute pre-image of ciphertext by multiplying by
  1.1315 +    ** blinding factor
  1.1316 +    */
  1.1317 +    if (nssRSAUseBlinding) {
  1.1318 +	CHECK_SEC_OK( get_blinding_params(key, &n, modLen, &f, &g) );
  1.1319 +	/* c' = c*f mod n */
  1.1320 +	CHECK_MPI_OK( mp_mulmod(&c, &f, &n, &c) );
  1.1321 +    }
  1.1322 +    /* Do the private key operation m = c**d mod n */
  1.1323 +    if ( key->prime1.len      == 0 ||
  1.1324 +         key->prime2.len      == 0 ||
  1.1325 +         key->exponent1.len   == 0 ||
  1.1326 +         key->exponent2.len   == 0 ||
  1.1327 +         key->coefficient.len == 0) {
  1.1328 +	CHECK_SEC_OK( rsa_PrivateKeyOpNoCRT(key, &m, &c, &n, modLen) );
  1.1329 +    } else if (check) {
  1.1330 +	CHECK_SEC_OK( rsa_PrivateKeyOpCRTCheckedPubKey(key, &m, &c) );
  1.1331 +    } else {
  1.1332 +	CHECK_SEC_OK( rsa_PrivateKeyOpCRTNoCheck(key, &m, &c) );
  1.1333 +    }
  1.1334 +    /* If blinding, compute post-image of plaintext by multiplying by
  1.1335 +    ** blinding factor
  1.1336 +    */
  1.1337 +    if (nssRSAUseBlinding) {
  1.1338 +	/* m = m'*g mod n */
  1.1339 +	CHECK_MPI_OK( mp_mulmod(&m, &g, &n, &m) );
  1.1340 +    }
  1.1341 +    err = mp_to_fixlen_octets(&m, output, modLen);
  1.1342 +    if (err >= 0) err = MP_OKAY;
  1.1343 +cleanup:
  1.1344 +    mp_clear(&n);
  1.1345 +    mp_clear(&c);
  1.1346 +    mp_clear(&m);
  1.1347 +    mp_clear(&f);
  1.1348 +    mp_clear(&g);
  1.1349 +    if (err) {
  1.1350 +	MP_TO_SEC_ERROR(err);
  1.1351 +	rv = SECFailure;
  1.1352 +    }
  1.1353 +    return rv;
  1.1354 +}
  1.1355 +
  1.1356 +SECStatus 
  1.1357 +RSA_PrivateKeyOp(RSAPrivateKey *key, 
  1.1358 +                 unsigned char *output, 
  1.1359 +                 const unsigned char *input)
  1.1360 +{
  1.1361 +    return rsa_PrivateKeyOp(key, output, input, PR_FALSE);
  1.1362 +}
  1.1363 +
  1.1364 +SECStatus 
  1.1365 +RSA_PrivateKeyOpDoubleChecked(RSAPrivateKey *key, 
  1.1366 +                              unsigned char *output, 
  1.1367 +                              const unsigned char *input)
  1.1368 +{
  1.1369 +    return rsa_PrivateKeyOp(key, output, input, PR_TRUE);
  1.1370 +}
  1.1371 +
  1.1372 +SECStatus
  1.1373 +RSA_PrivateKeyCheck(const RSAPrivateKey *key)
  1.1374 +{
  1.1375 +    mp_int p, q, n, psub1, qsub1, e, d, d_p, d_q, qInv, res;
  1.1376 +    mp_err   err = MP_OKAY;
  1.1377 +    SECStatus rv = SECSuccess;
  1.1378 +    MP_DIGITS(&p)    = 0;
  1.1379 +    MP_DIGITS(&q)    = 0;
  1.1380 +    MP_DIGITS(&n)    = 0;
  1.1381 +    MP_DIGITS(&psub1)= 0;
  1.1382 +    MP_DIGITS(&qsub1)= 0;
  1.1383 +    MP_DIGITS(&e)    = 0;
  1.1384 +    MP_DIGITS(&d)    = 0;
  1.1385 +    MP_DIGITS(&d_p)  = 0;
  1.1386 +    MP_DIGITS(&d_q)  = 0;
  1.1387 +    MP_DIGITS(&qInv) = 0;
  1.1388 +    MP_DIGITS(&res)  = 0;
  1.1389 +    CHECK_MPI_OK( mp_init(&p)    );
  1.1390 +    CHECK_MPI_OK( mp_init(&q)    );
  1.1391 +    CHECK_MPI_OK( mp_init(&n)    );
  1.1392 +    CHECK_MPI_OK( mp_init(&psub1));
  1.1393 +    CHECK_MPI_OK( mp_init(&qsub1));
  1.1394 +    CHECK_MPI_OK( mp_init(&e)    );
  1.1395 +    CHECK_MPI_OK( mp_init(&d)    );
  1.1396 +    CHECK_MPI_OK( mp_init(&d_p)  );
  1.1397 +    CHECK_MPI_OK( mp_init(&d_q)  );
  1.1398 +    CHECK_MPI_OK( mp_init(&qInv) );
  1.1399 +    CHECK_MPI_OK( mp_init(&res)  );
  1.1400 +
  1.1401 +    if (!key->modulus.data || !key->prime1.data || !key->prime2.data ||
  1.1402 +        !key->publicExponent.data || !key->privateExponent.data ||
  1.1403 +        !key->exponent1.data || !key->exponent2.data ||
  1.1404 +        !key->coefficient.data) {
  1.1405 +        /* call RSA_PopulatePrivateKey first, if the application wishes to
  1.1406 +         * recover these parameters */
  1.1407 +        err = MP_BADARG;
  1.1408 +        goto cleanup;
  1.1409 +    }
  1.1410 +
  1.1411 +    SECITEM_TO_MPINT(key->modulus,         &n);
  1.1412 +    SECITEM_TO_MPINT(key->prime1,          &p);
  1.1413 +    SECITEM_TO_MPINT(key->prime2,          &q);
  1.1414 +    SECITEM_TO_MPINT(key->publicExponent,  &e);
  1.1415 +    SECITEM_TO_MPINT(key->privateExponent, &d);
  1.1416 +    SECITEM_TO_MPINT(key->exponent1,       &d_p);
  1.1417 +    SECITEM_TO_MPINT(key->exponent2,       &d_q);
  1.1418 +    SECITEM_TO_MPINT(key->coefficient,     &qInv);
  1.1419 +    /* p and q must be distinct. */
  1.1420 +    if (mp_cmp(&p, &q) == 0) {
  1.1421 +	rv = SECFailure;
  1.1422 +	goto cleanup;
  1.1423 +    }
  1.1424 +#define VERIFY_MPI_EQUAL(m1, m2) \
  1.1425 +    if (mp_cmp(m1, m2) != 0) {   \
  1.1426 +	rv = SECFailure;         \
  1.1427 +	goto cleanup;            \
  1.1428 +    }
  1.1429 +#define VERIFY_MPI_EQUAL_1(m)    \
  1.1430 +    if (mp_cmp_d(m, 1) != 0) {   \
  1.1431 +	rv = SECFailure;         \
  1.1432 +	goto cleanup;            \
  1.1433 +    }
  1.1434 +    /* n == p * q */
  1.1435 +    CHECK_MPI_OK( mp_mul(&p, &q, &res) );
  1.1436 +    VERIFY_MPI_EQUAL(&res, &n);
  1.1437 +    /* gcd(e, p-1) == 1 */
  1.1438 +    CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) );
  1.1439 +    CHECK_MPI_OK( mp_gcd(&e, &psub1, &res) );
  1.1440 +    VERIFY_MPI_EQUAL_1(&res);
  1.1441 +    /* gcd(e, q-1) == 1 */
  1.1442 +    CHECK_MPI_OK( mp_sub_d(&q, 1, &qsub1) );
  1.1443 +    CHECK_MPI_OK( mp_gcd(&e, &qsub1, &res) );
  1.1444 +    VERIFY_MPI_EQUAL_1(&res);
  1.1445 +    /* d*e == 1 mod p-1 */
  1.1446 +    CHECK_MPI_OK( mp_mulmod(&d, &e, &psub1, &res) );
  1.1447 +    VERIFY_MPI_EQUAL_1(&res);
  1.1448 +    /* d*e == 1 mod q-1 */
  1.1449 +    CHECK_MPI_OK( mp_mulmod(&d, &e, &qsub1, &res) );
  1.1450 +    VERIFY_MPI_EQUAL_1(&res);
  1.1451 +    /* d_p == d mod p-1 */
  1.1452 +    CHECK_MPI_OK( mp_mod(&d, &psub1, &res) );
  1.1453 +    VERIFY_MPI_EQUAL(&res, &d_p);
  1.1454 +    /* d_q == d mod q-1 */
  1.1455 +    CHECK_MPI_OK( mp_mod(&d, &qsub1, &res) );
  1.1456 +    VERIFY_MPI_EQUAL(&res, &d_q);
  1.1457 +    /* q * q**-1 == 1 mod p */
  1.1458 +    CHECK_MPI_OK( mp_mulmod(&q, &qInv, &p, &res) );
  1.1459 +    VERIFY_MPI_EQUAL_1(&res);
  1.1460 +
  1.1461 +cleanup:
  1.1462 +    mp_clear(&n);
  1.1463 +    mp_clear(&p);
  1.1464 +    mp_clear(&q);
  1.1465 +    mp_clear(&psub1);
  1.1466 +    mp_clear(&qsub1);
  1.1467 +    mp_clear(&e);
  1.1468 +    mp_clear(&d);
  1.1469 +    mp_clear(&d_p);
  1.1470 +    mp_clear(&d_q);
  1.1471 +    mp_clear(&qInv);
  1.1472 +    mp_clear(&res);
  1.1473 +    if (err) {
  1.1474 +	MP_TO_SEC_ERROR(err);
  1.1475 +	rv = SECFailure;
  1.1476 +    }
  1.1477 +    return rv;
  1.1478 +}
  1.1479 +
  1.1480 +static SECStatus RSA_Init(void)
  1.1481 +{
  1.1482 +    if (PR_CallOnce(&coBPInit, init_blinding_params_list) != PR_SUCCESS) {
  1.1483 +        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
  1.1484 +        return SECFailure;
  1.1485 +    }
  1.1486 +    return SECSuccess;
  1.1487 +}
  1.1488 +
  1.1489 +SECStatus BL_Init(void)
  1.1490 +{
  1.1491 +    return RSA_Init();
  1.1492 +}
  1.1493 +
  1.1494 +/* cleanup at shutdown */
  1.1495 +void RSA_Cleanup(void)
  1.1496 +{
  1.1497 +    blindingParams * bp = NULL;
  1.1498 +    if (!coBPInit.initialized)
  1.1499 +	return;
  1.1500 +
  1.1501 +    while (!PR_CLIST_IS_EMPTY(&blindingParamsList.head)) {
  1.1502 +	RSABlindingParams *rsabp = 
  1.1503 +	    (RSABlindingParams *)PR_LIST_HEAD(&blindingParamsList.head);
  1.1504 +	PR_REMOVE_LINK(&rsabp->link);
  1.1505 +	/* clear parameters cache */
  1.1506 +	while (rsabp->bp != NULL) {
  1.1507 +	    bp = rsabp->bp;
  1.1508 +	    rsabp->bp = rsabp->bp->next;
  1.1509 +	    mp_clear( &bp->f );
  1.1510 +	    mp_clear( &bp->g );
  1.1511 +	}
  1.1512 +	SECITEM_FreeItem(&rsabp->modulus,PR_FALSE);
  1.1513 +	PORT_Free(rsabp);
  1.1514 +    }
  1.1515 +
  1.1516 +    if (blindingParamsList.cVar) {
  1.1517 +	PR_DestroyCondVar(blindingParamsList.cVar);
  1.1518 +	blindingParamsList.cVar = NULL;
  1.1519 +    }
  1.1520 +
  1.1521 +    if (blindingParamsList.lock) {
  1.1522 +	SKIP_AFTER_FORK(PZ_DestroyLock(blindingParamsList.lock));
  1.1523 +	blindingParamsList.lock = NULL;
  1.1524 +    }
  1.1525 +
  1.1526 +    coBPInit.initialized = 0;
  1.1527 +    coBPInit.inProgress = 0;
  1.1528 +    coBPInit.status = 0;
  1.1529 +}
  1.1530 +
  1.1531 +/*
  1.1532 + * need a central place for this function to free up all the memory that
  1.1533 + * free_bl may have allocated along the way. Currently only RSA does this,
  1.1534 + * so I've put it here for now.
  1.1535 + */
  1.1536 +void BL_Cleanup(void)
  1.1537 +{
  1.1538 +    RSA_Cleanup();
  1.1539 +}
  1.1540 +
  1.1541 +PRBool bl_parentForkedAfterC_Initialize;
  1.1542 +
  1.1543 +/*
  1.1544 + * Set fork flag so it can be tested in SKIP_AFTER_FORK on relevant platforms.
  1.1545 + */
  1.1546 +void BL_SetForkState(PRBool forked)
  1.1547 +{
  1.1548 +    bl_parentForkedAfterC_Initialize = forked;
  1.1549 +}
  1.1550 +

mercurial