Update contrib.
2 * Copyright (c) 2003-2009 Nokia Corporation and/or its subsidiary(-ies).
4 * This component and the accompanying materials are made available
5 * under the terms of the License "Eclipse Public License v1.0"
6 * which accompanies this distribution, and is available
7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
9 * Initial Contributors:
10 * Nokia Corporation - initial contribution.
21 #include <securityerr.h>
24 #include "algorithms.h"
26 #include "stackinteger.h"
28 static TBool IsSmallPrime(TUint aK);
30 static inline void EliminateComposites(TUint* aS, TUint aPrime, TUint aJ,
33 for(; aJ<aMaxIndex; aJ+=aPrime)
37 static inline TInt FindLeastSignificantZero(TUint aX)
41 if( aX << 16 == 0 ) aX>>=16, i+=16;
42 if( aX << 24 == 0 ) aX>>=8, i+=8;
43 if( aX << 28 == 0 ) aX>>=4, i+=4;
44 if( aX << 30 == 0 ) aX>>=2, i+=2;
45 if( aX << 31 == 0 ) ++i;
49 static inline TInt FindFirstPrimeCandidate(TUint* aS, TUint aBitLength)
51 assert(aBitLength % WORD_BITS == 0);
53 //The empty statement at the end of this is stop warnings in all compilers
54 for(; aS[i] == KMaxTUint && i<BitsToWords(aBitLength); i++) {;}
56 if(i == BitsToWords(aBitLength))
60 assert( FindLeastSignificantZero((TUint)(aS[i])) >= 0 );
61 assert( FindLeastSignificantZero((TUint)(aS[i])) <= 31 );
62 return i*WORD_BITS + FindLeastSignificantZero((TUint32)(aS[i]));
66 static inline TUint FindSmallestIndex(TUint aPrime, TUint aRemainder)
68 TUint& j = aRemainder;
71 j = aPrime - aRemainder;
74 //if j is odd then this + j is even so we actually want
75 //the next number for which (this + j % p == 0) st this + j is odd
76 //that is: this + j + p == 0 mod p
79 //Turn j into an index for a bit array representing odd numbers only
85 static inline TUint RabinMillerRounds(TUint aBits)
112 //All of the above are optimisations on the worst case. The worst case
113 //chance of odd composite integers being declared prime by Rabin-Miller is
114 //(1/4)^t where t is the number of rounds. Thus, t = 40 means that the
115 //chance of declaring a composite integer prime is less than 2^(-80). See
116 //HAC Fact 4.25 and most of chapter 4 for more details.
120 static TBool HasSmallDivisorL(const TInteger& aPossiblePrime)
122 assert(aPossiblePrime.IsOdd());
123 //Start checking at the first odd prime, whether it is even should have
124 //already been checked
125 for( TUint i=1; i < KPrimeTableSize; i++ )
127 if( aPossiblePrime.ModuloL(KPrimeTable[i]) == 0 )
135 static TBool RabinMillerIterationL(const CMontgomeryStructure& aMont,
136 const TInteger& aProbablePrime, const TInteger& aBase)
139 const TInteger& n = aProbablePrime;
140 assert(n > KLastSmallPrimeSquared);
142 assert(aBase > TInteger::One());
144 RInteger nminus1 = n.MinusL(TInteger::One());
145 CleanupStack::PushL(nminus1);
146 assert(aBase < nminus1);
148 // 1) find (s | 2^s*r == n-1) where r is odd
149 // we want the largest power of 2 that divides n-1
158 // (r = (n-1) / 2^s) which is equiv to (n-1 >>= s)
159 RInteger r = RInteger::NewL(nminus1);
160 CleanupStack::PushL(r);
163 //At no point do we own y, aMont owns it
164 const TInteger* y = &(aMont.ExponentiateL(aBase, r));
166 TBool probablePrime = EFalse;
169 if( *y == TInteger::One() || *y == nminus1 )
171 probablePrime = ETrue;
177 y = &(aMont.SquareL(*y));
180 probablePrime = ETrue;
185 CleanupStack::PopAndDestroy(&r);
186 CleanupStack::PopAndDestroy(&nminus1);//y,r,nminus1
187 return probablePrime;
190 static TBool RabinMillerTestL(const CMontgomeryStructure& aMont,
191 const TInteger& aProbablePrime, TUint aRounds)
193 const TInteger& n = aProbablePrime;
194 assert(n > KLastSmallPrimeSquared);
196 RInteger nminus2 = n.MinusL(TInteger::Two());
197 CleanupStack::PushL(nminus2);
199 for(TUint i=0; i<aRounds; i++)
201 RInteger base = RInteger::NewRandomL(TInteger::Two(), nminus2);
202 CleanupStack::PushL(base);
203 if(!RabinMillerIterationL(aMont, n, base))
205 CleanupStack::PopAndDestroy(2, &nminus2);//base, nminus2
208 CleanupStack::PopAndDestroy(&base);
210 CleanupStack::PopAndDestroy(&nminus2);
214 static TBool IsStrongProbablePrimeL(const TInteger& aPrime)
216 CMontgomeryStructure* mont = CMontgomeryStructure::NewLC(aPrime);
217 //This should be using short circuit evaluation
218 TBool probablePrime = RabinMillerIterationL(*mont, aPrime, TInteger::Two())
219 && RabinMillerTestL(*mont, aPrime,RabinMillerRounds(aPrime.BitCount()));
220 CleanupStack::PopAndDestroy(mont);
221 return probablePrime;
224 /* In the _vast_ majority of cases this simply checks that your chosen random
225 * number is >= KLastSmallPrimeSquared and return EFalse and lets the normal
226 * prime generation routines handle the situation. In the case where it is
227 * smaller, it generates a provable prime and returns ETrue. The algorithm for
228 * finding a provable prime < KLastPrimeSquared is not the most efficient in the
229 * world, but two points come to mind
230 * 1) The two if statements hardly _ever_ evaluate to ETrue in real life.
231 * 2) Even when it is, the distribution of primes < KLastPrimeSquared is pretty
232 * dense, so you aren't going to have check many.
233 * This function is essentially here for two reasons:
234 * 1) Ensures that it is possible to generate primes < KLastPrimeSquared (the
235 * test code does this)
236 * 2) Ensures that if you request a prime of a large bit size that there is an
237 * even probability distribution across all integers < 2^aBits
239 TBool TInteger::SmallPrimeRandomizeL(void)
241 TBool foundPrime = EFalse;
242 //If the random number we've chosen is less than KLastSmallPrime,
243 //testing for primality is easy.
244 if(*this <= KLastSmallPrime)
246 //If Zero or One, or two, next prime number is two
247 if(IsZero() || *this == One() || *this == Two())
249 CopyL(TInteger::Two());
254 //Make sure any number we bother testing is at least odd
256 //Binary search the small primes.
257 while(!IsSmallPrime(ConvertToUnsignedLong()))
259 //If not prime, add two and try the next odd number.
261 //will never carry as the minimum size of an RInteger is 2
262 //words. Much bigger than KLastSmallPrime on 32bit
264 IncrementNoCarry(Ptr(), Size(), 2);
266 assert(IsSmallPrime(ConvertToUnsignedLong()));
270 else if(*this <= KLastSmallPrimeSquared)
272 //Make sure any number we bother testing is at least odd
275 while(HasSmallDivisorL(*this) && *this <= KLastSmallPrimeSquared)
277 //If not prime, add two and try the next odd number.
279 //will never carry as the minimum size of an RInteger is 2
280 //words. Much bigger than KLastSmallPrime on 32bit
282 IncrementNoCarry(Ptr(), Size(), 2);
284 //If we exited while loop because it had no small divisor then it is
285 //prime. Otherwise, we've exceeded the limit of what we can provably
286 //generate. Therefore the normal prime gen routines will be run on it
288 if(*this < KLastSmallPrimeSquared)
293 //This doesn't mean there is no such prime, simply means that the number
294 //wasn't less than KSmallPrimeSquared and needs to be handled by the normal
295 //prime generation routines.
299 void TInteger::PrimeRandomizeL(TUint aBits, TRandomAttribute aAttr)
303 //"this" is "empty" currently. Consists of Size() words of 0's. This is just
304 //checking that sign flag is positive as we don't set it later.
305 assert(NotNegative());
307 //Flag for the whole function saying if we've found a prime
308 TBool foundProbablePrime = EFalse;
310 //Find 2^aBits + 1 -- any prime we find must be less than this.
311 RInteger max = RInteger::NewEmptyL(BitsToWords(aBits)+1);
312 CleanupStack::PushL(max);
314 assert(max.BitCount()-1 == aBits);
316 // aBits | approx number of odd numbers you must try to have a 50%
317 // chance of finding a prime
318 //---------------------------------------------------------
322 //Therefore if we are generating larger than 1024 bit numbers we'll use a
323 //bigger bit array to have a better chance of avoiding re-generating it.
324 TUint sLength = aBits > 1024 ? 1024 : 512;
325 RInteger S = RInteger::NewEmptyL(BitsToWords(sLength));
326 CleanupStack::PushL(S);
328 while(!foundProbablePrime)
330 //Randomly choose aBits
331 RandomizeL(aBits, aAttr);
333 //If the random number chosen is less than KSmallPrimeSquared, we have a
334 //special set of routines.
335 if(SmallPrimeRandomizeL())
337 foundProbablePrime = ETrue;
341 //if it was <= KLastSmallPrimeSquared then it would have been
342 //handled by SmallPrimeRandomizeL()
343 assert(*this > KLastSmallPrimeSquared);
345 //Make sure any number we bother testing is at least odd
348 //Ensure that this + 2*sLength < max
349 RInteger temp = max.MinusL(*this);
350 CleanupStack::PushL(temp);
355 //if this + 2*sLength >= max then we use a smaller sLength to
356 //ensure we don't find a number that is outside of our bounds
357 //(and bigger than our allocated memory for this)
359 //temp must be less than KMaxTUint as sLength is a TUint
360 sLength = temp.ConvertToUnsignedLong();
362 CleanupStack::PopAndDestroy(&temp);
364 //Start at 1 as no point in checking against 2 (all odd numbers)
365 for(TUint i=1; i<KPrimeTableSize; i++)
367 //no need to call ModuloL as we know KPrimeTable[i] is not 0
368 TUint remainder = Modulo(*this, KPrimeTable[i]);
369 TUint index = FindSmallestIndex(KPrimeTable[i], remainder);
370 EliminateComposites(S.Ptr(), KPrimeTable[i], index, sLength);
372 TInt j = FindFirstPrimeCandidate(S.Ptr(), sLength);
374 for(; j>=0; j=FindFirstPrimeCandidate(S.Ptr(), sLength))
376 ArraySetBit(S.Ptr(), j);
378 //should never carry as we earlier made sure that 2*j + this < max
379 //where max is 1 bit more than we asked for.
380 IncrementNoCarry(Ptr(), Size(), 2*(j-prev));
383 assert(!HasSmallDivisorL(*this));
387 if( IsStrongProbablePrimeL(*this) )
389 foundProbablePrime = ETrue;
393 //This clears the memory
397 CleanupStack::PopAndDestroy(2, &max);
400 EXPORT_C TBool TInteger::IsPrimeL(void) const
408 return *this == Two();
410 else if( *this <= KLastSmallPrime )
412 assert(KLastSmallPrime < KMaxTUint);
413 return IsSmallPrime(this->ConvertToUnsignedLong());
415 else if( *this <= KLastSmallPrimeSquared )
417 return !HasSmallDivisorL(*this);
421 return !HasSmallDivisorL(*this) && IsStrongProbablePrimeL(*this);
425 // Method is excluded from coverage due to the problem with BullsEye on ONB.
426 // Manually verified that this method is functionally covered.
427 #ifdef _BullseyeCoverage
428 #pragma suppress_warnings on
429 #pragma BullseyeCoverage off
430 #pragma suppress_warnings off
433 static TBool IsSmallPrime(TUint aK)
435 //This is just a binary search of our small prime table.
437 TUint u = KPrimeTableSize;
441 TUint p = KPrimeTable[m];