Practical - 1: AIM:-Implement RSA Algorithm. Take Two Prime Numbers P, Q N PXQ
Practical - 1: AIM:-Implement RSA Algorithm. Take Two Prime Numbers P, Q N PXQ
PRACTICAL - 1
AIM :- Implement RSA algorithm. Take two prime numbers p,q n=pxq.
Initially take encryption key such that it is relatively prime with ф(n).
Find out decryption key. Take plaintext message M, Ciphertext C=Me mod n.To get
plaintext from ciphertext M=Cd mod n.
Test case :
Two prime numbers 17,11Encryption key = 7 Decryption key = 23
M=88C=11
Program:
import java.util.*;
import java.math.*;
class RSA
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int p,q,n,z,d=0,e,i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg=sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p=sc.nextInt();
System.out.println("Enter 2nd prime number q");
q=sc.nextInt();
n=p*q;
z=(p-1)*(q-1);
System.out.println("the value of z = "+z);
System.out.println("the value of n = "+n);
{
if(gcd(e,z)==1) // e is for public key exponent
{
break;
}
}
System.out.println("the value of e = "+e);
for(i=0;i<=9;i++)
{
int x=1+(i*z);
if(x%e==0) //d is for private key exponent
{
d=x/e;
break;
}
}
System.out.println("the value of d = "+d);
c=(Math.pow(msg,e))%n;
System.out.println("Encrypted message is : -");
System.out.println(c);
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Derypted message is : -");
System.out.println(msgback);
OUTPUTS :-
CNS 180280116096
PRACTICAL - 2
AIM :- Implement playfair cipher.
BASIS OF
MONOALPHABETIC CIPHER POLYALPHABETIC CIPHER
COMPARISON
A monoalphabetic cipher is one where
Polyalphabetic cipher is any cipher
each symbol in the input(known as the
Description based on substitution,using
‘’plaintext’’ is mapped to a fixed
multiple substitution alphabets.
symbol in theoutput (referred to
ciphertext).
In monoalphabetic Cipher, once a key In polyalphabetic cipher, each
Alphabetic is chosen, each alphabetic character of alphabetic character of plaintext
Character of plaintext is mapped onto a unique can be mapped onto‘’m’’
Plaintext alphabetic characterof a ciphertext. alphabetic characters of a
ciphertext.
In Polyalphabetic Cipher, the
In monoalphabetic Cipher, the
Relation Between relationship between a character in
relationship between a character in the
Characters the plaintext andthe characters in
plaintext and the charactersin the
ciphertext is one-to-one, the ciphertext is one-to-many.
Program:
key = newKey;
}
// remove repeated characters from the cipher keyString tempKey = new String(key);
if (!set.contains(ch))tempKey += ch;
}
Key Matrix:");
return message;
}
for (int i = 0, cnt = 0; i < len / 2; i++) pairs[i] = message.substring(cnt, cnt += 2);
return pairs;
}
if (matrix[i][j] == ch)
{
keyPos[0] = i;keyPos[1] = j;break;
}
}
}
return keyPos;
}
{
char ch1 = msgPairs[i].charAt(0);char ch2 = msgPairs[i].charAt(1);int[] ch1Pos =
getCharPos(ch1); int[] ch2Pos = getCharPos(ch2);
return encText;
}
}
}
}
OUTPUTS:
CNS 180280116096
PRACTICAL - 3
It is substitution cipher.
Analyze the strength of the cipher in terms of brute force attack andcryptanalysis attack.
Suggest one way to improve and strengthen the cipher and analyze withrespect to cryptanalysis
attack.
Ceasar cipher –
Test case :
A B CD E F
See Cryptanalysis of the Caesar Cipher for a way of automatically breaking this cipher.
Cryptanalysis is the art of breaking codes and ciphers. The Caesar cipher is probably the easiest
of all ciphers to break. Since the shift has to be a number between 1 and 25, (0 or 26 would
result in an unchanged plaintext) we can simply try each possibility and see which one results in
a piece of readable text. If you happen to know what a piece of the ciphertext is, or you can guess
a piece, then this will allow you to immediately find the key.
If this is not possible, a more systematic approach is to calculate the frequency distribution of the
letters in the cipher text. This consists of counting how many times each letter appears.
Natural English text has a very distinct distribution that can be used help crack codes. This
distribution is as follows:
CNS 180280116096
This means that the letter e is the most common, and appears almost 13% of the time, whereas
z appears far less than 1 percent of time. Application of the Caesar cipher does not change these
letter frequencies, it merely shifts them along a bit (for a shift of 1, the most frequent ciphertext
letter becomes f). A cryptanalyst just has to find the shift that causes the ciphertext frequencies to
match up closely with the natural English frequencies, then decrypt the text using that shift. This
method can be used to easily break Caesar ciphers by hand.
If you are still having trouble, try the cryptanalysis section of the substitution cipher page. All
strategies that work with the substitution cipher will also work with the Caesar cipher (but
methods that work on the Caesar cipher do not necessarily work on the general substitution
cipher).
For a method that works well on computers, we need a way of figuring out which of the 25
possible decryptions looks the most like English text. See Cryptanalysis of the Caesar
Cipher for a walkthrough of how to break it using quadgram statistics. The key (or shift) that
results in a decryption with the highest likelyhood of being English text is most probably the
correct key. Of course, the more ciphertext you have, the more likely this is to be true (this is the
case for all statistical measures, including the frequency approach above). So the method used is
to take the ciphertext, try decrypting it with each key, then see which decryption looks the best.
This simplistic method of cryptanalysis only works on very simple ciphers suchas the Caesar
cipher and the rail fence cipher, even slightly more complex ciphers can have far too many
keys to check all of them.
The Caesar cipher can be easily broken even in a ciphertext-only scenario. Two situations can be
considered:
1. an attacker knows (or guesses) that some sort of simple substitution cipher has been used, but not
specifically that it is a Caesar scheme;
2. an attacker knows that a Caesar cipher is in use, but does not know the shift value.
In the first case, the cipher can be broken using the same techniques as for a general simple
substitution cipher, such as frequency analysis or pattern words.] While solving, it is likely that an
attacker will quickly notice the regularity in the solution and deduce that a Caesar cipher is the
specific algorithm employed.
In the second instance, breaking the scheme is even more straightforward. Since there are only a
limited number of possible shifts (25 in English), they can each be tested in turn in
a brute force attack. One way to do this is to write out a snippet of the ciphertext in a table of all
possible shifts – a technique sometimes known as "completing the plain component" The
example given is for the ciphertext "EXXEGOEXSRGI"; the plaintext is instantly recognisable
by eye at a shift of four. Another way of viewing this method is that, under each letter of the
ciphertext, the entire alphabet is written out in reverse starting at that letter. This attack can be
accelerated using a set of strips prepared with the alphabet written down in reverse order. The
CNS 180280116096
strips are then aligned to form the ciphertext along one row, and the plaintext should appear in
one of the other rows.
Another brute force approach is to match up the frequency distribution of the letters. By
graphing the frequencies of letters in the ciphertext, and by knowing the expected distribution
of those letters in the original language of the plaintext, a human can easily spot the value of the
shift by looking at the displacement of particular features of the graph. This is known as
frequency analysis. For example, in the English language the plaintext frequencies of the letters
E, T, (usually most frequent), and Q, Z (typically least frequent) are particularly distinctive
Computers can also do this by measuring how well the actual frequency distribution matches up
with the expected distribution; for example, the chi- squared statistic can be used.[
For natural language plaintext, there will typically be only one plausible decryption, although for
extremely short plaintexts, multiple candidates are possible. For example, the
ciphertext MPQY could, plausibly, decrypt to either "aden" or "know" (assuming the plaintext is
in English); similarly, "ALIIP" to "dolls" or "wheel"; and "AFCCP" to "jolly" or "cheer" (see
also unicity distance).
With the Caesar cipher, encrypting a text multiple times provides no additional security. This is
because two encryptions of, say, shift A and shift B, will be equivalent to a single encryption with
shift A + B. In mathematical terms, the set of encryption operations under each possible key
forms a group under composition.]
CNS 180280116096
Program:
}
}
return result;
}
// Driver code
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in); String text; System.out.println("Enter
text : ");text=sc.nextLine();
int s;
System.out.println("Enter s : "); s=sc.nextInt(); System.out.println("Text : " +
text);System.out.println("Shift : " + s);
System.out.println("Cipher: " + encrypt(text, s));
}
}
CNS 180280116096
OUTPUTS:
CNS 180280116096
PRACTICAL - 4
AIM :- Implement Hill cipher.
It is substitution cipher.
Analyze the strength of the cipher in terms of brute force attack andcryptanalysis attack.
Suggest one way to improve and strengthen the cipher and analyze withrespect to cryptanalysis
attack.
Hill Cipher -
Key K = 17 17 5
21 18 21
2 2 19
Plaintext = pay Ciphertext = RRL
Cryptanalysis
The first thing to note is that when encoding in Hill Cipher each row of the key matrix encodes to
1 letter independently of the rest of the key matrix.
Notice how the top row of the far left matrix is only involved in the top cell of the ciphertext
matrix, the middle row is only involved in the middle cell etc.
We can use this fact to dramatically decrease the number of keys we have to test to break the Hill
Cipher.
For square matrix of size N, there are 26N×N unique keys (there will be less as not all matrices have
an inverse). For N=3, there is 269 ≈ 5.43×1012 keys, to test all of these is not feasible (I
calculated on my pc it would take ≈ 8 years to test them all).
However, if we test each row individually then there is only 26N keys we need to test, For N=3
there is 263 = 17,576 which is a very small number in comparison (Takes 0.5 seconds on my pc!)
First you will need to identify N (the size of the matrix) the size will be a multiple of the text
length – this narrows it down a lot
Now you will be to iterate over all the row vectors with a size of N and possible values of 0
(inclusive) to 26 (exclusive).
CNS 180280116096
For a 3 by 3 there are 17,576 combinations. They look will look something like this. On the left is
the iteration number…
1/17576 [ 0, 0, 0]
2/17576 [ 0, 0, 1]
3/17576 [ 0, 0, 2] ……
16249/17576 [24, 0, 24]
16250/17576 [24, 0, 25]
16251/17576 [24, 1, 0] ……
17576/17576 [25, 25, 25]
For each one of these possibilities assume it is part of the key and multiply your ciphertext by it,
you will multiply in blocks of N and get a single letter out for each block.
Once you have all the output letters for a particular possibility, score the letters using
the Chi-Squared Statistic. Store the row vectors from smallest to largest Chi-Squared value.
Once you have checked all the possibilities. Take the best results from the list you havecompiled
and then go through all the permutations of creating an N by N matrix and checking it has an
inverse in modular 26.
Program:
import java.util.*;
class GFG
{
{
Scanner a = new Scanner(System.in); int key[][]=new int[3][3];
System.out.println("Enter the key: ");for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
key[i][j] =a.nextInt();
}
}
int [][]messageVector = new int[3][1];
new int[3][1];
String CipherText="";
// Driver code
public static void main(String[] args)
{
Scanner b = new Scanner(System.in);String message;
System.out.println("Enter the Message: ");message=b.nextLine();
HillCipher(message);
}
}
CNS 180280116096
OUTPUTS:
CNS 180280116096
PRACTICAL - 5
GCD(16,12) = 4
GCD(12,4) = 4
Program:
import java.util.*;
import java.lang.*;
class Practical5
{
public static int gcd(int a, int b)
{
if (a == 0)
return b;
OUTPUTS:
CNS 180280116096
PRACTICAL - 6
AIM :- Generate random number of 32 bits. Use different random number
generation algorithms. Which method gives the best ?
First method Linear congruential generator Xn+1 = (aXn + c) mod m m,a,c,X0 are
integersSecond method : Blum Blum shub generator.
import java.util.*;
class Practical6
{
static void LCM(int Xo, int m,int a, int c,int[] randomNums,int noOfRandom
Nums)
{
randomNums[0] = Xo;
for(int i = 1; i < noOfRandomNums; i++)
{
randomNums[i] = ((randomNums[i - 1] * a) + c) % m;
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
// Seed value
int Xo;
System.out.println("Enter Value of Xo:");
Xo=s.nextInt();
// Modulus parameter
int m ;
System.out.println("Enter Value of m:");
m=s.nextInt();
CNS 180280116096
// Multiplier term
int a;
System.out.println("Enter Value of a:");
a=s.nextInt();
// Increment term
int c;
System.out.println("Enter Value of c:");
c=s.nextInt();
// Number of Random numbers
// to be generated
int noOfRandomNums;
System.out.println("Enter number of elements generate:");
noOfRandomNums=s.nextInt();
// To store random numbers
int[] randomNums = new int[noOfRandomNums];
// Function Call
LCM(Xo, m, a, c,randomNums,noOfRandomNums);
// Print the generated random numbers
for(int i = 0; i < noOfRandomNums; i++)
{
System.out.print(randomNums[i] + " ");
}
}
}
Output:
CNS 180280116096
Program:
import java.util.Random;
import java.security.SecureRandom;import java.math.BigInteger; public class
BlumBlumShub
{
private static final BigInteger two = BigInteger.valueOf(2L); private static
final BigInteger three = BigInteger.valueOf(3L);private static final BigInteger
four = BigInteger.valueOf(4L);private BigInteger n;
private BigInteger state;
private static BigInteger getPrime(int bits, Random rand)
{
BigInteger p;while (true)
{
p = new BigInteger(bits, 100, rand);if (p.mod(four).equals(three)) break;
}
return p;
}
public static BigInteger generateN(int bits, Random rand)
{
BigInteger p = getPrime(bits/2, rand);BigInteger q = getPrime(bits/2, rand);
while (p.equals(q))
{
q = getPrime(bits, rand);
}
return p.multiply(q);
}
public BlumBlumShub(int bits)
{
this(bits, new Random());
}
public BlumBlumShub(int bits, Random rand)
{
this(generateN(bits, rand));
}
public BlumBlumShub(BigInteger n)
{
this(n, SecureRandom.getSeed(n.bitLength() / 8));
}
CNS 180280116096
Output:
CNS 180280116096
PRACTICAL - 7
AIM :- Implement Euler’s totient function
phi(n).It is defined as the number of positive integers less than n and relativelyprime to n.
Find phi(35) and phi(37).
Observe the value and analyze the behavior of totient function.
Program :
import java.io.*;
import java.util.*;
public class GP
{
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int phi(int n)
{
int result = 1;
for (int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}
public static void main(String[] args)
{
int n;
Scanner a=new Scanner(System.in);
System.out.println("Enter the n:");
n=a.nextInt();
System.out.println("phi(" + n + ") = " + phi(n));
}
}
CNS 180280116096
OUTPUTS:
CNS 180280116096
PRACTICAL - 8
Program:
Output:
Abcd.pdf on Desktop
CNS 180280116096
OrigiNAl LOCAtion
CNS 180280116096
PRACTICAL - 9
AIM: Write a program that increases file size by 10.
Program:
1. To Increase Size
import os
print(size)
Output:
CNS 180280116096
PRACTICAL - 10
AIM :- Implement rail Fence and transposition cipher. Both are
permutation cipher. Analyze the strength of the cipher in terms of
cryptanalysis.
Rail fence
#include<stdio.h>
#include<string.h>
void encryptMsg(char msg[], int key)
{
int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0;
char railMatrix[key][msgLen];
for(i = 0; i < key; ++i)
for(j = 0; j < msgLen; ++j)
railMatrix[i][j] = '\n';
void main()
{
char msg[50];
CNS 180280116096
OUTPUTS:
Cryptanalysis is the art of breaking codes and ciphers. The railfence cipher is a very easy cipher
to break. A cryptanalyst (code breaker) simply has to try several keys until the correct one is
found. It is very easy to find a key if you know some of the plaintext, or can guess some of it.
Anagramming is another very powerful method that can be used with any
transposition cipher, that consists of taking chunks of ciphertext and guessing what the plaintext
would be.
A peculiarity of transposition ciphers is that the frequency distribution of the characters will be
identical to that of natural text (since no substitutions have been performed, it is just the order
that has been mixed up). In other words it should look just like this:
CNS 180280116096
For a method that works well on computers, we need a way of figuring out which of the keys
results in the most english like plaintext after decryption. For automated methods of determining
how 'english like' a piece of text is, check out the Classical Cryptanalysis section, in particular
Quadgrams as a fitness measure. The key that results in a decryption with the highest likelyhood
of being english text is most probably the correct key. Of course, the more ciphertext you have,
the more likely this is to be true (this is the case for all statistical measures, including the
frequency approaches above). So the method used is to take the ciphertext, try decrypting it with
each key, then see which decryption looks the best. This simplistic method of cryptanalysis
(checking every single possible key) only works on very simple ciphers such as this cipher, even
slightly more complex ciphers can have far too
many keys to check all of them.
Transposition Cipher:
Program:
import java.util.*;
class h
{
public static void main(String sap[]){
Scanner sc = new Scanner(System.in);
/*Encryption Process*/
System.out.print("\n-----Encryption -------\n");
CNS 180280116096
System.out.println();
}
return cipherText;
}
}
CNS 180280116096
OUTPUTS:
PRACTICAL - 11
AIM :- Read traffic going on network. Analyze the traffic. Connect
tointernet and Read what is going on internet using Wireshark.
Step 3: Double Click on WIFI from Step 1 to capture the traffic of the internet.
Step 4: You will See different types of Traffic and Different criteria as seenbelow.
CNS 180280116096