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.

96 Chapter 4 ■ Cryptographic Math and Frequency Analysis

Modular Arithmetic and the Greatest Common Devisor

You witnessed briefly in the previous chapter how Python uses modular arithmetic

in cryptography. In this chapter, you’ll gain a greater understanding of it. The

logic of modular arithmetic began with the quotient-remainder theorem. The

quotient-remainder theorem states that for every integer A and positive B there

exist different integers Q and R such that: A = B * Q + R, 0 = < r = < b. When

a = 95 and b = 10, what is the unique value of q (quotient) and r (remainder)?

You find that the quotient equals 9 and the remainder equals 5.

Once you understand the quotient-remainder theorem, it is easier to understand

our first bit of cryptographic math: modular arithmetic.

Here is an example: 23 ≡ 2(mod7), which reads as “23 is equivalent to 2 mod

7.” You can also type it into a search engine as 23 mod 7 to see the answer. You

can further examine the modulo by stating that a ≡ b (mod q) when a minus

b is a multiple of q. Another way to state it numerically would be: 123 ≡ 13

(mod 11) because 123 – 13 = 110 = 11 * 10. An alternative way to think about it is to

examine 53 (mod 13), which would be to say that 53 is equivalent to 53 − 13 = 40,

which is equivalent to 27, which is equivalent to 14, which is equivalent to

1, which is equivalent to −12, which is equivalent to −25, and so on. In fact,

53 ≡ {53 + k⋅13|∀ k ∈Z} (you can read that as “is equivalent to the set of all numbers

of form 53 plus an integer multiple of 13”). As shown in the previous chapter,

we take the modulus by using the % sign.

To illustrate this example in Python, type the following:

>>> 53 % 13

1

>>> 40 % 13

1

>>> 27 % 13

1

>>> 14 % 13

1

>>> -12 % 13

1

Now that you understand modular arithmetic, we turn our attention to the

greatest common divisor (GCD). The GCD is the largest number that perfectly

divides two integers: a and b. For example, the GCD of 12 and 18 is 6. This is

an excellent opportunity to introduce Euclid’s algorithm, which is a technique

for finding the GCD of two integers with negligible effort. To find the GCD of

two integers A and B, use the following rules:

If A = 0 then GCD(A, B) = B

If B = 0 then GCD(A, B) = A

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

Saved successfully!

Ooh no, something went wrong!