Professional Documents
Culture Documents
LAB 1
i)Euclidean Algorithm
Theory:
he Euclidean algorithm is an efficient method to compute the greatest common divisor (gcd) of two integers.
The algorithm is based on the below facts.
1. If we subtract a smaller number from a larger (we reduce a larger number), GCD doesn’t change. So if we keep
subtracting repeatedly the larger of two, we end up with GCD.
2. Now instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0.
Code:
import java.util.*;
import java.lang.*;
class euclidean
{
public static int gcd(int a, int b)
{
if (a == 0)
return b;
}
}
Twisha Chattopadhyay
189303009
2
Theory:
Extended Euclidean algorithm also finds integer coefficients x and y such that:
ax + by = gcd(a, b)
Code:
import java.util.*;
import java.lang.*;
class ExtendedEuclidean
{
public static int Extended(int a, int b, int x, int y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
return gcd;
}
public static void main(String[] args)
{
int a,b,c;
int x=1, y=1;
Twisha Chattopadhyay
189303009
3
a=sc.nextInt();
System.out.println("Enter second number: ");
b=sc.nextInt();
c=Extended(a,b,x,y);
System.out.println("GCD of the 2 numbers=" + c);
}
}
Twisha Chattopadhyay
189303009
4
LAB 2
i) Caesar Cipher
Theory:
The Caesar Cipher technique is one of the earliest and simplest method of encryption technique. It’s simply a type of
substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of positions down the
alphabet.
Thus to cipher a given text we need an integer value, known as shift which indicates the number of position each letter
of the text has been moved down.
Code:
import java.util.*;
import java.lang.*;
class CaesarCipher
{
// Encrypts text using a shift od s
public static StringBuffer encrypt(String text, int s)
{
StringBuffer result= new StringBuffer();
Twisha Chattopadhyay
189303009
5
{
char ch = (char)(((int)text.charAt(i) -
s - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}
// Driver code
public static void main(String[] args)
{
String text;
int s,option;
Scanner sc=new Scanner(System.in);
System.out.println("Enter line of text: ");
text=sc.nextLine();
System.out.println(" Choose your option 1)Encrypt 2)Decrypt ");
option=sc.nextInt();
switch(option)
{
case 1: System.out.println("Cipher: " + encrypt(text, s));
break;
}
}
Twisha Chattopadhyay
189303009
6
Theory:
The vigenere cipher is an algorithm that is used to encrypting and decrypting the text. The vigenere cipher is an
algorithm of encrypting an alphabetic text that uses a series of interwoven caesar ciphers. It is based on a keyword's
letters. It is an example of a polyalphabetic substitution cipher.
Code:
import java.util.*;
import java.lang.*;
class VigenereCipher
{
cipher_text+=(char)(x);
}
return cipher_text;
}
Twisha Chattopadhyay
189303009
7
// Driver code
public static void main(String[] args)
{
String text,key;
int option;
Scanner sc=new Scanner(System.in);
System.out.println("Enter line of text: ");
text=sc.nextLine();
System.out.println("Enter key: ");
key=sc.nextLine();
text=LowerToUpper(text);
key=LowerToUpper(key);
System.out.println(" Choose your option 1)Encrypt 2)Decrypt ");
option=sc.nextInt();
switch(option)
{
case 1: System.out.println("Cipher: " + encrypt(text,key));
break;
}
}
Twisha Chattopadhyay
189303009
8
Theory:
One-time pad cipher is a type of Vignere cipher which includes the following features −
• It is an unbreakable cipher.
• The key is exactly same as the length of message which is encrypted.
• The key is made up of random symbols.
• As the name suggests, key is used one time only and never used again for any other message to be encrypted.
Code:
import java.io.*;
import java.util.*;
class OTP
{
public static String encrypt(String text, String key)
{
Twisha Chattopadhyay
189303009
9
return cipherText;
}
return plainText;
}
String text,key;
int option;
Scanner sc=new Scanner(System.in);
System.out.println("Enter line of text: ");
text=sc.nextLine();
System.out.println("Enter key: ");
key=sc.nextLine();
System.out.println(" Choose your option 1)Encrypt 2)Decrypt ");
option=sc.nextInt();
switch(option)
{
case 1: System.out.println("Cipher: " + encrypt(text.toUpperCase(),key.toUpperCase()));
break;
Twisha Chattopadhyay
189303009
10
}
}
LAB 3
i)Hill Cipher
Theory:
Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented by a number modulo
26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not an essential feature of the cipher. To encrypt
a message, each block of n letters (considered as an n-component vector) is multiplied by an invertible n × n matrix,
against modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
Code:
import java.util.ArrayList;
import java.util.Scanner;
class HillCipher{
Twisha Chattopadhyay
189303009
11
Twisha Chattopadhyay
189303009
12
}
}
// Calculate the reverse key matrix elements using the factor found
reverseMatrix[0][0] = keyMatrix[1][1] * factor % 26;
reverseMatrix[0][1] = (26 - keyMatrix[0][1]) * factor % 26;
reverseMatrix[1][0] = (26 - keyMatrix[1][0]) * factor % 26;
reverseMatrix[1][1] = keyMatrix[0][0] * factor % 26;
return reverseMatrix;
}
// This method echoes the result of encrypt/decrypt
private static void echoResult(String label, int adder, ArrayList<Integer> phrase) {
int i;
System.out.print(label);
// Loop for each pair
for(i=0; i < phrase.size(); i += 2) {
System.out.print(Character.toChars(phrase.get(i) + (64 + adder)));
System.out.print(Character.toChars(phrase.get(i+1) + (64 + adder)));
if(i+2 <phrase.size()) {
System.out.print("-");
}
}
System.out.println();
}
// This method makes the actual encryption
public static void encrypt(String phrase, boolean alphaZero)
{
int i;
int adder = alphaZero ? 1 : 0; // For calclulations depending on the alphabet
int[][] keyMatrix;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseEncoded = new ArrayList<>();
// Delete all non-english characters, and convert phrase to upper case
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();
Twisha Chattopadhyay
189303009
13
Twisha Chattopadhyay
189303009
14
encrypt(phrase, true);
break;
case "2":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, true);
break;
case "3":
System.out.print("Enter phrase to encrypt: ");
phrase = sc.nextLine();
encrypt(phrase, false);
break;
case "4":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, false);
break;
}
}
}
ii)Playfair Cipher
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. In playfair cipher unlike traditional
cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.
Code:
import java.util.*;
class PlayfairCipher
{
public static void main(String[] args)
Twisha Chattopadhyay
189303009
15
{
String key1;
String encrypt="";
String alpha = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
String unique="";
char matrix[][] = new char[5][5];
int k=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter key");
key1 = sc.nextLine()+alpha;
String key = key1.replaceAll("\\s", "").replace("I","J");
System.out.println("Enter your message");
String msg = sc.nextLine().replaceAll("\\s", "").replace("I","J");
for(int i=0;i<key.length();i++)
{
if(!unique.contains(""+key.charAt(i)))
{
unique = ""+unique+key.charAt(i);
}
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
matrix[i][j] = unique.charAt(k);
k++;
}
}
System.out.println("Matrix");
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.print(matrix[i][j]+" ");
}
System.out.println("");
}
for(int i=0;i<msg.length();i+=2)
{
if(msg.charAt(i)==msg.charAt((i+1)%msg.length()))
{
msg= msg.substring(0, i+1)+"X"+msg.substring(i+1, msg.length());
}
if(msg.length()%2!=0)
{
msg+="X";
}
System.out.println("Separating occurences(if there) = "+msg);
Twisha Chattopadhyay
189303009
16
if(msg.length()%2==0)
{
for(int i=0;i<msg.length();i+=2)
{
String pos =findPos(matrix,msg.charAt(i),msg.charAt(i+1));
if(pos.charAt(0)==pos.charAt(2))
{
//for same row
int r = Integer.parseInt(pos.charAt(0)+"");
int c = (Integer.parseInt(pos.charAt(1)+"")+1)%5;
int c1 = (Integer.parseInt(pos.charAt(3)+"")+1)%5;
encrypt=encrypt+matrix[r][c]+matrix[r][c1];
}
else if(pos.charAt(1)==pos.charAt(3))
{
//for same col
int r = (Integer.parseInt(pos.charAt(0)+"")+1)%5;
int r1 = (Integer.parseInt(pos.charAt(2)+"")+1)%5;
int c = Integer.parseInt(pos.charAt(1)+"");
encrypt=encrypt+matrix[r][c]+matrix[r1][c];
}
else
{
//for diff row and col
int r = Integer.parseInt(pos.charAt(0)+"");
int c = Integer.parseInt(pos.charAt(3)+"");
int r1 = Integer.parseInt(pos.charAt(2)+"");
int c1 = Integer.parseInt(pos.charAt(1)+"");
encrypt=encrypt+matrix[r][c]+matrix[r1][c1];
}
}
System.out.println("Encrypted msg = "+encrypt);
}
}
Twisha Chattopadhyay
189303009
17
Theory:
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence algorithm.
The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in
which it is encoded.
Code:
import java.util.*;
class RailFenceBasic
{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
Twisha Chattopadhyay
189303009
18
}
return cipherText;
}
String plainText="";
return plainText;
}
}
class RailFence{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
Twisha Chattopadhyay
189303009
19
LAB 4
i)DES Cipher
Theory:
Data encryption standard (DES) has been found vulnerable against very powerful attacks and therefore, the popularity
of DES has been found slightly on the decline.
DES is a block cipher and encrypts data in blocks of size of 64 bits each, which means 64 bits of plain text goes as the
input to DES, which produces 64 bits of ciphertext. The same algorithm and key are used for encryption and decryption,
with minor differences. The key length is 56 bits. DES is based on the two fundamental attributes of cryptography:
substitution (also called confusion) and transposition (also called diffusion). DES consists of 16 steps, each of which is
called a round. Each round performs the steps of substitution and transposition.
Code:
import java.util.*;
class Main {
private static class DES {
// CONSTANTS
// Initial Permutation Table
int[] IP = { 58, 50, 42, 34, 26, 18,
10, 2, 60, 52, 44, 36, 28, 20,
12, 4, 62, 54, 46, 38,
30, 22, 14, 6, 64, 56,
48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17,
9, 1, 59, 51, 43, 35, 27,
19, 11, 3, 61, 53, 45,
37, 29, 21, 13, 5, 63, 55,
47, 39, 31, 23, 15, 7 };
Twisha Chattopadhyay
189303009
20
// S-box Table
int[][][] sbox = {
{ { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 },
{ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 },
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 },
{ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } },
Twisha Chattopadhyay
189303009
21
Twisha Chattopadhyay
189303009
22
return output;
}
// s-box lookup
String sBox(String input)
{
String output = "";
input = hextoBin(input);
for (int i = 0; i < 48; i += 6) {
String temp = input.substring(i, i + 6);
Twisha Chattopadhyay
189303009
23
int num = i / 6;
int row = Integer.parseInt(
temp.charAt(0) + "" + temp.charAt(5), 2);
int col = Integer.parseInt(
temp.substring(1, 5), 2);
output += Integer.toHexString(
sbox[num][row][col]);
}
return output;
}
// swapper
return right + left;
}
// initial permutation
plainText = permutation(IP, plainText);
System.out.println(
"After initial permutation: "
+ plainText.toUpperCase());
System.out.println(
"After splitting: L0="
+ plainText.substring(0, 8).toUpperCase()
+ " R0="
+ plainText.substring(8, 16).toUpperCase() + "\n");
// 16 rounds
for (i = 0; i < 16; i++) {
plainText = round(plainText, keys[i], i);
Twisha Chattopadhyay
189303009
24
// 32-bit swap
plainText = plainText.substring(8, 16)
+ plainText.substring(0, 8);
// final permutation
plainText = permutation(IP1, plainText);
return plainText;
}
// initial permutation
plainText = permutation(IP, plainText);
System.out.println(
"After initial permutation: "
+ plainText.toUpperCase());
System.out.println(
"After splitting: L0="
+ plainText.substring(0, 8).toUpperCase()
+ " R0=" + plainText.substring(8, 16).toUpperCase()
+ "\n");
// 16-rounds
for (i = 15; i > -1; i--) {
plainText = round(plainText, keys[i], 15 - i);
}
// 32-bit swap
plainText = plainText.substring(8, 16)
+ plainText.substring(0, 8);
plainText = permutation(IP1, plainText);
return plainText;
}
}
public static void main(String args[])
{
String text = "123456ABCD132536";
String key = "AABB09182736CCDD";
Twisha Chattopadhyay
189303009
25
Twisha Chattopadhyay
189303009
26
ii)AES Cipher
Theory:
Advanced Encryption Standard (AES) is a specification for the encryption of electronic data established by the U.S
National Institute of Standards and Technology (NIST) in 2001. AES is widely used today as it is a much stronger than
DES and triple DES despite being harder to implement.
AES is a block cipher.
That means it takes 128 bits as input and outputs 128 bits of encrypted cipher text as output. AES relies on substitution-
permutation network principle which means it is performed using a series of linked operations which involves replacing
and shuffling of the input data.
Code:
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.*;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
class AES {
// Class private variables
private static final String SECRET_KEY
= "my_super_secret_key_ho_ho_ho";
Twisha Chattopadhyay
189303009
27
Twisha Chattopadhyay
189303009
28
+ e.toString());
}
return null;
}
}
// driver code
class Main {
public static void main(String[] args)
{
String text;
int option;
Scanner sc=new Scanner(System.in);
System.out.println("Enter line of text: ");
text=sc.nextLine();
iii)RSA Cipher
Theory:
RSA algorithm is asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys
i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and Private key is kept
private.
The idea of RSA is based on the fact that it is difficult to factorize a large integer. The public key consists of two
numbers where one number is multiplication of two large prime numbers. And private key is also derived from the same
two prime numbers.
Code:
Twisha Chattopadhyay
189303009
29
import java.math.BigInteger;
import java.security.SecureRandom;
modulus = p.multiply(q);
publicKey = new BigInteger("65537"); // common value in practice =
2^16 + 1
privateKey = publicKey.modInverse(phi);
}
Twisha Chattopadhyay
189303009
30
Twisha Chattopadhyay
189303009
31
LAB 5
iii)S-DES
Theory:
The S-DES encryption algorithm takes an 8-bit block of plaintext and a 10-bit key as input and produces an 8-bit block
of ciphertext as output. The S-DES decryption algorithm takes an 8-bit block of ciphertext and the same 10-bit key used
to produce that ciphertext as input and produces the original 8-bit block of plaintext.
Code:
import java.io.*;
import java.util.*;
class SDES
{
// int key[]= {0,0,1,0,0,1,0,1,1,1};
int key[] =
{
1, 0, 1, 0, 0, 0, 0, 0, 1, 0
};
int P10[] = { 3, 5, 2, 7, 4, 10, 1, 9, 8, 6 };
int P8[] = { 6, 3, 7, 4, 8, 5, 10, 9 };
int[] IP = { 2, 6, 3, 1, 4, 8, 5, 7 };
int[] EP = { 4, 1, 2, 3, 2, 3, 4, 1 };
int[] P4 = { 2, 4, 3, 1 };
int[] IP_inv = { 4, 1, 3, 5, 7, 2, 8, 6 };
int[][] S0 = { { 1, 0, 3, 2 },
{ 3, 2, 1, 0 },
{ 0, 2, 1, 3 },
{ 3, 1, 3, 2 } };
int[][] S1 = { { 0, 1, 2, 3 },
{ 2, 0, 1, 3 },
{ 3, 0, 1, 0 },
{ 2, 1, 0, 3 } };
void key_generation()
{
int key_[] = new int[10];
Twisha Chattopadhyay
189303009
32
Ls[i] = key_[i];
Rs[i] = key_[i + 5];
}
System.out.println();
System.out.println("Your Key-2 :");
Twisha Chattopadhyay
189303009
33
return ciphertext;
}
Twisha Chattopadhyay
189303009
34
Twisha Chattopadhyay
189303009
35
{
int[] l = new int[n];
int[] r = new int[n];
return output;
}
return decrypted;
}
Twisha Chattopadhyay
189303009
36
System.out.println();
System.out.println(
"Your cipher Text is :"); // printing the cipher
// text
for (int i = 0; i < 8; i++)
System.out.print(ciphertext[i] + " ");
System.out.println();
System.out.println(
"Your decrypted Text is :"); // printing the
// decrypted text
for (int i = 0; i < 8; i++)
System.out.print(decrypted[i] + " ");
}
}
iii)S-AES
Theory:
The structure of S-AES is exactly the same as AES. The differences are in the key size (16 bits),
the block size (16 bits) and the number of rounds (2 rounds).
Substitute nibbles Instead of dividing the block into a four by four array of bytes, S-AES divides it into a two by two
array of “nibbles”, which are four bits long. This is called the state array and is shown below.
Shift Rows The next stage is to shift the rows. In fact, the first row is left alone and the second row is shifted.
Twisha Chattopadhyay
189303009
37
Mix Columns After shifting the rows, we mix the columns. Each column is multiplied by the matrix
Add Round Key The last stage of each round of encryption is to add the round key.
Key Expansion Key expansion is done very similarly to AES. The four nibbles in the key are grouped into two 8-bit
“words”, which will be expanded into 6 words.
Code:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
class sAES {
Twisha Chattopadhyay
189303009
38
class Main
{
public static void main(String[] args)
{
final String secretKey = "ssshhhhhhhhhhh!!!!";
sAES obj= new sAES();
Scanner sc=new Scanner(System.in);
System.out.println("Enter message: ");
String originalString= sc.nextLine();
String encryptedString = sAES.encrypt(originalString, secretKey) ;
String decryptedString = sAES.decrypt(encryptedString, secretKey) ;
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}
Twisha Chattopadhyay
189303009