0% found this document useful (0 votes)
602 views42 pages

Practical - 1: AIM:-Implement RSA Algorithm. Take Two Prime Numbers P, Q N PXQ

This document discusses the Playfair cipher and compares monoalphabetic and polyalphabetic ciphers. It includes less than 3 sentences: The document discusses the Playfair cipher encryption algorithm and provides pseudocode to implement it. It also compares monoalphabetic and polyalphabetic ciphers, noting that polyalphabetic ciphers use multiple substitution alphabets instead of a single fixed mapping, making them more secure than monoalphabetic ciphers.

Uploaded by

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

Practical - 1: AIM:-Implement RSA Algorithm. Take Two Prime Numbers P, Q N PXQ

This document discusses the Playfair cipher and compares monoalphabetic and polyalphabetic ciphers. It includes less than 3 sentences: The document discusses the Playfair cipher encryption algorithm and provides pseudocode to implement it. It also compares monoalphabetic and polyalphabetic ciphers, noting that polyalphabetic ciphers use multiple substitution alphabets instead of a single fixed mapping, making them more secure than monoalphabetic ciphers.

Uploaded by

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

CNS 180280116096

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);

System.out.println("Enter the value of e = ");


e=sc.nextInt();
while(e<z)
CNS 180280116096

{
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);

static int gcd(int e, int z)


{
if(e==0)
return z;
else
return gcd(z%e,e);
}
}
CNS 180280116096

OUTPUTS :-
CNS 180280116096

PRACTICAL - 2
AIM :- Implement playfair cipher.

The plaintext is paired in two characters.

Discuss the advantage of polyalphabetic cipher over monoalphabetic cipher.Key = MONARCHY


Plaintext = ar mu hs ea Ciphertext = RM CM BP IM

The advantage of polyalphabetic cipher over monoalphabetic 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.

Monoalphabetic Cipher includes Polyalphabetic cipher includes


What it Includes additive, multiplicative, affine and Autokey, Playfair,Roto, One- time
monoalphabetic substitution cipher. pad, Enigma cipher and Vigenere.

For a stream cipher to be a For a stream to be a polyalphabetic


monoalphabetic cipher, the valueof ki cipher, the value of id does not
Dependency does not depend on the position of the depend onthe position of the
plaintext characterin the plaintext plaintext stream.
stream.
CNS 180280116096

Program:

import java.io.*; import java.util.*;

class Playfair { String key; String plainText;


char[][] matrix = new char[5][5];

public Playfair(String key, String plainText)


{
this.key = key.toLowerCase(); this.plainText = plainText.toLowerCase();
}

public void cleanPlayFairKey()


{
LinkedHashSet<Character> set
= new LinkedHashSet<Character>();String newKey = "";

for (int i = 0; i < key.length(); i++)set.add(key.charAt(i));

Iterator<Character> it = set.iterator();while (it.hasNext())


newKey += (Character)it.next();

key = newKey;
}

// function to generate playfair cipher key tablepublic void generateCipherKey()


{
Set<Character> set = new HashSet<Character>();

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


{
if (key.charAt(i) == 'j')continue;
set.add(key.charAt(i));
}
CNS 180280116096

// remove repeated characters from the cipher keyString tempKey = new String(key);

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


{
char ch = (char)(i + 97);if (ch == 'j')
continue;

if (!set.contains(ch))tempKey += ch;
}

// create cipher key table


for (int i = 0, idx = 0; i < 5; i++)for (int j = 0; j < 5; j++)
matrix[i][j] = tempKey.charAt(idx++); System.out.println("Playfair Cipher

Key Matrix:");

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


System.out.println(Arrays.toString(matrix[i]));
}

// function to preprocess plaintextpublic String formatPlainText()


{
String message = "";
int len = plainText.length();

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


{
// if plaintext contains the character 'j',
// replace it with 'i'
if (plainText.charAt(i) == 'j')message += 'i';
else
message += plainText.charAt(i);
}

// if two consecutive characters are same, then


// insert character 'x' in between them
for (int i = 0; i < message.length(); i += 2)
{
if (message.charAt(i) == message.charAt(i + 1))message = message.substring(0, i + 1) + 'x'
+ message.substring(i + 1);
}
CNS 180280116096

// make the plaintext of even lengthif (len % 2 == 1)


message += 'x'; // dummy character

return message;
}

// function to group every two characterspublic String[] formPairs(String message)


{
int len = message.length();
String[] pairs = new String[len / 2];

for (int i = 0, cnt = 0; i < len / 2; i++) pairs[i] = message.substring(cnt, cnt += 2);

return pairs;
}

// function to get position of character in key tablepublic int[] getCharPos(char ch)


{
int[] keyPos = new int[2];

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


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

if (matrix[i][j] == ch)
{
keyPos[0] = i;keyPos[1] = j;break;
}
}
}
return keyPos;
}

public String encryptMessage()


{
String message = formatPlainText(); String[] msgPairs = formPairs(message);String
encText = "";

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


CNS 180280116096

{
char ch1 = msgPairs[i].charAt(0);char ch2 = msgPairs[i].charAt(1);int[] ch1Pos =
getCharPos(ch1); int[] ch2Pos = getCharPos(ch2);

// if both the characters are in the same rowif (ch1Pos[0] == ch2Pos[0]) {


ch1Pos[1] = (ch1Pos[1] + 1) % 5;ch2Pos[1] = (ch2Pos[1] + 1) % 5;
}

// if both the characters are in the same columnelse if (ch1Pos[1] == ch2Pos[1])


{
ch1Pos[0] = (ch1Pos[0] + 1) % 5;ch2Pos[0] = (ch2Pos[0] + 1) % 5;
}

// if both the characters are in different rows


// and columnselse {
int temp = ch1Pos[1];ch1Pos[1] = ch2Pos[1];ch2Pos[1] = temp;
}

// get the corresponding cipher characters from


// the key matrix
encText = encText + matrix[ch1Pos[0]][ch1Pos[1]]
+ matrix[ch2Pos[0]][ch2Pos[1]];
}

return encText;
}
}

public class Practical2 {


public static void main(String[] args)
{
System.out.println("Example\n"); Scanner sc=new Scanner(System.in);

String key1; System.out.println("Enter Key");key1=sc.nextLine();


CNS 180280116096

String plainText1 = "Playfair";


System.out.println("Enter PlainText");
plainText1=sc.nextLine();

Playfair pfc1 = new Playfair(key1, plainText1);


pfc1.cleanPlayFairKey();
pfc1.generateCipherKey();

String encText1 = pfc1.encryptMessage();


System.out.println("Cipher Text is: " + encText1.toUpperCase());

}
}

OUTPUTS:
CNS 180280116096

PRACTICAL - 3

AIM :- Implement Ceasar 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.
Ceasar cipher –

You are given plaintext Hello, Welcome.The key used is 3.


How Ceaser cipher will work?

Test case :
A B CD E F

Cryptanalysis for Caesar Cipher

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

English Letter Frequencies

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:

//A Java Program to illustrate Caesar Cipher Techniqueimport java.util.*;


class Practical3
{
// Encrypts text using a shift od s
public static StringBuffer encrypt(String text, int s)
{
StringBuffer result= new StringBuffer();

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


{
if (Character.isUpperCase(text.charAt(i)))
{
char ch = (char)(((int)text.charAt(i) +
s - 65) % 26 + 65);
result.append(ch);
}
el
se
{ char ch = (char)(((int)text.charAt(i) +
s - 97) % 26 + 97);
result.append(ch);

}
}

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!)

With this property of Hill Cipher we can go about cracking it.

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
{

static void encrypt(int cipherMatrix[][],int key[][],int messageVector[][])


{
int x, i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 1; j++)
{
cipherMatrix[i][j] = 0;
for (x = 0; x < 3; x++)
{
cipherMatrix[i][j] +=key[i][x] * messageVector[x][j];
}
cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
}
}
}

// Function to implement Hill Cipher


static void HillCipher(String message)
CNS 180280116096

{
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];

// Generate vector for the messagefor (int i = 0; i < 3; i++)


messageVector[i][0] = (message.charAt(i)) % 65;int [][]cipherMatrix =

new int[3][1];

// Following function generates


// the encrypted vector encrypt(cipherMatrix, key, messageVector);

String CipherText="";

// Generate the encrypted text from


// the encrypted vectorfor (int i = 0; i < 3; i++)
CipherText += (char)(cipherMatrix[i][0] + 65);

// Finally print the ciphertext System.out.print(" Ciphertext:" + 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

AIM :- Implement Euclid algorithm to find GCD.

GCD(16,12) = 4

GCD(12,4) = 4

Then 4 is the GCD(16,12)

Program:

import java.util.*;
import java.lang.*;

class Practical5
{
public static int gcd(int a, int b)
{
if (a == 0)
return b;

return gcd(b%a, a);


}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
for(int i=0;i<2;i++)
{
int a, b, g;
System.out.println("Enter a : ");
a=sc.nextInt();
System.out.println("Enter b: ");
b=sc.nextInt();
g = gcd(a, b);
System.out.println("GCD(" + a + " , " + b+ ") = " + g);
}
}
}
CNS 180280116096

OUTPUTS:
CNS 180280116096

PRACTICAL - 6
AIM :- Generate random number of 32 bits. Use different random number
generation algorithms. Which method gives the best ?

Random number must pass 3 tests


3. Uniformity
4. Scalabilty
5. Consistency

First method Linear congruential generator Xn+1 = (aXn + c) mod m m,a,c,X0 are
integersSecond method : Blum Blum shub generator.

1) Liner Congruential Generator:


Program:

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

2) Blum Blum Shub Generator

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

public BlumBlumShub(BigInteger n, byte[] seed)


{
this.n = n; setSeed(seed);
}
public void setSeed(byte[] seedBytes)
{
BigInteger seed = new BigInteger(1, seedBytes);state = seed.mod(n);
}
public int next(int numBits)
{
int result = 0;
for (int i = numBits; i != 0; --i)
{
state = state.modPow(two, n);
result = (result << 1) | (state.testBit(0) == true ? 1 : 0);
}
return result;
}
public static void main(String[] args)
{
SecureRandom r = new SecureRandom(); System.out.println("Generating
stock random seed");r.nextInt();

System.out.println("Generating N");int bitsize = 512;


BigInteger nval = BlumBlumShub.generateN(bitsize, r);

byte[] seed = new byte[bitsize/8];r.nextBytes(seed);

BlumBlumShub bbs = new BlumBlumShub(nval, seed);


System.out.println("Generating 10 bytes");
for (int i = 0; i < 10; ++i)
{
System.out.println(bbs.next(8));
}
BlumBlumShub bbs2 = new BlumBlumShub(bitsize);BlumBlumShub bbs3 =
new BlumBlumShub(nval);
}
}
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

AIM :- Write a program that creates a shortcut of a file. (Virus program).

Program:

!pip install winshell


!pip install pywin32
import os, winshell,
win32com.client desktop = winshell.desktop()
#desktop = r"path to where you wanna put your .lnk file"
path = os.path.join(desktop, 'ShortCut_File.lnk')
target = r"C:\Users\sharm\OneDrive\Desktop\Bhumi_Reassement. pdf"
icon =r"C:\Users\sharm\OneDrive\Desktop\Bhumi_Reassement.
pdf" shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
shortcut.save()

Output:

Abcd.pdf on Desktop
CNS 180280116096

Shortcut_File CreAted 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

filename = 'Downloads/CNS.png'size = os.stat(filename).st_size print(size)

f = open(filename, "a+")f.write(" " * (9*size)) f.close()

2. To Print the Increased Size

filename = 'Downloads/CNS.png'size = os.stat(filename).st_size


CNS 180280116096

print(size)

Output:
CNS 180280116096

The Original Size of the File is 95.3 KB

The Increased Size is 953 KB (original size*10)


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

Test case : Meetme Ciphertext : MEMETE Transposition


Key : 4312567
Plaintext: attackpostponeduntiltwoam
Ciphertext: TTNAAPTMTSUOAODWCOIXKNLYPETZ.

Rail Fence Program:

#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';

for(i = 0; i < msgLen; ++i){


railMatrix[row][col++] = msg[i];
if(row == 0 || row == key-1)
k= k * (-1);
row = row + k;
}

printf("\nEncrypted Message: ");

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


for(j = 0; j < msgLen; ++j)
if(railMatrix[i][j] != '\n')
printf("%c", toupper(railMatrix[i][j]));
}
BHUMI SHARMA

void main()
{
char msg[50];
CNS 180280116096

printf("Enter the String: ");


scanf("%s",&msg);
int key = 3;
encryptMsg(msg, key);
}

OUTPUTS:

CryptaAnalysis for Rail Fence

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

English Letter Frequencies

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);

System.out.print("\nEnter plaintext(enter in lower case): ");


String message = sc.next().toUpperCase();
System.out.print("\nEnter key in numbers: ");
String key = sc.next();

/* columnCount would keep track of columns */


int columnCount = key.length();

/* rowCount will keep of track of rows...no of rows = (plaintextlength +


keylength) / keylength */
int rowCount = (message.length()+columnCount)/columnCount;

/*plainText and cipherText would be array containing ASCII values for re


spective alphabets */
int plainText[][] = new int[rowCount][columnCount];
int cipherText[][] = new int[rowCount][columnCount];

/*Encryption Process*/
System.out.print("\n-----Encryption -------\n");
CNS 180280116096

cipherText = encrypt(plainText, cipherText, message, rowCount, columnCou


nt, key);

// prepare final string


String ct = "";
for(int i=0; i<columnCount; i++)
{
for(int j=0; j<rowCount; j++)
{
if(cipherText[j][i] == 0)
ct = ct + ' ';
else{
ct = ct + (char)cipherText[j][i];
}
}
}
System.out.print("\nCipher Text: " + ct);

// prepare final string


String pt = "";
for(int i=0; i<rowCount; i++)
{
for(int j=0; j<columnCount; j++)
{
if(plainText[i][j] == 0)
pt = pt + "";
else{
pt = pt + (char)plainText[i][j];
}
}
}

System.out.println();
}

static int[][] encrypt(int plainText[][], int cipherText[][], String mes


sage, int rowCount, int
columnCount, String key){
int i,j;
int k=0;

/* here array would be filled row by row */


for(i=0; i<rowCount; i++)
{
for(j=0; j<columnCount; j++)
{
CNS 180280116096

/* terminating condition...as string length can be small


er than 2-D array */
if(k < message.length())
{
/* respective ASCII characters would be placed */
plainText[i][j] = (int)message.charAt(k);
k++;
}
else
{
break;
}
}
}

/* here array would be filled according to the key column by column


*/
for(i=0; i<columnCount; i++)
{
/* currentCol would have current column number i.e. to be read
...as there would be ASCII value stored in key so we would subtract it by 48 s
o that we can get the original number...and -
1 would be subtract as array position starts from 0*/
int currentCol= ( (int)key.charAt(i) - 48 ) -1;
for(j=0; j<rowCount; j++)
{
cipherText[j][i] = plainText[j][currentCol];
}

System.out.print("Cipher Array(read column by column): \n");


for(i=0;i<rowCount;i++){
for(j=0;j<columnCount;j++){
System.out.print((char)cipherText[i][j]+"\t");
}
System.out.println();
}

return cipherText;
}

}
CNS 180280116096

OUTPUTS:

CryptaAnalysis for Transposition Cipher

Cryptanalysis of Transposition Ciphers . It is usually possible to detect a transposition


cipher because the frequencies of letters are unchanged . Practiced cryptographers look for
patterns ofanagrams in a given language, allowing them to find the rules for transposition •
Transposition ciphers were used in practice as recently as World War II Note that
transposition ciphers require all the characters in the message before it can begin as well as
linear space
CNS 180280116096

PRACTICAL - 11
AIM :- Read traffic going on network. Analyze the traffic. Connect
tointernet and Read what is going on internet using Wireshark.

Step 1: Open the Wireshark on your PC.

It displays various connections available.

Step 2: Disable the Firewall, as it can stop some traffic.


CNS 180280116096

Step 3: Double Click on WIFI from Step 1 to capture the traffic of the internet.

The Traffic Started Capturing now.

Step 4: You will See different types of Traffic and Different criteria as seenbelow.
CNS 180280116096

Step 5: It Shows the details of protocol and port etc.

Step 6: It shows different number of bytes and their usage

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy