Hacking Secret Ciphers with Python

(Ann) #1
Chapter 23 – Finding Prime Numbers 373


  1. i = 0

  2. while v != (num - 1):

  3. if i == t - 1:

  4. return False

  5. else:

  6. i = i + 1

  7. v = (v ** 2) % num

  8. return True


The mathematics of the Rabin-Miller Primality algorithm are beyond the scope of this book, so
the code in this function will not be explained.


The Rabin-Miller algorithm is also not a surefire test for primality; however, you can be
extremely certain that it is accurate. (Although this is not good enough for commercial encryption
software, it is good enough for the purposes of the programs in this book.) The main benefit of
the Rabin-Miller algorithm is that it is a relatively simple primality test and only takes a few
seconds to run on a normal computer.


If rabinMiller() returns True, then the num argument is extremely likely to be prime. If
rabinMiller() returns False, then num is definitely composite.


The New and Improved isPrime() Function


rabinMiller.py


  1. def isPrime(num):


  2. Return True if num is a prime number. This function does a quicker




  3. prime number check before calling rabinMiller().





  4. if (num < 2):

  5. return False # 0, 1, and negative numbers are not prime


All numbers that are less than two (such as one, zero, and negative numbers) are all not prime, so
we can immediately return False.


rabinMiller.py



  1. About 1/3 of the time we can quickly determine if num is not prime




  2. by dividing by the first few dozen prime numbers. This is quicker




  3. than rabinMiller(), but unlike rabinMiller() is not guaranteed to




  4. prove that a number is prime.



  5. lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
    53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137,
    139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,
    229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
    317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,

Free download pdf