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.

118 Chapter 4 ■ Cryptographic Math and Frequency Analysis

# find the inverse of A

A_inverse = np.linalg.inv(A)

print (A_inverse)

# solve for X

X = A_inverse * B

print (X)

You can alternatively use the NumPy array method to accomplish the same

task, as shown here:

import numpy as np

# solve the following linear equation

print ('1a + 1b = 35')

print ('2a + 4b = 94')

# create equations

a = np.array([[1, 1],[2,4]])

b = np.array([35, 94])

# print answers

print (np.linalg.solve(a, b))

Now we will examine a practical example to show how matrices can be used

for encryption.

In this example, we will encrypt the message “prepare to negotiate.”

Message = “prepare to negotiate”

The encoding matrix for this example is as follows:

– 3– 3–

4

0 1 1

4 3 4

Assign a number to each letter in the alphabet much like you did for a Caesar

cipher. The letters do not have to map to the same numbers as long as both the

sender and receiver know the assignments. Python uses the ord() function to

assign a letter to a numerical value. You can convert the number back to a letter

using the chr() function.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

This message that we want to encrypt will look like the following:

P R E P A R E T O N E G O T I A T E

16 18 05 16 01 18 05 27 20 15 27 14 05 07 15 20 09 01 20 05

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

Saved successfully!

Ooh no, something went wrong!