os/security/crypto/weakcryptospi/source/bigint/primes.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
sl@0
     1
/*
sl@0
     2
* Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
sl@0
     3
* All rights reserved.
sl@0
     4
* This component and the accompanying materials are made available
sl@0
     5
* under the terms of the License "Eclipse Public License v1.0"
sl@0
     6
* which accompanies this distribution, and is available
sl@0
     7
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
sl@0
     8
*
sl@0
     9
* Initial Contributors:
sl@0
    10
* Nokia Corporation - initial contribution.
sl@0
    11
*
sl@0
    12
* Contributors:
sl@0
    13
*
sl@0
    14
* Description: 
sl@0
    15
*
sl@0
    16
*/
sl@0
    17
sl@0
    18
sl@0
    19
#include <bigint.h>
sl@0
    20
#include <e32std.h>
sl@0
    21
#include <securityerr.h>
sl@0
    22
#include "words.h"
sl@0
    23
#include "primes.h"
sl@0
    24
#include "algorithms.h"
sl@0
    25
#include "mont.h"
sl@0
    26
#include "stackinteger.h"
sl@0
    27
sl@0
    28
static TBool IsSmallPrime(TUint aK);
sl@0
    29
sl@0
    30
static inline void EliminateComposites(TUint* aS, TUint aPrime, TUint aJ, 
sl@0
    31
	TUint aMaxIndex)
sl@0
    32
	{
sl@0
    33
	for(; aJ<aMaxIndex; aJ+=aPrime)
sl@0
    34
		ArraySetBit(aS, aJ);
sl@0
    35
	}
sl@0
    36
sl@0
    37
static inline TInt FindLeastSignificantZero(TUint aX)
sl@0
    38
	{
sl@0
    39
	aX = ~aX;
sl@0
    40
	int i = 0;
sl@0
    41
	if( aX << 16 == 0 ) aX>>=16, i+=16;
sl@0
    42
	if( aX << 24 == 0 ) aX>>=8, i+=8;
sl@0
    43
	if( aX << 28 == 0 ) aX>>=4, i+=4;
sl@0
    44
	if( aX << 30 == 0 ) aX>>=2, i+=2;
sl@0
    45
	if( aX << 31 == 0 ) ++i;
sl@0
    46
	return i;
sl@0
    47
	}
sl@0
    48
sl@0
    49
static inline TInt FindFirstPrimeCandidate(TUint* aS, TUint aBitLength)
sl@0
    50
	{
sl@0
    51
	assert(aBitLength % WORD_BITS == 0);
sl@0
    52
	TUint i=0;
sl@0
    53
	//The empty statement at the end of this is stop warnings in all compilers
sl@0
    54
	for(; aS[i] == KMaxTUint && i<BitsToWords(aBitLength); i++) {;}
sl@0
    55
sl@0
    56
	if(i == BitsToWords(aBitLength))
sl@0
    57
		return -1;
sl@0
    58
	else
sl@0
    59
		{
sl@0
    60
		assert( FindLeastSignificantZero((TUint)(aS[i])) >= 0 );
sl@0
    61
		assert( FindLeastSignificantZero((TUint)(aS[i])) <= 31 );
sl@0
    62
		return i*WORD_BITS + FindLeastSignificantZero((TUint32)(aS[i]));
sl@0
    63
		}
sl@0
    64
	}
sl@0
    65
sl@0
    66
static inline TUint FindSmallestIndex(TUint aPrime, TUint aRemainder)
sl@0
    67
	{
sl@0
    68
	TUint& j = aRemainder;
sl@0
    69
	if(j)
sl@0
    70
		{
sl@0
    71
		j = aPrime - aRemainder;
sl@0
    72
		if( j & 0x1L )
sl@0
    73
			{
sl@0
    74
			//if j is odd then this + j is even so we actually want 
sl@0
    75
			//the next number for which (this + j % p == 0) st this + j is odd
sl@0
    76
			//that is: this + j + p == 0 mod p
sl@0
    77
			j += aPrime;
sl@0
    78
			}
sl@0
    79
		//Turn j into an index for a bit array representing odd numbers only
sl@0
    80
		j>>=1;
sl@0
    81
		}
sl@0
    82
	return j;
sl@0
    83
	}
sl@0
    84
sl@0
    85
static inline TUint RabinMillerRounds(TUint aBits) 
sl@0
    86
	{
sl@0
    87
	//See HAC Table 4.4
sl@0
    88
	if(aBits > 1300)
sl@0
    89
		return 2;
sl@0
    90
	if (aBits > 850)
sl@0
    91
		return 3;
sl@0
    92
	if (aBits > 650)
sl@0
    93
		return 4;
sl@0
    94
	if (aBits > 550)
sl@0
    95
		return 5;
sl@0
    96
	if (aBits > 450)
sl@0
    97
		return 6;
sl@0
    98
	if (aBits > 400)
sl@0
    99
		return 7;
sl@0
   100
	if (aBits > 350)
sl@0
   101
		return 8;
sl@0
   102
	if (aBits > 300)
sl@0
   103
		return 9;
sl@0
   104
	if (aBits > 250)
sl@0
   105
		return 12;
sl@0
   106
	if (aBits > 200)
sl@0
   107
		return 15;
sl@0
   108
	if (aBits > 150)
sl@0
   109
		return 18;
sl@0
   110
	if (aBits > 100)
sl@0
   111
		return 27;
sl@0
   112
	//All of the above are optimisations on the worst case.  The worst case
sl@0
   113
	//chance of odd composite integers being declared prime by Rabin-Miller is
sl@0
   114
	//(1/4)^t where t is the number of rounds.  Thus, t = 40 means that the
sl@0
   115
	//chance of declaring a composite integer prime is less than 2^(-80).  See
sl@0
   116
	//HAC Fact 4.25 and most of chapter 4 for more details.
sl@0
   117
	return 40;
sl@0
   118
	}
sl@0
   119
sl@0
   120
static TBool HasSmallDivisorL(const TInteger& aPossiblePrime)
sl@0
   121
	{
sl@0
   122
	assert(aPossiblePrime.IsOdd());
sl@0
   123
	//Start checking at the first odd prime, whether it is even should have
sl@0
   124
	//already been checked
sl@0
   125
	for( TUint i=1; i < KPrimeTableSize; i++ )
sl@0
   126
		{
sl@0
   127
		if( aPossiblePrime.ModuloL(KPrimeTable[i]) == 0 )
sl@0
   128
			{
sl@0
   129
			return ETrue;
sl@0
   130
			}
sl@0
   131
		}
sl@0
   132
	return EFalse;
sl@0
   133
	}
sl@0
   134
sl@0
   135
static TBool RabinMillerIterationL(const CMontgomeryStructure& aMont, 
sl@0
   136
	const TInteger& aProbablePrime, const TInteger& aBase)
sl@0
   137
	{
sl@0
   138
	//see HAC 4.24
sl@0
   139
	const TInteger& n = aProbablePrime;
sl@0
   140
	assert(n > KLastSmallPrimeSquared);
sl@0
   141
	assert(n.IsOdd());
sl@0
   142
	assert(aBase > TInteger::One());
sl@0
   143
sl@0
   144
	RInteger nminus1 = n.MinusL(TInteger::One());
sl@0
   145
	CleanupStack::PushL(nminus1);
sl@0
   146
	assert(aBase < nminus1);
sl@0
   147
sl@0
   148
	// 1) find (s | 2^s*r == n-1) where r is odd
sl@0
   149
	// we want the largest power of 2 that divides n-1
sl@0
   150
	TUint s=0;
sl@0
   151
	for(;;s++)
sl@0
   152
		{
sl@0
   153
		if(nminus1.Bit(s))
sl@0
   154
			{
sl@0
   155
			break;
sl@0
   156
			}
sl@0
   157
		}
sl@0
   158
	// (r = (n-1) / 2^s) which is equiv to (n-1 >>= s)
sl@0
   159
	RInteger r = RInteger::NewL(nminus1);
sl@0
   160
	CleanupStack::PushL(r);
sl@0
   161
	r >>= s;
sl@0
   162
sl@0
   163
	//At no point do we own y, aMont owns it
sl@0
   164
	const TInteger* y = &(aMont.ExponentiateL(aBase, r));
sl@0
   165
sl@0
   166
	TBool probablePrime = EFalse;
sl@0
   167
	
sl@0
   168
	TUint j=1;
sl@0
   169
	if( *y == TInteger::One() || *y == nminus1 )
sl@0
   170
		{
sl@0
   171
		probablePrime = ETrue;
sl@0
   172
		}
sl@0
   173
	else
sl@0
   174
		{
sl@0
   175
		for(j=1; j<s; j++)
sl@0
   176
			{
sl@0
   177
			y = &(aMont.SquareL(*y));
sl@0
   178
			if(*y == nminus1)
sl@0
   179
				{
sl@0
   180
				probablePrime = ETrue;
sl@0
   181
				break;
sl@0
   182
				}
sl@0
   183
			}
sl@0
   184
		}
sl@0
   185
	CleanupStack::PopAndDestroy(&r);
sl@0
   186
	CleanupStack::PopAndDestroy(&nminus1);//y,r,nminus1
sl@0
   187
	return probablePrime;
sl@0
   188
	}
sl@0
   189
sl@0
   190
static TBool RabinMillerTestL(const CMontgomeryStructure& aMont, 
sl@0
   191
	const TInteger& aProbablePrime, TUint aRounds) 
sl@0
   192
	{
sl@0
   193
	const TInteger& n = aProbablePrime;
sl@0
   194
	assert(n > KLastSmallPrimeSquared);
sl@0
   195
	
sl@0
   196
	RInteger nminus2 = n.MinusL(TInteger::Two());
sl@0
   197
	CleanupStack::PushL(nminus2);
sl@0
   198
sl@0
   199
	for(TUint i=0; i<aRounds; i++)
sl@0
   200
		{
sl@0
   201
		RInteger base = RInteger::NewRandomL(TInteger::Two(), nminus2);
sl@0
   202
		CleanupStack::PushL(base);
sl@0
   203
		if(!RabinMillerIterationL(aMont, n, base))
sl@0
   204
			{
sl@0
   205
			CleanupStack::PopAndDestroy(2, &nminus2);//base, nminus2
sl@0
   206
			return EFalse;
sl@0
   207
			}
sl@0
   208
		CleanupStack::PopAndDestroy(&base);
sl@0
   209
		}
sl@0
   210
	CleanupStack::PopAndDestroy(&nminus2);
sl@0
   211
	return ETrue;
sl@0
   212
	}
sl@0
   213
sl@0
   214
static TBool IsStrongProbablePrimeL(const TInteger& aPrime) 
sl@0
   215
	{
sl@0
   216
	CMontgomeryStructure* mont = CMontgomeryStructure::NewLC(aPrime);
sl@0
   217
	//This should be using short circuit evaluation
sl@0
   218
	TBool probablePrime = RabinMillerIterationL(*mont, aPrime, TInteger::Two())
sl@0
   219
		&& RabinMillerTestL(*mont, aPrime,RabinMillerRounds(aPrime.BitCount()));
sl@0
   220
	CleanupStack::PopAndDestroy(mont);
sl@0
   221
	return probablePrime;
sl@0
   222
	}
sl@0
   223
sl@0
   224
/* In the _vast_ majority of cases this simply checks that your chosen random
sl@0
   225
 * number is >= KLastSmallPrimeSquared and return EFalse and lets the normal
sl@0
   226
 * prime generation routines handle the situation.  In the case where it is
sl@0
   227
 * smaller, it generates a provable prime and returns ETrue.  The algorithm for
sl@0
   228
 * finding a provable prime < KLastPrimeSquared is not the most efficient in the
sl@0
   229
 * world, but two points come to mind
sl@0
   230
 * 1) The two if statements hardly _ever_ evaluate to ETrue in real life.
sl@0
   231
 * 2) Even when it is, the distribution of primes < KLastPrimeSquared is pretty
sl@0
   232
 * dense, so you aren't going to have check many.
sl@0
   233
 * This function is essentially here for two reasons:
sl@0
   234
 * 1) Ensures that it is possible to generate primes < KLastPrimeSquared (the
sl@0
   235
 * test code does this)
sl@0
   236
 * 2) Ensures that if you request a prime of a large bit size that there is an
sl@0
   237
 * even probability distribution across all integers < 2^aBits
sl@0
   238
 */
sl@0
   239
TBool TInteger::SmallPrimeRandomizeL(void)
sl@0
   240
	{
sl@0
   241
	TBool foundPrime = EFalse;
sl@0
   242
	//If the random number we've chosen is less than KLastSmallPrime,
sl@0
   243
	//testing for primality is easy.
sl@0
   244
	if(*this <= KLastSmallPrime)
sl@0
   245
		{
sl@0
   246
		//If Zero or One, or two, next prime number is two
sl@0
   247
		if(IsZero() || *this == One() || *this == Two())
sl@0
   248
			{
sl@0
   249
			CopyL(TInteger::Two());
sl@0
   250
			foundPrime = ETrue;
sl@0
   251
			}
sl@0
   252
		else
sl@0
   253
			{
sl@0
   254
			//Make sure any number we bother testing is at least odd
sl@0
   255
			SetBit(0);
sl@0
   256
			//Binary search the small primes.
sl@0
   257
			while(!IsSmallPrime(ConvertToUnsignedLong()))
sl@0
   258
				{
sl@0
   259
				//If not prime, add two and try the next odd number.
sl@0
   260
sl@0
   261
				//will never carry as the minimum size of an RInteger is 2
sl@0
   262
				//words.  Much bigger than KLastSmallPrime on 32bit
sl@0
   263
				//architectures.
sl@0
   264
				IncrementNoCarry(Ptr(), Size(), 2);
sl@0
   265
				}
sl@0
   266
			assert(IsSmallPrime(ConvertToUnsignedLong()));
sl@0
   267
			foundPrime = ETrue;
sl@0
   268
			}
sl@0
   269
		}
sl@0
   270
	else if(*this <= KLastSmallPrimeSquared)
sl@0
   271
		{
sl@0
   272
		//Make sure any number we bother testing is at least odd
sl@0
   273
		SetBit(0);
sl@0
   274
sl@0
   275
		while(HasSmallDivisorL(*this) && *this <= KLastSmallPrimeSquared)
sl@0
   276
			{
sl@0
   277
			//If not prime, add two and try the next odd number.
sl@0
   278
sl@0
   279
			//will never carry as the minimum size of an RInteger is 2
sl@0
   280
			//words.  Much bigger than KLastSmallPrime on 32bit
sl@0
   281
			//architectures.
sl@0
   282
			IncrementNoCarry(Ptr(), Size(), 2);
sl@0
   283
			}
sl@0
   284
		//If we exited while loop because it had no small divisor then it is
sl@0
   285
		//prime.  Otherwise, we've exceeded the limit of what we can provably
sl@0
   286
		//generate.  Therefore the normal prime gen routines will be run on it
sl@0
   287
		//now.
sl@0
   288
		if(*this < KLastSmallPrimeSquared)
sl@0
   289
			{
sl@0
   290
			foundPrime = ETrue;
sl@0
   291
			}
sl@0
   292
		}
sl@0
   293
	//This doesn't mean there is no such prime, simply means that the number
sl@0
   294
	//wasn't less than KSmallPrimeSquared and needs to be handled by the normal
sl@0
   295
	//prime generation routines.
sl@0
   296
	return foundPrime;
sl@0
   297
	}
sl@0
   298
sl@0
   299
void TInteger::PrimeRandomizeL(TUint aBits, TRandomAttribute aAttr)
sl@0
   300
	{
sl@0
   301
	assert(aBits > 1); 
sl@0
   302
	
sl@0
   303
	//"this" is "empty" currently.  Consists of Size() words of 0's.  This is just
sl@0
   304
	//checking that sign flag is positive as we don't set it later.
sl@0
   305
	assert(NotNegative());
sl@0
   306
sl@0
   307
	//Flag for the whole function saying if we've found a prime
sl@0
   308
	TBool foundProbablePrime = EFalse;
sl@0
   309
sl@0
   310
	//Find 2^aBits + 1 -- any prime we find must be less than this.
sl@0
   311
	RInteger max = RInteger::NewEmptyL(BitsToWords(aBits)+1);
sl@0
   312
	CleanupStack::PushL(max);
sl@0
   313
	max.SetBit(aBits);
sl@0
   314
	assert(max.BitCount()-1 == aBits);
sl@0
   315
sl@0
   316
	// aBits 	| approx number of odd numbers you must try to have a 50% 
sl@0
   317
	//			chance of finding a prime
sl@0
   318
	//---------------------------------------------------------
sl@0
   319
	// 512		| 122		
sl@0
   320
	// 1024		| 245
sl@0
   321
	// 2048		| 1023
sl@0
   322
	//Therefore if we are generating larger than 1024 bit numbers we'll use a
sl@0
   323
	//bigger bit array to have a better chance of avoiding re-generating it.
sl@0
   324
	TUint sLength = aBits > 1024 ? 1024 : 512;
sl@0
   325
	RInteger S = RInteger::NewEmptyL(BitsToWords(sLength));
sl@0
   326
	CleanupStack::PushL(S);
sl@0
   327
sl@0
   328
	while(!foundProbablePrime)
sl@0
   329
		{
sl@0
   330
		//Randomly choose aBits
sl@0
   331
		RandomizeL(aBits, aAttr);
sl@0
   332
sl@0
   333
		//If the random number chosen is less than KSmallPrimeSquared, we have a
sl@0
   334
		//special set of routines.
sl@0
   335
		if(SmallPrimeRandomizeL())
sl@0
   336
			{
sl@0
   337
			foundProbablePrime = ETrue;
sl@0
   338
			}
sl@0
   339
		else
sl@0
   340
			{
sl@0
   341
			//if it was <= KLastSmallPrimeSquared then it would have been
sl@0
   342
			//handled by SmallPrimeRandomizeL()
sl@0
   343
			assert(*this > KLastSmallPrimeSquared);
sl@0
   344
sl@0
   345
			//Make sure any number we bother testing is at least odd
sl@0
   346
			SetBit(0);
sl@0
   347
sl@0
   348
			//Ensure that this + 2*sLength < max
sl@0
   349
			RInteger temp = max.MinusL(*this);
sl@0
   350
			CleanupStack::PushL(temp);
sl@0
   351
			++temp;
sl@0
   352
			temp >>=1;
sl@0
   353
			if(temp < sLength)
sl@0
   354
				{
sl@0
   355
				//if this + 2*sLength >= max then we use a smaller sLength to
sl@0
   356
				//ensure we don't find a number that is outside of our bounds
sl@0
   357
				//(and bigger than our allocated memory for this)
sl@0
   358
sl@0
   359
				//temp must be less than KMaxTUint as sLength is a TUint 
sl@0
   360
				sLength = temp.ConvertToUnsignedLong();	
sl@0
   361
				}
sl@0
   362
			CleanupStack::PopAndDestroy(&temp);
sl@0
   363
sl@0
   364
			//Start at 1 as no point in checking against 2 (all odd numbers)
sl@0
   365
			for(TUint i=1; i<KPrimeTableSize; i++)
sl@0
   366
				{
sl@0
   367
				//no need to call ModuloL as we know KPrimeTable[i] is not 0
sl@0
   368
				TUint remainder = Modulo(*this, KPrimeTable[i]);
sl@0
   369
				TUint index = FindSmallestIndex(KPrimeTable[i], remainder);
sl@0
   370
				EliminateComposites(S.Ptr(), KPrimeTable[i], index, sLength);
sl@0
   371
				}
sl@0
   372
			TInt j = FindFirstPrimeCandidate(S.Ptr(), sLength);
sl@0
   373
			TInt prev = 0;
sl@0
   374
			for(; j>=0; j=FindFirstPrimeCandidate(S.Ptr(), sLength))
sl@0
   375
				{
sl@0
   376
				ArraySetBit(S.Ptr(), j);
sl@0
   377
sl@0
   378
				//should never carry as we earlier made sure that 2*j + this < max
sl@0
   379
				//where max is 1 bit more than we asked for.
sl@0
   380
				IncrementNoCarry(Ptr(), Size(), 2*(j-prev));
sl@0
   381
sl@0
   382
				assert(*this < max);
sl@0
   383
				assert(!HasSmallDivisorL(*this));
sl@0
   384
sl@0
   385
				prev = j;
sl@0
   386
sl@0
   387
				if( IsStrongProbablePrimeL(*this) )
sl@0
   388
					{
sl@0
   389
					foundProbablePrime = ETrue;
sl@0
   390
					break;
sl@0
   391
					}
sl@0
   392
				}
sl@0
   393
			//This clears the memory
sl@0
   394
			S.CopyL(0, EFalse);
sl@0
   395
			}
sl@0
   396
		}
sl@0
   397
	CleanupStack::PopAndDestroy(2, &max);
sl@0
   398
	}
sl@0
   399
sl@0
   400
EXPORT_C TBool TInteger::IsPrimeL(void) const
sl@0
   401
	{
sl@0
   402
	if( NotPositive() )
sl@0
   403
		{
sl@0
   404
		return EFalse;
sl@0
   405
		}
sl@0
   406
	else if( IsEven() )
sl@0
   407
		{
sl@0
   408
		return *this == Two();
sl@0
   409
		}
sl@0
   410
	else if( *this <= KLastSmallPrime )
sl@0
   411
		{
sl@0
   412
		assert(KLastSmallPrime < KMaxTUint);
sl@0
   413
		return IsSmallPrime(this->ConvertToUnsignedLong());
sl@0
   414
		}
sl@0
   415
	else if( *this <= KLastSmallPrimeSquared )
sl@0
   416
		{
sl@0
   417
		return !HasSmallDivisorL(*this);
sl@0
   418
		}
sl@0
   419
	else 
sl@0
   420
		{
sl@0
   421
		return !HasSmallDivisorL(*this) && IsStrongProbablePrimeL(*this);
sl@0
   422
		}
sl@0
   423
	}
sl@0
   424
sl@0
   425
// Method is excluded from coverage due to the problem with BullsEye on ONB.
sl@0
   426
// Manually verified that this method is functionally covered.
sl@0
   427
#ifdef _BullseyeCoverage
sl@0
   428
#pragma suppress_warnings on
sl@0
   429
#pragma BullseyeCoverage off
sl@0
   430
#pragma suppress_warnings off
sl@0
   431
#endif
sl@0
   432
sl@0
   433
static TBool IsSmallPrime(TUint aK) 
sl@0
   434
	{
sl@0
   435
	//This is just a binary search of our small prime table.
sl@0
   436
	TUint l = 0;
sl@0
   437
	TUint u = KPrimeTableSize;
sl@0
   438
	while( u > l )
sl@0
   439
		{
sl@0
   440
		TUint m = (l+u)>>1;
sl@0
   441
		TUint p = KPrimeTable[m];
sl@0
   442
		if(aK < p)
sl@0
   443
			u = m;
sl@0
   444
		else if (aK > p)
sl@0
   445
			l = m + 1;
sl@0
   446
		else
sl@0
   447
			return ETrue;
sl@0
   448
		}
sl@0
   449
	return EFalse;
sl@0
   450
	}