Cryptography Algorithms Implemented in Python PDF
Cryptography Algorithms Implemented in Python PDF
What is Cryptography?
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.
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
In [40]:
In [43]:
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]:
In [45]:
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]:
print
print("Encrypted Message:", c1)
print
print("Decrypted Message:", subs_cipher_decrypt(c1))
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 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"
# ---------------------------------------------------
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]
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.
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
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
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)
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]:
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.
msg_list = chunk8(msg_num)
print(msg_list)
This is a numeric representation of the message A wants to send B. So she encrypts each chunk. This is done below
In [72]:
cipher_list = encrypt_chunks(msg_list)
print(cipher_list)
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_list = decrypt_chunks(cipher_list)
print(decipher_list)
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?
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.
"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"""
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)
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]
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]
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.