07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

100 Chapter 4 ■ Cryptographic Math and Frequency Analysis

Fermat’s Little Theorem

Fermat’s little theorem is used in number theory to compute the powers of integers

modulo prime numbers. The theorem is a special case of Euler’s theorem.

(We explore Euler’s theorem later in this chapter.) Fermat’s little theorem states

let p be a prime number, and a be any integer.

or

If n is a prime number, then for every a, 1 < a < p − 1,

a p − 1 ≡ 1 (mod p)

a p − 1 % p = 1

To ensure this makes sense, let’s look at an example:

p = prime integer number

a = integer which is not a multiple of p

According to Fermat’s little theorem,

2 (17 − 1) ≡ 1 mod (17)

65,536 % 17 ≡ 1

This means (65,536 – 1) is a multiple of 17. This is proven by multiplying 17 *

3,855, which equals (65,536 – 1) or 65,535. If you know the modulo m is prime,

then you can also use Fermat’s little theorem to find the inverse. We will cover

this in more detail later in this chapter.

Here is a quick and easy function that will return whether an integer is

prime or not:

>>> def CheckIfProbablyPrime(x):

... return pow(2, x-1, x) == 1

>>> CheckIfProbablyPrime(19)

True

>>> CheckIfProbablyPrime(31)

True

>>> CheckIfProbablyPrime(589)

False

Miller-Rabin Primality Test

Similar to the other tests featured in this section, the Miller-Rabin primality

test is a primality test; it was first discovered by M. M. Artjuhov in 1967. It was

later rediscovered in 1976 by Gary L. Miller. Miller’s version of the test is deterministic.

Michael Rabin further modified the algorithm in 1980 to obtain an

unconditional probabilistic algorithm.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!