Sunteți pe pagina 1din 74

CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 1
AIM:Implement a program which can decrypt the original message from the given cipher text without
knowing the key for Caesar cipher.For a generated cipher text of both the inputs, implement brute force attack
for Caesar cipher.

(i) Input- “CHARUSAT”

Key- 3

(ii) INPUT-“The vast majority of programmers do not work on operating systems There is so much software
around that no human can comprehend more than a tiny fraction of it. How come we can keep writing
software without getting hopelessly confused by its complexity How come the software written nowadays
does so much more than the software written 50 years ago There is an unlikely person who would know the
answer to that last question Isaac Newton He knew he saw far because he stood on the shoulders of giants He
may not know what software is But he would probably guess that todays software stands on the shoulders of
yesterdays software and thats how it does more In fact the whole edifice built by programmers looks like a
skyscraper reaching up at dizzying heights because it is carefully built layer upon layer”

KEY- 23

Theory :-

 Caesar Cipher
 The Caesar Cipher, also known as a shift cipher, is one of the oldest and simplest forms of
encrypting a message. It is a type of substitution cipher where each letter in the original message
(which in cryptography is called the plaintext) is replaced with a letter corresponding to a certain
number of letters shifted up or down in the alphabet.
 For each letter of the alphabet, you would take its position in the alphabet, say 3 for the letter 'C',
and shift it by the key number. If we had a key of +3, that 'C' would be shifted down to an 'F' -
and that same process would be applied to every letter in the plaintext.
 In this way, a message that initially was quite readable, ends up in a form that cannot be
understood at a simple glance.

1
CE348:INFORMATION SEQURITY 16CE068

 For example, here's the Caesar Cipher encryption of a full message, using a left shift of 3.

Plaintext:
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

Ciphertext:
QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD

 The Caesar Cipher can be expressed in a more mathematical form as follows:

 In plain terms, this means that the encryption of a letter x is equal to a shift of x + n, where n is
the number of letters shifted. The result of the process is then taken under modulo division,
essentially meaning that if a letter is shifted past the end of the alphabet, it wraps around to the
beginning.
 Decryption of the encrypted text (called the ciphertext) would be carried out similarly,
subtracting the shift amount.

 First used by Julius Caesar, the Caesar Cipher is one of the more well-known older historical
encryption methods. While you certainly wouldn't want to use it in today's modern world, a long
time ago it might have done the trick.
 As unreadable as the resulting ciphertext may appear, the Caesar Cipher is one of the weakest
forms of encryption one can employ for the following reasons:

 The key space is very small. Using a brute force attack method, one could easily try all
(25) possible combinations to decrypt the message without initially knowing the key.

 The structure of the original plaintext remains intact. This makes the encryption method
vulnerable to frequency analysis - by looking at how often certain characters or
sequences of characters appear, one can discover patterns and potentially discover the key
without having to perform a full brute forcesearch.

 Brute Force Attack For Caesar Cipher


 Brute force (also known as brute force cracking) is a trial and error method used by application
programs to decode encrypted data such as passwords or Data Encryption Standard (DES) keys,
through exhaustive effort (using brute force) rather than employing intellectual strategies. Just as
a criminal might break into, or "crack" a safe by trying many possible combinations, a brute
force cracking application proceeds through all possible combinations of legal characters in
sequence. Brute force is considered to be an infallible, although time-consuming, approach.
 Brute-force attack consists of an attacker trying many passwords or passphrases with the hope of
eventually guessing correctly. The attacker systematically checks all possible passwords and
passphrases until the correct one is found. Alternatively, the attacker can attempt to guess the key

2
CE348:INFORMATION SEQURITY 16CE068

which is typically created from the password using a key derivation function. This is known as
an exhaustive key search.
 A brute-force attack is a cryptanalytic attack that can, in theory, be used to attempt to decrypt
any encrypted data (except for data encrypted in an information-theoretically secure manner).
Such an attack might be used when it is not possible to take advantage of other weaknesses in an
encryption system (if any exist) that would make the task easier.

Code:

1)

#include <iostream>

#include<stdlib.h>

#include <stdio.h>

#include <string>

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 if(text[i]==' ')

result+=' ';

else if(text[i]=='.')

result+='.';

else if(text[i]==':')

result+=':';

else if(text[i]=='"')

result+='"';

else if(text[i]=='-')

3
CE348:INFORMATION SEQURITY 16CE068

result+='-';

else

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

return result;

int main()

int s; string text;

cout<<"enter text\n";

getline(cin, text);

fflush(stdin);

cout<<"enter key:";

cin>>s;

string cipher=encrypt(text, s);

cout << "\nHAVE Cipher: " << cipher;

cout<<"\n"; cout<<"\n"; cout<<"\n";

cout<<"\n";

return 0;

OUTPUT:

4
CE348:INFORMATION SEQURITY 16CE068

DECRYPT CODE:

#include <iostream>

#include<stdlib.h>

#include <stdio.h>

#include "string"

using namespace std;

bool CheckSubstring(std::string firstString, std::string secondString){

if(secondString.size() > firstString.size())

return false;

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

int j = 0;

// If the first characters match

if(firstString[i] == secondString[j]){

int k = i;

while (firstString[i] == secondString[j] && j < secondString.size()){

5
CE348:INFORMATION SEQURITY 16CE068

j++;

i++;

if (j == secondString.size())

return true;

else // Re-initialize i to its original value

i = k;

return false;

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 if(text[i]==' ')

result+=' ';

else if(text[i]=='.')

result+='.';

else if(text[i]==':')

result+=':';

else if(text[i]=='"')

result+='"';

else if(text[i]=='-')

result+='-';

else

6
CE348:INFORMATION SEQURITY 16CE068

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

return result;

int main()

int s;

string cipher;

cout<<"enter cipher text\n";

getline(cin, cipher);

fflush(stdin);

cout<<"\n";

cout<<"\n";

cout<<"\n";

cout<<"\n";

int a[26]={};

string intellegentdecision;

for(int i=25;i>=0;i--)

string guess=encrypt(cipher, i);

cout<<"key"<<25-i<<" :"<<guess<<"\n\n\n";

if(CheckSubstring(guess," or ")||CheckSubstring(guess," the ")||CheckSubstring(guess," in ")||


CheckSubstring(guess," is ")||CheckSubstring(guess," of ")||CheckSubstring(guess," on ")||
CheckSubstring(guess," am ")||CheckSubstring(guess," was ")||CheckSubstring(guess," were ")||
CheckSubstring(guess," under "))

7
CE348:INFORMATION SEQURITY 16CE068

a[i]++;

int max=0;

for(int j=0;j<26;j++)

if(a[j]>max)

max=a[j];

if(a[i]==max)

intellegentdecision=guess;

cout<<"\n";

cout<<"\n";

cout<<"\n";

cout<<"\n";

cout<<"INTELLEGENT DESISION:"<<intellegentdecision;

return 0;

OUTPUT:

8
CE348:INFORMATION SEQURITY 16CE068

9
CE348:INFORMATION SEQURITY 16CE068

Conclusion :By performing this practical, I learnt to Implement a program which can decrypt the
original message from the given cipher text without knowing the key for Caesar cipher
and Brute force attack for Caesar cipher.

10
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 2
AIM:Apply attacks for cryptanalysis to decrypt the original message from a given cipher text using Play fair
cipher. Key = charusat

Theory :-
 The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in
1854 by Charles Wheatstone, but was named after Lord Playfair who promoted the use of the
cipher. The technique encrypts pairs of letters (digraphs), instead of single letters as in the simple
substitution cipher. The Playfair is significantly harder to break since the frequency analysis used
for simple substitution ciphers does not work with it. Frequency analysis can still be undertaken,
but on the 25*25=625 possible digraphs rather than the 25 possible monographs. Frequency
analysis thus requires much more ciphertext in order to work.

 It was used for tactical purposes by British forces in the Second Boer War and in World War I and
for the same purpose by the Australians during World War II. This was because Playfair is
reasonably fast to use and requires no special equipment. A typical scenario for Playfair use would
be to protect important but non-critical secrets during actual combat. By the time the enemy
cryptanalysts could break the message the information was useless to them.

Plaintext digraphs are encrypted with the matrix by first locating the two plaintext letters in the
matrix. They are (1) in different rows and columns; (2) in the same row; (3) in the same column; or
(4) alike. The corresponding encryption (replacement) rules are the following:

 When the two letters are in different rows and columns, each is replaced by the letter that
is in the same row but in the other column; i.e., to encrypt WE, W is replaced by U and E
by G.
 When A and R are in the same row, A is encrypted as R and R (reading the row cyclically)
as M.
 When I and S are in the same column, I is encrypted as S and S as X.
 When a double letter occurs, a spurious symbol, say Q, is introduced so that the MM in
SUMMER is encrypted as NL for MQ and CL for ME.

11
CE348:INFORMATION SEQURITY 16CE068

 An X is appended to the end of the plaintext if necessary to give the plaintext an even
number of letters.
 Encrypting the familiar plaintext example using Sayers’s Playfair array yields:

Program:

import re

def generateTable(key=''):
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
table = [[0] * 5 for row in range(5)]
key=re.sub(r'[\WJ]', '', key.upper())
for row in range(5):
for col in range(5):
if len(key):
table[row][col] = key[0]
alphabet = alphabet.replace(key[0], '')
key = key.replace(key[0], '', -1)
else:
table[row][col] = alphabet[0]
alphabet = alphabet[1:]
return table

def position(table, ch):


for row in range(5):
for col in range(5):
if table[row][col] == ch:
return [row, col]
return [row, col]

def encrypt(key, words):


table = generateTable(key)

cipher = ''
words = re.sub(r'[\WJ]', '', words.upper())
text = ''

for i in range(0, len(words) - 1):


text += words[i]
if words[i] == words[i + 1]:
text += 'X'
print(words)

12
CE348:INFORMATION SEQURITY 16CE068

for i in range(0, len(text), 2):


digraphs = text[i:i + 2]
a, b = digraphs[0], 'X'
if len(digraphs) > 1:
b = digraphs[1]
a = position(table, a)
b = position(table, b)

if (a[0] == b[0]):
cipher += table[a[0]][(a[1] + 1)% 5] + table[b[0]][(b[1] + 1)% 5]
elif (a[1] == b[1]):
cipher += table[(a[0] + 1)% 5][a[1]] + table[(b[0] + 1)% 5][b[1]]
else:
cipher += table[a[0]][b[1]] + table[b[0]][a[1]]
return cipher;
def decrypt(key, text):
table = generateTable(key)
text = re.sub(r'[\WJ]', '', text.upper())
words = ''

for i in range(0, len(text), 2):


digraphs = text[i:i+2]
if len(digraphs) != 2:
print('cipher text is not right');
quit(-1)
a, b = digraphs[0], digraphs[1]
a = position(table, a)
b = position(table, b)

if (a[0] == b[0]):
words += table[a[0]][(a[1] - 1) % 5] + table[b[0]][(b[1] - 1) % 5]
elif (a[1] == b[1]):
words += table[(a[0] - 1) % 5][a[1]] + table[(b[0] - 1) % 5][b[1]]
else:
words += table[a[0]][b[1]] + table[b[0]][a[1]]
return words
print()
print(encrypt("playfairexample","spouralisnottechnicalfest"))

OUTPUT:

13
CE348:INFORMATION SEQURITY 16CE068

Conclusion :By performing this practical, we come to know about playfair cipher and implemented that
in code blocks.

PRACTICAL 3
Decrypt the original message from a chosen text using transposition cipher. Apply statistical attack, brute-force
attack or pattern attack for cryptanalysis.

**RAIL FENCE** code:

Theory :-
 Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar
Transposition Cipher
 The Columnar Transposition Cipher is a form of transposition cipher just like Rain Cipher.
Columnar Transposition involves writing the plaintext out in rows, and then reading the cipher
text off in columns one by one.

Encryption
 In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text.
 The message is written out in rows of a fixed length, and then read out again column by column,
and the columns are chosen in some scrambled order.
 Width of the rows and the permutation of the columns are usually defined by a keyword.
 For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is
defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3
1 2 4”.
 Any spare spaces are filled with nulls or left blank or placed by a character (Example: _).
 Finally, the message is read off in columns, in the order specified by the keyword.

14
CE348:INFORMATION SEQURITY 16CE068

def printFence(fence):
for rail in range(len(fence)):
print(''.join(fence[rail]))

def encryptFence(plain, rails, debug=False):


cipher = ''

length = len(plain)
fence = [['#'] * length for _ in range(rails)]

# build fence
rail = 0
for x in range(length):
fence[rail][x] = plain[x]
if rail >= rails - 1:
dr = -1
elif rail <= 0:
dr = 1
rail += dr

# print fence
if debug:
printFence(fence)

15
CE348:INFORMATION SEQURITY 16CE068

# read fence
for rail in range(rails):
for x in range(length):
if fence[rail][x] != '#':
cipher += fence[rail][x]
return cipher

def decryptFence(cipher, rails, debug=False):


plain = ''

length = len(cipher)
fence = [['#'] * length for _ in range(rails)]

# build fence
i=0
for rail in range(rails):
p = (rail != (rails - 1))
x = rail
while (x < length and i < length):
fence[rail][x] = cipher[i]
if p:
x += 2 * (rails - rail - 1)
else:
x += 2 * rail
if (rail != 0) and (rail != (rails - 1)):
p = not p
i += 1

print(fence)
if debug:
printFence(fence)

# read fence
for i in range(length):
for rail in range(rails):
if fence[rail][i] != '#':
plain += fence[rail][i]
return plain

plain = "HELLO WORLD"


print(plain)

cipher = encryptFence(plain, 3, debug=False)


print(cipher)

16
CE348:INFORMATION SEQURITY 16CE068

plaind = decryptFence(cipher, 3, debug=False)


print(plaind)

OUTPUT:

HELLO WORLD

HOREL OLLWD

[['H', '#', '#', '#', 'O', '#', '#', '#', 'R', '#', '#'], ['#', 'E', '#', 'L', '#', ' ', '#', 'O', '#', 'L', '#'], ['#', '#', 'L', '#', '#', '#', 'W', '#', '#',
'#', 'D']]

HELLO WORLD

**columnar cipher code:**

#include<iostream>

#include<cmath>

using namespace std;

string encryptColumnar(string s,int col)

string cipher="";

int r=ceil(s.length()/float(col));

char enc[r][col];

int k=0;

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

for(int j=0;j<col;j++)

enc[i][j]=s[k];

if(!isalpha(s[k]))

enc[i][j]=' ';

17
CE348:INFORMATION SEQURITY 16CE068

k++;

cout<<enc[i][j];

cout<<endl;

cout<<endl<<endl;

for(int j=0;j<col;j++)

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

cout<<enc[i][j];

cipher+=enc[i][j];

return cipher;

string decryptColumnar(string s,int col)

string plain;

int r=floor(s.length()/float(col));

char enc[r][col]={};

int k=0;

cout<<endl;

18
CE348:INFORMATION SEQURITY 16CE068

for(int j=0;j<col;j++)

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

enc[i][j]=s[k];

k++;

cout<<enc[i][j];

cout<<endl;

cout<<endl<<endl;

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

for(int j=0;j<col;j++)

cout<<enc[i][j];

plain+=enc[i][j];

return plain;

int main()

string s;

int col;

cout<<"Enter the string:"<<endl;

getline(cin,s);

19
CE348:INFORMATION SEQURITY 16CE068

cout<<"Enter the number of columns:"<<endl;

cin>>col;

string cipher=encryptColumnar(s,col);

decryptColumnar(cipher,col);

OUTPUT:

20
CE348:INFORMATION SEQURITY 16CE068

Conclusion :By performing this practical, I come to know about transposition cipher and also
implemented that in code blocks.

PRACTICAL 4

21
CE348:INFORMATION SEQURITY 16CE068

Aim: Implement RSA algorithm.

Theory :-
 RSA is one of the first practical public-key cryptosystems and is widely used for secure data
transmission. In such a cryptosystem, the encryption key is public and differs from
the decryption key which is kept secret. In RSA, this asymmetry is based on the practical
difficulty of factoring the product of two large prime numbers, the factoring problem. RSA is
made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman,
who first publicly described the algorithm in 1977.
 RSA is a relatively slow algorithm, and because of this it is less commonly used to directly
encrypt user data.
 The RSA algorithm involves four steps: key generation, key distribution, encryption and
decryption.
 Encryption: C = Me mod n
 Decryption: M = Cd mod n

 Key Generation:

1. Choose two distinct prime numbers p and q.


 For security purposes, the integers p and q should be chosen at random, and should be
similar in magnitude but differ in length by a few digits to make factoring harder. Prime
integers can be efficiently found using a primality test.
2. Compute n = pq.
 n is used as the modulus for both the public and private keys. Its length, usually
expressed in bits, is the key length.
3. Compute φ(n) = (p − 1, q − 1), where φ(n) is Euler totient function. This value is kept private.
4. Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e., e and φ(n) are coprime.
5. Determine d as d ≡ e−1 (mod φ(n)); i.e., d is the modular multiplicative
inverse of e (modulo φ(n)).

CODE:

#include<iostream>

#include<stdio.h>

#include<math.h>

#include<string>

#include <sstream>

using namespace std;

int mod(string num, int a)

22
CE348:INFORMATION SEQURITY 16CE068

// Initialize result

int res = 0;

// One by one process all digits of 'num'

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

res = (res*10 + (int)num[i] - '0') %a;

return res;

int gcd(int a, int h)

int temp;

while (1)

temp = a%h;

if (temp == 0)

return h;

a = h;

h = temp;

unsigned int aModM(string s, unsigned int mod)

23
CE348:INFORMATION SEQURITY 16CE068

unsigned int number = 0;

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

// (s[i]-'0') gives the digit value and form

// the number

number = (number*10 + (s[i] - '0'));

number %= mod;

return number;

// Returns find (a^b) % m

unsigned int ApowBmodM(string &a, unsigned int b,

unsigned int m)

// Find a%m

unsigned int ans = aModM(a, m);

unsigned int mul = ans;

// now multiply ans by b-1 times and take

// mod with m

for (unsigned int i=1; i<b; i++)

ans = (ans*mul) % m;

return ans;

string encrypt(long n,string message,long e)

24
CE348:INFORMATION SEQURITY 16CE068

string encrypted="";

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

string mystring;

stringstream mystream;

mystream << (long)pow(message[i],e)%n;

mystring = mystream.str();

encrypted=encrypted+mystring+",";

return encrypted;

string decrypt(long p,long q,int n,int e,string message)

long phi = (p-1)*(q-1);

long d=0;

while(true)

if((((long)(d*e))%phi)==1)

break;

d++;

string decryptedtext="";

std::string s = message;

25
CE348:INFORMATION SEQURITY 16CE068

std::string delimiter = ",";

size_t pos = 0;

std::string token;

while ((pos = s.find(delimiter)) != std::string::npos) {

token = s.substr(0, pos);

string mystring;

stringstream mystream;

mystream << ApowBmodM(token, d, n);

mystring = mystream.str();

decryptedtext=decryptedtext+mystring+",";

s.erase(0, pos + delimiter.length());

std::cout << s << std::endl;

return decryptedtext;

int main()

long p = 53;

long q = 59;

long n = p*q;

long e = 2;

long phi = (p-1)*(q-1);

while (e < phi)

26
CE348:INFORMATION SEQURITY 16CE068

// e must be co-prime to phi and

// smaller than phi.

if (gcd(e, phi)==1)

break;

else

e++;

string message;

cout<<"enter your message:";

cin>>message;

cout<<encrypt(n,message,e)<<"\n";

cout<<decrypt(p,q,n,e,encrypt(n,message,e));

OUTPUT:

Conclusion :In this practical we have learnt about an asymmetric key encryption algorithm named RSA
and its implementation.

PRACTICAL 5

27
CE348:INFORMATION SEQURITY 16CE068

Demonstrate how Diffie -Hellman key exchange works with Man-In-The-Middle attack.

Theory :-
 Diffie-Hellman is a way of generating a shared secret between two people in such a way that the
secret can't be seen by observing the communication. That's an important distinction: You're not
sharing information during the key exchange, you're creating a key together.

 This is particularly useful because you can use this technique to create an encryption key with
someone, and then start encrypting your traffic with that key. And even if the traffic is recorded
and later analyzed, there's absolutely no way to figure out what the key was, even though the
exchanges that created it may have been visible. This is where perfect forward secrecy comes
from. Nobody analyzing the traffic at a later date can break in because the key was never saved,
never transmitted, and never made visible anywhere.

 The way it works is reasonably simple. A lot of the math is the same as you see in public key
crypto in that a trapdoor function is used. And while the discrete logarithm problem is
traditionally used (the xy mod p business), the general process can be modified to use elliptic
curve cryptography as well.

 But even though it uses the same underlying principles as public key cryptography, this is not
asymmetric cryptography because nothing is ever encrypted or decrypted during the exchange. It
is, however, an essential building-block, and was in fact the base upon which asymmetric crypto
was later built.

 The basic idea works like this:


 I come up with two prime numbers g and p and tell you what they are.
 You then pick a secret number (a), but you don't tell anyone. Instead you
compute ga mod p and send that result back to me. (We'll call that A since it came from a).
 I do the same thing, but we'll call my secret number b and the computed number B. So I
compute gb mod p and send you the result (called "B")
 Now, you take the number I sent you and do the exact same operation with it. So
that's Ba modp.
 I do the same operation with the result you sent me, so: Ab mod p.

 The "magic" here is that the answer I get at step 5 is the same number you got at step 4. Now
it's not really magic, it's just math, and it comes down to a fancy property of modulo
exponents. Specifically:

(ga mod p)b mod p = gab mod p


(gb mod p)a mod p = gba mod p

 Which, if you examine closer, means that you'll get the same answer no matter which order
you do the exponentiation in. So I do it in one order, and you do it in the other. I never know
what secret number you used to get to the result and you never know what number I used, but
we still arrive at the same result.

28
CE348:INFORMATION SEQURITY 16CE068

 That result, that number we both stumbled upon in step 4 and 5, is our shared secret key. We
can use that as our password for AES or Blowfish, or any other algorithm that uses
sharedsecrets. And we can be certain that nobody else, nobody but us, knows the key that we
created together.

CODE:

#include<iostream>

#include<cmath>

#include<iostream>

#include<stdio.h>

#include<math.h>

#include<string>

#include <sstream>

using namespace std;

int mod(string num, int a)

// Initialize result

int res = 0;

// One by one process all digits of 'num'

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

res = (res*10 + (int)num[i] - '0') %a;

return res;

29
CE348:INFORMATION SEQURITY 16CE068

int gcd(int a, int h)

int temp;

while (1)

temp = a%h;

if (temp == 0)

return h;

a = h;

h = temp;

unsigned int aModM(string s, unsigned int mod)

unsigned int number = 0;

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

// (s[i]-'0') gives the digit value and form

// the number

number = (number*10 + (s[i] - '0'));

number %= mod;

return number;

// Returns find (a^b) % m

30
CE348:INFORMATION SEQURITY 16CE068

unsigned int ApowBmodM(string &a, unsigned int b,

unsigned int m)

// Find a%m

unsigned int ans = aModM(a, m);

unsigned int mul = ans;

// now multiply ans by b-1 times and take

// mod with m

for (unsigned int i=1; i<b; i++)

ans = (ans*mul) % m;

return ans;

int alicewillsend(int prime,int base,int secret)

stringstream ss;

ss << base;

string str = ss.str();

return(ApowBmodM(str,secret,prime));

31
CE348:INFORMATION SEQURITY 16CE068

//return(pow(str,secret)%prime);

int bobwillsend(int prime,int base,int secret)

stringstream ss;

ss << base;

string str = ss.str();

return(ApowBmodM(str,secret,prime));

//return(pow(base,secret)%prime);

int alicewilldecrypt(int prime,int received,int alicesecret)

stringstream ss;

ss << received;

string str = ss.str();

return(ApowBmodM(str,alicesecret,prime));

//return(pow(received,alicesecret)%prime);

int bobwilldecrypt(int prime,int received,int bobsecret)

stringstream ss;

ss << received;

string str = ss.str();

return(ApowBmodM(str,bobsecret,prime));

//return(pow(received,bobsecret)%prime);

32
CE348:INFORMATION SEQURITY 16CE068

int main()

int prime=71;

int base=5;

int bobsecret=15;

int alicesecret=6;

cout<<"alice secret key:"<<bobwilldecrypt(prime,alicewillsend(prime,base,alicesecret),bobsecret);

cout<<endl;

cout<<"bob secret key:"<<alicewilldecrypt(prime,bobwillsend(prime,base,bobsecret),alicesecret);

cout<<endl;

OUTPUT:

Conclusion :By performing this practical, I learnt how to generate secrete key and private key using
that how to apply cryptography on data.

PRACTICAL 6

33
CE348:INFORMATION SEQURITY 16CE068

Aim: Implement BlowFish Algorithm.

Theory :-
The Blowfish algorithm
 Blowfish is a symmetric encryption algorithm, meaning that it uses the same secret key to both
encrypt and decrypt messages. Blowfish is also a block cipher, meaning that it divides a message
up into fixed length blocks during encryption and decryption. The block length for Blowfish is
64 bits; messages that aren't a multiple of eight bytes in size must be padded.

 Blowfish requires about 5KB of memory. A careful implementation on a 32-bit processor can
encrypt or decrypt a 64-bit message in approximately 12 clock cycles. (Not-so-careful
implementations, like Kocher, don't increase that time by much.) Longer messages increase
computation time in a linear fashion; for example, a 128-bit message takes about (2 x 12) clocks.
Blowfish works with keys up to 448 bits in length.

Figure 1: Blowfish algorithm

34
CE348:INFORMATION SEQURITY 16CE068

 A graphical representation of the Blowfish algorithm appears in Figure 1. In this description, a


64-bit plaintext message is first divided into 32 bits. The "left" 32 bits are XORed with the first
element of a P-array to create a value I'll call P', run through a transformation function called F,
then XORed with the "right" 32 bits of the message to produce a new value I'll call F'. F' then
replaces the "left" half of the message and P' replaces the "right" half, and the process is repeated
15 more times with successive members of the P-array. The resulting P' and F' are then XORed
with the last two entries in the P-array (entries 17 and 18), and recombined to produce the 64-bit
ciphertext.

Figure 2: Graphic representation of F


 A graphical representation of F appears in Figure 2. The function divides a 32-bit input into four
bytes and uses those as indices into an S-array. The lookup results are then added and XORed
together to produce the output.

 Because Blowfish is a symmetric algorithm, the same procedure is used for decryption as well as
encryption. The only difference is that the input to the encryption is plaintext; for decryption, the
input is ciphertext.

 The P-array and S-array values used by Blowfish are precomputed based on the user's key. In
effect, the user's key is transformed into the P-array and S-array; the key itself may be discarded
after the transformation. The P-array and S-array need not be recomputed (as long as the key
doesn't change), but must remain secret.

 I'll refer you to the source code for computing the P and S arrays and only briefly summarize the
procedure as follows:

 P is an array of eighteen 32-bit integers.


 S is a two-dimensional array of 32-bit integer of dimension 4x256.

35
CE348:INFORMATION SEQURITY 16CE068

 Both arrays are initialized with constants, which happen to be the hexadecimal digits of
π (a pretty decent random number source).
 The key is divided up into 32-bit blocks and XORed with the initial elements of the P
and S arrays. The results are written back into the array.
 A message of all zeros is encrypted; the results of the encryption are written back to the
P and S arrays. The P and S arrays are now ready for use.

Code:

import blowfish
from os import urandom
key=b"jainilpatel"
print("KEY text value is:",end="")
print(key)
cipher = blowfish.Cipher(key)
print("p value is:",end="")
print(cipher.P)
print("s value is:",end="")
print(cipher.S)
block = b'himyname'
print("plain text value is:",end="")
print(block)
ciphertext = cipher.encrypt_block(block)
print("cipher text value is:",end="")
print(ciphertext)
plaintext = cipher.decrypt_block(ciphertext)
print("decrypted plain text value is:",end="")
print(plaintext)

OUTPUT:

Conclusion :By performing this practical, I come to know about blowfish algorithm.

36
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 7
Aim :- Demonstrate DNS based phishing attack.
Software Requirement :- N/A
Hardware Requirement :- N/A
Theory :-
Phishing attack
 Phishing is a type of social engineering attack often used to steal user data, including login
credentials and credit card numbers. It occurs when an attacker, masquerading as a trusted entity,
dupes a victim into opening an email, instant message, or text message. The recipient is then
tricked into clicking a malicious link, which can lead to the installation of malware, the freezing
of the system as part of a ransomware attack or the revealing of sensitive information.
 An attack can have devastating results. For individuals, this includes unauthorized purchases, the
stealing of funds, or identify theft.
 Moreover, phishing is often used to gain a foothold in corporate or governmental networks as a
part of a larger attack, such as an advanced persistent threat (APT) event. In this latter scenario,
employees are compromised in order to bypass security perimeters, distribute malware inside a
closed environment, or gain privileged access to secured data.
 An organization succumbing to such an attack typically sustains severe financial losses in
addition to declining market share, reputation, and consumer trust. Depending on scope, a
phishing attempt might escalate into a security incident from which a business will have a
difficult time recovering.

DNS based Phishing attack (“Pharming”)

Pharming is the term given to hosts file modification or Domain Name System (DNS)-
based phishing. With a pharming scheme, hackers tamper with a company's hosts files or
domain name system so that requests for URLs or name service return a bogus address
and subsequent communications are directed to a fake site. The result: users are unaware
that the website where they are entering confidential information is controlled by hackers
and is probably not even in the same country as the legitimate website.

37
CE348:INFORMATION SEQURITY 16CE068

Steps to perform DNS based Phishing attack :

1. Find the IP Address of the website to which you want to redirect the user.
In this case it is yahoo.com

2. Navigate to C:\Windows\System32\drivers\etc and open hosts file in any of the


text editor. The hosts file will look like

38
CE348:INFORMATION SEQURITY 16CE068

3. Type the IP address of the website you want the user to redirect to followed by the
URL which user originally wants to visit

4. After editing the host file we have successfully performed phishing attack. If we
now try to access www.google.com we will be redirected to yahoo.com

Conclusion: Thus we have studied and performed phishing attack by changing the hosts
file and redirected the user to another website which he was not intended to.

39
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 8
Aim :- Identify Web Application vulnerabilities that leads to SQL injection attack and
also find out precautions to be taken by web designers.
Software Requirement :- N/A
Hardware Requirement :- N/A
Theory :-
What Is an SQL Injection Attack?
 SQL injection (SQLi) is an injection attack where an attacker executes malicious SQL statements
to control a web application's database server, thereby accessing, modifying, and deleting
unauthorized data.
 In the early days of the Internet, building websites was a simple process: no JavaScript, no CSS,
and few images. But as the websites gained popularity, the need for more advanced technology
and dynamic websites grew. This led to the development of server-side scripting languages like
JSP and PHP. Websites started storing user input and content in databases. MySQL became the
most popular and standardized language for accessing and manipulating databases. However,
hackers found new ways to leverage the loopholes present in SQL technology. SQL injection
attacks are one of the most popular ways of targeting databases. SQL injections target the
databases using specifically-crafted SQL statements to trick the systems into doing unexpected
and undesired things.

What Can SQL Injection Attacks Do?


 There are a lot of things an attacker can do when exploiting an SQL injection on a vulnerable
website. By leveraging an SQL injection vulnerability, given the right circumstances, an attacker
can do the following things:
 Bypass a web application's authorization mechanisms and extract sensitive information
 Easily control application behavior that's based on data in the database
 Inject further malicious code to be executed when users access the application
 Add, modify, and delete data, corrupting the database, and making the application or
unusable
 Enumerate the authentication details of a user registered on a website and use the data in
attacks on other sites
 It all depends on the capability of the attacker, but sometimes, an SQL injection attack can lead
to a complete takeover of the database and web application. Now, how does an attacker achieve
that?

40
CE348:INFORMATION SEQURITY 16CE068

How Do SQL Injection Attacks Work?


 A developer usually defines an SQL query to perform some database action necessary for his
application to function. This query has one or two arguments so that only desired records are
returned when the value for that argument is provided by a user.
 An SQL injection attack plays out in two stages:
1. Research: Attacker gives some random unexpected values for the argument, observes how
the application responds, and decides an attack to attempt.
2. Attack: Here, the attacker provides carefully-crafted value for the argument. The
application will interpret the value part of an SQL command rather than merely data. The
database then executes the SQL command as modified by the attacker.
 Consider the following example in which a website user is able to change the values of $user and
$password, such as in a login form:

$statement = "SELECT * FROM users WHERE username ='$user' AND password


'$password'";

This particular SQL statement is passed to a function, which, in turn, sends the string to the
connected database where it is parsed, executed, and returns a result.

#Define POST variables


uname = request.POST['username']
passwd = request.POST['password']
#SQL query vulnerable to SQLi
sql = "SELECT id FROM users WHERE username='" + uname + "' AND password='" + passwd
+ "'"
#Execute the SQL statement
database.execute(sql)

 Now, if the input is not properly sanitized but the application, the attacker can easily insert
carefully crafted value as input. For example, this will look something like:

41
CE348:INFORMATION SEQURITY 16CE068

$statement = "SELECT * FROM users WHERE username ='Dean' OR '1'='1'-- ' AND password
= 'WinchesterS'";

 So, what's happening here? The highlighted part is the attacker's input, it contains two special
parts:
 OR '1' = '1' is a condition that will always be true, thereby it is accepted as a valid input
by the application
 -(double hyphen) instructs the SQL parser that the rest of the line is a comment and
should not be executed
 Once the query executes, the SQL injection effectively removes the password verification,
resulting in an authentication bypass. The application will most likely log the attacker in with the
first account from the query result - the first account in a database is usually of an administrative
user.
Note that this is just one way of exploiting the SQL Queries to get the necessary information in an
unofficial way. SQL injection attacks are divided into multiple types.

What Are the Different Types of SQL Injection Attacks?


Attackers can extract data from servers by leveraging an SQL injection vulnerability in various ways.
SQL injection can be classified into three major categories:
Let's explore the variants.
 In-Band SQL Injection
It is the most common SQL injection attack. Usually, it occurs when an attacker is able to use the
same communication channel to both launch the attack and gather results. The two most common
types of in-band SQL injection are:
 Error-based SQL Injection — It is a technique that relies on error messages thrown by the
database server to obtain information about the structure of the database. Sometimes, this
simple attack is more than enough for an attacker to enumerate an entire database.
 Union-based SQL Injection — This technique leverages the UNION SQL operator to
combine the results of two or more SELECT statements into a single result, which is then
returned as part of the HTTP response.
In this type of injection, no data is actually transferred via the web application. So, the attacker
will not be able to see the result of an attack. Here, the attacker reconstructs the database
structure by sending payloads and observing the web application's response and the resulting
behavior of the database server. The two types of inferential SQL injection are:
 Boolean-based SQL Injection — In this technique application is forced to return a different
result depending on whether the query returns a TRUE or FALSE result. Based on the
result, the content within the HTTP response will change, or remain the same.
 Time-based SQL Injection — It is a technique that relies on sending an SQL query to the
database, which forces the database to wait for a specified amount of time (in seconds)
before responding. The time website takes to respond will indicate to the attacker whether
the result of the query is TRUE or FALSE.

 Out-of-Band SQL Injection


These types of SQL injection attacks are the least common and generally the most difficult to
execute. They usually involve sending the data directly from the database server to a machine

42
CE348:INFORMATION SEQURITY 16CE068

that is controlled by the attacker. Out-of-band techniques offer the attacker an alternative to In-
band or Blind SQL injection attacks, especially if the server responses are not very stable.

So, server-scripting languages are not able to determine if or not the SQL query string is
malformed. All that they can do is send a string to the database server and wait for the interpreted
response. But surely, there must be ways to sanitize user input and ensure that an SQL injection
is infeasible, right?

How Can SQL Injection Attacks Be Prevented?


There are a lot of easy ways to avoid falling prey for SQL injection attacks and to limit the damage they
can cause. Few of them include:
 Discover SQL injection vulnerabilities by routinely testing applications both using static
testing and dynamic testing
 Avoid and repair injection vulnerabilities by using parameterized queries and Object Relational
Mappers (ORMs). These types of queries specify placeholders for parameters so that the
database will always treat them as data rather than part of a SQL command.
 Remediate SQL injection vulnerabilities by using escape characters so that special characters are
ignored.
 Mitigate the impact of SQL injection vulnerabilities by enforcing least privilege on the database,
this way each software component of an application can access and affect only the resources it
needs.
 Use a Web Application Firewall (WAF) for web applications that access databases. This can
help identify SQL injection attempts and sometimes help prevent SQL injection attempts from
reaching the application as well.

SQL injection attacks are popular attack methods for cybercriminals, but by taking the proper
precautions, such as ensuring that data is encrypted, performing security tests, and being up to date with
patches, you can take meaningful steps toward keeping your data secure.

Conclusion :By performing this practical, I come to know about SQL injection attack and how to
prevent that.

43
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 9
Aim :- Retrieve Database Schema and data using HAVIJ.
Software Requirement :- Havij
Hardware Requirement :- N/A
Theory :-
What is Havij?
 Havij is an automated SQL Injection tool that helps penetration testers to find and exploit SQL
Injection vulnerabilities on a web page.
 It can take advantage of a vulnerable web application. By using this software user can perform
back-end database fingerprint, retrieve DBMS users and password hashes, dump tables and
columns, fetching data from the database, running SQL statements and even accessing the
underlying file system and executing commands on the operating system.
 The power of Havij that makes it different from similar tools is its injection methods. The
success rate is more than 95% at injecting vulnerable targets using Havij.

Practical:
Steps to Install Havij :

Step-1:
Go to https://www.darknet.org.uk/2010/09/havij-advanced-automated-sql-injection-tool/ and download
havij.

44
CE348:INFORMATION SEQURITY 16CE068

Step-2:

Step-3:

45
CE348:INFORMATION SEQURITY 16CE068

Step-4:

Step-5:

46
CE348:INFORMATION SEQURITY 16CE068

Step-6 :

47
CE348:INFORMATION SEQURITY 16CE068

How to retrieve data using havij


Step-1: Enter website you want to retrieve data in target

Step-2: In info section you get the information of the website

Step-3: In table Section you get the database of the website.

48
CE348:INFORMATION SEQURITY 16CE068

We also get tables by clicking get tables in table tab and then we can get table and columns and other
data by clicking further.

49
CE348:INFORMATION SEQURITY 16CE068

Step-4: Insert Query into Query section

50
CE348:INFORMATION SEQURITY 16CE068

Step-5:

How to Crack Hash?

As You Can See, We Have Received All Information Of Admin. Like Username,Password And
UserGroup. But We Have Received Password In The Shape Of Hash. In Order To See The Real
Password. We Have To Crack This Code. For Cracking This Code. We Will Make Use Of Havij Tool
Again. Follow Me To Crack This Hash.

 You Can See A Button Of MD5 In Buttons List Of Havij. Hit That Button And Paste Your Hash
Code Inside It And Press Start Button.

 You Can See Password In Plain Text In Result Now. See Picture Below.

51
CE348:INFORMATION SEQURITY 16CE068

Step-6:
Find Admin Page

We Have Got Everything. Like Username, Password. But Where To Use Them And Get Admin Rights?
You Need To Find The Admin Login Page Of Target Site. For Finding Admin Page of Target Site. We
Will Use Havij Again.

 In Buttons List, Press Find AdminButton. Type Homepage Url Of Target Site. Press Start
Button.

You will get result same like hash cracking.


You will be able to see the page which Admin of your target site use to Login.

Conclusion :By performing this practical, i retrieved database schema using Havij and concept of SQL
injection attack.

52
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL 10
Aim :- How Identity based Encryption is used to prove authentication?
Software Requirement :- N/A
Hardware Requirement :- N/A
Theory :-
ID-based encryption, or identity-based encryption (IBE), is an important primitive of ID-based
cryptography. As such it is a type of public-key encryption in which the public key of a user is some
unique information about the identity of the user (e.g. a user's email address). This means that a
sender who has access to the public parameters of the system can encrypt a message using e.g. the
text-value of the receiver's name or email address as a key. The receiver obtains its decryption key
from a central authority, which needs to be trusted as it generates secret keys for every user.

Technical Summary
 In 1984 Shamir asked for a public key encryption scheme in which the public key can be an
arbitrary string. Encryption schemes of this type are called Identity Based Encryption (IBE).
Shamir's original motivation for identity-based encryption was to simplify certificate
management in e-mail systems. When Alice sends mail to Bob at bob@hotmail.com she simply
encrypts her message using the public key string ``bob@hotmail.com''. There is no need for
Alice to obtain Bob's public key certificate. When Bob receives the encrypted mail he contacts a

53
CE348:INFORMATION SEQURITY 16CE068

third party, which we call the Private Key Generator (PKG). Bob authenticates himself to the
PKG in the same way he would authenticate himself to a CA and obtains his private key from the
PKG. Bob can then read his e-mail. Note that unlike the existing secure e-mail infrastructure,
Alice can send encrypted mail to Bob even if Bob has not yet setup his public key certificate.
However, in this scenario the IBE system provides key escrow since the PKG knows Bob's
private key. Other applications (discussed below) do not require key escrow. In more detail, an
IBE scheme consists of four algorithms: (1) Setup generates global system parameters and a
master-key, (2) Extract uses the master-key to generate the private key corresponding to an
arbitrary public key string ID, (3) Encrypt encrypts messages using the public key ID, and (4)
Decrypt decrypts messages using the corresponding private key.

 Since the problem was posed in 1984 there have been several proposals for IBE schemes.
However, none of these are fully satisfactory. Some solutions require that users not collude.
Other solutions require the PKG to spend a long time for each private key generation request.
Some solutions require tamper resistant hardware. It is fair to say that, until now, constructing a
usable IBE system was an open problem.

 The IBE email system uses a new fully functional identity-based encryption scheme. The
performance of the cryptosystem is comparable to the performance of ElGamal encryption. The
security of the system is based on a natural analogue of the computational Diffie-Hellman
assumption on elliptic curves. Based on this assumption we show that the new system has chosen
ciphertext security in the random oracle model.

How IBE Works


 The success of IBE depends upon the third-party IBE server that generates private keys. The
only information this server stores permanently is a secret master key -- a large random number
that is exclusive to the security domain. The server uses this key to create a common set of
public-key parameters (including the server's address) that are given to each user who installs the
IBE software, and recipients' private keys as required.

 When a sender creates an encrypted message, the IBE software on his system uses three
parameters to generate the public key for the message: a starting value, the current week number
and the recipient's identity (normally the e-mail address). Because a calendar reference is
included, the public key that is generated will automatically expire.

 A user who receives an IBE-encrypted e-mail message but has not used the process before can
request -- upon authentication -- a private key that allows him to decrypt all e-mails encrypted
using his e-mail address as the public key.

Pros
 No certificates needed. A recipient's public key is derived from his identity.
 No pre-enrollment required.
 Keys expire, so they don't need to be revoked. In a traditional public-key system, keys must be
revoked if compromised.

54
CE348:INFORMATION SEQURITY 16CE068

 Less vulnerable to spam.


 Enables postdating of messages for future decryption.
 Enables automatic expiration, rendering messages unreadable after a certain date.
Cons
 Requires a centralized server. IBE's centralized approach implies that some keys must be created
and held in escrow -- and are therefore at greater risk of disclosure.
 Requires a secure channel between a sender or recipient and the IBE server for transmitting the
private key.

Conclusion : By performing this practical, I learnt how identity based encryption is used to generate a
public key that can be used for encrypting and decrypting electronic messages.

55
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL-11
AIM: How Identity based Encryption is used to prove authentication?
SOFTWARE REQUIRED: N/A

HARDWARE REQUIRED: N/A

THEORY:

ID-based encryption, or identity-based encryption (IBE), is an important primitive of ID-based


cryptography. As such it is a type of public-key encryption in which the public key of a user is
some unique information about the identity of the user (e.g. a user's email address). This
means that a sender who has access to the public parameters of the system can encrypt a
message using e.g. the text-value of the receiver's name or email address as a key. The receiver
obtains its decryption key from a central authority, which needs to be trusted as it generates
secret keys for every user.

Technical Summary

56
CE348:INFORMATION SEQURITY 16CE068

In 1984 Shamir asked for a public key encryption scheme in which the public key can be an
arbitrary string. Encryption schemes of this type are called Identity Based Encryption (IBE).
Shamir's original motivation for identity-based encryption was to simplify certificate
management in e-mail systems. When Alice sends mail to Bob at bob@hotmail.com she
simply encrypts her message using the public key string “bob@hotmail.com”. There is no
need for Alice to obtain Bob's public key certificate. When Bob receives the encrypted mail he
contacts a third party, which we call the Private Key Generator (PKG). Bob authenticates
himself to the PKG in the same way he would authenticate himself to a CA and obtains his
private key from the PKG. Bob can then read his e-mail. Note that unlike the existing secure e-
mail infrastructure, Alice can send encrypted mail to Bob even if Bob has not yet setup his
public key certificate. However, in this scenario the IBE system provides key escrow since the
PKG knows Bob's private key. Other applications (discussed below) do not require key
escrow. In more detail, an IBE scheme consists of four algorithms: (1) Setup generates global
system parameters and a master-key, (2) Extract uses the master-key to generate the private
key corresponding to an arbitrary public key string ID, (3) Encrypt encrypts messages using
the public key ID, and (4) Decrypt decrypts messages using the corresponding private key.

Since the problem was posed in 1984 there have been several proposals for IBE schemes.
However, none of these are fully satisfactory. Some solutions require that users not collude.
Other solutions require the PKG to spend a long time for each private key generation request.
Some solutions require tamper resistant hardware. It is fair to say that, until now, constructing
a usable IBE system was an open problem.

The IBE email system uses a new fully functional identity-based encryption scheme. The
performance of the cryptosystem is comparable to the performance of ElGamal encryption.
The security of the system is based on a natural analogue of the computational Diffie-Hellman
assumption on elliptic curves. Based on this assumption we show that the new system has
chosen ciphertext security in the random oracle model.

HOW IBE WORKS

The success of IBE depends upon the third-party IBE server that generates private keys. The
only information this server stores permanently is a secret master key -- a large random
number that is exclusive to the security domain. The server uses this key to create a common
set of public-key parameters (including the server's address) that are given to each user who
installs the IBE software, and recipients' private keys as required.

When a sender creates an encrypted message, the IBE software on his system uses three
parameters to generate the public key for the message: a starting value, the current week
57
CE348:INFORMATION SEQURITY 16CE068

number and the recipient's identity (normally the e-mail address). Because a calendar
reference is included, the public key that is generated will automatically expire.
A user who receives an IBE-encrypted e-mail message but has not used the process before can
request -- upon authentication -- a private key that allows him to decrypt all e-mails encrypted
using his e-mail address as the public key.

PROS
 No certificates needed. A recipient's public key is derived from his identity.
 No pre-enrollment required.
 Keys expire, so they don't need to be revoked. In a traditional public-key system, keys
must be revoked if compromised.
 Less vulnerable to spam.
 Enables postdating of messages for future decryption.
 Enables automatic expiration, rendering messages unreadable after a certain date.

CONS
 Requires a centralized server. IBE's centralized approach implies that some keys must be
created and held in escrow -- and are therefore at greater risk of disclosure.
 Requires a secure channel between a sender or recipient and the IBE server for
transmitting the private key.

CONCLUSION:
Thus, we learnt how Identity based Encryption is used to prove authentication

58
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL-12
AIM: Explore the types of HOMOMORPHIC Encryption Techniques and compare them.
SOFTWARE REQUIRED: N/A

HARDWARE REQUIRED: N/A

THEORY:

During the last few years, homomorphic encryption schemes have been studied extensively
since they have become more and more important in many different cryptographic protocols
such as, e.g., voting protocols. In this Section, we introduce homomorphic cryptosystems in
three steps: what, howand why that reflects the main aspects of this interesting encryption
technique. We start by defining homomorphic cryptosystems and algebraically homomorphic
cryptosystems. Then we develop a method to construct algebraically homomorphic schemes
given special homomorphic schemes. Finally, we describe applications of homomorphic
schemes.\

DEFINITION:

Let the message space (M, o) be a finite (semi-)group, and let σ be the security parameter. A
homomorphic public-key encryption scheme (or homomorphic cryptosystem) on M is a
quadruple (K, E, D, A) of probabilistic, expected polynomial
time algorithms, satisfying the following functionalities:
 Key Generation: On input 1σ the algorithm K outputs an encryption/decryption key pair
(ke, kd)=k∈K,ke, kd=k∈K, where KK denotes the key space.
 Encryption: On inputs 1σ, ke, and an element m ∈M m ∈M the encryption algorithm E
outputs a ciphertext c ∈C , c ∈C , where CC denotes the ciphertext space.
 Decryption: The decryption algorithm D is deterministic. On inputs 1σ, k, and an element
c ∈C c ∈C it outputs an element in the message space M so that for all m ∈M it holds:
m ∈M it holds: if c=E(11σ,ke, m)c=E11σ,ke, m then

59
CE348:INFORMATION SEQURITY 16CE068

Prob[D(1σ,k,c)≠m]Prob[D(1σ,k,c)≠m] is negligible, i.e., it holds that


Prob[D(1σ,k,c)≠m]≤ 2−σProbD1σ,k,c≠m≤ 2-σ.
 Homomorphic Property: A is an algorithm that on inputs 1σ, ke 1σ, ke , and elements c1,
c2 ∈C c1, c2 ∈C outputs an element c3 ∈Cc3 ∈C so that for all m1, m2 ∈M m1, m2
∈M it holds: if m3=m1 o m2m3=m1 o m2 and c1=E(1σ,ke, m1)c1=E1σ,ke, m1, and
c2=E(1σ, ke, m2)c2=E1σ, ke, m2, then Prob[D(A(1σ, ke, c1, c2))]≠ m3]ProbDA1σ, ke,
c1, c2≠ m3] is negligible.

TYPES OF HOMOMORPHIC ENCRYPTION TECHNIQUES:

1. Goldwasser-Micali scheme: This scheme is historically very important since many of


subsequent proposals on homomorphic encryption were largely motivated by its approach.
 Like in RSA, in this scheme, we use computations modulo n = p.q, a product of two large
primes. The encryption process is simple which uses a product and a square, whereas
decryption is heavier and involves exponentiation.
 The complexity of the decryption process is: O(k.l(p)2)O(k.lp2), where l(p)l(p) denotes
the number of bits in p.
 Unfortunately, this scheme has a limitation since its input consists of a single bit.
 First, this implies that encrypting k bits leads to a cost of O(k.l(p)2)O(k.l(p)2). This is not
very efficient even if it may be considered as practical.
 The second concern is related to the issue of expansion – a single bit of plaintext is
encrypted in an integer modulo n, that is, l(n)l(n) bits. This leads to a huge blow up of
ciphertext causing a serious problem with this scheme.

2. Benaloh’s scheme: Benaloh is a generalization of GM scheme that enables one to


manage inputs of l(k)l(k) bits, k being a prime satisfying some specified constraints.
 Encryption is similar as in GM scheme (encrypting a message m ∈{0,….,k−1}m ∈{0,
….,k-1} is tantamount to picking an integer r ∈ Z*nr ∈ Zn* and computing c= gmrk
mod n)c= gmrk mod n.
 However, the decryption phase is more complex. If the input and output sizes are l(k)l(k)
and l(n)l(n) bits respectively, the expansion is equal to l(n)/l(k)l(n)/l(k).

60
CE348:INFORMATION SEQURITY 16CE068

 The value of expansion obtained in this approach is less than that achieved in GM. This
makes the scheme more attractive.
 Moreover, the encryption is not too expensive as well. The overhead in the decryption
process is estimated to be O(k−−√.l(k))O(k.l(k)) for pre-computation which remains
constant for each dynamic decryption step.
 This implies that the value of k has to be taken very small, which in turn limits the gain
obtained on the value of expansion.

3. Paillier Scheme: One of the most well-known homomorphic encryption schemes is due
to Paillier. It is an improvement over the earlier schemes in the sense that it can decrease the
value of expansion from 3 to 2.
 The scheme uses n=p.qn=p.q with gcd(n, ϕ(n))=1 gcdn, ϕn=1. As usual p and q are
two large primes. However,
 it considered the group G= Z*n2G= Zn2* and a proper choice of H led to
k=l(n)k=l(n). While the cost of encryption is not too high, decryption needs one
exponentiation modulo n2n2 to the power λ(n)λ(n), and a multiplication modulo n.
 This makes decryption a bit heavyweight process. The author has shown how to
manage decryption efficiently using the famous Chinese Remainder Theorem.
 With smaller expansion and lower cost compared with the other schemes, this scheme
found great acceptance. In 2002, Cramer and Shoup proposed a general approach to
achieve higher security against adaptive chosen-ciphertext attacks for certain
cryptosystems with some particular algebraic properties .
 They applied their propositions on Paillier’s original scheme and designed a stronger
variant of homomorphic encryption. Bresson et al. proposed a slightly different
version of a homomorphic encryption scheme that is more accurate for some
applications.

4. Galbraith Scheme: This is an adaptation of the existing homomorphic encryption


schemes in the context of elliptic curves.
 Its expansion is equal to 3. For s=1s=1, the ratio of the encryption cost for this scheme
over that of Paillier’s scheme can be estimated to be about 7, while the same ratio for
the cost of decryption cost is about 14 for the same value of s.
61
CE348:INFORMATION SEQURITY 16CE068

 However, the most important advantage of this scheme is that the cost of encryption
and decryption can be decreased using larger values of s.
 In addition, the security of the scheme increases with the increase in the value of s as
it is the case in Damgard-Jurik’s scheme.

APPLICATIONS:

 In election schemes, the homomorphic property provides a tool to obtain the tally
given the encrypted votes without decrypting the individual votes.
 In secret sharing schemes, parties share a secret so that no individual party can
reconstruct the secret form the information available to it.
 One of the most interesting applications of homomorphic encryption is its use in
protection of mobile agents.
 Digital watermarking and fingerprinting schemes embed additional information into
digital data. The homomorphic property is used to add a mark to previously encrypted
data.
 Usually in a cryptographic lottery, a number pointing to the winning ticket has to be
jointly and randomly chosen by all participants.

CONCLUSION: Thus, we came to know about homomorphic encryption and its types and
what are the applications of them.

PRACTICAL-13
AIM: Study execution of photon to achieve security. Compare wired and wireless quantum
cryptography techniques.
SOFTWARE REQUIRED: N/A

HARDWARE REQUIRED: N/A

THEORY:

62
CE348:INFORMATION SEQURITY 16CE068

QUANTUM CRYPTOGRAPHY:

Cryptography is the process of encrypting data, or converting plain text into scrambled text so
that only someone who has the right “key” can read it. Quantum cryptography, by extension,
simply uses the principles of quantum mechanics to encrypt data and transmit it in a way that
cannot be hacked.

While the definition sounds simple, the complexity lies in the principles of quantum
mechanics behind quantum cryptography, such as:
 The particles that make up the universe are inherently uncertain and can simultaneously
exist in more than one place or more than one state of being.
 Photons are generated randomly in one of two quantum states.
 You can’t measure a quantum property without changing or disturbing it.
 You can clone some quantum properties of a particle, but not the whole particle.
 All these principles play a role in how quantum cryptography works.
Quantum cryptography is the only known method for transmitting a secret key over distance
that is secure in principle and based on the laws of physics. Current methods for
communicating secret keys are all based on unproven mathematical assumptions.

These same methods also are at risk of becoming cracked in the future, compromising today's
encrypted transmissions retroactively. This matters very much if you care about long-term
security

Quantum Key Distribution uses quantum mechanics to guarantee secure communication. It


enables two parties to produce a shared random secret key known only to them, which can
then be used to encrypt and decrypt messages

QKD and qubits:

In quantum computing, a qubit or quantum bit is a unit of quantum information — the


quantum analogue of the classical bit. Unlike a classical bit which can take only the value of
either 0 or 1, the state of a qubit can be in a ‘superposition' of 0 and 1 simultaneously.

HOW QUANTUM CRYPTOGRAPHY WORKS:

63
CE348:INFORMATION SEQURITY 16CE068

Quantum cryptography, or quantum key distribution (QKD), uses a series of photons (light
particles) to transmit data from one location to another over a fiber optic cable.

By comparing measurements of the properties of a fraction of these photons, the two endpoints
can determine what the key is and if it is safe to use.

Breaking the process down further helps to explain it better:


1. The sender transmits photons through a filter (or polarizer) which randomly gives them
one of four possible polarizations and bit designations: Vertical (One bit), Horizontal
(Zero bit), 45 degree right (One bit), or 45 degree left (Zero bit).
2. The photons travel to a receiver, which uses two beam splitters (horizontal/vertical and
diagonal) to “read” the polarization of each photon. The receiver does not know which
beam splitter to use for each photon and has to guess which one to use.
3. Once the stream of photons has been sent, the receiver tells the sender which beam
splitter was used for each of the photons in the sequence they were sent, and the sender
compares that information with the sequence of polarizers used to send the key. The
photons that were read using the wrong beam splitter are discarded, and the resulting
sequence of bits becomes the key.
If the photon is read or copied in any way by an eavesdropper, the photon’s state will change.
The change will be detected by the endpoints. In other words, this means you cannot read the
photon and forward it on or make a copy of it without being detected.

QUANTUM PROPERTIES:

Digital systems use the familiar binary states: One/Zero, Yes/No, or On/Off. I'm afraid that's
not the case with quantum mechanics, "maybe one or the other" or "both" is more the norm. To
help explain, consider a qubit to be a single photon and watch how it can be manipulated in the
diagram below.

64
CE348:INFORMATION SEQURITY 16CE068

(a): A single photon is emitted from a light source and passes through a linear polarizer, in this
case — horizontal. That process creates a qubit with horizontal polarization.

(b): When the horizontally-polarized photon passes through a horizontally/vertically-oriented


polarizing beamsplitter, it always retains its horizontal polarization.

(c): If that horizontally-polarized photon passes through a diagonally-oriented polarizing


beamsplitter:

 There is a 50% probability of finding the photon at one of the exits.


 The photon will only be detected at one of the exits.
 The polarization of the photon will have changed to the corresponding diagonal
polarization.
Another interesting thing to note - polarized photons are able to convey digital information.
The next diagram shows how it's done.

65
CE348:INFORMATION SEQURITY 16CE068

You may have heard the term BB84 Protocol and wondered how it worked. Here's how:
 Alice uses a light source to create a photon.
 The photon is sent through a polarizer and randomly given one of four possible
polarization and bit designations — Vertical (One bit), Horizontal (Zero bit), 45 degree
right (One bit), or 45 degree left (Zero bit).
 The photon travels to Bob's location.
 Bob has two beamsplitters — a diagonal and vertical/horizontal - and two photon
detectors.
 Bob randomly chooses one of the two beamsplitters and checks the photon detectors.
 The process is repeated until the entire key has been transmitted to Bob.
 Bob then tells Alice in sequence which beamsplitter he used.
 Alice compares this information with the sequence of polarizers she used to send the key.
 Alice tells Bob where in the sequence of sent photons he used the right beamsplitter.
 Now both Alice and Bob have a sequence of bits (sifted key) they both know.
All in all, a pretty cool way of securely transferring an encryption key between two different
locations.

AN EXAMPLE OF HOW QUANTUM CRYPTOGRAPHY WORKS

Imagine you have two people, Alice and Bob, who want to send a secret to each other that no
one else can intercept. With QKD, Alice sends Bob a series of polarized photons over a fiber
optic cable. This cable doesn’t need to be secured because the photons have a randomized
quantum state.

66
CE348:INFORMATION SEQURITY 16CE068

If an eavesdropper, named Eve, tries to listen in on the conversation, she has to read each
photon to read the secret. Then she must pass that photon on to Bob. By reading the photon,
Eve alters the photon’s quantum state, which introduces errors into the quantum key. This
alerts Alice and Bob that someone is listening and the key has been compromised, so they
discard the key. Alice has to send Bob a new key that isn’t compromised, and then Bob can use
that key to read the secret.

CONCLUSION:

Thus, we learnt about Quantum Cryptography and how it works.

67
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL-14
AIM: Demonstrate usage of TWO LAYER WATER MARKING to prevent piracy.
SOFTWARE REQUIRED: N/A

HARDWARE REQUIRED: N/A

THEORY:

WATERMARKING:

Watermarking is a method to digitally sign a product to provide authentication and prevent


copyright infringement to proving the ownership of a product and provides integrity for
companies to protect their product.

In dual/two layer watermark, two different/same watermarking techniques at each layer is


presented. This implies greater integrity as it contains of two signatures in providing
authentication.

DIGITAL WATERMARK LIFE CYCLE PHASES:

The information to be embedded in a signal is called a digital watermark, although in some


contexts the phrase digital watermark means the difference between the watermarked signal

68
CE348:INFORMATION SEQURITY 16CE068

and the cover signal. The signal where the watermark is to be embedded is called the host
signal. A watermarking system is usually divided into three distinct steps, embedding, attack,
and detection. In embedding, an algorithm accepts the host and the data to be embedded, and
produces a watermarked signal.

Then the watermarked digital signal is transmitted or stored, usually transmitted to another
person. If this person makes a modification, this is called an attack. While the modification
may not be malicious, the term attack arises from copyright protection application, where third
parties may attempt to remove the digital watermark through modification. There are many
possible modifications, for example, lossy compression of the data (in which resolution is
diminished), cropping an image or video, or intentionally adding noise.

Detection (often called extraction) is an algorithm which is applied to the attacked signal to
attempt to extract the watermark from it. If the signal was unmodified during transmission,
then the watermark still is present and it may be extracted. In robust digital watermarking
applications, the extraction algorithm should be able to produce the watermark correctly, even
if the modifications were strong. In fragile digital watermarking, the extraction algorithm
should fail if any change is made to the signal

SOME USES OF DIGITAL WATERMARKING:

Audience monitoring:
 In Europe and in the USA, the audio of TV channels is watermarked. The embedded
message encodes the name of the channel.
 Panelists have at home a device capturing the sound in their TV room. It decodes the
message and sends it to the monitoring companies via Internet. They can measure the
audience and market share live.
Content integrity:

69
CE348:INFORMATION SEQURITY 16CE068

 In Africa, the TV ads are typically long spots. They are broadcasted through many local
channels which sometimes shorten the ads to increase their number and whence the
revenues. The embedded message is the identifier of the TV spot followed by a time-
code. Some companies have platform listening to all TV channels 24hours a day and
check that any single second of a TV spot is duly broadcasted.
Content protection:
 The audio of movies are watermarked in theaters and on Blu-Ray discs. The decoder is
embedded in a Blu Ray disc player.
 If it detects a watermark while playing a content in the clear, it concludes that this content
is indeed a pirated copy (either a camcord of a theater projection or a ripped Blu Ray)
and it stops the playback.
Forensics:
 Videos in movie theaters are also watermarked. The embedded message is the date of the
projection and also the ID of the beamer. That way, “Hollywood” knows in which
theater a pirate has camcorded a movie and puts the pressure on the owner of the
theater.
User tracing:
 Websites selling multimedia content on demand (movies, songs, cartoons, e-books) send
the client a personalised copy of the content. The ID of the client is embedded so that
dishonest people illegally sharing their versions (like on P2P networks) are identified
and black-listed (or sued).
Packaging identification:
 Some companies use digital watermarking as a replacement of the bar code on packaging.

CONCLUSION:

Thus, we learnt about dual layer watermarking and its applications.

70
CE348:INFORMATION SEQURITY 16CE068

PRACTICAL-15
AIM: Case Study on “How Hashing is used/implemented in Block Chain Technology.
SOFTWARE REQUIRED: N/A

HARDWARE REQUIRED: N/A

THEORY:

HASHING:

The reliability and integrity of blockchain is rooted in there being no chance of any fraudulent
data or transactions, such as a double spend, being accepted or recorded. A cornerstone of the
technology as a whole and the key components in maintaining this reliability is hashing.
Hashing is the process of taking an input of any length and turning it into a cryptographic
fixed output through a mathematical algorithm (Bitcoin uses SHA-256, for example).
Examples of such inputs can include a short piece of information such as a message or a huge
cache of varying pieces of information such as a block of transactions or even all of the
information contained on the internet.

SECURING DATA WITH HASHING:

Hashing drastically increases the security of the data. Anyone who may be trying to decrypt
the data by looking at the hash will not be able to work out the length of the encrypted
information based on the hash. A cryptographic hash function needs to have several crucial
qualities to be considered useful, these include:

 Impossible to produce the same hash value for differing inputs:


This is important because if it were not the case it would be impossible to keep track of
the authenticity of inputs.

 The same message will always produce the same hash value:
The importance of this is similar to the prior point.
71
CE348:INFORMATION SEQURITY 16CE068

 Quick to produce a hash for any given message:


The system would not be efficient or provide value otherwise.

 Impossible to determine input based on hash value:


This is one of the foremost aspects and qualities of hashing and securing data.

 Even the slightest change to an input completely alters the hash:


This is also a matter of a security. If a slight change only made a slight difference it
would be considerably easier to work out what the input was. The better and more
complex the hashing algorithm, the larger the impact of changing an input will be on
what the output is.

Hashing secures data by providing certainty that it hasn’t been tampered with before being
seen by the intended recipient. So, as an example, if you downloaded a file containing
sensitive information, you could run it through a hashing algorithm, calculate the hash of that
data and compare it to the one shown by whoever sent you the data. If the hashes don’t match,
you can be certain that the file was altered before you received it.

BLOCKCHAIN HASHING:

In blockchain, hashes are used to represent the current state of the world, or to be more
precise, the state of a blockchain. As such, the input represents everything that has happened
on a blockchain, so every single transaction up to that point, combined with the new data that
is being added. What this means is that the output is based on, and therefore shaped by, all
previous transactions that have occurred on a blockchain.

As mentioned, the slightest change to any part of the input results in a huge change to the
output; in this lies the irrefutable security of blockchain technology. Changing any record that
has previously happened on a blockchain would change all the hashes, making them false and

72
CE348:INFORMATION SEQURITY 16CE068

obsolete. This becomes impossible when the transparent nature of blockchain is taken into
account, as these changes would need to be done in plain sight of the whole network.

The first block of a blockchain, known as a genesis block, contains its transactions that, when
combined and validated, produce a unique hash. This hash and all the new transactions that are
being processed are then used as input to create a brand new hash that is used in the next block
in the chain. This means that each block links back to its previous block through its hash,
forming a chain back to the genesis block, hence the name blockchain. In this way,
transactions can be added securely as long as the nodes on the network are in consensus on
what the hash should be.

AN EXPLANATION OF DATA STRUCTURES:

Data structures are a specialized way of storing data. The two foremost hashing objects
carrying out this function are pointers and linked lists. Pointers store addresses as variables
and as such point to the locations of other variables. Linked lists are a sequence of blocks
connected to one another through pointers. As such, the variable in each pointer is the address
of the next node, with the last node having no pointer and the pointer in the first block, the
genesis block, actually lying outside of the block itself. At its simplest, a blockchain is simply
a linked list of recorded transactions pointing back to one another through hash pointers.

73
CE348:INFORMATION SEQURITY 16CE068

Hash pointers are where blockchain sets itself apart in terms of certainty as pointers not only
contain the address of the previous block, but also the hash data of that block too. As described
earlier, this is the foundation of the secure nature of blockchain. For example, if a hacker
wanted to attack the ninth block in a chain and change its data, he would have to alter the data
in all following blocks, as their hash would also change. In essence, this makes it impossible
to alter any data that is recorded on a blockchain.

Hashing is of the core fundamentals and foremost aspects of the immutable and defining
potential of blockchain technology. It preserves the authenticity of the data that is recorded and
viewed, and as such, the integrity of a blockchain as a whole. It is one of the more technical
aspect of the technology, however understanding it is a solid step in understanding how
blockchain functions and the immeasurable potential and value that it has.

CONCLUSION:

Thus, we learnt about hashing and how hashing is implemented in blockchain and also come
to know about what data structures are used by hashing to implement blockchain.

74

S-ar putea să vă placă și