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

Unit :- 3

Practical :- 1

AIM :- Write Ceaser Cipher algorithm & Solve various examples based
on Encryption and Decryption.

Modular Math and the Shift Cipher


The Caesar Cipher is a type of shift cipher. Shift Ciphers work by using the modulo
operator to encrypt and decrypt messages. The Shift Cipher has a key K, which is
an integer from 0 to 25. We will only share this key with people that we want to see our
message.

How to Encrypt:

For every letter in the message M :

1. Convert the letter into the number that matches its order in the alphabet starting from 0,
and call this number X.
( A=0, B=1, C=2, ...,Y=24, Z=25)

2. Calculate: Y = (X + K) mod 26

3. Convert the number Y into a letter that matches its order in the alphabet starting from 0.

(A=0, B=1, C=2, ...,Y=24, Z=25)

For Example: We agree with our friend to use the Shift Cipher with key K=19for our
message.
We encrypt the message "KHAN", as follows:​
So, after applying the Shift Cipher with key K=19 our message text "KHAN" gave
us cipher text "DATG".

We give the message "DATG" to our friend.

How to decrypt:

For every letter in the cipher text C :

1. Convert the letter into the number that matches its order in the alphabet starting from 0,
and call this number Y.
(A=0, B=1, C=2, ..., Y=24, Z=25)

2. Calculate: X= (Y - K) mod 26

3. Convert the number X into a letter that matches its order in the alphabet starting from 0.
(A=0, B=1, C=2, ..., Y=24, Z=25)

Our friend now decodes the message using our agreed upon key K=19. As follows:

So, after decrypting the Shift Cipher with key K=19 our friend deciphers the cipher text
"DATG" into the message text "KHAN".
Practical :- 2

AIM :- Write test and debug Ceaser Cipher program in


C.

#include <stdio.h>
#include <ctype.h>

#define MAXSIZE 1024

void encrypt(char*);
void decrypt(char*);

int menu();

int
main(void)
{

char c,
choice[2],
s[MAXSIZE];

while(1)
{
menu();

gets(choice);

if((choice[0]=='e')||(choice[0]=='E'))
{
puts("Input text to encrypt->");
gets(s);
encrypt(s);
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
puts("Input text to decrypt->");
gets(s);
decrypt(s);
}
else
break;
}

return 0;
}

void encrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];

while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
else if(*p=='x')
q[n]='A';
else if(*p=='y')
q[n]='B';
else
q[n]='C';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}

void decrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
else if(*p=='A')
q[n]='x';
else if(*p=='B')
q[n]='y';
else
q[n]='z';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}

int menu()
{
puts("To encrypt, input e or E\n");
puts("To decrypt, input d or D\n");
puts("To exit, input any other letter\n");
puts("Your choice:->\n");
return 0;
}
Practical :- 3

AIM :- Write algorithm / steps for Hill Cipher and solve examples on it.

 The Hill Cipher was invented by Lester S. Hill in 1929.


 It is extendable to work on different sized blocks of letters. So, technically it is
a polygraphic substitution cipher, as it can work on digraphs, trigraphs (3
letter blocks) or theoretically any sized blocks.
 The Hill Cipher uses Linear Algebra, matrices and Modulo Arithmetic.
Because of this, the cipher has a significantly more mathematical nature than
some of the others.
 Encryption
 To encrypt a message using the Hill Cipher we must first turn our keyword
into a key matrix (either in 2x2 matrix or 3x3 matrix).
 We also turn the plaintext into digraphs (or trigraphs) and each of these into a
column vector.
 We then perform matrix multiplication modulo the length of the alphabet (i.e.
26) on each vector. These vectors are then converted back into letters to
produce the ciphertext.
 2 x 2 Example
Plaintext : "short example"
Key : hill
 The first step is to turn the keyword into a matrix. If the keyword
was longer than the 4 letters needed, we would only take the first 4
letters, and if it was shorter, we would fill it up with the alphabet in
order.

 With the keyword in a


matrix, we need to convert this into a key matrix. We do this by
converting each letter into a number by its position in the alphabet
(starting at 0). So, A = 0, B = 1, C= 2, D = 3, etc.
( The keyword written as a matrix.)
T

The key :- Hill)

 We now split the plaintext into digraphs, and write these as column
vectors. That is, in the first column vector we write the first plaintext
letter at the top, and the second letter at the bottom. Then we move to
the next column vector, where the third plaintext letter goes at the
top, and the fourth at the bottom. This continues for the whole
plaintext.
(The plaintext "short example" split into column vectors.)

 Now we must convert the plaintext column vectors in the same way
that we converted the keyword into the key matrix. Each letter is
replaced by its appropriate number.

(The plaintext converted into numeric column vectors)


 We multiply the key matrix by each column vector in turn. We write
the

key matrix first, followed by the column vector.

(The calculations performed when doing a matrix multiplication.)

( The shorthand for the matrix multiplication.)


 Next we have to take each of these numbers, in our resultant column
vector, modulo 26 (remember that means divide by 26 and take the
remainder).

 Finally we have to convert these numbers back to letters, so 0


becomes "A" and 15 becomes "P", and our first two letters of the
ciphertext are "AP".
 This gives us a final ciphertext of "APADJ TFTWLFJ".
Practical :- 4

AIM :- Write algorithm / steps for Play fair Cipher and solve examples
on it.

 The Playfair cipher encrypts pairs of letters (digraphs), instead of single letters
as is the case with simpler substitution ciphers such as the Caesar Cipher.
 Frequency analysis is still possible on the Playfair cipher, however it would be
against 600 possible pairs of letters instead of 26 different possible letters. For
this reason the Playfair cipher is much more secure than older substitution
ciphers.

 Encryption
 In order to encrypt using the Playfair Cipher, we must first draw up a Polybius
Square (5x5 Matrics but without the need for the number headings). This is
usually done using a keyword, and either combining "i" and "j" or omitting
"q" from the square.
 We must now split the plaintext up into digraphs (that is pairs of letters). On
each digraph we peform the following encryption steps:

1. If the digraph consists of the same letter twice (or there is only one letter
left by itself at the end of the plaintext) then insert the letter "X" between
the same letters (or at the end), and then continue with the rest of the steps.
2. If the two letters appear on the same row in the square, then replace each
letter by the letter immediately to the right of it in the square (cycling
round to the left hand side if necessary).
3. If the two letters appear in the same column in the square, then replace
each letter by the letter immediately below it in the square (cycling round
to the top of the square if necessary).
4. Otherwise, form the rectangle for which the two plaintext letters are two
opposite corners. Then replace each plaintext letter with the letter that
forms the other corner of the rectangle that lies on the same row as that
plaintext letter (being careful to maintain the order).
 Example:
Plaintext: hide the gold in the tree stump
Key: playfair example

 Encryption
 Firstly we must generate the Polybius Square that we are going to use. We do
this by setting out a 5x5 grid, and filling it with the alphabet, starting with the
letters of the key, and ignoring any letters we already have in the square. We
are also going to combine "I" and "J" in the square.
(The Mixed Square created for the Playfair Cipher, using the key: playfair
example)
 We must now split the plaintext into digraphs(Pairs). At this point it is a good
idea to apply Rule 1, and split up any double letter digraphs by inserting an
"x" between them.
 The first image below shows the initial digraph split of the plaintext, and the
second image displays how we split up the "ee" into "ex" and "es". In this case,
when we insert this extra "x", we no longer need to have one at the end of the
plaintext.

(The intial split into digraphs )

( The digraph split once we apply Rule 1, and remove any digraphs made from
two of the same letter.)
 We now take each digraph in turn and apply rule 2, 3 or 4 as necessary. Each
step is show below.
 We can now take each of the ciphertext digraphs that we produced and put
them all together.
 We can now write out the ciphertext as a long string
"BMODZBXDNABEKUDMUIXMMOUVIF" or split it into block of 5
"BMODZ BXDNA BEKUD MUIXM MOUVI F" or even give it the same
layout as the original "BMOD ZBX DNAB EK UDM UIXMM OUVIF"

Decryption:
 Decryption is nearly identical to the encryption process, except for rules 2 and
3 we must take the letters to the left and above respectively.
 Also, we remove any extra "X" in the decrypted text to reveal the final
plaintext.

 Ciphertext : UA ARBED EXAPO PR QNX AXANR


 Key : example

 We shall decipher the ciphertext "UA ARBED EXAPO PR QNX AXANR"


which has been encrypted using the keyword example. Firstly we must
generate the Polybius Square which we are using, as shown below.

 (The Mixed Square with keyword example)


 The next step is to split the ciphertext into digraphs. There is no need to add
any "X" in the decryption process as these will be revealed as we decrypt.

 (The ciphertext split into digraphs.)


 Now we apply the rules as needed to each digraph in the ciphertext.
 We now combine all the digraphs together.

(The plaintext digraphs.)

 So we get the message "we wilxl mexet at thex exit". When we remove the
unnecessary "x"s we get a final plaintext of "we will meet at the exit". Note
that we cannot just remove all the "x"s as one is part of the word "exit".
Practical :- 5

AIM :- Write algorithm / steps for Verman Cipher and solve examples
on it.

 The One-Time Pad (OTP) is the cryptographers dream.


 It is so special as a cipher because it offers perfect secrecy. That is, the
ciphertext offers no extra information to the cryptanalyst other than the
maximum possible length of the plaintext.
 The basic premise of the OTP is that the key is truly random.
 The other important aspect of the key is that it must be as long as the plaintext,
and not repeating.
 With a truly random keystream, you can then use the Tabula Recta to encrypt
the plaintext, just as with the Vigenere cipher.
 As an example, we shall encrypt the simple message "hello" using the random
keystream jqxyt.
 Cipher Text will be “QUIJH”

 To decrypt the message, with the key, we follow the same method as Vigenere
cipher.but,the strength is shown when we try to break it.
 We have numbers of Plaintext corresponding to different Keys but using
same Ciphertext .

Ciphertext Plaintext Key


"hello" Jqxyt
“QUIJH” "later" fupfq
"table" xuhyd

 The One-Time Pad is only perfectly secure providing certain criteria are met:
the keystream must be truly random; the keystream must never be reused; the
keystream must be at least as long as the plaintext; the keystream must be kept
secret. Unfortunately, some of these criteria cause logistal problems for the
use of the OTP.
 The keystream must never be reused (hence the name one-time) is easy
enough in theory, but in practical terms, it means that each time you want to
send a message you need a new truly random keystream.
 The keystream must be as long as the plaintext means that our key has to be
long. If we have a plaintext that is a page long, then we need a keystream of
random letters that is also a page long. This is near impossible to remember,
and so must be written down, which leads to our final problem.
Practical :- 6

AIM :- Write algorithm / steps for Vignere Cipher and solve examples
on it.

 One of the main problems with simple substitution ciphers is that they are so
vulnerable to frequency analysis.
 Given a sufficiently large ciphertext, it can easily be broken by mapping the
frequency of its letters to the know frequencies of, say, English text. Therefore,
to make ciphers more secure, cryptographers have long been interested in
developing enciphering techniques that are immune to frequency analysis.
 One of the most common approaches is to suppress the normal frequency data
by using more than one alphabet to encrypt the message.
 A polyalphabetic substitution cipher involves the use of two or more cipher
alphabets. Instead of there being a one-to-one relationship between each letter
and its substitute, there is a one-to-many relationship between each letter and
its substitutes.
 For Vigenere Cipher, we use Tabula Recta in which each row of the table
corresponds to a Caesar Cipher. The first row is a shift of 0; the second is a
shift of 1; and the last is a shift of 25.
 The Vigenere cipher uses this table together with a keyword to encipher a
message.
 Encryption
 To encrypt a message using the Vigenère Cipher you first need to choose a
keyword (or keyphrase). You then repeat this keyword over and over until it is
the same length as the plaintext. This is called the keystream.
 Now for each plaintext letter, you find the letter down the left hand side of the
tabula recta. You also take the corresponding letter from the keystream, and
find this across the top of the tabula recta. Where these two lines cross in the
table is the ciphertext letter you use.

 As an example, we shall encrypt the plaintext "a simple example" using the
keyword battista. First we must generate the keystream, by repeating the
letters of the keyword until it is the same length as the plaintext.

 Now we must use the tabula recta and the information in the table above. The
keystream b means we choose the column with B at the top, and the plaintext
"a" means we choose the row with A at the left. We get the ciphertext "B".
====
 For the second plaintext letter "s", we go down to S on the left, and use the keystream
a to go to A along the top. We get the ciphertext letter "S".
 With the plaintext letter "i", we go down to I on the left, and the keystream
letter t means we go to T across the top. We get the ciphertext letter "B".
 Continuing in this way we get the final ciphertext "BSBF XDXEYA FITW".
 Decryption
 To decrypt a ciphertext with the keyword, we first have to generate the
keystream by repeating the keyword until we have a keystream the same
length as the ciphertext. Then you find the column with the letter of the
keystream at the top, and go down this column until you find the ciphertext
letter. Now read across to the far left of the table to reveal the plaintext letter.

 As an example we shall decipher the ciphertext


"ZPSPNOXMOFAORMQDPUKZ" which has been encoded using the
keyword giovan. We start by generating the keystream.

 We look along the top row to find the letter from the keystream G. We look
down this column and find the ciphertext letter "Z". We then go along this
row to the left hand edge, and the letter here is the plaintext letter. In this
case it is "t".

 In the same way as above, we find the keystream letter I, and find the ciphertext
letter "P" in this column. We then follow this row to find the plaintext letter "h".

 Continuing in this way we retrieve the ciphertext "the unbreakable cipher".


Practical :- 7

AIM :- Draw diagram of Public Key Infrastructure.


Practical :- 8

AIM :- Demonstrate Cross-Scripting.

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in


Web applications. XSS enables attackers to inject client-side script into Web pages
viewed by other users. A cross-site scripting vulnerability may be used by attackers to
bypass access controls such as the same origin policy. Cross-site scripting carried out on
websites accounted for roughly 84% of all security vulnerabilities documented by
Symantec as of 2007.Their effect may range from a petty nuisance to a significant
security risk, depending on the sensitivity of the data handled by the vulnerable site and
the nature of any security mitigation implemented by the site's owner.

Identifying Cross-Site Scripting Vulnerabilities


XSS vulnerabilities may occur if:
 Input coming into Web applications is not validated
 Output to the browser is not HTML encoded
Introduction

In this article we will try to see what is Cross Site Scripting(XSS). We will try to see some
samples that are vulnerable to XSS and try to inject some scripts. We will then see how
we can prevent XSS attacks in an ASP.NET website.

Background

Cross Site scripting is one of the problem that has plagued a lot of websites. According to
WhiteHat Security Top Ten more than 50% of the websites are vulnerable to cross site
scripting. As a web developer, it is important to understand what is cross site scripting
and how can we safeguard our site from such attacks.

Cross site scripting is nothing but injection of client side scripts into a website. These
scripts can be HTML scripts or JavaScript scripts. Now the question would be how can a
person inject scripts on a running page. This can easily be done using all the various ways
a website is collecting inputs. Cross site scripting can be performed by passing scripts in
form of:

 TextBox (input controls)


 Query Strings
 Cookies
 Session variables
 Application variables
 Retrieved data from an external or shared source

Now let us see some very rudimentary example of cross site scripting and then we will try
to see what ASP.NET provides to prevent cross site scripting. We will also look at the
best practices that needs to be followed in order to make our website safe from cross site
scripting attacks.

Using the code

Now before writing applications that are vulnerable to cross site scripting we should
know that ASP.NET provides some security out of the box against such attacks i.e.
RequestValidations. This is a good thing for an ASP.NET developer. We will talk about it in
the later part of the article but for now lets us see how can we disable this
prevention mechanism.

Getting the Test Project Ready

The first thing that we need to do to disable the request validations is to set the
ValidateRequest property of the page directive to false. If we need to do this for the whole
website then we can do this from the web.config pages element.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default"
ValidateRequest="false" %>

Now in order for the above setting to work we also need to change the
requestValidationMode of the httpRuntime to 2.0. The request validation will only be turned off
when this mode is set to 2.0 otherwise it will not work.

<httpRuntime requestValidationMode="2.0"/>
Note: We are disabling the
request validation because we want to test the cross site scripting. without disabling it
wont be possible to see cross site scripting in action. It is not recommended to turn off
requestvalidation in production environment because this will open the website for cross site
scripting attacks.

Perform XSS using Query Strings

Now let us create a simple web form that will simply accept a query string from the user
and display the query string values on page.

The code behind for the page looks like: :-

protected void Page_Load(object sender, EventArgs e)


{
string id = Request.QueryString["id"] as string;

if (id == null)
{
Now under normal circumstances this will work just fine but if I try to pass some script in
the query string variable then we have a problem. Let me now pass the query string
parameter as:

Default.aspx?id=<h3>Hello from XSS"</h3>

and now when we open the page

And now we have a problem. The user can pass any HTML from the query string and that
HTML will be rendered on the page. This was a very basic example but imagine an
HTML with absolutely positioned tags and images could possibly wipe out the original
page and show something else entirely.

Same thing can happen with JavaScript too. I can inject any javascript into this page. Let
us try this:

Default.aspx?id=<script>alert('you have been hacked');</script>

and the output will be


Now we can go crazy and try to write this javascript to manipulate DOM objects in any
manner.

Perform XSS using Input fields

Let us now create a simple textbox to accept the user name and then display the user's
name on the page with some welcome message.

The code behind for the button click looks like:

protected void Button1_Click(object sender, EventArgs e)


{
lblMessage.Text = "Hello " + TextBox1.Text;
Now everything will work fine under normal input scenarios but as soon as we
try pausing some HTML and Javascript in the textbox, the problem will come in front of
us. Lets put an image on the page on top of everything else on page by using the
following input in the textbox:

<img src="dilbert-03.jpg" style="position:absolute;top:0;left:0;display:block"/>

So we saw how we can inject client side script easily in the pages using Cross site
scripting attacks. let us see what we need to do from an ASP.NET developer's
perspective(or as a web developer) to curb these attacks.

You might also like