You are on page 1of 39

Name: Twisha Chattpadhyay

Registration number: 189303009


Subject: Network Security Lab
Class: CCE-B, 7th Semester

Serial Date Name of Experiment Page


Number Number
1 19/11/2021 LAB 1 1
(i) 19/11/2021 Euclidean Algorithm 1
(ii) 19/11/2021 Extended Euclidean Algorithm 2
2 22/11/2021 LAB 2 4
(i) 22/11/2021 Caesar CIpher 4
(ii) 22/11/2021 Vigenere Cipher 6
(iii) 22/11/2021 One Time Pad 8
3 23/11/2021 LAB 3 10
(i) 23/11/2021 Hill Cipher 10
(ii) 23/11/2021 Playfair Cipher 14
(iii) 23/11/2021 Rail Fence Cipher 17
4 23/11/2021 LAB 4 19
(i) 24/11/2021 DES 19
(ii) 24/11/2021 AES 26
(iii) 24/11/2021 RSA 28
5 26/11/2021 LAB 5 31
(i) 26/11/2021 s-DES 31
(ii) 26/11/2021 s-AES 36
1

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;

return gcd(b%a, a);


}

public static void main(String[] args)


{
int a,b,x;

Scanner sc= new Scanner(System.in);


System.out.println("Enter first number: ");
a=sc.nextInt();
System.out.println("Enter second number: ");
b=sc.nextInt();
x=gcd(a,b);
System.out.println("GCD of the 2 numbers=" + x);

}
}

Twisha Chattopadhyay
189303009
2

ii)Extended Euclidean Algorithm

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

int x1=1, y1=1;


int gcd = Extended(b%a, a, x1, y1);
x = y1 - (b/a) * x1;
y = x1;

return gcd;
}
public static void main(String[] args)
{
int a,b,c;
int x=1, y=1;

Scanner sc= new Scanner(System.in);


System.out.println("Enter first number: ");

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

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);
}
else
{
char ch = (char)(((int)text.charAt(i) +
s - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}

public static StringBuffer decrypt(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);
}
else

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

System.out.println("Enter Shift: ");


s=sc.nextInt();

switch(option)
{
case 1: System.out.println("Cipher: " + encrypt(text, s));
break;

case 2: System.out.println("Cipher: " + decrypt(text, s));


break;
}

}
}

Twisha Chattopadhyay
189303009
6

ii) Vigenere Cipher

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
{

static String generateKey(String str,String key)


{
int x = str.length();

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


{
if (x == i)
i = 0;
if (key.length() == str.length())
break;
key+=(key.charAt(i));
}
return key;
}

static String encrypt(String str,String key)


{
String cipher_text="";

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


{
int x = (str.charAt(i) + key.charAt(i)) %26;
x += 'A';

cipher_text+=(char)(x);
}
return cipher_text;
}

static String decrypt(String cipher_text, String key)


{
String orig_text="";

for (int i = 0 ; i < cipher_text.length() &&


i < key.length(); i++)
{
// converting in range 0-25
int x = (cipher_text.charAt(i) -
key.charAt(i) + 26) %26;

Twisha Chattopadhyay
189303009
7

// convert into alphabets(ASCII)


x += 'A';
orig_text+=(char)(x);
}
return orig_text;
}

static String LowerToUpper(String s)


{
StringBuffer str =new StringBuffer(s);
for(int i = 0; i < s.length(); i++)
{
if(Character.isLowerCase(s.charAt(i)))
{
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
}
s = str.toString();
return s;
}

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

key = generateKey(text, key);

switch(option)
{
case 1: System.out.println("Cipher: " + encrypt(text,key));
break;

case 2: System.out.println("Cipher: " + decrypt(text,key));


break;
}

}
}

Twisha Chattopadhyay
189303009
8

iii) One Time Pad

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

String cipherText = "";


int cipher[] = new int[key.length()];

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


{
cipher[i] = text.charAt(i) - 'A' + key.charAt(i)
- 'A';
}

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


{
if (cipher[i] > 25)
{
cipher[i] = cipher[i] - 26;
}
}

Twisha Chattopadhyay
189303009
9

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


{
int x = cipher[i] + 'A';
cipherText += (char)x;
}

return cipherText;
}

public static String decrypt(String s,String key)


{
String plainText = "";
int plain[] = new int[key.length()];
for (int i = 0; i < key.length(); i++)
{
plain[i]= s.charAt(i) - 'A' - (key.charAt(i) - 'A');
}
for (int i = 0; i < key.length(); i++)
{
if (plain[i] < 0)
{
plain[i] = plain[i] + 26;
}
}
for (int i = 0; i < key.length(); i++)
{
int x = plain[i] + 'A';
plainText += (char)x;
}

return plainText;
}

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

case 2: System.out.println("Cipher: " + decrypt(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

//method to accept key matrix


private static int[][] getKeyMatrix() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter key matrix:");
String key = sc.nextLine();
//int len = key.length();
double sq = Math.sqrt(key.length());
if (sq != (long) sq) {
System.out.println("Cannot Form a square matrix");
}
int len = (int) sq;
int[][] keyMatrix = new int[len][len];
int k = 0;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
keyMatrix[i][j] = ((int) key.charAt(k)) - 97;
k++;
}
}
return keyMatrix;
}
// Below method checks whether the key matrix is valid (det=0)
private static void isValidMatrix(int[][] keyMatrix) {
int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0];
// If det=0, throw exception and terminate
if(det == 0) {
throw new java.lang.Error("Det equals to zero, invalid key matrix!");
}
}
// This method checks if the reverse key matrix is valid (matrix mod26 = (1,0,0,1)
private static void isValidReverseMatrix(int[][] keyMatrix, int[][] reverseMatrix) {
int[][] product = new int[2][2];
// Find the product matrix of key matrix times reverse key matrix
product[0][0] = (keyMatrix[0][0]*reverseMatrix[0][0] + keyMatrix[0][1] * reverseMatrix[1][0]) % 26;
product[0][1] = (keyMatrix[0][0]*reverseMatrix[0][1] + keyMatrix[0][1] * reverseMatrix[1][1]) % 26;
product[1][0] = (keyMatrix[1][0]*reverseMatrix[0][0] + keyMatrix[1][1] * reverseMatrix[1][0]) % 26;
product[1][1] = (keyMatrix[1][0]*reverseMatrix[0][1] + keyMatrix[1][1] * reverseMatrix[1][1]) % 26;
// Check if a=1 and b=0 and c=0 and d=1
// If not, throw exception and terminate
if(product[0][0] != 1 || product[0][1] != 0 || product[1][0] != 0 || product[1][1] != 1) {
throw new java.lang.Error("Invalid reverse matrix found!");
}
}
// This method calculates the reverse key matrix
private static int[][] reverseMatrix(int[][] keyMatrix) {
int detmod26 = (keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0]) % 26; // Calc det
int factor;
int[][] reverseMatrix = new int[2][2];
// Find the factor for which is true that
// factor*det = 1 mod 26
for(factor=1; factor < 26; factor++)
{
if((detmod26 * factor) % 26 == 1)
{
break;

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

// If phrase length is not an even number, add "Q" to make it even


if(phrase.length() % 2 == 1) {
phrase += "Q";
}
// Get the 2x2 key matrix from sc
keyMatrix = getKeyMatrix();
// Check if the matrix is valid (det != 0)
isValidMatrix(keyMatrix);
// Convert characters to numbers according to their
// place in ASCII table minus 64 positions (A=65 in ASCII table)
// If we use A=0 alphabet, subtract one more (adder)
for(i=0; i < phrase.length(); i++) {
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}
// Find the product per pair of the phrase with the key matrix modulo 26
// If we use A=1 alphabet and result is 0, replace it with 26 (Z)
for(i=0; i < phraseToNum.size(); i += 2) {
int x = (keyMatrix[0][0] * phraseToNum.get(i) + keyMatrix[0][1] * phraseToNum.get(i+1)) % 26;
int y = (keyMatrix[1][0] * phraseToNum.get(i) + keyMatrix[1][1] * phraseToNum.get(i+1)) % 26;
phraseEncoded.add(alphaZero ? x : (x == 0 ? 26 : x ));
phraseEncoded.add(alphaZero ? y : (y == 0 ? 26 : y ));
}
// Print the result

Twisha Chattopadhyay
189303009
13

echoResult("Encoded phrase: ", adder, phraseEncoded);


}
// This method makes the actual decryption
public static void decrypt(String phrase, boolean alphaZero)
{
int i, adder = alphaZero ? 1 : 0;
int[][] keyMatrix, revKeyMatrix;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseDecoded = new ArrayList<>();
// Delete all non-english characters, and convert phrase to upper case
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();

// Get the 2x2 key matrix from sc


keyMatrix = getKeyMatrix();
// Check if the matrix is valid (det != 0)
isValidMatrix(keyMatrix);
// Convert numbers to characters according to their
// place in ASCII table minus 64 positions (A=65 in ASCII table)
// If we use A=0 alphabet, subtract one more (adder)
for(i=0; i < phrase.length(); i++) {
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}
// Find the reverse key matrix
revKeyMatrix = reverseMatrix(keyMatrix);
// Check if the reverse key matrix is valid (product = 1,0,0,1)
isValidReverseMatrix(keyMatrix, revKeyMatrix);
// Find the product per pair of the phrase with the reverse key matrix modulo 26
for(i=0; i < phraseToNum.size(); i += 2) {
phraseDecoded.add((revKeyMatrix[0][0] * phraseToNum.get(i) + revKeyMatrix[0][1] * phraseToNum.get(i+1))
% 26);
phraseDecoded.add((revKeyMatrix[1][0] * phraseToNum.get(i) + revKeyMatrix[1][1] * phraseToNum.get(i+1))
% 26);
}
// Print the result
echoResult("Decoded phrase: ", adder, phraseDecoded);
}
//main method
public static void main(String[] args) {
String opt, phrase;
byte[] p;
Scanner sc = new Scanner(System.in);
System.out.println("Hill Cipher Implementation (2x2)");
System.out.println("-------------------------");
System.out.println("1. Encrypt text (A=0,B=1,...Z=25)");
System.out.println("2. Decrypt text (A=0,B=1,...Z=25)");
System.out.println("3. Encrypt text (A=1,B=2,...Z=26)");
System.out.println("4. Decrypt text (A=1,B=2,...Z=26)");
System.out.println();
System.out.println("Type any other character to exit");
System.out.println();
System.out.print("Select your choice: ");
opt = sc.nextLine();
switch (opt)
{
case "1":
System.out.print("Enter phrase to encrypt: ");
phrase = sc.nextLine();

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

public static String findPos(char arr[][],char ch,char ch1)


{
String chPos="";
String ch1Pos="";
for (int i=0;i<5;i++ )
{
for(int j=0;j<5;j++)
{
if(arr[i][j]==ch)
{
chPos=chPos+i+j;
}
else if(arr[i][j]==ch1)
{
ch1Pos=ch1Pos+i+j;
}
}
}
return chPos+ch1Pos;
}
}

Twisha Chattopadhyay
189303009
17

iii)Rail Fence Cipher

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="";

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


{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}

Twisha Chattopadhyay
189303009
18

}
return cipherText;
}

String Decryption(String cipherText,int depth)throws Exception


{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;

String plainText="";

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


{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}

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;

System.out.println("Enter plain text:");


plainText=scn.nextLine();

System.out.println("Enter depth for Encryption:");


depth=scn.nextInt();

cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);

decryptedText=rf.Decryption(cipherText, depth);

System.out.println("Decrypted text is:\n"+decryptedText);

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

// Inverse Initial Permutation Table


int[] IP1 = { 40, 8, 48, 16, 56, 24, 64,
32, 39, 7, 47, 15, 55,

Twisha Chattopadhyay
189303009
20

23, 63, 31, 38, 6, 46,


14, 54, 22, 62, 30, 37,
5, 45, 13, 53, 21, 61,
29, 36, 4, 44, 12, 52,
20, 60, 28, 35, 3, 43,
11, 51, 19, 59, 27, 34,
2, 42, 10, 50, 18, 58,
26, 33, 1, 41, 9, 49,
17, 57, 25 };

// first key-hePermutation Table


int[] PC1 = { 57, 49, 41, 33, 25,
17, 9, 1, 58, 50, 42, 34, 26,
18, 10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36, 63,
55, 47, 39, 31, 23, 15, 7, 62,
54, 46, 38, 30, 22, 14, 6, 61,
53, 45, 37, 29, 21, 13, 5, 28,
20, 12, 4 };

// second key-Permutation Table


int[] PC2 = { 14, 17, 11, 24, 1, 5, 3,
28, 15, 6, 21, 10, 23, 19, 12,
4, 26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32 };

// Expansion D-box Table


int[] EP = { 32, 1, 2, 3, 4, 5, 4,
5, 6, 7, 8, 9, 8, 9, 10,
11, 12, 13, 12, 13, 14, 15,
16, 17, 16, 17, 18, 19, 20,
21, 20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29, 28,
29, 30, 31, 32, 1 };

// Straight Permutation Table


int[] P = { 16, 7, 20, 21, 29, 12, 28,
17, 1, 15, 23, 26, 5, 18,
31, 10, 2, 8, 24, 14, 32,
27, 3, 9, 19, 13, 30, 6,
22, 11, 4, 25 };

// 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 } },

{ { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 },


{ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 },
{ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 },
{ 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } },
{ { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 },
{ 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 },

Twisha Chattopadhyay
189303009
21

{ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 },


{ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } },
{ { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 },
{ 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 },
{ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 },
{ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } },
{ { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 },
{ 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 },
{ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 },
{ 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } },
{ { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 },
{ 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 },
{ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 },
{ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } },
{ { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 },
{ 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 },
{ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 },
{ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } },
{ { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 },
{ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 },
{ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 },
{ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } }
};
int[] shiftBits = { 1, 1, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 1 };

// hexadecimal to binary conversion


String hextoBin(String input)
{
int n = input.length() * 4;
input = Long.toBinaryString(
Long.parseUnsignedLong(input, 16));
while (input.length() < n)
input = "0" + input;
return input;
}

// binary to hexadecimal conversion


String binToHex(String input)
{
int n = (int)input.length() / 4;
input = Long.toHexString(
Long.parseUnsignedLong(input, 2));
while (input.length() < n)
input = "0" + input;
return input;
}

// per-mutate input hexadecimal


// according to specified sequence
String permutation(int[] sequence, String input)
{
String output = "";
input = hextoBin(input);
for (int i = 0; i < sequence.length; i++)
output += input.charAt(sequence[i] - 1);
output = binToHex(output);

Twisha Chattopadhyay
189303009
22

return output;
}

// xor 2 hexadecimal strings


String xor(String a, String b)
{
// hexadecimal to decimal(base 10)
long t_a = Long.parseUnsignedLong(a, 16);
// hexadecimal to decimal(base 10)
long t_b = Long.parseUnsignedLong(b, 16);
// xor
t_a = t_a ^ t_b;
// decimal to hexadecimal
a = Long.toHexString(t_a);
// prepend 0's to maintain length
while (a.length() < b.length())
a = "0" + a;
return a;
}

// left Circular Shifting bits


String leftCircularShift(String input, int numBits)
{
int n = input.length() * 4;
int perm[] = new int[n];
for (int i = 0; i < n - 1; i++)
perm[i] = (i + 2);
perm[n - 1] = 1;
while (numBits-- > 0)
input = permutation(perm, input);
return input;
}

// preparing 16 keys for 16 rounds


String[] getKeys(String key)
{
String keys[] = new String[16];
// first key permutation
key = permutation(PC1, key);
for (int i = 0; i < 16; i++) {
key = leftCircularShift(
key.substring(0, 7), shiftBits[i])
+ leftCircularShift(key.substring(7, 14),
shiftBits[i]);
// second key permutation
keys[i] = permutation(PC2, key);
}
return keys;
}

// 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;
}

String round(String input, String key, int num)


{
// fk
String left = input.substring(0, 8);
String temp = input.substring(8, 16);
String right = temp;
// Expansion permutation
temp = permutation(EP, temp);
// xor temp and round key
temp = xor(temp, key);
// lookup in s-box table
temp = sBox(temp);
// Straight D-box
temp = permutation(P, temp);
// xor
left = xor(left, temp);
System.out.println("Round "
+ (num + 1) + " "
+ right.toUpperCase()
+ " " + left.toUpperCase() + " "
+ key.toUpperCase());

// swapper
return right + left;
}

String encrypt(String plainText, String key)


{
int i;
// get round keys
String keys[] = getKeys(key);

// 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;
}

String decrypt(String plainText, String key)


{
int i;
// get round keys
String keys[] = getKeys(key);

// 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";

DES cipher = new DES();


System.out.println("Encryption:\n");
text = cipher.encrypt(text, key);
System.out.println(
"\nCipher Text: " + text.toUpperCase() + "\n");
System.out.println("Decryption\n");
text = cipher.decrypt(text, key);
System.out.println(
"\nPlain Text: "
+ text.toUpperCase());
}
}

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.

The key size can be 128/192/256 bits.

Encrypts data in blocks of 128 bits each.

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

private static final String SALT = "ssshhhhhhhhhhh!!!!";

// This method use to encrypt to string


public static String encrypt(String strToEncrypt)
{
try {

// Create default byte array


byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec
= new IvParameterSpec(iv);

// Create SecretKeyFactory object


SecretKeyFactory factory
= SecretKeyFactory.getInstance(
"PBKDF2WithHmacSHA256");

// Create KeySpec object and assign with


// constructor
KeySpec spec = new PBEKeySpec(
SECRET_KEY.toCharArray(), SALT.getBytes(),
65536, 256);

Twisha Chattopadhyay
189303009
27

SecretKey tmp = factory.generateSecret(spec);


SecretKeySpec secretKey = new SecretKeySpec(
tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance(


"AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey,
ivspec);
// Return encrypted string
return Base64.getEncoder().encodeToString(
cipher.doFinal(strToEncrypt.getBytes(
StandardCharsets.UTF_8)));
}
catch (Exception e) {
System.out.println("Error while encrypting: "
+ e.toString());
}
return null;
}

// This method use to decrypt to string


public static String decrypt(String strToDecrypt)
{
try {

// Default byte array


byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
// Create IvParameterSpec object and assign with
// constructor
IvParameterSpec ivspec
= new IvParameterSpec(iv);

// Create SecretKeyFactory Object


SecretKeyFactory factory
= SecretKeyFactory.getInstance(
"PBKDF2WithHmacSHA256");

// Create KeySpec object and assign with


// constructor
KeySpec spec = new PBEKeySpec(
SECRET_KEY.toCharArray(), SALT.getBytes(),
65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(
tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance(


"AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey,
ivspec);
// Return decrypted string
return new String(cipher.doFinal(
Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e) {
System.out.println("Error while decrypting: "

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

// Call encryption method


String encryptedString
= AES.encrypt(text);

// Call decryption method


String decryptedString
= AES.decrypt(encryptedString);

// Print all strings


System.out.println(text);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}

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;

public class RSA {


private final static BigInteger one = new BigInteger("1");
private final static SecureRandom random = new SecureRandom();

private BigInteger privateKey;


private BigInteger publicKey;
private BigInteger modulus;

// generate an N-bit (roughly) public and private key


RSA(int N) {
BigInteger p = BigInteger.probablePrime(N/2, random);
BigInteger q = BigInteger.probablePrime(N/2, random);
BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));

modulus = p.multiply(q);
publicKey = new BigInteger("65537"); // common value in practice =
2^16 + 1
privateKey = publicKey.modInverse(phi);
}

BigInteger encrypt(BigInteger message) {


return message.modPow(publicKey, modulus);
}

BigInteger decrypt(BigInteger encrypted) {


return encrypted.modPow(privateKey, modulus);
}

public String toString() {


String s = "";
s += "public = " + publicKey + "\n";
s += "private = " + privateKey + "\n";
s += "modulus = " + modulus;
return s;
}

public static void main(String[] args) {


int N = Integer.parseInt(args[0]);
RSA key = new RSA(N);
StdOut.println(key);

// create random message, encrypt and decrypt


BigInteger message = new BigInteger(N-1, random);

//// create message by converting string to integer


// String s = "test";
// byte[] bytes = s.getBytes();
// BigInteger message = new BigInteger(bytes);

BigInteger encrypt = key.encrypt(message);


BigInteger decrypt = key.decrypt(encrypt);

Twisha Chattopadhyay
189303009
30

StdOut.println("message = " + message);


StdOut.println("encrypted = " + encrypt);
StdOut.println("decrypted = " + decrypt);
}
}

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 key1[] = new int[8];


int key2[] = new int[8];

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

// this function basically generates the key(key1 and


//key2) using P10 and P8 with (1 and 2)left shifts

void key_generation()
{
int key_[] = new int[10];

for (int i = 0; i < 10; i++) {


key_[i] = key[P10[i] - 1];
}

int Ls[] = new int[5];


int Rs[] = new int[5];

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

Twisha Chattopadhyay
189303009
32

Ls[i] = key_[i];
Rs[i] = key_[i + 5];
}

int[] Ls_1 = shift(Ls, 1);


int[] Rs_1 = shift(Rs, 1);

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


key_[i] = Ls_1[i];
key_[i + 5] = Rs_1[i];
}

for (int i = 0; i < 8; i++) {


key1[i] = key_[P8[i] - 1];
}

int[] Ls_2 = shift(Ls, 2);


int[] Rs_2 = shift(Rs, 2);

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


key_[i] = Ls_2[i];
key_[i + 5] = Rs_2[i];
}

for (int i = 0; i < 8; i++) {


key2[i] = key_[P8[i] - 1];
}

System.out.println("Your Key-1 :");

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


System.out.print(key1[i] + " ");

System.out.println();
System.out.println("Your Key-2 :");

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


System.out.print(key2[i] + " ");
}

// this function is use full for shifting(circular) the


//array n position towards left

int[] shift(int[] ar, int n)


{
while (n > 0) {
int temp = ar[0];
for (int i = 0; i < ar.length - 1; i++) {
ar[i] = ar[i + 1];
}
ar[ar.length - 1] = temp;
n--;
}
return ar;
}

// this is main encryption function takes plain text as

Twisha Chattopadhyay
189303009
33

//input uses another functions and returns the array of


//cipher text

int[] encryption(int[] plaintext)


{
int[] arr = new int[8];

for (int i = 0; i < 8; i++) {


arr[i] = plaintext[IP[i] - 1];
}
int[] arr1 = function_(arr, key1);

int[] after_swap = swap(arr1, arr1.length / 2);

int[] arr2 = function_(after_swap, key2);

int[] ciphertext = new int[8];

for (int i = 0; i < 8; i++) {


ciphertext[i] = arr2[IP_inv[i] - 1];
}

return ciphertext;
}

// decimal to binary string 0-3

String binary_(int val)


{
if (val == 0)
return "00";
else if (val == 1)
return "01";
else if (val == 2)
return "10";
else
return "11";
}

// this function is doing core things like expansion


// then xor with desired key then S0 and S1
//substitution P4 permutation and again xor we have used
//this function 2 times(key-1 and key-2) during
//encryption and 2 times(key-2 and key-1) during
//decryption

int[] function_(int[] ar, int[] key_)


{

int[] l = new int[4];


int[] r = new int[4];

for (int i = 0; i < 4; i++) {


l[i] = ar[i];
r[i] = ar[i + 4];
}

Twisha Chattopadhyay
189303009
34

int[] ep = new int[8];

for (int i = 0; i < 8; i++) {


ep[i] = r[EP[i] - 1];
}

for (int i = 0; i < 8; i++) {


ar[i] = key_[i] ^ ep[i];
}

int[] l_1 = new int[4];


int[] r_1 = new int[4];

for (int i = 0; i < 4; i++) {


l_1[i] = ar[i];
r_1[i] = ar[i + 4];
}

int row, col, val;

row = Integer.parseInt("" + l_1[0] + l_1[3], 2);


col = Integer.parseInt("" + l_1[1] + l_1[2], 2);
val = S0[row][col];
String str_l = binary_(val);

row = Integer.parseInt("" + r_1[0] + r_1[3], 2);


col = Integer.parseInt("" + r_1[1] + r_1[2], 2);
val = S1[row][col];
String str_r = binary_(val);

int[] r_ = new int[4];


for (int i = 0; i < 2; i++) {
char c1 = str_l.charAt(i);
char c2 = str_r.charAt(i);
r_[i] = Character.getNumericValue(c1);
r_[i + 2] = Character.getNumericValue(c2);
}
int[] r_p4 = new int[4];
for (int i = 0; i < 4; i++) {
r_p4[i] = r_[P4[i] - 1];
}

for (int i = 0; i < 4; i++) {


l[i] = l[i] ^ r_p4[i];
}

int[] output = new int[8];


for (int i = 0; i < 4; i++) {
output[i] = l[i];
output[i + 4] = r[i];
}
return output;
}

// this function swaps the nibble of size n(4)

int[] swap(int[] array, int n)

Twisha Chattopadhyay
189303009
35

{
int[] l = new int[n];
int[] r = new int[n];

for (int i = 0; i < n; i++) {


l[i] = array[i];
r[i] = array[i + n];
}

int[] output = new int[2 * n];


for (int i = 0; i < n; i++) {
output[i] = r[i];
output[i + n] = l[i];
}

return output;
}

// this is main decryption function


// here we have used all previously defined function
// it takes cipher text as input and returns the array
//of decrypted text

int[] decryption(int[] ar)


{
int[] arr = new int[8];

for (int i = 0; i < 8; i++) {


arr[i] = ar[IP[i] - 1];
}

int[] arr1 = function_(arr, key2);

int[] after_swap = swap(arr1, arr1.length / 2);

int[] arr2 = function_(after_swap, key1);

int[] decrypted = new int[8];

for (int i = 0; i < 8; i++) {


decrypted[i] = arr2[IP_inv[i] - 1];
}

return decrypted;
}

public static void main(String[] args)


{

SDES obj = new SDES();


int [] plaintext = new int[8];
Scanner sc=new Scanner(System.in);
obj.key_generation();
System.out.println("Plain Text is: ");
for (int i = 0; i < 8; i++)
plaintext[i]=sc.nextInt();

Twisha Chattopadhyay
189303009
36

int[] ciphertext = obj.encryption(plaintext);

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] + " ");

int[] decrypted = obj.decryption(ciphertext);

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 {

private static SecretKeySpec secretKey;


private static byte[] key;

public static void setKey(String myKey)


{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static String encrypt(String strToEncrypt, String secret)


{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}

Twisha Chattopadhyay
189303009
38

public static String decrypt(String strToDecrypt, String secret)


{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
}

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

You might also like