0% found this document useful (0 votes)
528 views

Cryptography Algorithms Implemented in Python PDF

The document discusses various cryptography techniques including the Caesar cipher, substitution cipher, and the German Enigma cipher. It provides examples of encrypting and decrypting messages with the Caesar and substitution ciphers using Python code. It also includes an overview of how the complex Enigma cipher worked using rotors and reflections to perform polyalphabetic substitution encryption.

Uploaded by

Roger Shah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
528 views

Cryptography Algorithms Implemented in Python PDF

The document discusses various cryptography techniques including the Caesar cipher, substitution cipher, and the German Enigma cipher. It provides examples of encrypting and decrypting messages with the Caesar and substitution ciphers using Python code. It also includes an overview of how the complex Enigma cipher worked using rotors and reflections to perform polyalphabetic substitution encryption.

Uploaded by

Roger Shah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Prepared By : Soham Thaker

Practising Various Cryptography Techniques

What is Cryptography?

We have two people, A and B. A wants to send B a secure message.

What do we mean by "secure?" We mean that even though that C might intercept and read the sent message, C won't understand anything about the
actual message A wants to send to B.

Before the 1970s, the only way for A to send B a secure message required A and B to get together beforehand and agree on a secret method of
communicating. To communicate, A first decides on a message. The original message is sometimes called the plaintext. She then encrypts the
message, producing a ciphertext.

She then sends the ciphertext. If C gets hold of hte ciphertext, she shouldn't be able to decode it (unless it's a poor encryption scheme).

When B receives the ciphertext, he can decrypt it to recover the plaintext message, since he agreed on the encryption scheme beforehand.

Caesar Shift
The first known instance of cryptography came from Julius Caesar. It was not a very good method. To encrypt a message, he shifted each letter over by 2,
so for instance "A" becomes "C", and "B" becomes "D", and so on.

Let's see what sort of message comes out.

Example

Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

When encrypting, a person looks up each letter of the message in the "plain" line and writes down the corresponding letter in the "cipher" line.

Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD Deciphering is done in reverse, with a right shift of 3.

The encryption can also be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A → 0, B → 1, ...,
Z → 25. Encryption of a letter x by a shift n can be described mathematically as,
( )=( + ) mod 26. ( )=( + ) mod 26.
Decryption is performed similarly,
( )=( − ) mod 26. ( )=( − ) mod 26.
(There are different definitions for the modulo operation. In the above, the result is in the range 0 to 25; i.e., if x + n or x − n are not in the range 0 to 25, we
have to subtract or add 26.)

The replacement remains the same throughout the message, so the cipher is classed as a type of monoalphabetic substitution, as opposed to
polyalphabetic substitution.

In [1]:

alpha = "abcdefghijklmnopqrstuvwxyz".upper()
punct = ",.?:;'\n "
In [2]: Prepared By : Soham Thaker
from functools import partial

def shift(l, s=2):


l = l.upper()
return alpha[(alpha.index(l) + s) % 26]

def caesar_shift_encrypt(m, s=2):


m = m.upper()
c = "".join(map(partial(shift, s=s), m))
return c

def caesar_shift_decrypt(c, s=-2):


c = c.upper()
m = "".join(map(partial(shift, s=s), c))
return m

In [40]:

print("Original Message: Hello")


print("Ciphertext:", caesar_shift_encrypt("Hello"))

Original Message: Hello


Ciphertext: JGNNQ

In [43]:

m = """Your time is limited, so don't waste it living someone else's life:


Don't be trapped by dogma
which is living with the results of other people's thinking."""

m = "".join([l for l in m if not l in punct])

print("Original Message:")
print(m)

print
print("Ciphertext:")
tobe_ciphertext = caesar_shift_encrypt(m)
print(tobe_ciphertext)

Original Message:
YourtimeislimitedsodontwasteitlivingsomeoneelseslifeDontbetrappedbydogmawhichislivingwiththeresultso
fotherpeoplesthinking
Ciphertext:
AQWTVKOGKUNKOKVGFUQFQPVYCUVGKVNKXKPIUQOGQPGGNUGUNKHGFQPVDGVTCRRGFDAFQIOCYJKEJKUNKXKPIYKVJVJGTGUWNVUQ
HQVJGTRGQRNGUVJKPMKPI

In [44]:

print("Decrypted first message:", caesar_shift_decrypt("HELLO"))

Decrypted first message: FCJJM

In [45]:

print("Decrypted second message:")


print(caesar_shift_decrypt(tobe_ciphertext))

Decrypted second message:


YOURTIMEISLIMITEDSODONTWASTEITLIVINGSOMEONEELSESLIFEDONTBETRAPPEDBYDOGMAWHICHISLIVINGWITHTHERESULTSO
FOTHERPEOPLESTHINKING

Is this a good encryption scheme? No, not really. There are only 26 different things to try. This can be decrypted very quickly and easily, even if entirely by
hand.

Substitution Cipher
A slightly different scheme is to choose a different letter for each letter. For instance, maybe "A" actually means "G" while "B" actually means "E". We call
this a substitution cipher as each letter is substituted for another.

In [46]:

import random
permutation = list(alpha)
random.shuffle(permutation)
In [47]: Prepared By : Soham Thaker
# Display the new alphabet
print(alpha)
subs = "".join(permutation)
print(subs)

ABCDEFGHIJKLMNOPQRSTUVWXYZ
DQMTOCXISFLNKWJHYREBPZGVUA

In [9]:

def subs_cipher_encrypt(m):
m = "".join([l.upper() for l in m if not l in punct])
return "".join([subs[alpha.find(l)] for l in m])

def subs_cipher_decrypt(c):
c = "".join([l.upper() for l in c if not l in punct])
return "".join([alpha[subs.find(l)] for l in c])

In [48]:

m1 = "Trying Substitution Cipher"

print("Original message:", m1)


c1 = subs_cipher_encrypt(m1)

print
print("Encrypted Message:", c1)

print
print("Decrypted Message:", subs_cipher_decrypt(c1))

Original message: Trying Substitution Cipher


Encrypted Message: BRUSWXEPQEBSBPBSJWMSHIOR
Decrypted Message: TRYINGSUBSTITUTIONCIPHER

In [49]:
print("Original message:")
print(m)

print
c2 = subs_cipher_encrypt(m)
print("Encrypted Message:")
print(c2)

print
print("Decrypted Message:")
print(subs_cipher_decrypt(c2))

Original message:
YourtimeislimitedsodontwasteitlivingsomeoneelseslifeDontbetrappedbydogmawhichislivingwiththeresultso
fotherpeoplesthinking
Encrypted Message:
UJPRBSKOSENSKSBOTEJTJWBGDEBOSBNSZSWXEJKOJWOONEOENSCOTJWBQOBRDHHOTQUTJXKDGISMISENSZSWXGSBIBIOROEPNBEJ
CJBIORHOJHNOEBISWLSWX
Decrypted Message:
YOURTIMEISLIMITEDSODONTWASTEITLIVINGSOMEONEELSESLIFEDONTBETRAPPEDBYDOGMAWHICHISLIVINGWITHTHERESULTSO
FOTHERPEOPLESTHINKING

This is also not a good cipher technique, these are frequently asked in Higher Studies Enterance Examination, because given a reasonably long message,
it's pretty easy to figure it out using things like the frequency of letters.

The German Enigma


One very well-known polyalphabetic encryption scheme is the German Enigma used before and during World War II. This was by far the most
complicated cryptosystem in use up to that point.

Alan Turing developed electromechanical computers to help break the Enigma.

The Enigma worked by having a series of cogs or rotors whose positions determined a substitution cipher. After each letter, the positions were changed
through a mechanical process.

In [5]:
In [5]:
Prepared By : Soham Thaker
# ----------------- Enigma Settings -----------------
rotors = ("I","II","III")
reflector = "UKW-B"
ringSettings ="ABC"
ringPositions = "DEF"
plugboard = "AT BS DE FM IR KN LZ OW PV XY"
# ---------------------------------------------------

def caesarShift(str, amount):


output = ""

for i in range(0,len(str)):
c = str[i]
code = ord(c)
if ((code >= 65) and (code <= 90)):
c = chr(((code - 65 + amount) % 26) + 65)
output = output + c

return output

def encode(plaintext):
global rotors, reflector,ringSettings,ringPositions,plugboard
#Enigma Rotors and reflectors
rotor1 = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"
rotor1Notch = "Q"
rotor2 = "AJDKSIRUXBLHWTMCQGZNPYFVOE"
rotor2Notch = "E"
rotor3 = "BDFHJLCPRTXVZNYEIWGAKMUSQO"
rotor3Notch = "V"
rotor4 = "ESOVPZJAYQUIRHXLNFTGKDCMWB"
rotor4Notch = "J"
rotor5 = "VZBRGITYUPSDNHLXAWMJQOFECK"
rotor5Notch = "Z"

rotorDict = {"I":rotor1,"II":rotor2,"III":rotor3,"IV":rotor4,"V":rotor5}
rotorNotchDict = {"I":rotor1Notch,"II":rotor2Notch,"III":rotor3Notch,"IV":rotor4Notch,"V":rotor5Notch}

reflectorB = {"A":"Y","Y":"A","B":"R","R":"B","C":"U","U":"C","D":"H","H":"D","E":"Q","Q":"E","F":"S","S":"F","
G":"L","L":"G","I":"P","P":"I","J":"X","X":"J","K":"N","N":"K","M":"O","O":"M","T":"Z","Z":"T","V":"W","W":"V"}
reflectorC = {"A":"F","F":"A","B":"V","V":"B","C":"P","P":"C","D":"J","J":"D","E":"I","I":"E","G":"O","O":"G","
H":"Y","Y":"H","K":"R","R":"K","L":"Z","Z":"L","M":"X","X":"M","N":"W","W":"N","Q":"T","T":"Q","S":"U","U":"S"}

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
rotorANotch = False
rotorBNotch = False
rotorCNotch = False

if reflector=="UKW-B":
reflectorDict = reflectorB
else:
reflectorDict = reflectorC

#A = Left, B = Mid, C=Right
rotorA = rotorDict[rotors[0]]
rotorB = rotorDict[rotors[1]]
rotorC = rotorDict[rotors[2]]
rotorANotch = rotorNotchDict[rotors[0]]
rotorBNotch = rotorNotchDict[rotors[1]]
rotorCNotch = rotorNotchDict[rotors[2]]

rotorALetter = ringPositions[0]
rotorBLetter = ringPositions[1]
rotorCLetter = ringPositions[2]

rotorASetting = ringSettings[0]
offsetASetting = alphabet.index(rotorASetting)
rotorBSetting = ringSettings[1]
offsetBSetting = alphabet.index(rotorBSetting)
rotorCSetting = ringSettings[2]
offsetCSetting = alphabet.index(rotorCSetting)

rotorA = caesarShift(rotorA,offsetASetting)
rotorB = caesarShift(rotorB,offsetBSetting)
rotorC = caesarShift(rotorC,offsetCSetting)

if offsetASetting>0:
rotorA = rotorA[26-offsetASetting:] + rotorA[0:26-offsetASetting]
if offsetBSetting>0:
rotorB = rotorB[26-offsetBSetting:] + rotorB[0:26-offsetBSetting]
if offsetCSetting>0:
rotorC = rotorC[26-offsetCSetting:] + rotorC[0:26-offsetCSetting]

ciphertext = ""
ciphertext = ""
Prepared By : Soham Thaker
#Converplugboard settings into a dictionary
plugboardConnections = plugboard.upper().split(" ")
plugboardDict = {}
for pair in plugboardConnections:
if len(pair)==2:
plugboardDict[pair[0]] = pair[1]
plugboardDict[pair[1]] = pair[0]

plaintext = plaintext.upper()
for letter in plaintext:
encryptedLetter = letter

if letter in alphabet:
#Rotate Rotors - This happens as soon as a key is pressed, before encrypting the letter!
rotorTrigger = False
#Third rotor rotates by 1 for every key being pressed
if rotorCLetter == rotorCNotch:
rotorTrigger = True
rotorCLetter = alphabet[(alphabet.index(rotorCLetter) + 1) % 26]
#Check if rotorB needs to rotate
if rotorTrigger:
rotorTrigger = False
if rotorBLetter == rotorBNotch:
rotorTrigger = True
rotorBLetter = alphabet[(alphabet.index(rotorBLetter) + 1) % 26]

#Check if rotorA needs to rotate
if (rotorTrigger):
rotorTrigger = False
rotorALetter = alphabet[(alphabet.index(rotorALetter) + 1) % 26]

else:
#Check for double step sequence!
if rotorBLetter == rotorBNotch:
rotorBLetter = alphabet[(alphabet.index(rotorBLetter) + 1) % 26]
rotorALetter = alphabet[(alphabet.index(rotorALetter) + 1) % 26]

#Implement plugboard encryption!
if letter in plugboardDict.keys():
if plugboardDict[letter]!="":
encryptedLetter = plugboardDict[letter]

#Rotors & Reflector Encryption
offsetA = alphabet.index(rotorALetter)
offsetB = alphabet.index(rotorBLetter)
offsetC = alphabet.index(rotorCLetter)

# Wheel 3 Encryption
pos = alphabet.index(encryptedLetter)
let = rotorC[(pos + offsetC)%26]
pos = alphabet.index(let)
encryptedLetter = alphabet[(pos - offsetC +26)%26]

# Wheel 2 Encryption
pos = alphabet.index(encryptedLetter)
let = rotorB[(pos + offsetB)%26]
pos = alphabet.index(let)
encryptedLetter = alphabet[(pos - offsetB +26)%26]

# Wheel 1 Encryption
pos = alphabet.index(encryptedLetter)
let = rotorA[(pos + offsetA)%26]
pos = alphabet.index(let)
encryptedLetter = alphabet[(pos - offsetA +26)%26]

# Reflector encryption!
if encryptedLetter in reflectorDict.keys():
if reflectorDict[encryptedLetter]!="":
encryptedLetter = reflectorDict[encryptedLetter]

#Back through the rotors
# Wheel 1 Encryption
pos = alphabet.index(encryptedLetter)
let = alphabet[(pos + offsetA)%26]
pos = rotorA.index(let)
encryptedLetter = alphabet[(pos - offsetA +26)%26]

# Wheel 2 Encryption
pos = alphabet.index(encryptedLetter)
let = alphabet[(pos + offsetB)%26]
pos = rotorB.index(let)
encryptedLetter = alphabet[(pos - offsetB +26)%26]


Prepared By : Soham Thaker
# Wheel 3 Encryption
pos = alphabet.index(encryptedLetter)
let = alphabet[(pos + offsetC)%26]
pos = rotorC.index(let)
encryptedLetter = alphabet[(pos - offsetC +26)%26]

#Implement plugboard encryption!
if encryptedLetter in plugboardDict.keys():
if plugboardDict[encryptedLetter]!="":
encryptedLetter = plugboardDict[encryptedLetter]

ciphertext = ciphertext + encryptedLetter



return ciphertext

#Main Program Starts Here


print(" ##### Enigma Encoder #####")
print("")
plaintext = input("Enter text to encode or decode:\n")
ciphertext = encode(plaintext)

print("\nEncoded text: \n " + ciphertext)

##### Enigma Encoder #####

Enter text to encode or decode:


I am Soham Thaker

Encoded text:
Y TQ XNLEW CZHMGM

The advent of computers brought in a paradigm shift in approaches towards cryptography. Prior to computers, one of the ways of maintaining security was
to come up with a hidden key and a hidden cryptosystem, and keep it safe merely by not letting anyone know anything about how it actually worked at all.
This has the short name security through obscurity. As the number of type of attacks on cryptosystems are much, much higher with computers, a
different model of security and safety became necessary.

It is interesting to note that it is not obvious that security through obscurity is always bad, as long as it's really really well-hidden. This is relevant to some
problems concerning current events and cryptography.

Public Key Cryptography


The new model begins with a slightly different setup. We should think of A and B as sitting on opposite sides of a classroom, trying to communicate
securely even though there are lots of people in the middle of the classroom who might be listening in. In particular, A has something she wants to tell B.

Instead of keeping the cryptosystem secret, B tells everyone (in our metaphor, he shouts to the entire classroom) a public key K, and explains how to use
it to send him a message. A uses this key to encrypt her message. She then sends this message to B.

If the system is well-designed, no one will be able to understand the ciphertext even though they all know how the cryptosystem works. This is why the
system is called Public Key.

B receives this message and (using something only he knows) he decrypts the message.

RSA, named after Rivest, Shamir, and Addleman --- the first major public key cryptosystem.

RSA
B takes two primes such as = 12553 and = 13007 . He notes their product
= = 163276871
and computes ( ),
( ) = ( − 1)( − 1) = 163251312.
Finally, he chooses some integer relatively prime to ( ) , like say
= 79921.
Then the public key he distributes is
( , ) = (163276871, 79921).
In order to send B a message using this key, A must convert her message to numbers. She might use the identification A = 11, B = 12, C = 13, ... and
concatenate her numbers. To send the word CAB, for instance, she would send 131112.
In [25]: Prepared By : Soham Thaker
conversion_dict = dict()
alpha = "abcdefghijklmnopqrstuvwxyz".upper()
curnum = 11
for l in alpha:
conversion_dict[l] = curnum
curnum += 1

In [26]:

print("Original Message:")
msg = "NUMBERTHEORYISTHEQUEENOFTHESCIENCES"
print(msg)
print

def letters_to_numbers(m):
return "".join([str(conversion_dict[l]) for l in m.upper()])

print("Numerical Message:")
msg_num = letters_to_numbers(msg)
print(msg_num)

Original Message:
NUMBERTHEORYISTHEQUEENOFTHESCIENCES
Numerical Message:
2431231215283018152528351929301815273115152425163018152913191524131529

So A's message is the number


2431231215283018152528351929301815273115152425163018152913191524131529
which she wants to encrypt and send to B. To make this manageable, she cuts the message into 8-digit numbers,
24312312, 15283018, 15252835, 19293018, 15273115, 15242516, 30181529, 13191524, 131529.
To send her message, she takes one of the 8-digit blocks and raises it to the power of modulo . That is, to transmit the first block, she computes
24312312 79921 ≡ 13851252 (mod 163276871).

In [67]:

# Secret information
p = 12553
q = 13007
phi = (p-1)*(q-1) # varphi(pq)

# Public information
m = p*q # 163276871
k = 79921

print(pow(24312312, k, m))

13851252

She sends this number


13851252
to B (maybe by shouting. Even though everyone can hear, they cannot decrypt it). How does B decrypt this message?

He computes ( ) = ( − 1)( − 1) (which he can do because he knows and separately), and then finds a solution to
=1+ ( ) .
This can be done quickly through the Euclidean Algorithm.
In [68]: Prepared By : Soham Thaker
def extended_euclidean(a,b):
if b == 0:
return (1,0,a)
else :
x, y, gcd = extended_euclidean(b, a % b) # Aside: Python has no tail recursion
return y, x - y * (a // b),gcd # But it does have meaningful stack traces

# This version comes from Exercise 6.3 in the book, but without recursion
def extended_euclidean2(a,b):
x = 1
g = a
v = 0
w = b
while w != 0:
q = g // w
t = g - q*w
s = x - q*v
x,g = v,w
v,w = s,t
y = (g - a*x) / b
return (x,y,g)

def modular_inverse(a,m) :
x,y,gcd = extended_euclidean(a,m)
if gcd == 1 :
return x % m
else :
return None

In [69]:

print("k, p, q:", k, p, q)
print
u = modular_inverse(k,(p-1)*(q-1))
print(u)

k, p, q: 79921 12553 13007


145604785

In particular, B computes that his = 145604785 . To recover the message, he takes the number 13851252 sent to him by A and raises it to the
power. He computes
13851252 ≡ 24312312 (mod ),
which we can see must be true as
13851252 ≡ (24312312 ) ≡ 24312312 1+ ( )
≡ 24312312 (mod ).
In this last step, we have used Euler's Theorem to see that
( )
24312312 ≡1 (mod ).

In [70]:

# Checking this power explicitly.


print(pow(13851252, 145604785, m))

24312312

Now B needs to perform this process for each 8-digit chunk that A sent over. Note that the work is very easy, as he computes the integer only once.
Each other time, he simply computes (mod ) for each ciphertext , and this is very fast with repeated-squaring.
We do this below, in an automated fashion, step by step.

First, we split the message into 8-digit chunks.


In [71]: Prepared By : Soham Thaker
# Break into chunks of 8 digits in length.
def chunk8(message_number):
cp = str(message_number)
ret_list = []
while len(cp) > 7:
ret_list.append(cp[:8])
cp = cp[8:]
if cp:
ret_list.append(cp)
return ret_list

msg_list = chunk8(msg_num)
print(msg_list)

['24312312', '15283018', '15252835', '19293018', '15273115', '15242516', '30181529', '13191524', '13


1529']

This is a numeric representation of the message A wants to send B. So she encrypts each chunk. This is done below

In [72]:

# Compute ciphertexts separately on each 8-digit chunk.


def encrypt_chunks(chunked_list):
ret_list = []
for chunk in chunked_list:
#print chunk
#print int(chunk)
ret_list.append(pow(int(chunk), k, m))
return ret_list

cipher_list = encrypt_chunks(msg_list)
print(cipher_list)

[13851252, 14944940, 158577269, 117640431, 139757098, 25099917, 88562046, 6640362, 10543199]

This is the encrypted message. Having computed this, A sends this message to B.

To decrypt the message, B uses his knowledge of , which comes from his ability to compute ( ) , and decrypts each part of the message. This looks
like below.

In [73]:

# Decipher the ciphertexts all in the same way


def decrypt_chunks(chunked_list):
ret_list = []
for chunk in chunked_list:
ret_list.append(pow(int(chunk), u, m))
return ret_list

decipher_list = decrypt_chunks(cipher_list)
print(decipher_list)

[24312312, 15283018, 15252835, 19293018, 15273115, 15242516, 30181529, 13191524, 131529]

Finally, B concatenates these numbers together and translates them back into letters. Will he get the right message back?

In [74]:
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# Collect deciphered texts into a single list, and translate back into letters.
def chunks_to_letters(chunked_list):
s = "".join([str(chunk) for chunk in chunked_list])
ret_str = ""
while s:
ret_str += alpha[int(s[:2])-11].upper()
s = s[2:]
return ret_str

print(chunks_to_letters(decipher_list))

NUMBERTHEORYISTHEQUEENOFTHESCIENCES

Yes! B successfully decrypts the message and sees that A thinks that Number Theory is the Queen of the Sciences. This is a quote from Gauss, the
famous mathematician who has been popping up again and again in this course.
Prepared By : Soham Thaker
Why is this Secure?
Let's pause to think about why this is secure.

What if someone catches the message in transit? Suppose C is eavesdropping and hears A's first chunk, 13851252 . How would she decrypt it?

C knows that she wants to solve


≡ 13851252 (mod )
or rather
79921
≡ 13851252 (mod 163276871).
How can she do that? We can do that because we know to raise this to a particular power depending on (163276871) . But C doesn't know what
(163276871) is since she can't factor 163276871 . In fact, knowing (163276871) is exactly as hard as factoring 163276871 .
But if C could somehow find 79921 st roots modulo 163276871 , or if C could factor 163276871 , then she would be able to decrypt the message.
These are both really hard problems! And it's these problems that give the method its security.

More generally, one might use primes and that are each about 200 digits long, and a fairly large . Then the resulting would be about 400 digits,
which is far larger than we know how to factor effectively. The reason for choosing a somewhat large is for security reasons that are beyond the scope
of this segment. The relevant idea here is that since this is a publicly known encryption scheme, many people have strenghtened it over the years by
making it more secure against every clever attack known. This is another, sometimes overlooked benefit of public-key cryptography: since the
methodology isn't secret, everyone can contribute to its security --- indeed, it is in the interest of anyone desiring such security to contribute. This is sort of
the exact opposite of Security through Obscurity.

The nature of code being open, public, private, or secret is also very topical in current events. Recently, Volkswagen cheated in its car emissions-software
and had it report false outputs, leading to a large scandal. Their software is proprietary and secret, and the deliberate bug went unnoticed for years. Some
argue that this means that more software, and especially software that either serves the public or that is under strong jurisdiction, should be publicly
viewable for analysis.

Another relevant current case is that the code for most voting machines in the United States is proprietary and secret. Hopefully they aren't cheating!

On the other side, many say that it is necessary for companies to be able to have secret software for at least some time period to recuperate the expenses
that go into developing the software. This is similar to how drug companies have patents on new drugs for a number of years. This way, a new successful
drug pays for its development since the company can charge above the otherwise-market-rate.

Further, many say that opening some code would open it up to attacks from malicious users who otherwise wouldn't be able to see the code. Of course,
this sounds a lot like trying for security through obscurity.

This is a very relevant and big topic, and the shape it takes over the next few years may very well have long-lasting impacts.

Condensed Version
Now that we've gone through it all once, we have a condensed RSA system set up with our , , and from above. To show that this can be done quickly
with a computer, let's do another right now.

Let us encrypt, transmit, and decrypt the message

"I have never done anything useful. No discovery of mine has made, or is likely to make, directly or indirectly, for good or ill, the least difference to the
amenity of the world".

In [35]:

message = """I have never done anything useful. No discovery of mine has made,
or is likely to make, directly or indirectly, for good or ill, the least
difference to the amenity of the world"""

message = "".join([l.upper() for l in message if not l in "\n .,"])


print("Our message:\n"+message)

Our message:
IHAVENEVERDONEANYTHINGUSEFULNODISCOVERYOFMINEHASMADEORISLIKELYTOMAKEDIRECTLYORINDIRECTLYFORGOODORILL
THELEASTDIFFERENCETOTHEAMENITYOFTHEWORLD

Now we convert the message to numbers, and transform those numbers into 8-digit chunks.
In [36]: Prepared By : Soham Thaker
numerical_message = letters_to_numbers(message)
print("Our message, converted to numbers:")
print(numerical_message)
print

plaintext_chunks = chunk8(numerical_message)
print("Separated into 8-digit chunks:")
print(plaintext_chunks)

Our message, converted to numbers:


1918113215241532152814252415112435301819241731291516312224251419291325321528352516231924151811292311
1415252819292219211522353025231121151419281513302235252819241419281513302235162528172525142528192222
30181522151129301419161615281524131530253018151123152419303525163018153325282214
Separated into 8-digit chunks:
['19181132', '15241532', '15281425', '24151124', '35301819', '24173129', '15163122', '24251419', '29
132532', '15283525', '16231924', '15181129', '23111415', '25281929', '22192115', '22353025', '231121
15', '14192815', '13302235', '25281924', '14192815', '13302235', '16252817', '25251425', '28192222',
'30181522', '15112930', '14191616', '15281524', '13153025', '30181511', '23152419', '30352516', '301
81533', '25282214']

We encrypt each chunk by computing mod for each plaintext chunk .

In [37]:
ciphertext_chunks = encrypt_chunks(plaintext_chunks)
print(ciphertext_chunks)

[99080958, 142898385, 80369161, 11935375, 108220081, 82708130, 158605094, 96274325, 154177847, 12185
6444, 91409978, 47916550, 155466420, 92033719, 95710042, 86490776, 15468891, 139085799, 68027514, 53
153945, 139085799, 68027514, 9216376, 155619290, 83776861, 132272900, 57738842, 119368739, 88984801,
83144549, 136916742, 13608445, 92485089, 89508242, 25375188]

This is the message that A can sent B.

To decrypt it, he computes mod for each ciphertext chunk .

In [38]:

deciphered_chunks = decrypt_chunks(ciphertext_chunks)
print("Deciphered chunks:")
print(deciphered_chunks)

Deciphered chunks:
[19181132, 15241532, 15281425, 24151124, 35301819, 24173129, 15163122, 24251419, 29132532, 15283525,
16231924, 15181129, 23111415, 25281929, 22192115, 22353025, 23112115, 14192815, 13302235, 25281924,
14192815, 13302235, 16252817, 25251425, 28192222, 30181522, 15112930, 14191616, 15281524, 13153025,
30181511, 23152419, 30352516, 30181533, 25282214]

Finally, he translates the chunks back into letters.

In [39]:
decoded_message = chunks_to_letters(deciphered_chunks)
print("Decoded Message:")
print(decoded_message)

Decoded Message:
IHAVENEVERDONEANYTHINGUSEFULNODISCOVERYOFMINEHASMADEORISLIKELYTOMAKEDIRECTLYORINDIRECTLYFORGOODORILL
THELEASTDIFFERENCETOTHEAMENITYOFTHEWORLD

Even with large numbers, RSA is pretty fast. But one of the key things that one can do with RSA is securely transmit secret keys for other types of faster-
encryption that don't work in a public-key sense. There is a lot of material in this subject, and it's very important.

I should mention that in practice, RSA is performed a little bit differently to make it more secure.

I have practised these Algorithms as part of my #100DaysOfCode Challenege

You might also like