You are on page 1of 27

Vaghani Pavitra

J.
200031101611058

Experiment No : 01
Aim :
Implementing Caesar Cipher

Introduction :
It is a type of substitution cipher in which each letter in the plaintext is
replaced by a letter some fixed number of positions down the alphabet. For
example, with a left shift of 3, D would be replaced by A, E would become
B, and so on.

Program (Source Code):


Output (Program):

Output (Cryptool):

Cryptanalysis :
The key is a number between 1 and 25. The method is to shift each letter in the
alphabet by n. To decrypt, you need to shift back. One way might be to try each of the
25 shifts and select the strings that are words in the dictionary.

Applications :
Caesar Box. The "Caesar Box," or "Caesar Cipher," is one of the earliest known ciphers.
Developed around 100 BC, it was used by Julius Caesar to send secret messages to his
generals in the field. In the event that one of his messages got intercepted, his opponent
could not read them.

References :
1. https://challenges.wolfram.com/challenge/breaking-
the-caesar-cipher
Experiment No :2
Aim:
Implementing Rail Fence Cipher
Introduction:
The rail fence cipher (sometimes called zigzag cipher) is
a transposition cipher that jumbles up the order of the letters of a
message using a basic algorithm.The rail fence cipher works by
writing your message on alternate lines across the page, and then
reading off each line in turn. all white spaces have been removed
from the plain text while converting plain text to cipher text using
rail fence technique.

Program(source code):

def encrypt(mes, dep):


rail = [['\n' for i in range(len(mes))]
for j in range(dep)]
dir_down = False
row, col = 0, 0
for i in range(len(mes)):
if (row == 0) or (row == dep - 1):
dir_down = not dir_down
rail[row][col] = mes[i]
col += 1
if dir_down:
row += 1
else:
row -= 1
result = []
for i in range(dep):
for j in range(len(mes)):
if rail[i][j] != '\
n':
result.append(rail[i][j])
return("" . join(result))

def decrypt(cipher, dep):


rail = [['\n' for i in range(len(cipher))]
for j in range(dep)]
dir_down = None
row, col = 0, 0

for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == dep - 1:
dir_down = False
rail[row][col] = '*'
col += 1
if dir_down:
row += 1
else:
row -= 1
index = 0
for i in range(dep):
for j in range(len(cipher)):
if ((rail[i][j] == '*') and
(index < len(cipher))):
rail[i][j] = cipher[index]
index += 1
result = []
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == dep-1:
dir_down = False
if (rail[row][col] != '*'):
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return("".join(result))
d1=int(input("Enter the depth:\n"))
pt=str(input("Enter plain text:\n"))
print(encrypt(pt, d1))
ct=str(input("Enter cipher text:\n"))
print(decrypt(ct, d1))
Output (program) :

Output (crypt pool) :

Cryptanalysis:
Cryptanalysis is the art of breaking codes and ciphers. The rail fence
cipher is a very easy cipher to break. A cryptanalyst (code breaker) simply
has to try several keys until the correct one is found. It is very easy to find
a key if you know some of the plaintext,
or can guess some of it. Anagramming is another very powerful method
that can be used with any transposition cipher, that consists of taking
chunks of ciphertext and guessing what the plaintext would be.A
peculiarity of transposition ciphers is that the frequency distribution of the
characters will be identical to that of natural text (since no substitutions
have been performed, it is just the order that has been mixed up).

Application:
Client information, payment information, personal files, bank account
details must be protected. All of this information may be difficult to
replace and potentially dangerous if it falls into the wrong
hands.Sometimes a person does not realize that his data has been
taken over bysomeone else at the time of sending data. Data security
refers to protection measures to secure data from unauthorized access
and data corruption throughout the data life cycle. In the process, they
use data security solutions that include tokenization, data encryption,
and essential management practices that protect data. An algorithm is
needed to secure data. The Rail Fence Cipher algorithm is perfect for
use in randomized words. The characters in the plaintext will be
transposed to another place so that others cannot understand the
plaintext. By applying this algorithm, the data will be guaranteed
confidentiality.

Reference:
 www.jardcs.org
 www.101computing.net
 crypto.interactive-maths.com

Experiment No :3
Aim:
Columnar Transposition Cipher
Introduction:
Columnar Transposition involves writing the plaintext out in rows, and then
reading the ciphertext off in columns. In its simplest form, it is the Route
Cipher where the route is to read down each column in order. For example, the
plaintext "a simple transposition" with 5 columns looks like the grid below

If we now read down each column we get the ciphertext


"ALNISESTITPIMROOPASN".
So far this is no different to a specific route cipher. Columnar
Transposition builds in a keyword to order the way we read
the columns, as well as to ascertain how
many columns to use.

Program(source code):

msg = input("Enter Plain Text: ").replace(" ", "").upper()


key = input("Enter keyword: ").upper()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
kywrd_num_list = list(range(len(key)))
init = 0
for i in range(len(alpha)):
for j in range(len(key)):
if alpha[i] ==
key[j]:
init += 1
kywrd_num_list[j] = init
for i in range(len(key)):
print(key[i], end=" ")
print()
for i in range(len(key)):
print(str(kywrd_num_list[i]), end=" ")
print()
extra_letter=len(msg)%len(key)
underscore=len(key)-extra_letter
if(extra_letter!=0):
for i in range(underscore):
msg+="_"
ct = ""
num_of_rows = int(len(msg) / len(key))
a = [[0] * len(key) for i in range(num_of_rows)]
z = 0
for i in range(num_of_rows):
for j in
range(len(key)):
a[i][j] = msg[z]
z += 1
for i in range(num_of_rows):
for j in
range(len(key)):
print(a[i][j], end=" ", flush=True)
print()
num_loc = ""
for i in range(len(key) + 1):
for j in range(len(key)):
if kywrd_num_list[j] == i:
num_loc += str(j)
print(num_of_rows)
k=0
for i in range(len(key)):
if k == len(key):
break
else:
d = int(num_loc[k])
for j in range(num_of_rows):
ct += a[j][d]
print(ct)
k += 1

Output:
Output (crypt pool) :
Cryptanalysis:
1. Enumerate all short key
2. dictionary Attacks
3. Hill climbing
Application:
A columnar transposition cipher can be applied more than
once. This several time security increases the security of the
cipher significantly.
Reference:
 https://www.geeksforgeeks.org/columnar-transposition-
cipher/
 https://crypto.interactive-maths.com/columnar-
transposition-cipher.html
Experiment No :4

AIM:
To Implement Vigenere Cipher.
 INTRODUCTION:
Is a method of encrypting alphabetic text by using a series of
interwoven Caesar ciphers, based on the letters of a keyword.
For encryption,
E[i]=(m[i]+key[i])%26
For decryption,
M[i]=(E[i]-key[i])%26
 PROGRAM (Source Code):

def gk(string, key):


key = list(key)
if len(string) == len(key):
return (key)
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return ("".join(key))

def encryption(string, key):


encrypt_text = []
for i in range(len(string)):
x = (ord(string[i]) +ord(key[i])) % 26
x += ord('A')
encrypt_text.append(chr(x))
return "" . join(encrypt_text)

a=input("ENTER THE PLAIN TEXT: -")


b=input("ENTER THE KEY: -")
key=gk(a,b)
e_text=encryption(a,key)
print("ENCRYPTED TEXT: -",e_text)

 OUTPUT(Program):
 OUTPUT(Cryptool):

CRYPTANALYSIS:
 This cipher has been unbreakable for years and even if
one uses a long key they are still unbreakable.
 Cryptanalysis of this cipher has the following 2
steps:-
 Finding the period-it uses the Index of
Coincidence (I.C.) is a statistical technique
that indicates how English-like a piece of text
is.

Finding the key- after the first step we have a
value of period which is the amount of Ceaser
cipher we have to break now.
 APPLICATIONS:
 The vigenere cipher algorithm method is used for
securing data in the form of digital images,
especially for the logo of a company which is one of
the methods of the science of cryptography.
 REFERENCE:

https://ieeexplore.ieee.org/document/7577571#:~:text=vigenere%2
0cipher%20algorithm%20method%20is,during%20transmission%20over%
20the%20Internet.
 https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
Experiment No :5
Aim
:
To perform the simple encryption technique named playfair cipher.

Introduction:
The Playfair cipher or Playfair square or Wheatstone–Playfair cipher is a
manual symmetric encryption technique and was the first literal digram
substitution cipher. The technique encrypts pairs of letters (bigrams or digrams), instead of
single letters as in the simple substitution cipher and rather more complex Vigenère cipher
systems then in use. Playfair is reasonably fast to use and requires no special equipment.
Program (Source Code):
def create_matrix(key):
key = key.upper()
matrix = [[0 for i in range(5)] for j in range(5)]
letters_added = []
row = 0
col = 0
for letter in key:
if letter not in letters_added:
matrix[row][col] = letter
letters_added.append(letter)
else:
continue
if (col ==
4):
col = 0
row += 1
else:
col += 1

for letter in range(65, 91):


if letter == 74:
continue
if chr(letter) not in letters_added:
letters_added.append(chr(letter))

index = 0
for i in range(5):
for j in range(5):
matrix[i][j] = letters_added[index]
index += 1
return matrix

def separate_same_letters(message):
index = 0
while (index < len(message)):
l1 = message[index]
if index == len(message) - 1:
message = message + 'X'
index += 2
continue
l2 = message[index + 1]
if l1 == l2:
message = message[:index + 1] + "X" + message[index + 1:]
index += 2
return message

def indexOf(letter, matrix):


for i in range(5):
try:
index = matrix[i].index(letter)
return (i, index)
except:
continue

def playfair(key, message, encrypt=True):


inc = 1
if encrypt == False:
inc = -1
matrix = create_matrix(key)
message = message.upper()
message = message.replace(' ', '')
message = separate_same_letters(message)
cipher_text = ''
for (l1, l2) in zip(message[0::2], message[1::2]):
row1, col1 = indexOf(l1, matrix)
row2, col2 = indexOf(l2, matrix)
if row1 == row2:
cipher_text += matrix[row1][(col1 + inc) % 5] + matrix[row2][(col2 +
inc) % 5]
elif col1 == col2:
cipher_text += matrix[(row1 + inc) % 5][col1] + matrix[(row2 + inc) %
5][col2]
else:
cipher_text += matrix[row1][col2] + matrix[row2][col1]

return cipher_text

if name == ' main ':


# a sample of encryption and decryption
print('plain text :: vaghani')
print('cipher text')
print(playfair('pavitra', 'vaghani'))
print('cipher text')
print(playfair('pavitra', 'IVHKBWVY', False))
print('plain text :: vaghani')
Output (Program):

Output (Cryptool):
Cryptanalysis:
Because the Playfair cipher encrypts digraphs – two-letter blocks – plaintext frequencies are
spread over 676 digraphs rather than 26 single letters. The frequency distribution will tend to be
more uniform. Security much improved over monoalphabetic since have 26 * 26=676 diagrams.
would need a 676-entry frequency table to analyses (verses 26 for a monoalphabetic) and
correspondingly more ciphertext.it can be broken, it leaves much of the structure of the plaintext
language intact. A few hundred letters of ciphertext are generally sufficient.

Applications:
The Playfair cipher was predominantly used by British forces during the Second Boer
War (1899-1902) and World War I (1914-1918). Other countries–Australia, Germany, and New
Zealand–would use the Playfair cipher in the 1940's. The primary use of the cipher was for
protecting vital but non-critical secrets during actual combat. By the time the enemy
cryptanalysts could decrypt the information.

References:
1. https://en.wikipedia.org/wiki/Playfair_cipher
2. http://practicalcryptography.com/ciphers/playfair-cipher/
Aim:

To perform the simple encryption technique named heel cipher.

Introduction:
Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter
is represented by a number modulo 26. Often the simple scheme A = 0, B = 1, …,
Z = 25 is used, but this is not an essential feature of the cipher. To encrypt a
message, each block of n letters (considered as an n- component vector) is
multiplied by an invertible n × n matrix, against modulus 26. To decrypt the
message, each block is multiplied by the inverse of the matrix used for encryption.
The matrix used for encryption is the cipher key, and it should be chosen
randomly from the set of invertible n × n matrices (modulo 26).

Program :
keyMatrix = [[0] * 3 for i in range(3)]
messageVector = [[0] for i in range(3)]
cipherMatrix = [[0] for i in range(3)]

def getKeyMatrix(key):
k = 0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = ord(key[k]) % 65
k += 1
def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] = 0
for x in range(3):
cipherMatrix[i][j] += (keyMatrix[i][x] *
messageVector[x][j])
cipherMatrix[i][j] = cipherMatrix[i][j] % 26

def HillCipher(message, key):


getKeyMatrix(key)
for i in range(3):
messageVector[i][0] = ord(message[i]) % 65
encrypt(messageVector)
CipherText = []
for i in range(3):
CipherText.append(chr(cipherMatrix[i][0] + 65))
return "".join(CipherText)

pt=input("Enter the plain text: ").replace(" ","")


key=input("Enter the key:")
while(len(pt)%3!=0):
pt=pt+'x'
ct=""
for i in range(0,len(pt),3):
ct+=HillCipher(pt[i:i+3],key)

print(ct)

Output (Program):

Output (Cryptool):

Cryptanalysis:
The Hill cipher is a classical block cipher based upon matrix multiplication. In
2007, Bauer and Millward completed a ciphertext-only attack in which they
recovered the individual rows of the encrypting matrix to reduce the work
previously necessary to recover the entire matrix at one time. In 2015, Leap et al.
improved Bauer and Millward’s attack by changing the scoring statistic to the
Index of Coincidence, making it possible to score all members of entire classes of
rows by testing a single member of each class and decreasing the necessary work
by a factor of φ(L), where φ is the Euler totient function and L is the length of the
alphabet. This paper presents further improvements by focusing attention on
subsequences of the putative plaintext instead of the rows of the matrix, thereby
making the search more efficient and more amenable to implementation on
multiple computer processors.

Applications:
Computer security aims to help users prevent fraud or detect fraud in an
information-based system. The information must be secured to be free
from threats. Cryptographic techniques can prevent data theft. One
cryptographic algorithm is Hill Cipher. This algorithm is one symmetric
cryptography algorithm. The Hill Cipher algorithm uses an m x m sized
matrix as the key to encryption and decryption. The fundamental matrix
theory used in Hill Cipher is multiplication between matrices and inverses
the matrix. Hill Cipher has two types of matrices in general, 2 x 2 and 3 x
3. This study discusses the order 2 x 2. The application of Hill Cipher in text-
shaped media is highly recommended because it has fast encryption and
decryption speeds. This method is very good at securing data that will be
transmitted on an open network.
References:
1. https://jayscholar.etown.edu
2. https://www.researchgate.net
3. https://osf.io/n2kdb/download
4. https://www.geeksforgeeks.org/hill-cipher/
5. https://en.wikipedia.org/wiki/Hill_cipher
EXPERIMENT No: 07
 AIM:
o To Implement RSA Encryption.
 INTRODUCTION:
o The RSA algorithm is an asymmetric cryptography
algorithm; this means that it uses a public key and
a private key.
o As their names suggest, a public key is shared publicly,
while a private key is secret and must not be shared with
anyone.
 PROGRAM (Source Code):

import math as m

msg = int(input("Enter the message to be encrypted: "))

p = int(input("Enter the First Prime number - "))


q = int(input("Enter the Second Prime number - "))
e = int(input("Enter the value of e -"))

n = p * q

def enc(me):
en = m.pow(me, e)
c = en % n
print("Encrypted Message is: ", c)

print("Original Message is: ", msg)


enc(msg)

 OUTPUT(Program):
 OUTPUT(Cryptool):
 CRYPTANALYSIS:
o Correlation attack achieved their goal with break
keys whose key stream is designed by the output of
linear feedback shift registers and Boolean function.
o Coppersmith attack is a class of cryptographic attack
and mainly designed and focused on RSA Public key
cryptosystem.
o Such two cases, coppersmith attack to break
RSA cryptosystem that are:
 When the hacker has partial knowledge of the secret
key.
 When the public exponent e is a small value
 APPLICATIONS:
o RSA algorithm is commonly used by banks to protect their data,
like customer information and transaction record.
o RSA encryption is often used in combination with other
encryption schemes, or for digital signatures which can prove
the authenticity and integrity of a message.
 REFERENCE:
o https://www.techtarget.com/searchsecurity/definition/RSA
o https://en.wikipedia.org/wiki/RSA_(cryptosystem)
EXPERIMANT-8
 AIM:
Implement digital signature using RSA.

 INTRODUCTION:
 Digital signatures are used to verify the authenticity of the message sent
electronically.

 It ensures that the intended user sends the message without tampering
by any third party (attacker).

 PROGRAM (Source code):

def euclid(m, n):


if n == 0:
return m
else:
r = m % n
return euclid(n, r)

def exteuclid(a, b):


r1 = a
r2 = b
s1 = int(1)
s2 = int(0)
t1 = int(0)
t2 = int(1)

while r2 > 0:
q = r1 // r2
r = r1 - q * r2
r1 = r2
r2 = r
s = s1 - q * s2
s1 = s2
s2 = s
t = t1 - q * t2
t1 = t2
t2 = t

if t1 < 0:
t1 = t1 % a

return (r1, t1)

p = int(input("Enter the First Prime number - "))


q = int(input("Enter the Second Prime number - "))
n = p * q
Pn = (p - 1) * (q - 1)

key = []

for i in range(2, Pn):

gcd = euclid(Pn, i)

if gcd == 1:
key.append(i)
break

e = key[0]

r, d = exteuclid(Pn, e)
if r == 1:
d = int(d)
print("decryption key is: ", d)

else:
print("Multiplicative inverse for the given encryption key does not exist.
Choose a different encryption key ")

M = int(input("Enter the Message: -"))

S = (M ** d) % n

M1 = (S ** e) % n

if M == M1:
print("VERIFIED")
else:
print("INTRUDER")

 OUTPUT:

 APPLICATIONS:

[1] Authentication
Digital signatures can be used to authenticate the identity of the source messages.
[2] Integrity
The message content was not changed or tampered with since it was digitally
signed.
[3] non-repudiation
By this property, an entity that has signed some information cannot at a later time deny
having signed it. Similarly, access to the public key only does not enable a fraudulent
party to fake a valid signature.

 REFERENCE:
Geeks for geeks
Wikipedia

You might also like