0% found this document useful (0 votes)
116 views35 pages

CN Lab 2

This document contains information about simulating a simple computer network using the OMNeT++ simulator. It describes: 1. Creating a project called "tictoc" and adding two nodes called "Tic" and "Toc" connected in a loop with 100ms delays between each node. 2. Defining the nodes and network in a NED file. 3. Implementing the node functionality in C++ source code. 4. Configuring the simulation using an omnetpp.ini file to specify the network and parameters. 5. Compiling and running the simulation successfully, passing a message between the two nodes.

Uploaded by

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

CN Lab 2

This document contains information about simulating a simple computer network using the OMNeT++ simulator. It describes: 1. Creating a project called "tictoc" and adding two nodes called "Tic" and "Toc" connected in a loop with 100ms delays between each node. 2. Defining the nodes and network in a NED file. 3. Implementing the node functionality in C++ source code. 4. Configuring the simulation using an omnetpp.ini file to specify the network and parameters. 5. Compiling and running the simulation successfully, passing a message between the two nodes.

Uploaded by

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

Dr.

B R AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY JALANDHAR, PUNJAB

COMPUTER NETWORK LAB

CSX – 321

SESSION 2018-2019

Submitted To: Submitted By:


Dr. Avtar Singh Kunal Khandelwal -17103045
Assistant professor Group -G-2
CSE Department
COMPUTER NETWORK LAB-1

OPNET

OPNET Network Simulator is used to simulate the performance and behavior of any network. It stands
better than other simulators in terms of its power and versatility. OPNET network simulator supports
simulation of wireless and fixed networks. It is widely used as a research tool or a network analysis tool,
which is the reason for its widespread usage. We have highly skilled and talented developers working with
OPNET based projects and research works for providing research guidance for budding scholars. We provide
online guidance and tutoring for research scholars to enlighten their research work with novel and innovative
ideas. We feel to impart our immense knowledge to the budding students, as the more knowledge we share,
more we gain. Mine best and novel ideas for your projects and research work with the help of our top
experts. Let’s have a glance over the highlights of OPNET Network simulator.

KEY features-

 Provides support for building models, execution of simulation and analysis of output result.
 Hierarchical structure of modeling
 Provide Detailed library of models [supports existing protocols and either adds or modify models
or develop new models]
 It can be compiled into executable code
 Three major tools: Model development tool, simulation execution tool and results analysis tool.
 Discrete event simulation engine with object oriented modeling
 OPNET Network Simulator is an open free software
 Large number of project scenarios that are offered information on OPNET Network Simulator

Platform and Programming language support-

 Platform support [Sun Solaris, Microsoft windows, Red Hat Linux]


 Main programming language- C
 Recent version supports C++

Uses of OPNET simulator-


 Operational validation.
 Application troubleshooting.
 Network planning and design.
 Validating hardware architecture.
 Protocol modeling.
 Traffic modeling of telecommunication networks.
 Evaluating performance aspects of complex software systems.
Discrete event simulation workflow-
 Create/import topology/configuration.
 Create traffic.
 Run simulation.
 View results.
 Duplicate or create new scenario.
 Publish results.

NS2

NS2 stands for Network Simulator Version 2. It is an open-source event-driven simulator designed
specifically for research in computer communication networks.

Features of NS2-
1. It is a discrete event simulator for networking research.
2. It provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https and DSR.
3. It simulates wired and wireless network.
4. It is primarily UNIX based.
5. Uses TCL as its scripting language.
6. OTCL: Object oriented support
7. TCLCL: C++ and OTCL linkage
8. Discrete event scheduler

Basic Architecture-
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTCL). While the
C++ defines the internal mechanism (i.e., a backend) of the simulation objects, the OTCL sets up simulation
by assembling and configuring the objects as well as scheduling discrete events. The C++ and the OTCL are
linked together using TCLCL

OPNET vs NS2

1.Accuracy-
In terms of accuracy of bandwidth estimation for the pure CBR-type traffic, Ns-2 performed better than
OPNET Modeler using the default Modeler package.
Reference- https://www.researchgate.net/publication/228560494_OPNET_Modeler_and_Ns-
2_comparing_the_accuracy_of_network_simulators_for_packet-level_analysis_using_a_network_testbed
2.GUI support-
Ns-2 provides very similar results compared to OPNET Modeler, but the “freeware” version of Ns-2
makes it more attractive to a researcher. However, the complete set of OPNET Modeler modules provides
more features than Ns-2, and it therefore will be more attractive to network operator.

3.Programming language supported-


NS-2 supports C++/OTCL programming language while OPNET uses C++/JAVA.

4.Memory usage-
NS-2 uses more memory then OPNET.
Reference- https://arxiv.org/ftp/arxiv/papers/1307/1307.4129.pdf

5.Operating system supported-


NS-2 supports both Windows and UNIX while OPNET only supports Windows.
Reference- https://www.ijert.org/research/comparative-study-of-ns2-and-OPNET-simulator-for-aodv-and-
dsr-routing-protocols-in-manet-IJERTV2IS70647.pdf

6.Packet Loss-
Packet drop (loss) = Total packet sent- total packet received.
NS-2 => Less in AODV (Ad Hoc On-Demand Distance Vector), but very much for DSR (Dynamic
Source Routing Protocol).
OPNET => More data loss in AODV, but in DSR negligible.
Reference- https://www.ijert.org/research/comparative-study-of-ns2-and-OPNET-simulator-for-aodv-and-
dsr-routing-protocols-in-manet-IJERTV2IS70647.pdf

OMNET++

OMNeT++ is an object-oriented modular discrete event network simulation framework. It has a generic
architecture, so it can be (and has been) used in various problem domains:

 modeling of wired and wireless communication networks


 protocol modeling
 modeling of queuing networks
 modeling of multiprocessors and other distributed hardware systems
 validating of hardware architectures
 evaluating performance aspects of complex software systems
 In general, modeling and simulation of any system where the discrete event approach is suitable, and
can be conveniently mapped into entities communicating by exchanging messages.

OMNeT++ itself is not a simulator of anything concrete, but rather provides infrastructure and tools for
writing simulations. One of the fundamental ingredients of this infrastructure is a component architecture for
simulation models. Models are assembled from reusable components termed modules. Well-written modules
are truly reusable.

Advantages of OMNET++ =>


 Well structured.
 Highly modular.
 Not limited to network protocol simulation.
 Source code is publicly available.
 Simulation model for internet, IPV6, mobility is also available.
COMPUTER NETWORK LAB-2

AIM:
Connecting two nodes(named Tic and Toc) to get familiar with network simulation in Omnet++.

Procedure:

Step 1:
Start the OMNeT++ IDE by typing omnetpp in your terminal. (We assume that you already have a working
OMNeT++ installation. If not, please install the latest version, consulting the Installation Guide as needed.)
Once in the IDE, choose New -> OMNeT++ Project from the menu.
A wizard dialog will appear. Enter tictoc as project name, choose Empty project when asked about the initial
content of the project, then click Finish. An empty project will be created, as you can see in the Project
Explorer. (Note: Some OMNeT++ versions will generate a package.ned file into the project. We don't need it
now: delete the file by selecting it and hitting Delete.)
The project will hold all files that belong to our simulation. In our example, the project consists of a single
directory. For larger simulations, the project's contents are usually sorted into src/ and simulations/
folders, and possibly subfolders underneath them.

Step2:
OMNeT++ uses NED files to define components and to assemble them into larger units like networks. We
start implementing our model by adding a NED file. To add the file to the project, right-click the project
directory in the Project Explorer panel on the left, and choose New -> Network Description File (NED) from
the menu. Enter tictoc1.ned when prompted for the file name.
Switch into Source mode, and enter the following:

simple Txc1
{
gates:
input in;
output out;
}
network Tictoc1
{
submodules:
tic: Txc1; toc: Txc1; connections:
tic.out --> { delay = 100ms; } --> toc.in;
tic.in <-- { delay = 100ms; } <-- toc.out;
}

When you're done, switch back to Design mode. You should see something like this:
Step3:
We now need to implement the functionality of the Txc1 simple module in C++. Create a file named txc1.cc
by choosing New -> Source File from the project's context menu (or File -> New -> File from the IDE's
main menu), and enter the following content:
Step 4:
To be able to run the simulation, we need to create an omnetpp.ini file. omnetpp.ini tells the simulation
program which network you want to simulate (as NED files may contain several networks), you can pass
parameters to the model, explicitly specify seeds for the random number generators, etc.

Create an omnetpp.ini file using the File -> New -> Initialization file (INI) menu item. The new file will
open in an Inifile Editor. As the NED Editor, the Inifile Editor also has two modes, Form and Source, which
edit the same content. The former is more suitable for configuring the simulation kernel, and the latter for
entering module parameters.
For now, just switch to Source mode and enter the following: [General]
network = Tictoc1

Step5:
We are now done with creating the first model, and ready to compile and run it.

Result:
The program is compiled and executed successfully.
COMPUTER NETWORK LAB-3

Aim: - Create a simple simulation of Tic Toc model for passing message back and forth and change colour
of the nodes.

Apparatus used: - Omnet++ IDE

Steps:-

1) Setting up project

Start OMNET++ IDE by typing omnetpp in the terminal.


Once IDE is opened Choose New->OMNET++ Project from the menu.
A wizard dialog will appear. Enter tictoc as project name. An empty project will appear in the project
explorer.

2) Adding the NED file

OMNeT++ uses NED files to define components and to assemble them into larger units like networks. We
start implementing our model by adding a NED file. To add the file to the project, right-click the project
directory in the Project Explorer panel on the left, and choose New -> Network Description File (NED) from
the menu. Enter tictoc1.ned when prompted for the file name.

Now in the source section type the following code:-

loka1ned.ned

simple Txc1

parameters:

@display("i=block/routing");

gates:

input in;

output out;

network Tictoc1

@display("bgb=261,199");
submodules:

tic: Txc1 {

parameters:

@display("i=,cyan");

toc: Txc1 {

parameters:

@display("i=,gold;p=140,119");

connections:

tic.out --> { delay = 100ms; } --> toc.in;

tic.in <-- { delay = 100ms; } <-- toc.out;

The design section will look like:-


3) Adding the C++ file

We now need to implement the functionality of the Txc1 simple module in C++. Create a file
named loka1.cc by choosing New -> Source File from the project's context menu (or File -> New ->
File from the IDE's main menu), and enter the following content:

loka1.cc

#include <string.h>

#include<omnetpp.h>

using namespace omnetpp;

class tictocNode:public cSimpleModule{

protected:

void initialize() override;

void handleMessage(cMessage*msg) override;

};

Define_Module(tictocNode)//register OMNET++

void tictocNode::initialize(){

if(strcmp("tic",getName())==0)

cMessage *msg=new cMessage("Himanshu ");

send(msg,"portOut");

void tictocNode::handleMessage(cMessage *msg){

send(msg,"portOut");

4) Adding omnetpp.ini file

To be able to run the simulation, we need to create an omnetpp.ini file. omnetpp.initells the simulation
program which network you want to simulate (as NED files may contain several networks), you can pass
parameters to the model, explicitly specify seeds for the random number generators, etc.
Create an omnetpp.ini file using the File -> New -> Initialization file (INI) menu item. The new file will
open in an Inifile Editor. As the NED Editor, the Inifile Editor also has two modes, Form and Source, which
edit the same content. The former is more suitable for configuring the simulation kernel, and the latter for
entering module parameters.

For now, just switch to Source mode and enter the following:

[General]

network = Tictoc1

5) Running the simulation

Once you complete the above steps, you can launch the simulation by selecting %omnetpp.ini (in either the
editor area or the Project Explorer), and pressing the Runbutton.

The IDE will build your project automatically. If there are compilation errors, you need to rectify those until
you get an error-free compilation and linking. You can manually trigger a build by hitting choosing Project
-
> Build All from the menu, or hitting Ctrl+B.
COMPUTER NETWORK LAB-4

Aim: - Create a simple simulation of Tic Toc model for passing message back and forth and change colour
of more than 2 nodes.

Apparatus used: - Omnet++ IDE

Steps:-

1) Setting up project

Start OMNET++ IDE by typing omnetpp in the terminal.


Once IDE is opened Choose New->OMNET++ Project from the menu.
A wizard dialog will appear. Enter tictoc as project name. An empty project will appear in the project
explorer.

2) Adding the NED file

OMNeT++ uses NED files to define components and to assemble them into larger units like networks. We
start implementing our model by adding a NED file. To add the file to the project, right-click the project
directory in the Project Explorer panel on the left, and choose New -> Network Description File (NED) from
the menu. Enter tictoc1.ned when prompted for the file name.

Now in the source section type the following code:-

lab3morethan2.ned

simple Txc1

parameters:

@display("i=block/routing");

gates:

input in;

output out;

network Tictoc1

@display("bgb=211,186");

submodules:
tic: Txc1 {

parameters:

@display("i=,cyan;p=44.433334,35.833336");

toc: Txc1 {

parameters:

@display("i=,gold;p=164.11667,35.833336");

tac: Txc1 {

parameters:

@display("i=,red;p=164.11667,131.15001");

tol: Txc1 {

parameters:

@display("i=,orange;p=44.433334,131.15001");

connections:

tic.out-->toc.in;

toc.out-->tac.in;

tac.out-->tol.in;

tol.out-->tic.in;

The design section will look like:-


3) Adding the C++ file

We now need to implement the functionality of the Txc1 simple module in C++. Create a file
named lab2.cc by choosing New -> Source File from the project's context menu (or File -> New ->
File from the IDE's main menu), and enter the following content:

lab2.cc

#include <stdio.h>

#include <string.h>

#include <omnetpp.h>

using namespace omnetpp;

class Txc1 : public cSimpleModule

protected:

virtual void initialize() override;


virtual void handleMessage(cMessage *msg) override;

};

Define_Module(Txc1);

void Txc1::initialize()

if (strcmp("tic", getName()) == 0) {

cMessage *msg = new cMessage("Himanshu ");

send(msg, "out");

void Txc1::handleMessage(cMessage *msg)

send(msg, "out");

4) Adding omnetpp.ini file

To be able to run the simulation, we need to create an omnetpp.ini file. omnetpp.initells the simulation
program which network you want to simulate (as NED files may contain several networks), you can pass
parameters to the model, explicitly specify seeds for the random number generators, etc.

Create an omnetpp.ini file using the File -> New -> Initialization file (INI) menu item. The new file will
open in an Inifile Editor. As the NED Editor, the Inifile Editor also has two modes, Form and Source, which
edit the same content. The former is more suitable for configuring the simulation kernel, and the latter for
entering module parameters.

For now, just switch to Source mode and enter the following:

[General]

network = Tictoc1
5) Running the simulation

Once you complete the above steps, you can launch the simulation by selecting %omnetpp.ini (in either the
editor area or the Project Explorer), and pressing the Runbutton.

The IDE will build your project automatically. If there are compilation errors, you need to rectify those until
you get an error-free compilation and linking. You can manually trigger a build by hitting choosing Project
-
> Build All from the menu, or hitting Ctrl+B.
COMPUTER NETWORK LAB-5

AIM- Introduction to OSI Layer and its protocol.

INTRODUCTION-

Protocol is a set of rules that defines how end point communication takes place between devices. Large
number of protocols are present in networking that are operated at different layers.
1) Application / Presentation/ Session Layer :- FTP, SMTP, HTTP, DNS , SNMP ,TELNET
2) Transport Layer :- SCTP, UDP, TCP.
3) Network Layer :- ICMP, IGMP, RARP, ARP
4) Physical and Data Link Layer :- these two layers defines protocol that is to be followed by upper layer

Application Layer protocol:-

1. TELNET:

Telnet stands for the TELecomunications NETwork. It helps in terminal emulation. It allows Telnet client to
access the resources of the Telnet server. It is used for managing the files on the internet. It is used for initial
set up of devices like switches. The telnet command is a command that uses the Telnet protocol to
communicate with a remote device or system. Port number of telnet is 23.

2. FTP:

FTP stands for file transfer protocol. It is the protocol that actually lets us transfer files.It can facilitate this
between any two machines using it. But FTP is not just a protocol but it is also a program.FTP promotes
sharing of files via remote computers with reliable and efficient data transfer. Port number for FTP is 20 for
data and 21 for control.

3. TFTP:

The Trivial File Transfer Protocol (TFTP) is the stripped-down, stock version of FTP, but it’s the protocol of
choice if you know exactly what you want and where to find it. It’s a technology for transferring files
between network devices and is a simplified version of FTP

4. NFS:

It stands for network file system.It allows remote hosts to mount file systems over a network and interact
with those file systems as though they are mounted locally. This enables system administrators to
consolidate resources onto centralized servers on the network.
5. SMTP:

It stands for Simple Mail Transfer Protocol. It is a part of the TCP/IP protocol. Using a process called “store
and forward,” SMTP moves your email on and across networks. It works closely with something called the
Mail Transfer Agent (MTA) to send your communication to the right computer and email inbox. Port number
for SMTP is 25.

6. LPD:

It stands for Line Printer Daemon.It is designed for printer sharing.It is the part that receives and processes
the request. A “daemon” is a server or agent.

7. DNS:

It stands for Domain Name Service. Every time you use a domain name, therefore, a DNS service must
translate the name into the corresponding IP address. For example, the domain name www.abc.com might
translate to 198.105.232.4.
Port number for DNS is 53.

8. DHCP:

It stands for Dynamic Host Configuration Protocol (DHCP).It gives IP addresses to hosts.There is a lot of
information a DHCP server can provide to a host when the host is registering for an IP address with the
DHCP server. Port number for DHCP is 67, 68.

Transport layer

TCP (Transmission Control Protocol):


TCP is a layer 4 protocol which provides acknowledgement of the received packets and is also reliable as it
resends the lost packets. It is better than UDP but due to these features it has an additional overhead. It is
used by application protocols like HTTP and FTP.

UDP (User Datagram Protocol):


UDP is also a layer 4 protocol but unlike TCP it doesn’t provide acknowledgement of the sent packets.
Therefore, it isn’t reliable and depends on the higher layer protocols for the same. But on the other hand it is
simple, scalable and comes with lesser overhead as compared to TCP. It is used in video and voice
streaming.

TCP Vs UDP –
1. Session Multiplexing:
A single host with a single IP address is able to communicate with multiple servers. While using TCP,
first a connection must be established between the server and the receiver and the connection is closed
when the transfer is completed. TCP also maintains reliability while the transfer is taking place.
UDP on the other hand sends no acknowledgement of receiving the packets. Therefore, provides
no reliability.

2. Segmentation:
Information sent is first broken into smaller chunks for transmission.
Maximum Transmission Unit or MTU of a Fastethernet is 1500 bytes whereas the theoretical value of
TCP is 65495 bytes. Therefore, data has to be broken into smaller chunks before being sent to the lower
layers. MSS or Maximum Segment Size should be set small enough to avoid fragmentation. TCP
supports MSS and Path MTU discovery with which the sender and the receiver can automatically
determine the maximum transmission capability.
UDP doesn’t support this; therefore it depends on the higher layer protocols for data segmentation.

3. Flow Control:
If sender sends data faster than what receiver can process then the receiver will drop the data and then
request for a retransmission, leading to wastage of time and resources. TCP provides end-to-end flow
control which is realized using a sliding window. The sliding window sends an acknowledgement from
receiver’s end regarding the data that the receiver can receive at a time.
UDP doesn’t implement flow control and depends on the higher layer protocols for the same.

4. Connection Oriented:
TCP is connection oriented, i.e., it creates a connection for the transmission to take place, and once the
transfer is over that connection is terminated.
UDP on the other hand is connectionless just like IP (Internet Protocol).
5. Reliability:
TCP sends an acknowledgement when it receives a packet. It requests a retransmission in case a packet
is lost.
COMPUTER NETWORK LAB-6

AIM- Write a Program in C to implement ALOHA protocol.

Introduction-

• In pure ALOHA, the stations transmit frames whenever they have data to send.

• When two or more stations transmit simultaneously, there is collision and the frames are
destroyed.

• In pure ALOHA, whenever any station transmits a frame, it expects the acknowledgement
from the receiver.

• If acknowledgement is not received within specified time, the station assumes that the frame
(or acknowledgement) has been destroyed.

• If the frame is destroyed because of collision the station waits for a random amount of time
and sends it again. This waiting time must be random otherwise same frames will collide again and again.

• Therefore pure ALOHA dictates that when time-out period passes, each station must wait for a random
amount of time before resending its frame. This randomness will help avoid more
collisions.

• Figure shows an example of frame collisions in pure ALOHA.

Program:

#include<stdio.h>
#include<math.h>;

int main()
{

float time,frames,G,S;

printf("Enter the duration of communication in sec. :");

scanf("%f",&time);

printf("Enter the no. of frames transmitted during that time :");

scanf("%f",&frames);

G = frames/(time*1000);
printf("G=%f\n",G);

printf("***********\n\n"); S = G*pow(2.72,-2*G);

printf("\nEfficiency for Pure ALOHA is %f \n",S);

printf("In Pure ALOHA only %f out of %f frames will be transmitted\n\n",S*frames,frames);

printf("***********\n\n"); S = G*pow(2.72,-G);

printf("Efficiency for Slotted ALOHA is %f \n",S);

printf("In Slotted ALOHA only %1.0f out of %1.0f frames will be transmitted \n\n",S*frames,frames);
}

OUTPUT-
COMPUTER NETWORK LAB-7

AIM- Introduction to Cryptography and its types.

INTRODUCTION

Cryptography is an important aspect when we deal with network security. ‘Crypto’ means secret or hidden.
Cryptography is the science of secret writing with the intention of keeping the data secret. Cryptanalysis, on
the other hand, is the science or sometimes the art of breaking cryptosystems. These both terms are a subset
of what is called as Cryptology.

Modern cryptography concerns with:

1. Confidentiality - Information cannot be understood by anyone

2. Integrity - Information cannot be altered.

3. Non-repudiation - Sender cannot deny his/her intentions in the transmission of the information at a
later stage

4. Authentication - Sender and receiver can confirm each

CLASSIFICATION

Cryptography is classified into symmetric cryptography, asymmetric cryptography and hashing. Below are
the description of these types.

Symmetric-key Cryptography: Both the sender and receiver share a single key. The sender uses this key
to encrypt plaintext and send the cipher text to the receiver. On the other side the receiver applies the same
key to decrypt the message and recover the plain text.
Public-Key Cryptography: This is the most revolutionary concept in the last 300-400 years. In Public-Key
Cryptography two related keys (public and private key) are used. Public key may be freely distributed, while
its paired private key, remains a secret. The public key is used for encryption and for decryption private key
is used.

Hash Functions: No key is used in this algorithm. A fixed-length hash value is computed as per the plain
text that makes it impossible for the contents of the plain text to be recovered. Hash functions are also used
by many operating systems to encrypt passwords.
COMPUTER NETWORK LAB-8

AIM- Implement Caesar Cypher

INTRODUCTION-

The Caesar Cipher technique is one of the earliest and simplest method of encryption technique. It’s simply a
type of substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of
positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C,
and so on. The method is apparently named after Julius Caesar, who apparently used it to communicate with
his officials.
Thus to cipher a given text we need an integer value, known as shift which indicates the number of position
each letter of the text has been moved down.

ALGORITHM-
Input:

1.A String of lower case letters, called Text.


2.An Integer between 0-25 denoting the required shift.
Procedure:

 Traverse the given text one character at a time .


 For each character, transform the given character as per the rule, depending on whether
we’re encrypting or decrypting the text.
 Return the new string generated.

PROGRAM-

#include <iostream>

using namespace std;

string decrypt(string result,int s)

{ string ans;

for (int i=0;i<result.length();i++)

{ if (isupper(result[i]))

ans += char(int(result[i]-s-65)%26 +65);

else

result += char(int(result[i]-s-97)%26 +97);

cout<<ans;}
string encrypt(string text, int s)

string result = "";

for (int i=0;i<text.length();i++)

if (isupper(text[i]))

result += char(int(text[i]+s-65)%26 +65);

else

result += char(int(text[i]+s-97)%26 +97);

decrypt(result,s);

return result;

int main()

{ string text;

cout<<"Enter text- ";

cin>>text;

cout<<"ENTER KEY- ";

int s;

cin>>s;

cout << "Text : " << text;

cout << "\nShift: " << s;

cout << "\nCipher: " << encrypt(text, s);

return 0;

}
OUTPUT-
COMPUTER NETWORK LAB-9

AIM- Implement VIgenere Cypher

PROGRAM-

#include<bits/stdc++.h>

using namespace std;

string generateKey(string str, string key)

{int x = str.size();

for (int i = 0; ; i++)

{if (x == i)

i = 0;

if (key.size() == str.size())

break;

key.push_back(key[i]);}

return key;}

string cipherText(string str, string key)

{string cipher_text;

for (int i = 0; i < str.size(); i++)

{int x = (str[i] + key[i]) %26;

x += 'A';

cipher_text.push_back(x);}

return cipher_text;}

string originalText(string cipher_text, string key)

{string orig_text;

for (int i = 0 ; i < cipher_text.size(); i++)

{int x = (cipher_text[i] - key[i] + 26) %26;

x += 'A';

orig_text.push_back(x);}
return orig_text;}

int main()

string str = "Kunalkhandelwal";

string keyword = "khan";

string key = generateKey(str, keyword);

string cipher_text = cipherText(str, key);

cout << "Ciphertext : "<< cipher_text << "\n";

cout << "Original or Data after decrpytion : "<< originalText(cipher_text, key);

return 0;

OUTPUT-
COMPUTER NETWORK LAB-10

AIM- IMPLEMENT HILL CYPHER

PROGRAM-

#include<iostream>

using namespace std;

void getKeyMatrix(string key, int keyMatrix[][3])

int k = 0;

for (int i = 0; i < 3; i++)

{for (int j = 0; j < 3; j++)

{keyMatrix[i][j] = (key[k]) % 65;

k++;}}}

void encrypt(int cipherMatrix[][1],

int keyMatrix[][3], int messageVector[][1])

{int x, i, j;

for (i = 0; i < 3; i++)

{for (j = 0; j < 1; j++)

{cipherMatrix[i][j] = 0;

for (x = 0; x < 3; x++)

cipherMatrix[i][j] +=

keyMatrix[i][x] * messageVector[x][j];

cipherMatrix[i][j] = cipherMatrix[i][j] % 26;}}

void HillCipher(string message, string key)

{int keyMatrix[3][3];
getKeyMatrix(key, keyMatrix);

int messageVector[3][1]; for (int i = 0; i < 3; i++)

messageVector[i][0] = (message[i]) % 65;

int cipherMatrix[3][1];

encrypt(cipherMatrix, keyMatrix, messageVector);

string CipherText;

for (int i = 0; i < 3; i++)

CipherText += cipherMatrix[i][0] + 65;

cout << " Ciphertext:" << CipherText;

int main()

string message = "CNLAB";

string key = "KUNALKHANDELWAL";

HillCipher(message, key);

cout<<"\nOriginal OR Data after Decryption: "<<key;

return 0;

OUTPUT-
COMPUTER NETWORK LAB-11

AIM- Implement PlayFair Cypher

PROGRAM-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
void toLowerCase(char plain[], int ps)
{
int i;
for (i = 0; i < ps; i++) {
if (plain[i] > 64 && plain[i] < 91)
plain[i] += 32;
}
}
int removeSpaces(char* plain, int ps)
{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
void generateKeyTable(char key[], int ks, char keyT[5][5])
{
int i, j, k, flag = 0, *dicty;
dicty = (int*)calloc(26, sizeof(int));
for (i = 0; i < ks; i++) {
if (key[i] != 'j')
dicty[key[i] - 97] = 2;
}
dicty['j' - 97] = 1;
i = 0;
j = 0;
for (k = 0; k < ks; k++) {
if (dicty[key[k] - 97] == 2) {
dicty[key[k] - 97] -= 1;
keyT[i][j] = key[k];
j++;
if (j == 5) {
i++;
j = 0;
}}}
for (k = 0; k < 26; k++)
{ if (dicty[k] == 0)
{ keyT[i][j] = (char)(k +
97); j++;
if (j == 5) {
i++;
j = 0;
}}}}

void search(char keyT[5][5], char a, char b, int arr[])


{
int i, j;
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (keyT[i][j] == a)
{ arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}}}}

int mod5(int a)
{ return (a % 5);}
int prepare(char str[], int ptrs)
{
if (ptrs % 2 != 0) {
str[ptrs++] = 'z';
str[ptrs] = '\0';
}

return ptrs;
}
void encrypt(char str[], char keyT[5][5], int ps)
{
int i, a[4];
for (i = 0; i < ps; i += 2)
{ search(keyT, str[i], str[i + 1],
a); if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] + 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] + 1)];
}
else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] + 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] + 1)][a[1]];
}
else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}}}
void encryptByPlayfairCipher(char str[], char key[])
{
char ps, ks, keyT[5][5];
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
ps = prepare(str, ps);
generateKeyTable(key, ks, keyT);
encrypt(str, keyT, ps);
}
void decrypt(char str[], char keyT[5][5], int ps)
{
int i, a[4];
for (i = 0; i < ps; i += 2)
{ search(keyT, str[i], str[i + 1],
a); if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] - 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] - 1)];
}
else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] - 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] - 1)][a[1]];
}
else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}}}
void decryptByPlayfairCipher(char str[], char key[])
{
char ps, ks, keyT[5][5];
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
generateKeyTable(key, ks, keyT);
decrypt(str, keyT, ps);
}
int main()
{
char str[SIZE], key[SIZE];
printf("Enter plain text to be encrypted:");
scanf("%s",str);
printf("Enter key string:");
scanf("%s",key);
encryptByPlayfairCipher(str, key);
printf("Cipher text: %s\n", str);
decryptByPlayfairCipher(str, key);
printf("decrypted text:%s\n",str);
return 0;
}

OUTPUT-

You might also like