CA Lab Manual
CA Lab Manual
(UGC-AUTONOMOUS)
(Affiliated to J.N.T.U.A, Anantapuramu and Approved by AICTE New Delhi)
An ISO 9001:2008 Certified Institution
CYPTOGRAPHY ALGORITHM
LABORAT0RY
The Department is committed to inculcate discipline, offering best Technical Education and
Research Opportunities with inculcated discipline and ethically strong to meet the global
challenges, who in turn shall contribute to the improvement and well-being of the society.
Mission
2
The engineer and society: Apply reasoning informed by the contextual
PO6 knowledge to assess societal, health, safety, legal, and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member
PO9
or leader in teams, and in multidisciplinary settings.
Communication: Communicate effectively with the engineering community and
with society at large. Be able to comprehend and write effective reports
PO10
documentation. Make effective presentations, and give and receive clear
instructions
Project management and finance: Demonstrate knowledge and understanding of
PO11 engineering and management principles and apply these to one’s own work, as a
member and leader in a team. Manage projects in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability
PO12 to engage in independent and life-long learning in the broadest context of
technological change.
3
Course Description:
This course covers the principles and practices of cryptography. The fundamental topics of
attacks, attack model, and few classical techniques are introduced. Symmetric and Asymmetric
ciphers are illustrated. Message authentication and Hash functions are exemplified. Also,
practical exposure on encryption algorithms, authentication techniques.
Course Objectives:
This course enables students to
1. Understand the basic categories of threats to computers and networks
2. Learn the Symmetric cryptographic algorithms.
3. Learn the Asymmetric cryptographic algorithms
4. Understand cryptographic Hash Functions
5. Understand message authentication and Digital Signature.
List of Programs:
4
Course Outcomes:
1. Upon successful completion of the course, students will be able to 1.
Implement classical Encryption Techniques 2. Apply symmetric key
cryptographic algorithms 3. Experiment with various asymmetric key
cryptographic algorithms 4. Execute stream cipher algorithms and hash
algorithms 5. Make use of Authentication functions
Text Books:
1. “Cryptography and Network Security - Principles and Practice” by William Stallings,
Pearson Education, 7th Edition, 2017.
Reference Books:
1. “Cryptography and Network Security” by C K Shyamala, N Harini and Dr T R Padmanabhan,
Wiley, 1st Edition, 2011.
2. “Cryptography and Network Security” by Forouzan and Mukhopadhyay, McGraw Hill, 2nd
Edition, 2010.
3. “Cryptography and Network Security” by Atul Kahate, McGraw Hill, 3 rd Edition, 2017.
Mode of Evaluation: Continuous Internal Evaluation and End Semester Examination
5
INDEX
6
Implementation of Caesar cipher
AIM:
To implement a Caesar cipher substitution technique inJava.
ALGORITHM:
1. Assign the 26 letters in alphabet to the variable named ALPHABET.
2. Convert the plaintext letters into lowercase.
3. To encrypt a plaintext letter, the first set of plaintext letters and slides it to LEFT by the number of
positions of the secret shift.
4. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath.
5. On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler
underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case.
6. Then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.
PROGRAM
#Ceaser Cipher
def encrypt(text,s):
result=""
for i in range(len(text)):
char=text[i]
if char.isupper():
result+=chr((ord(char)+s-65)%26+65)
else:
result+=chr((ord(char)+s-97)%26+97)
return result
def decrypt(text,s):
result=""
for i in range(len(text)):
char=text[i]
if char.isupper():
result+=chr((ord(char)-s-65)%26+65)
else:
result+=chr((ord(char)-s-97)%26+97)
return result
text='ATTACKONCE'
s=4
print("Text:"+text)
print("Shift:"+str(s))
print("Cipher:"+encrypt(text,s))
print("original text:"+decrypt(encrypt(text,s),s))
OUTPUT:
Text:ATTACKONCE
Shift:4
Cipher:EXXEGOSRGI
7
original text:ATTACKONCE
RESULT:
Thus the Ceaser cipher substitution technique was implemented and executed
Successfully.
PLAYFAIR CIPHER
PROGRAM:
#Playfair Cipher
def toLowerCase(text):
return text.lower()
def removeSpaces(text):
newText = ""
for i in text:
if i == " ":
continue
else:
newText = newText + i
return newText
def Diagraph(text):
Diagraph = []
group = 0
for i in range(2, len(text), 2):
8
Diagraph.append(text[group:i])
group = i
Diagraph.append(text[group:])
return Diagraph
def FillerLetter(text):
k = len(text)
if k % 2 == 0:
for i in range(0, k, 2):
if text[i] == text[i+1]:
new_word = text[0:i+1] + str('x') + text[i+1:]
new_word = FillerLetter(new_word)
break
else:
new_word = text
else:
for i in range(0, k-1, 2):
if text[i] == text[i+1]:
new_word = text[0:i+1] + str('x') + text[i+1:]
new_word = FillerLetter(new_word)
break
else:
new_word = text
return new_word
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def generateKeyTable(word, list1):
key_letters = []
for i in word:
if i not in key_letters:
key_letters.append(i)
compElements = []
for i in key_letters:
if i not in compElements:
compElements.append(i)
for i in list1:
if i not in compElements:
compElements.append(i)
matrix = []
while compElements != []:
matrix.append(compElements[:5])
compElements = compElements[5:]
return matrix
def search(mat, element):
for i in range(5):
for j in range(5):
if(mat[i][j] == element):
return i, j
def encrypt_RowRule(matr, e1r, e1c, e2r, e2c):
9
char1 = ''
if e1c == 4:
char1 = matr[e1r][0]
else:
char1 = matr[e1r][e1c+1]
char2 = ''
if e2c == 4:
char2 = matr[e2r][0]
else:
char2 = matr[e2r][e2c+1]
return char1, char2
if ele1_x == ele2_x:
c1, c2 = encrypt_RowRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
elif ele1_y == ele2_y:
c1, c2 = encrypt_ColumnRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
else:
c1, c2 = encrypt_RectangleRule(
Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
cipher = c1 + c2
10
CipherText.append(cipher)
return CipherText
text_Plain = 'instruments'
text_Plain = removeSpaces(toLowerCase(text_Plain))
PlainTextList = Diagraph(FillerLetter(text_Plain))
if len(PlainTextList[-1]) != 2:
PlainTextList[-1] = PlainTextList[-1]+'z'
key = "Monarchy"
print("Key text:", key)
key = toLowerCase(key)
Matrix = generateKeyTable(key, list1)
CipherText = ""
for i in CipherList:
CipherText += i
print("CipherText:", CipherText)
OUTPUT:
Key text: Monarchy
Plain Text: instruments
CipherText: gatlmzclrqtx
RESULT:
Thus the Playfair cipher substitution technique was implemented and executed
successfully
PYTHON
"""
Created on Wed Nov 15 10:54:53 2023
@author: Nandhini
"""
def columnar(plaintext,key):
values={}
seqlist=[]
nextvalue=1
indices=rand(len(key))
for letter in plaintext:
for i in indices:
if letter==key[i]:
values[i]=nextvalue
nextvalue=nextvalue+1
for i in indices:
seqlist.append(values[i])
return seqlist
def encode(txt,key):
sz = len(key) # how big are the columns
cols = list(map("".join,zip(*zip(*[iter(txt)]*sz)))) # list partitioned into
columns
return "".join([cols[key.index(str(c))] for c in range(1,sz+1)])
12
encoded = encode("IHAVETWOCATS","3124")
print (encoded)
order = {
int(val): num for num, val in enumerate(key)
}
ciphertext = ''
for index in sorted(order.keys()):
for part in split_len(plaintext, len(key)):
try:
ciphertext += part[order[index]]
except IndexError:
continue
return ciphertext
print(encode('3214', 'IHAVETWOCATS'))
#>>> HTAAWTIECVOS
OUTPUT:
13
Implementation of AES.
AIM:
To apply Advanced Encryption Standard (AES) Algorithm for a practical
application
like URL Encryption.
ALGORITHM:
1. AES is based on a design principle known as a substitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of128 bits, and a key size of 128, 192, or 256
bits.
4. AES operates on a 4 × 4 column-major order array of bytes, termed the
state
PROGRAM:
pip install pycryptodome
Collecting pycryptodome
Downloading pycryptodome-3.19.0-cp35-abi3-
manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 25.3 MB/s eta
0:00:00
Installing collected packages: pycryptodome
Successfully installed pycryptodome-3.19.0
PROGRAM:
#Advanced Encryption Standard
#Using ECB(Electronic CodeBook) mode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad,unpad
Block_Size=32
def aes_encrypt(plaintext,key):
cipher=AES.new(key,AES.MODE_ECB)
ciphertext=cipher.encrypt(pad(plaintext.encode(),Block_Size))
return ciphertext
def aes_decrypt(ciphertext,key):
cipher=AES.new(key,AES.MODE_ECB)
decrypttext=cipher.decrypt(ciphertext)
return decrypttext.decode()
14
plaintext="HELLO123"
key = b'AESKey1234567890'
ciphertext = aes_encrypt(plaintext, key)
print("Ciphertext:", ciphertext.hex())
decrypted_text = aes_decrypt(ciphertext, key)
print("Decrypted Text:", decrypted_text)
OR
#AES using CBC mode which is more secure than ECB mode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad,unpad
Block_Size=16
def aes_encrypt(plaintext,key,iv):
cipher=AES.new(key,AES.MODE_CBC,iv)
ciphertext=cipher.encrypt(pad(plaintext.encode(),Block_Size))
return ciphertext
def aes_decrypt(ciphertext,key,iv):
cipher=AES.new(key,AES.MODE_CBC,iv)
decrypttext=unpad(cipher.decrypt(ciphertext),Block_Size)
return decrypttext.decode()
plaintext="HELLO123"
key = b'AESKey1234567890'
iv=get_random_bytes(Block_Size)
ciphertext = aes_encrypt(plaintext, key,iv)
print("Ciphertext:", ciphertext.hex())
decrypted_text = aes_decrypt(ciphertext, key,iv)
print("Decrypted Text:", decrypted_text)
OUTPUT:
Ciphertext: 448639e5802a1ec13dcfa7189c0b31c6
Decrypted Text: HELLO123
OUTPUT:
Ciphertext: b48dcf62e2c913c89228fc98a4cab2f4219ed6ff0ff8bcd543f1edf670ec7cc2
Decrypted Text: HELLO123
RESULT:
Thus the java program for applying Advanced EncryptionStandard (AES)
Algorithm
for a practical application of URL encryption is written and executed
successfully
15
Implementation of RSA Algorithm
AIM:
To implement a RSA algorithm using HTML and Javascript.
ALGORITHM:
1. Choose two prime number p and q.
2. Compute the value of n and t.
3. Find the value of public key e.
4. Compute the value of private key d.
5. Do the encryption and decryption
a. Encryption is given as,
c=t
e mod n
b. Decryption is given as,
t=c
d mod n
PROGRAM
#Rivest-Shamir-Adelman
import math
p=3
q=7
n=p*q
e=2
phi=(p-1)*(q-1)
while(e<phi):
if math.gcd(e,phi)==1:
break
else:
e+=1
16
k=2
d=(1+(k*phi))/e
msg=12.0
print("Message data:",msg)
c=pow(msg,e)
c=math.fmod(c,n)
print("Encrypted data:",c)
m=pow(c,d)
m=math.fmod(m,n)
print("Original message sent:",m)
OUTPUT:
Message data: 12.0
Encrypted data: 3.0
Original message sent: 12.0
17
Implementation of Diffie-Hellman Algorithm .
AIM:
To implement a Diffie-Hellman Key Exchange algorithm.
ALGORITHM:
1. Sender and receiver publicly agree to use a modulus p and base g which is a primitive
root modulo p.
2. Sender chooses a secret integer x then sends Bob R1 = g
x mod p
3. Receiver chooses a secret integer y, then sends Alice R2 = g
y mod p
4. Sender computes k1 = B
x mod p
5. Receiver computes k2 = A
y mod p
6. Sender and Receiver now share a secret key.
PROGRAM
#Diffie-Hellman
import random
p=23
q=5
def compute_public_key(private_key):
return (q**private_key)%p
private_key_a=random.randint(1,p-1)
private_key_b=random.randint(1,p-1)
public_key_a=compute_public_key(private_key_a)
public_key_b=compute_public_key(private_key_b)
shared_secret_a=(public_key_b**private_key_a)%p
shared_secret_b=(public_key_a**private_key_b)%p
print(shared_secret_a)
print(shared_secret_b)
OUTPUT:
12
12
18
PROGRAM:
#RC-4
def key_scheduling(key):
sched = [i for i in range(0, 256)]
i = 0
for j in range(0, 256):
i = (i + sched[j] + key[j % len(key)]) % 256
tmp = sched[j]
sched[j] = sched[i]
sched[i] = tmp
return sched
def stream_generation(sched):
stream = []
i = 0
j = 0
while True:
i = (1 + i) % 256
j = (sched[i] + j) % 256
tmp = sched[j]
sched[j] = sched[i]
sched[i] = tmp
yield sched[(sched[i] + sched[j]) % 256]
def encrypt(text, key):
text = [ord(char) for char in text]
key = [ord(char) for char in key]
sched = key_scheduling(key)
key_stream = stream_generation(sched)
ciphertext = ''
for char in text:
enc = str(hex(char ^ next(key_stream))).upper()
ciphertext += (enc)
return ciphertext
19
ed = input('Enter E for Encrypt, or D for Decrypt: ').upper()
if ed == 'E':
plaintext = input('Enter your plaintext: ')
key = input('Enter your secret key: ')
result = encrypt(plaintext, key)
print('Result: ')
print(result)
elif ed == 'D':
ciphertext = input('Enter your ciphertext: ')
key = input('Enter your secret key: ')
result = decrypt(ciphertext, key)
print('Result: ')
print(result)
else:
print('Error in input - try again.')
Output :
Result:
Implemmentation of HMAC
AIM:
ALGORITHM:
PROGRAM:
#HMAC
import hmac
import hashlib
def generate(key,message):
hash_function=hashlib.sha256
key=bytes(key,'utf-8')
hmac_res=hmac.new(key,bytes(message,'utf-8'),digestmod=hash_function)
hmac_hex=hmac_res.hexdigest()
return hmac_hex
secret_key='my_secret_key'
data_to_hash="Hello, HMAC!"
res=generate(secret_key,data_to_hash)
print("Input Message:",data_to_hash)
print("Secret Key:",secret_key)
print("HMAC Output:",res)
OUTPUT:
Input Message: Hello, HMAC!
20
Secret Key: my_secret_key
HMAC Output: 2135134b3d2d6ac11a8eb3f6340dac59282a4edbb21ba861772ab2cb3ca56942
PROGRAM:
#SHA-3
import sys
import hashlib
if sys.version_info<(3,6):
import sha3
s=hashlib.sha3_224()
print(s.name)
print(s.digest_size)
s.update(b"Geeks")
print(s.hexdigest())
OUTPUT:
sha3_224
28
a32d875e701e4b6b0c582d39562fa989e1f4b6dfc17e45ad22fee234
Implementation of DSS(DIGITAL SIGNATURE SCHEME)
AIM:
To implement the signature scheme - Digital Signature Standard.
ALGORITHM:
1. Declare the class and required variables.
2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME - Digital Signature Standard.
5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a random
number K generated for the particular signature.
7. The signature function also depends on the sender„s private key.
8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10.The hash code and signature are given as input to a verification function.
PROGRAM
#DSA-Digital Signature Standard
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.backends import default_backend
def generate_dsa_key():
21
private_key=dsa.generate_private_key(key_size=1024,backend=default_backend)
public_key=private_key.public_key()
return private_key,public_key
def sign_message(private_key,message):
signature=private_key.sign(message,hashes.SHA256())
return signature
def verify_signature(public_key,signature,message):
try:
public_key.verify(signature,message,hashes.SHA256())
return True
except dsa.InvalidSignature:
return False
private_key,public_key=generate_dsa_key()
message=b"Hello,DSA!"
signature=sign_message(private_key,message)
verification_result=verify_signature(public_key,signature,message)
print("Message:",message.decode('utf-8'))
print("Signature:",signature)
print("Verification Result:", verification_result)
OUTPUT:
Message: Hello,DSA!
Signature: b'0.\x02\x15\x00\xba\xdb\xff\xf5H\xf3\x88\xb1\xafQC\xa4)R\x01I\
xac\xb0\xc2K\x02\x15\x00\xf4\xfe\xd3\xb8\x9bzv\xee\xda\xf3\xb9\x86\xf2\x87\
xa1\xd0\x07\x00\xc0|'
Verification Result: True
RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and
executed successfully.
22