0% found this document useful (0 votes)
77 views37 pages

INS Practical Journal

Uploaded by

bhavikp0026
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views37 pages

INS Practical Journal

Uploaded by

bhavikp0026
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Practical-1

AIM:- Implementing Substitution and Transposition ciphers.

1) Design and implement algorithms to encrypt and decrypt messages using classical
substitution techniques

CODE- Caesar Cipher

#A python program to illustrate Caesar Cipher Technique

def encrypt(text,s):
result = ""

# traverse text
for i in range(len(text)):
char = text[i]

# Encrypt uppercase characters


if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)

# Encrypt lowercase characters


else:
result += chr((ord(char) + s - 97) % 26 + 97)

return result

#check the above function


text = "ATTACKATONCE"
s=4
print ("Text : " + text)
print ("Shift : " + str(s))
print ("Cipher: " + encrypt(text,s))

Output-

CODE- Monoalphabetic cipher


// Java Program to Implement the Monoalphabetic Cypher

import java.io.*;
class GFG {
public static char normalChar[]
= { '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' };

public static char codedChar[]


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

// Function which returns encrypted string


public static String stringEncryption(String s)
{
// initializing an empty String
String encryptedString = "";

// comparing each character of the string and


// encoding each character using the indices
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < 26; j++) {

// comparing the character and


// adding the corresponding char
// to the encryptedString
if (s.charAt(i) == normalChar[j])
{
encryptedString += codedChar[j];
break;
}

// if there are any special characters


// add them directly to the string
if (s.charAt(i) < 'a' || s.charAt(i) > 'z')
{
encryptedString += s.charAt(i);
break;
}
}
}

// return encryptedString
return encryptedString;
}

// Function which returns descryptedString


public static String stringDecryption(String s)
{
// Initializing the string
String decryptedString = "";

// Run the for loop for total string


for (int i = 0; i < s.length(); i++)
{
for (int j = 0; j < 26; j++) {

// compare each characters and decode them


// using indices
if (s.charAt(i) == codedChar[j])
{
decryptedString += normalChar[j];
break;
}

// Add the special characters directly to


// the String
if (s.charAt(i) < 'A' || s.charAt(i) > 'Z')
{
decryptedString += s.charAt(i);
break;
}
}
}

// return the decryptedString


return decryptedString;
}
public static void main(String args[])
{
String str = "Welcome to Mumbai";

// print plain text


System.out.println("Plain text: " + str);

// Changing whole string to lower case


// function call to stringEncryption and storing in
// encryptedString
String encryptedString = stringEncryption(str.toLowerCase());

// printing encryptedString
System.out.println("Encrypted message: "
+ encryptedString);

// function call to stringDecryption and printing


// the decryptedString
System.out.println("Decrypted message: "
+ stringDecryption(encryptedString));
}
}

Output-

2) Design and implement algorithms to encrypt and decrypt messages using classical
Transposition techniques

Code- Railfence Cipher

# Python3 program to illustrate Rail Fence Cipher Encryption and Decryption

def encryptRailFence(text, key):

rail = [['\n' for i in range(len(text))]


for j in range(key)]
dir_down = False
row, col = 0, 0

for i in range(len(text)):

if (row == 0) or (row == key - 1):


dir_down = not dir_down

rail[row][col] = text[i]
col += 1

if dir_down:
row += 1
else:
row -= 1
result = []
for i in range(key):
for j in range(len(text)):
if rail[i][j] != '\n':
result.append(rail[i][j])
return("" . join(result))

def decryptRailFence(cipher, key):

rail = [['\n' for i in range(len(cipher))]


for j in range(key)]

dir_down = None
row, col = 0, 0
for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False

rail[row][col] = '*'
col += 1

if dir_down:
row += 1
else:
row -= 1

index = 0
for i in range(key):
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 == key-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))

# Driver code
if __name__ == "__main__":
print(encryptRailFence("Vanga", 3))
print(encryptRailFence("Sapdunga ", 3))
print(encryptRailFence("Poitu Vanga", 3))

print(decryptRailFence("Vaagn", 3))
print(decryptRailFence("Su adnapg", 3))
print(decryptRailFence("Punot agiVa", 3))
Output:

Code: Playfair Cipher

# Python program to implement 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):
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):


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

def encrypt_ColumnRule(matr, e1r, e1c, e2r, e2c):


char1 = ''
if e1r == 4:
char1 = matr[0][e1c]
else:
char1 = matr[e1r+1][e1c]

char2 = ''
if e2r == 4:
char2 = matr[0][e2c]
else:
char2 = matr[e2r+1][e2c]

return char1, char2

def encrypt_RectangleRule(matr, e1r, e1c, e2r, e2c):


char1 = ''
char1 = matr[e1r][e2c]

char2 = ''
char2 = matr[e2r][e1c]

return char1, char2

def encryptByPlayfairCipher(Matrix, plainList):


CipherText = []
for i in range(0, len(plainList)):
c1 = 0
c2 = 0
ele1_x, ele1_y = search(Matrix, plainList[i][0])
ele2_x, ele2_y = search(Matrix, plainList[i][1])

if ele1_x == ele2_x:
c1, c2 = encrypt_RowRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
# Get 2 letter cipherText
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
CipherText.append(cipher)
return CipherText
text_Plain = 'Vetrivel Muruganuku'
text_Plain = removeSpaces(toLowerCase(text_Plain))
PlainTextList = Diagraph(FillerLetter(text_Plain))
if len(PlainTextList[-1]) != 2:
PlainTextList[-1] = PlainTextList[-1]+'z'

key = "Arogharaa"
print("Key text:", key)
key = toLowerCase(key)
Matrix = generateKeyTable(key, list1)

print("Plain Text:", text_Plain)


CipherList = encryptByPlayfairCipher(Matrix, PlainTextList)

CipherText = ""
for i in CipherList:
CipherText += i
print("CipherText:", CipherText)

Output:
Practical-2

Aim: RSA Encryption and Decryption:


Implement the RSA algorithm for public-key encryption and decryption, and explore its
properties and security considerations.

Code:

import math
#step1
p=3
q=7
#step2
n=p*q
print("n =",n)
#step3
phi=(p-1)* (q-1)
#step4
e=2
while (e<phi):
if (math.gcd(e, phi) == 1):
break
else:
e+=1
print("e =",e)
#step5
k=2
d=((k*phi)+1)/e
print("d =",d)
print("Public key:",e,n)
print("Private key:",d,n)
#plaintext
msg=11
print("Original message:",msg)
#encryption
C=pow(msg,e)
C=math.fmod(C,n)
print("Encrypted message:",C)
#decryption
M=pow(C,d)
M=math.fmod(M,n)
print("Decrypted message:",M)

Output:
Practical 3

Message Authentication Codes: Implement algorithms to generate and verify message authentication
codes (MACs) for ensuring data integrity and authenticity.

1) Using hmac

import hmac
message="Welcome to TYCS."
key="INS"

hmac1= hmac.new(key= key.encode(), msg=message.encode(), digestmod="sha1")


message_digest1=hmac1.digest()
print("Message Digest 1: ",hmac1.name, message_digest1)

hmac2=hmac.new(key=key.encode(), digestmod="sha1")
hmac2.update(bytes(message, encoding="utf-8"))
message_digest2=hmac2.digest()
print("Message Digest 2: ",hmac2.name, message_digest2)

hmac3=hmac.new(key=key.encode(), digestmod="sha1")
hmac3.update(bytes("Welcome to ", encoding="utf-8"))
hmac3.update(bytes("CoderzColumn.", encoding="utf-8"))
message_digest3=hmac3.digest()

print("Message Digest 3: ",hmac3.name, message_digest3)

print("\nMessage Digest Size for 1:{}, 2:{} and 3:{}".


format(hmac1.digest_size, hmac2.digest_size,hmac3.digest_size,))
print("Message Block Size for 1:{}, 2:{} and 3:{}".
format(hmac1.block_size, hmac2.block_size,hmac3.block_size,))

Output:
2) Python Code for implementing MD5 Algorithm

import hashlib
result = hashlib.md5(b'NetworkSecurity')
result1 = hashlib.md5(b'NetworkSecuriti')

print("The byte equivalent of hash is: ", end= "")


print(result.digest())
print("The byte equivalent of hash is: ", end= "")
print(result1.digest())

Output:

3) Python Code for implementing SHA Algorithm

import hashlib
str = input(" Enter the value to encode ")
result = hashlib.sha1(str.encode())
print("The hexadecimal equivalent if SHA1 is : ")
print(result.hexdigest())

Output:
Practical 4

Aim: To study and implement the Digital Signature algorithm

pip install pycryptodome

Code: Python code for implementing SHA Algorithm

from Crypto.PublicKey import RSA


from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256

# Generate RSA key pair


key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

# Simulated document content


original_document = b"This is the original document content."
modified_document = b"This is the modified document content."

# Hash the document content


original_hash = SHA256.new(original_document)
modified_hash = SHA256.new(modified_document)

# Create a signature using the private key


signature = pkcs1_15.new(RSA.import_key(private_key)).sign(original_hash)

# Verify the signature using the public key and the original hash
try:
pkcs1_15.new(RSA.import_key(public_key)).verify(original_hash, signature)
print("Signature is valid.")
except (ValueError, TypeError):
print("Signature is invalid.")

Output:
Practical - 5

Aim: Key Exchange using Diffie-Hellman


Implement the Diffie-Hellman key exchange algorithm to securely exchange keys
between two entities over an insecure network.

Code:

def prime_checker(p):
if p<1:
return -1
elif p>1:
if p==2:
return 1
for i in range(2,p):
if p%i==0:
return-1
return 1

def primitive_check(g,p,L):
for i in range(1,p):
L.append(pow(g, i) % p)
for i in range(1,p):
if L.count(i)>1:
L.clear()
return -1
return 1
l=[]
while 1:
P=int(input("Enter P:"))
if prime_checker(P)==-1:
print("Number Is Not Prime, Please Enter Again!")
continue
break
while 1:
G=int(input(f"Enter The Primitive Root Of {P}:"))
if primitive_check(G,P,l) == -1:
print(f"Number Is Not A Primitive Root Of {P}. Please Try Again!")
continue
break
x1,x2=int(input("Enter The Private Key Of User 1:")),int(
input("Enter The Private Key Of User 2:"))
while 1:
if x1>P or x2>=P:
print(f"Private Key Of Both The Users Should Be Less Than (P)!")
continue
break
y1,y2 = pow(G,x1) % P,pow(G, x2) % P
k1,k2= pow(y2,x1) % P,pow(y1, x2) % P

print(f"\nSecret Key For User 1 Is {k1}\nSecret Key For User 2 Is {k2}\n")

if k1== k2:
print("Keys Have Been Exchanged Successfully")
else:
print("Keys Have Not Been Exchanged Successfully")

Output:
Practical – 6

Aim: Configure IPsec on network devices to provide secure communication and


protect against unauthorized access and attacks.

Part 1: Implementing the Topology using Cisco Packet Tracer, configure the IP and set
the IP route
Step1 : Implement the topology as given in the below diagram

Step 2 : Configure the IP address of the PC and gateway


Step 3: Configure all the router as

Part 2: Configure the Hostname on all Routers and enable the security
package on R1 and R2, Ping on PC from the other(All packets are lost)

Step 1: Click on router 1 click on CLI and execute the following command

Router>enable
Router#configure terminal

Router(config)#ip route
0.0.0.0 0.0.0.0 20.0.0.2

Step 2 : Click on router 2 and click on CLI and execute the following command
Router>enable
Router#configure terminal
Router(config)#ip route 0.0.0.0 0.0.0.0 30.0.0.2

Step3: Now ping one PC from another from the command line( Ping should fail)

Part 3: Apply the Access Control List(ACL) at Router 1 and 2, Set the
ISALMP policy and ISAKMP key, Set IPSec transform set

Step 1: Go to the CLI of router 1 and type the following command and enable
security package

Router>enable
Router#configure terminal
Router(config)#hostname R1

R1(config)#license boot module c1900 technology-package securityk9

R1(config)#exit
R1#copy run startup-config
R1#reload
R1>enable
R1#show version

Step2: Repeat the above step for Router 2 with hostname R2


Step 3: Enable the policy. To do so go to CLI and type the following command
R1>enable
R1#configure terminal

R1(config)#access-list 100 permit ip 192.168.1.0 0.0.0.255 192.168.2.0


0.0.0.255
R1(config)#crypto isakmp policy 10
R1(config-isakmp)#encryption aes 256
R1(config-isakmp)#authentication pre-share
R1(config-isakmp)#group 5

R1(config-isakmp)#exit
R1(config)#crypto isakmp key ismile address 30.0.0.1
R1(config)#crypto ipsec transform-set R1->R2 esp-aes 256 esp-sha-hamc
R1(config)#crypto ipsec transform-set R2->R1 esp-aes 256 esp-sha-hamc

Step4: Repeat the above step for Router 2


R2>enable R2#configure terminal

R2 (config)#access-list 100 permit ip 192.168.2.0 0.0.0.255 192.168.1.0

0.0.0.255
R2 (config)#crypto isakmp policy 10
R2 (config-isakmp)#encryption aes 256
R2 (config-isakmp)#authentication pre-share R2
(config-isakmp)#group 5

R2 (config-isakmp)#exit
R2(config)#crypto isakmp key ismile address 20.0.0.1
R2(config)#crypto ipsec transform-set R2->R1 esp-aes 256 esp-sha-hamc

Part 4 : Create the crypto map and apply to the required interface. Verify the output by
pinging one PC from other
R1(config)#Crypto map IPSEC-MAP 10 ipsec-isakmp
R1(Config-crypto-map)#set peer 30.0.0.1

R1(Config-crypto-map)#set pfs group5

R1(Config-crypto-map)#set security-association lifetime 86400


R1(Config-crypto-map)#set transform-set R1->R2

R1(Config-crypto-map)#match address 100


R1(Config-crypto-map)#exit R1(Config)#interface g0/0

R1(Config-if)#crypto map IPSEC-MAP

Repeat the same for router 2.


R2(Config-crypto-map)#set peer 20.0.0.1 R1(Config-crypto-map)#set transform-set R2->R1
Now ping the system again we will get the output
Practical – 7
Aim: Configure and implement secure web communication using SSL/TLS protocols, including certificate
management and secure session establishment.

Steps: Go to Control Panel->Program and Features->Turn Windows Feature on

Turn On Internet Information Service

Turn on the IIS Management Console and World Wide Web services
Now from window explorer, open IIS Manager

Click on server in the left pane and Choose default web site.

Click on Desktop and click on server Certificate

Create Self Signed Certificate, give a proper name and certificate store as Web hosting
Click on Default Website & Click on bindings and bind with type https port 443 by clicking Add btn.

Click on Default Website and click SSL Settings


Click on Require SSL Checkbox and click Apply in the right pane , it is successfully changed.

Type localhost in google URL and you would get the following page

Now, Type https://localhost in google URL and you would get the following page
Now, click on Advanced and then click on proceed to localhost and you will get the following screen.
Practical – 9
Aim: To do Detect and Analyse Malware
Steps:
Open the website www.virusshare.com to download the clean sample of Malware.
Create account by sending a mail to Melissa at [email protected] with 'access' in the subject. She
will review your request and hopefully send you an invitation link.

By clicking the above download icon the Malware gets downloaded in ZIP format.

Do not unzip the file, we create a folder “Malware” on desktop and save the file in the folder. In order to
analyse the Malware, we select the website www.virustotal.com
Click on “Choose File” and select the file from the location (ZIP file will do, if asks for password enter
infected). We get the following after the upload is completed

We interpret the following findings


a) 64 security vendors out of 69 flagged this file as malicious
b) The detection tab shows the threats-type which were flagged by the vendors for e.g
c) The details tab gives the following information
i. Basic properties
ii. History
iii. Compiler products
iv. Header
v. Sections
vi. Imports
vii. Exports
viii. Overlays
d) The Behavior tab gives the following information
i. Activity summary
ii. MITRE ATT&CK Tactics and Techniques
iii. Behavior Similarity Hashes
iv. Process and service actions
Practical - 10

Aim: Firewall Configuration and Rule- based Filtering

Part 1: Blocking the Port


We access any website through the browser and confirm that the HTTP/HTTPS protocols are working.

Step 2: We open ‘Windows Defender Firewall’


Next we click on ‘Inbound Rules’

Then click on ‘New Rule’


Select the radio button ‘Port’ and click ‘Next’ and enter the following

After next, we need to finalise the rule


Click ‘Next’ and we get the following

After clicking the ‘Next’ button we need to name the rule and click finish
The Inbound rule is added

We repeat all the above steps for creating ‘Outbound Rules’, and then try to access the internet.
We see that the accessed is blocked
Part 2: Blocking the website www.android.com
We open the browser and access the website, which is now accessible

We find the IP addresses of the website using the following command

We save the IP addresses

IPv4 216.58.196.68

IPv6 2404:6800:4009:809::2004
We open the windows Firewall settings and apply the Inbound Rule
Insert the IP addresses both IPv4 and IPv6

Select Block connection


Provide a suitable name and finish

Repeat the above for Outbound Rules now!

if we try to access the website www.android.com , it would be blocked

You might also like