Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Dr. B.R. Ambedkar National Institute of Technology: Computer Networks CSX-321

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

DR. B.R.

AMBEDKAR NATIONAL INSTITUTE OF


TECHNOLOGY

COMPUTER NETWORKS
CSX-321

SUBMITTED TO: SUBMITTED BY:


Dr. Avtar Singh Dussa Prashanth

Assistant Professor 17103031

CSE Department G-2


Experiment 1

Aim: (a) Introduction to Network Simulator: NS2, OMNET++, and OPNET.

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

Characteristics

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 Structure
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
OMNeT++
OMNeT++ is an extensible, modular, component-based C++ simulation library and framework,
primarily for building network simulators. “Network” is meant in a broader sense that includes
wired and wireless communication networks, on-chip networks, queueing networks, and so on.
Domain-specific functionality such as support for sensor networks, wireless ad-hoc networks,
Internet protocols, performance modeling, photonic networks, etc., is provided by model
frameworks, developed as independent projects. OMNeT++ offers an Eclipse-based IDE, a
graphical runtime environment, and a host of other tools. There are extensions for real-time
simulation, network emulation, database integration, SystemC integration, and several other
functions. OMNeT++ is distributed under the Academic Public License.

Although OMNeT++ is not a network simulator itself, it has gained widespread popularity as a
network simulation platform in the scientific community as well as in industrial settings, and
building up a large user community.

OMNeT++ provides a component architecture for models. Components (modules) are


programmed in C++, then assembled into larger components and models using a high-level
language (NED). Reusability of models comes for free. OMNeT++ has extensive GUI support,
and due to its modular architecture, the simulation kernel (and models) can be embedded easily
into your applications.

Characteristics

 Simulation kernel library (C++)


 The NED topology description language
 Simulation IDE based on the Eclipse platform
 Interactive simulation runtime GUI (Qtenv)
 Command-line interface for simulation execution (Cmdenv)
 Utilities (makefile creation tool, etc.)
 Documentation, sample simulations, etc.
OPNet
OPNET Network simulator is a tool to simulate the behavior and performance of any type of
network. The main difference Opnet Network Simulator comparing to other simulators lies in its
power and versatility.

Characteristics

 Opnet Network Simulator is a open free software


 Large number of project scenarios that are offered information on Opnet Network Simulator
 Can be overlooked using Opnet Network Simulator.

Used for

 Application troubleshooting.
 Network planning and design.
 Validating hardware architecture.
 Protocol modeling.
 Traffic modeling of telecommunication networks.
 Evaluating performance aspects of complex software systems.
 Create/import topology/configuration.
 Create traffic.
 Choose statistics
 Run simulation.
 View results.
 Duplicate or create new scenario.
 Publish results.
COMPARISON
Features NS2 OMNeT++ OPNeT
Language C++/OTCL C++ C (C++)
Supported
GUI Poor Good excellent
support
Time taken to Long Moderate long
learn
Time take for Moderate time Very easy, takes very less Moderate time
download and time. Easily available
installation
Platform Linux, unix ,windows, Linux ,unix, Linux ,solar is
Cygwin windows, windows
MAC OS
Network It supports network It supports It supports
Visualization tool visualization tool network network
visualization tool visualization tool
Availability of It has analysis tool It has analysis tool It has analysis tool
analysis tool
Creates trace file It creates trace file It creates trace file It creates trace file
Possibility to It is Possible It is Possible It is Possible
design and
modify the
network
scenarios
Design and Supports both wired and Supports both Supports both
Implementation wireless simulation wired and wired and
Protocols of protocols wireless wireless
simulation of simulation of
protocols protocols
Interaction with It is Possible It is Possible It is Possible
real
time system
Fast simulation Moderate Moderate Moderate
capabilities

Merits -Easy to add new -Powerful -Opnet


protocols. graphical User communicate
-A large number of Interface with other
protocols available (making tracing simulators
publicly. and bugging -Fast discrete
easier) event
-Simulate simulation engine
power -Scalable
Consumption wireless
problem simulation
support
Demerits -Supports only two -Number of -It is a
wireless protocol is not large commercial
MAC protocols, 802.11, enough. product
and a single-hop TDMA -Compatibility -Memory
protocol. problem (not Consuming models
-Need to familiar with portable). -
writing scripting language -bit slow due to high insufficient
memory consumption and tutorials
large simulation.

(b) Installation Steps of NS2, OMNET++, and OPNET.


Installing NS2 on windows NS2 builds and runs under windows using Cygwin. Cygwin
provides Linux like environment under windows.

System Requirements: A computer with C++ compiler. Building full NS2 package requires large
memory space approximately 250MB

Steps to install NS 2 on windows are given below

1. Download Cygwin from following linkhttps://www.cygwin.com/setup.exe 2. Run the


downloaded setup.exe and you will see screen shown below click next.

3. Select option "Install From Internet". If you have already downloaded the package select
"Install from local directory" and click next

4. Keep the default installation directory as "C:\cygwin" and click next

5. Keep default local package directory as your download folder and click next.

Installing Omnet++ In Ubuntu 18.04.1 Before starting the installation, refresh the database of
available packages.

1. Type in the terminal:

$ sudo apt-get update

2. To install the required packages, type in the terminal:

$ sudo apt-get install build-essential gcc g++ bison flex perl \python python3 qt5-default
libqt5opengl5-dev tcl-dev tk-dev \libxml2-dev zlib1g-dev default-jre doxygen graphviz
libwebkitgtk-1.0 openscenegraph-plugin-osgearth libosgearth-dev openmpi-bin libopenmpi-dev
libpcap-dev gnome-color-chooser nemiver

3. Now Download the omnetpp file from omnet website Click on this: Get the Ubuntu File open
a new terminal
$ cd Downloads $ tar xvfz omnetpp-5.4.1-src-linux.tgz $ cd omnetpp-5.4.1 $ . setenv ** note
down space between . and setenv **

4. Now copy the path which is /home/user/Downloads/omnetpp-5.4.1 $ gedit ~/.bashrc **

5. Add the following line at the end of the file, then save it: export
PATH=$PATH:/home/user/Downloads/omnetpp-5.4.1/bi n **

6. Here user is your pc-name **

7. now closed the current terminal which is very important open a new terminal $ cd Downloads
$ cd omnetpp-5.2.1 $ ./configure $ make $ omnetpp.
Experiment 2
Aim: First Simulation on omnetpp.
1. Create a working directory called tictoc1, and cd to this directory.

2. Describe your example network by creating a topology file. A topology file is a text file that
identifies the network's nodes and the links between them. You can create it with your favourite
text editor. Let's call it tictoc1.ned:

simple Txc1
{
gates:
input in;
output out;
}

//
// Two instances (tic and toc) of Txc1 connected both ways.
// Tic and toc will pass messages to one another.
//
network Tictoc1
{
submodules:
tic: Txc1;
toc: Txc1;
connections:
tic.out --> { delay = 100ms; } -->
toc.in; tic.in <-- { delay = 100ms; }
<-- toc.out;
3. We now need to implement the functionality of the simple module Txc2. This is achieved by
writing a C++ file txc2::cc:

#include <string.h>
#include <omnetpp.h>

class Txc1 : public cSimpleModule


{
protected:
// The following redefined virtual function holds the algorithm.
virtual void initialize();
virtual void handleMessage(cMessage *msg);
};

// The module class needs to be registered with OMNeT++


Define_Module(Txc1);

void Txc1::initialize()
{
// Initialize is called at the beginning of the simulation.
// To bootstrap the tic-toc-tic-toc process, one of the modules needs
// to send the first message. Let this be `tic'.

// Am I Tic or Toc?
if (strcmp("tic", getName()) == 0)
{
// create and send first message on gate "out". "tictocMsg" is an
// arbitrary string which will be the name of the message object.
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}

void Txc1::handleMessage(cMessage *msg)


{
// The handleMessage() method is called whenever a message arrives
// at the module. Here, we just send it to the other module, through
// gate `out'. Because both `tic' and `toc' does the same, the message
// will bounce between the two.
send(msg, "out");
}
4. We now create the Makefile which will help us to compile and link our program to create
the executable tictoc:

5. Let's now compile and link our very first simulation by issuing the make command:

6. If you start the executable now, it will complain that it cannot find the file omnetpp.ini, so you
have to create one. omnetpp.ini tells the simulation program which network you want to
simulate (yes, several networks can live in the same simulation program), you can pass
parameters to the model, explicitly specify seeds for the random number generators etc.

8. Press the Run button on the toolbar to start the simulation. What you should see is that tic and
toc are exchanging messages with each other.
Experiment 3
Aim: Making Nodes Colorful in Omnet++.
1. Create a working directory called tictoc, and cd to this directory.

2. Describe your example network by creating a topology file. A topology file is a text file that
identifies the network's nodes and the links between them. You can create it with your favorite
text editor. Let's call it tictoc1.ned:

simple Txc2
{
parameters:
@display("i=block/routing"); // add a default icon
gates:
input in;
output out;
}

//
// Make the two module look a bit different with colorization effect.
// Use cyan for `tic', and yellow for `toc'.
//
network Tictoc2
{
submodules:
tic: Txc2 {
parameters:
@display("i=,cyan"); // do not change the icon (first arg of i=) just
colorize it
}
toc: Txc2 {
parameters:
@display("i=,gold"); // here too
}
connections:

3. We now need to implement the functionality of the simple module Txc1. This is achieved by
writing a C++ file txc1::cc:

#include <string.h>
#include <omnetpp.h>
class Txc2 : public cSimpleModule
{
protected:
// The following redefined virtual function holds the algorithm.
virtual void initialize();
virtual void handleMessage(cMessage *msg);
};

// The module class needs to be registered with OMNeT++


Define_Module(Txc2);

void Txc2::initialize()
{
// Initialize is called at the beginning of the simulation.
// To bootstrap the tic-toc-tic-toc process, one of the modules needs
// to send the first message. Let this be `tic'.

// Am I Tic or Toc?
if (strcmp("tic", getName()) == 0)
{
// create and send first message on gate "out". "tictocMsg" is an
// arbitrary string which will be the name of the message object.
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}

void Txc2::handleMessage(cMessage *msg)


{
// The handleMessage() method is called whenever a message arrives
// at the module. Here, we just send it to the other module, through
// gate `out'. Because both `tic' and `toc' does the same, the message
// will bounce between the two.
send(msg, "out");
}

4. We now create the Makefile which will help us to compile and link our program to create
the executable tictoc:

5. Let's now compile and link our very first simulation by issuing the make command:

6. If you start the executable now, it will complain that it cannot find the file omnetpp.ini, so you
have to create one. Omnetpp.ini tells the simulation program which network you want to
simulate (yes, several networks can live in the same simulation program), you can pass
parameters to the model, explicitly specify seeds for the random number generators etc.
8. Press the Run button on the toolbar to start the simulation. What you should see is that colorful
tic and toc are exchanging messages with each other
Experiment 4
Aim: To implement more than two nodes in Omnet++.
1. Create a working directory called tictoc, and cd to this directory.

2. Describe your example network by creating a topology file. A topology file is a text file that
identifies the network's nodes and the links between them. You can create it with your favorite
text editor. Let's call it tictoc10.ned:

simple Txc10
{
parameters:
@display("i=block/routing");
gates:
input in[]; // declare in[] and out[] to be vector gates
output out[];
}
network Tictoc10
{
submodules:
tic[6]: Txc10;
connections:
tic[0].out++ --> { delay = 100ms; } --> tic[1].in++;
tic[0].in++ <-- { delay = 100ms; } <-- tic[1].out++;

tic[1].out++ --> { delay = 100ms; } --> tic[2].in++;


tic[1].in++ <-- { delay = 100ms; } <-- tic[2].out++;

tic[1].out++ --> { delay = 100ms; } --> tic[4].in++;


tic[1].in++ <-- { delay = 100ms; } <-- tic[4].out++;

tic[3].out++ --> { delay = 100ms; } --> tic[4].in++;


tic[3].in++ <-- { delay = 100ms; } <-- tic[4].out++;

tic[4].out++ --> { delay = 100ms; } --> tic[5].in++;


tic[4].in++ <-- { delay = 100ms; } <-- tic[5].out++;
}

3. We now need to implement the functionality of the simple module Txc10. This is achieved by
writing a C++ file txc10::cc:

#include <string.h>
#include <omnetpp.h>
class Txc10 : public cSimpleModule
{
protected:
// The following redefined virtual function holds the algorithm.
virtual void initialize();
virtual void handleMessage(cMessage *msg);
};

// The module class needs to be registered with OMNeT++


Define_Module(Txc10);

void Txc10::initialize()
{
// Initialize is called at the beginning of the simulation.
// To bootstrap the tic-toc-tic-toc process, one of the modules needs
// to send the first message. Let this be `tic'.

// Am I Tic or Toc?
if (strcmp("tic", getName()) == 0)
{
// create and send first message on gate "out". "tictocMsg" is an
// arbitrary string which will be the name of the message object.
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}

void Txc10::handleMessage(cMessage *msg)


{
// The handleMessage() method is called whenever a message arrives
// at the module. Here, we just send it to the other module, through
// gate `out'. Because both `tic' and `toc' does the same, the message
// will bounce between the two.
send(msg, "out");
}

4. We now create the Makefile which will help us to compile and link our program to create the
executable tictoc:

5. Let's now compile and link our very first simulation by issuing the make command:

6. Create omnet.ini file.

8. Press the Run button on the toolbar to start the simulation. What you should see is that tic and
toc are exchanging messages with each other
Experiment-5

Aim: Implement Pure Aloha.


Theory:

• 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:
Experiment-6

Aim: Introduction to Layers of OSI Model.


Established in 1947, the International Standards Organization (ISO) is a multinational body dedicated to
worldwide agreement on international standards. Almost three-fourths of countries in the world are
represented in the ISO. An ISO standard that
covers all aspects of network communications is the Open Systems Interconnection (OSI) model. It was
first introduced in the late 1970s.

. An open system is a set of protocols that allows any two different systems to communicate regardless of
their underlying architecture. The purpose of the OSI model is to show how to facilitate communication
between different systems without requiring changes to the logic of the underlying hardware and software.
The OSI model is not a protocol; it is a model for understanding and designing a network architecture that is
flexible, robust, and interoperable. The OSI model was intended to be the basis for the creation of the
protocols in the OSI stack. The OSI model is a layered framework for the design of network systems that
allows communication between all types of computer systems. It consists of seven separate but related layers,
each of which defines a part of the process of moving information across a network . Understanding the
fundamentals of the OSI model provides a solid basis for exploring data communications.

The OSI Model

In developing the model, the designers distilled the process of transmitting data to its most fundamental
elements. They identified which networking functions had related uses and collected those functions into
discrete groups that became the layers. Each layer defines a family of functions distinct from those of the
other layers. By defining and localizing functionality in this fashion, the designers created an architecture that
is both comprehensive and flexible. Most important, the OSI model allows complete interoperability between
otherwise incompatible systems.

1.Physical Layer

The physical layer coordinates the functions required to carry a bit stream over a physical medium. It deals
with the mechanical and electrical specifications of the interface and transmission media. It also defines the
procedures and functions that physical devices and interfaces have to perform for transmission to occur.
The physical layer is also concerned with the following:
❑ Physical characteristics of interfaces and media. The physical layer defines the characteristics of the
interface between the devices and the transmission media. It also defines the type of transmission media .
❑ Representation of bits. The physical layer data consists of a stream of bits (sequence of 0s or 1s) with no
interpretation. To be transmitted, bits must be encoded into signals—electrical or optical. The physical layer
defines the type of encoding (how 0s and 1s are changed to signals).
❑ Data rate. The transmission rate—the number of bits sent each second—is also defined by the physical
layer. In other words, the physical layer defines the duration of a bit, which is how long it lasts.
❑ Synchronization of bits. The sender and receiver must not only use the same bit rate but must also be
synchronized at the bit level. In other words, the sender and the receiver clocks must be synchronized.

2.Data Link Layer

The data link layer transforms the physical layer, a raw transmission facility, to a reliable link. It makes the
physical layer appear error-free to the upper layer (network layer). Other responsibilities of the data link layer
include the following:
❑ Framing. The data link layer divides the stream of bits received from the network layer into manageable
data units called frames.
❑ Physical addressing. If frames are to be distributed to different systems on the network, the data link
layer adds a header to the frame to define the sender and/or receiver of the frame. If the frame is intended for
a system outside the sender’s network, the receiver address is the address of the connecting device that
connects the network to the next one.
❑ Flow control. If the rate at which the data is absorbed by the receiver is less than the rate produced at the
sender, the data link layer imposes a flow control mechanism to prevent overwhelming the receiver.
❑ Error control. The data link layer adds reliability to the physical layer by adding mechanisms to detect
and retransmit damaged or lost frames. It also uses a mechanism to recognize duplicate frames. Error control
is normally achieved through a trailer added to the end of the frame.

3.Network Layer

The network layer is responsible for the source-to-destination delivery of a packet, possibly across multiple
networks (links). Whereas the data link layer oversees the delivery of the packet between two systems on the
same network (link), the network layer ensures that each packet gets from its point of origin to its final
destination. If two systems are connected to the same link, there is usually no need for a network layer.
However, if the two systems are attached to different networks (links) with connecting devices between the
networks (links), there is often a need for the network layer to accomplish source-to-destination delivery.
Other responsibilities of the network layer include the following:
❑ Logical addressing. The physical addressing implemented by the data link layer handles the addressing
problem locally. If a packet passes the network boundary, we need another addressing system to help
distinguish the source and destination systems. The network layer adds a header to the packet coming from
the upper layer that, among other things, includes the logical addresses of the sender and
receiver.
❑ Routing. When independent networks or links are connected together to create internetworks (network of
networks) or a large network, the connecting devices (called routers or switches) route or switch the packets
to their final destination. One of the functions of the network layer is to provide this mechanism.

4.Transport Layer

The transport layer is responsible for process-to-process delivery of the entire message. A process is an
application program running on the host. Whereas the network layer oversees source-to-destination delivery
of individual packets, it does not recognize any relationship between those packets. It treats each one
independently, as though each piece belonged to a separate message, whether or not it does. The transport
layer, on the other hand, ensures that the whole message arrives intact and in order, overseeing both error
control and flow control at the source-to-destination level. Other responsibilities of the transport layer include
the following:
❑ Service-point addressing. Computers often run several programs at the same time. For this reason,
source-to-destination delivery means delivery not only from one computer to the next but also from a specific
process (running program) on one computer to a specific process (running program) on the other. The
transport layer header must therefore include a type of address called a service-point address (or port
address). The network layer gets each packet to the correct computer; the transport layer gets the entire
message to the correct process on that computer.
❑ Segmentation and reassembly. A message is divided into transmittable segments, with each segment
containing a sequence number. These numbers enable the transport layer to reassemble the message correctly
upon arriving at the destination and to identify and replace packets that were lost in transmission.
❑ Connection control. The transport layer can be either connectionless or connection oriented. A
connectionless transport layer treats each segment as an independent packet and delivers it to the transport
layer at the destination machine. A connection oriented transport layer makes a connection with the transport
layer at the destination machine first before delivering the packets. After all the data are transferred,
the connection is terminated.

5.Session Layer

The services provided by the first four layers (physical, data link, network and transport) are not sufficient for
some processes. The session layer is the network dialog controller. It establishes, maintains, and
synchronizes the interaction between communicating systems. Specific responsibilities of the session layer
include the following:
❑ Dialog control. The session layer allows two systems to enter into a dialog. It allows the communication
between two processes to take place in either halfduplex (one way at a time) or full-duplex (two ways at a
time) mode.
❑ Synchronization. The session layer allows a process to add checkpoints (synchronization points) into a
stream of data. For example, if a system is sending a file of 2,000 pages, it is advisable to insert checkpoints
after every 100 pages to ensure that each 100-page unit is received and acknowledged independently. In this
case, if a crash happens during the transmission of page 523, the only pages that need to be resent after
system recovery are pages 501 to 523. Pages previous to 501 need not be resent.

6.Presentation Layer

The presentation layer is concerned with the syntax and semantics of the information exchanged between
two systems. Specific responsibilities of the presentation layer include the following:
❑ Translation. The processes (running programs) in two systems are usually exchanging information in the
form of character strings, numbers, and so on. The information should be changed to bit streams before being
transmitted. Because different computers use different encoding systems, the presentation layer is responsible
for interoperability between these different encoding methods. The presentation layer at the sender changes
the information from its sender-dependent format into a common format. The presentation layer at the
receiving machine changes the common format into its receiver-dependent format.
❑ Encryption. To carry sensitive information a system must be able to assure privacy. Encryption means
that the sender transforms the original information to another form and sends the resulting message out over
the network. Decryption reverses the original process to transform the message back to its original form.
❑ Compression. Data compression reduces the number of bits contained in the information. Data
compression becomes particularly important in the transmission of multimedia such as text, audio, and video.
Experiment-7

Aim: Introduction to Cryptography and its types

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.
Classification –
The flowchart depicts that cryptology is only one of the factors involved in securing networks. Cryptology
refers to study of codes, which involves both writing (cryptography) and solving (cryptanalysis) them. Below
is a classification of the crypto-terminologies and their various types.

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

It involves usage of one secret key along with encryption and decryption algorithms which help
in securing the contents of the message. The strength of symmetric key cryptography depends
upon the number of key bits. It is relatively faster than asymmetric key cryptography. There
arises a key distribution problem as the key has to be transferred from the sender to receiver
through a secure channel.

Assymetric key cryptography –

It is also known as public key cryptography because it involves usage of a public key along with secret key. It
solves the problem of key distribution as both parties uses different keys for encryption/decryption. It is not
feasible to use for decrypting bulk messages as it is very slow compared to symmetric key cryptography.
Hashing –

It involves taking the plain-text and converting it to a hash value of fixed size by a hash
function. This process ensures integrity of the message as the hash value on both, sender\’s and
receiver\’s side should match if the message is unaltered.
Experiment-8

Aim: Write a program to implement Caesar cipher in cryptography.

#include <iostream>
using namespace std;
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);}
return result;
}
string decrypt(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);}
return result;
}
int main()
{
string text,result;
cout<<"Enter text to encrypt";
cin>>text;
int s;
cout<<"enter key shift";
cin>>s;
result=encrypt(text,s);
cout << "Text : " << text;
cout << "\nShift: " << s;
cout << "\nCipher: " << result;
cout<<"\ndecrypted msg:"<<decrypt(result,s);
return 0;
}

Output:
Experiment-9

Aim: Write a program to implement playfair cipher in cryptography.

#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:
Experiment-10

Aim: Write a program to implement Hill cipher in cryptography.

#include<iostream>
#include<math.h>
using namespace std;
float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];
void encryption();
void decryption();
void getKeyMessage();
void inverse();
int main() {
getKeyMessage();
encryption();
decryption();
}
void encryption() {
int i, j, k;

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


for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
cout<<"\nEncrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(encrypt[i][0], 26) + 97);
}
void decryption() {
int i, j, k;
inverse();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
cout<<"\nDecrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(decrypt[i][0], 26) + 97);
cout<<"\n";
}
void getKeyMessage() {
int i, j;
char msg[3];
cout<<"Enter 3x3 matrix for key (It should be inversible):\n";
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
cin>>a[i][j];
c[i][j] = a[i][j];
}
cout<<"\nEnter a 3 letter string: ";
cin>>msg;
for(i = 0; i < 3; i++)
mes[i][0] = msg[i] - 97;
}
void inverse() {
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j)
b[i][j]=1;
else
b[i][j]=0;
}

for(k = 0; k < 3; k++) {


for(i = 0; i < 3; i++) {
p = c[i][k];
q = c[k][k];

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


if(i != k) {
c[i][j] = c[i][j]*q - p*c[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / c[i][i];
cout<<"\n\nInverse Matrix is:\n";
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
cout<<b[i][j]<<" ";
cout<<"\n";}}

Output:
Experiment-11

Aim: Write a program to implement vegenere cipher in cryptography.

#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;
string keyword;
cout<<"enter string:";
cin>>str;
cout<<"enter key:";
cin>>keyword;
string key = generateKey(str, keyword);
string cipher_text = cipherText(str, key);

cout << "Ciphertext : "


<< cipher_text << "\n";

cout << "Original/Decrypted Text : "


<< originalText(cipher_text, key);
return 0;
}

Output:

You might also like