0% found this document useful (0 votes)
28 views

CS Record

Uploaded by

Sanjay Blazze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

CS Record

Uploaded by

Sanjay Blazze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
NUMBER THEORY

A) Implementation of Euclidean Algorithm to find GCD between two numbers.

AIM:
To write a java program to find GCD of given two numbers using
Eucledian Algorithm.

ALGORITHM:

1) Start
2) Read two numbers
3) Recursively replace a with b and b with a%b
4) When b becomes 0 , return a as GCD
5) Stop

PROGRAM:

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

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

return gcd(b % a, a);


}

Roll Number:2127210501149 Page No.:


// Driver code
public static void main(String[] args)
{
int a = 10, b = 15, g;
g = gcd(a, b);
System.out.println("GCD(" + a + " , " + b
+ ") = " + g);
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
It is used to find prime factors of two numbers by iteratingly
reducing the problem to find gcd of 2 numbers until the reminder equals 0.

RESULT:
The Java program to implement Euclidean algorithm was executed
Successfully.

Roll Number:2127210501149 Page No.:


b) Implementation of Extended Euclid Algorithm to find Inverse Modulo.

AIM:
To write a java program to find inverse modulo using extended Euclid
algorithm.

ALGORITHM:

1) Start
2) Initialise s1,s2,t1 = 0 and t2=1
3) Recursively find the following till r2 becomes zero
q = r1/r2; r = r1%r2; t = t1-t2*q;
s = s1-s2*q; r1 = r2; r2 = r; t1 = t2; t2 = t; s1 = s2; s2 = t;
4) Call inverseModulo(r1, r2)
5) Stop.

PROGRAM:

import java.lang.*;
import java.util.*;
public class ExtendedEuclid {
static int t1 = 0,t2=1,s1 = 1,s2 =0;
static int t,q,r,s;
public static int[] inverseModulo(int r1,int r2)
{
if(r2==0) {
int a[] = {r1,t1};
return a;
}
q = r1/r2;
r = r1%r2;
t = t1-t2*q;
s = s1-s2*q;
r1 = r2;
r2 = r;
t1 = t2;

Roll Number:2127210501149 Page No.:


t2 = t;
s1 = s2;
s2 = t;
return inverseModulo(r1, r2);
}
public static void main(String[] args) {
int num=7,mod=26;
int ans = 0;
int res[] = inverseModulo(mod,num);
if(res[1]<0)
ans = mod+res[1];
System.out.println("Inverse = " + ans);
System.out.println("GCD = " + res[0]);
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
It is used to find modulo inverse of an integer and to verify the
correctness of GCD.

RESULT:
The Java program to implement Extended Euclidean algorithm was
executed successfully.

Roll Number:2127210501149 Page No.:


D) Implementation of Miller and Rabin’s algorithm for primality check

AIM:
To write a java program to find to implement Miller and Rabin’s
algorithm for primality check.

ALGORITHM:

1) Start
2) Miller-Rabin-Test (n, a) // n is the number; a is the base
{
Find m and k such that n − 1 = m x 2k
T ← am mod n
If (T = ±1)return "a prime"
for (i ← 1 to k − 1) // k – 1 is the maximum number of steps
{
T ← T2 mod n
if (T = ±1) return "a composite"
if (T = −1) return "a prime"
}
return "a composite"
}
3) Stop

PROGRAM:

import java.util.*;
public class Main {
static ArrayList<Integer> l = new ArrayList<>();
public static int findFactors(int n)
{
int t = n;
while(n%2==0)
{
l.add(2);
n = n/2;
}

Roll Number:2127210501149 Page No.:


int k = t/(int)Math.pow(2, l.size());
return k;
}
public static boolean checkPrime(int x)
{
if(x%2==0 && x!=2)
{
return false;
}
else {
int n = x-1; //mod
int k = findFactors(n);
long T = (long)Math.pow(2, k)%x;
if(T==1 || x-T==1)
{
return true;
}
else {
for(int i=1;i<=l.size();i++)
{
T = (long)Math.pow(T, 2)%x;
if(x-T==1)return true; //-52 mod 53
if(T==1)
return false;
}
}
}
return false;
}
public static void main(String[] args) {
Scanner o=new Scanner(System.in);
System.out.println("\nEnter a number:");

int x = o.nextInt();
if(checkPrime(x))
System.out.println("Prime");
else
System.out.println("Composite");
}
}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
It is a method to find and prove whether the given number is
prime or not.

RESULT:
The Java program to implement Extended Euclidean algorithm was
executed successfully.

Roll Number:2127210501149 Page No.:


C) Implementation of Euler Totient function.

AIM:
To write a java program to implement Euler Totient Function.

ALGORITHM:

1) Start
2) Factorize the number
3) Perform p^c – p^(c-1) Where p is factor and c is its count
4) return sum*= p^c – p^(c-1) as output
5) Stop

PROGRAM:

import java.io.*;

class Main {

// Function to return GCD of a and b


static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// A simple method to evaluate


// Euler Totient Function
static int phi(int n)
{
int result = 1;
for (int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}

Roll Number:2127210501149 Page No.:


// Driver code
public static void main(String[] args)
{
int n=7;
System.out.println("phi(" + n + ") = " + phi(n));
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
Euler Totient function phi(n) returns integer from one to n that
are relatively prime to n.

RESULT:
The Java program to implement Euler Totient function was
executed successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
SUBSTITUTIONS CIPHER

A) Implementation of Caesar Cipher

AIM:
To write a java program to implement Caesar Cipher.

ALGORITHM:

1) Start
2) Read the message and shift value (say 3)
3) Encyrption: For every character , corresponding cipher character is 3 positions
ahead
4) Decyrption: For every character , corresponding plain text character is 3
positions behind
5) Stop

PROGRAM:

class Main
{
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
{

Roll Number:2127210501149 Page No.:


char ch = (char)(((int)text.charAt(i) +
s - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}
public static void main(String[] args)
{
String text = "WELCOME";
int s = 3;
System.out.println("Text : " + text);
System.out.println("Shift : " + s);
System.out.println("Cipher: " + encrypt(text, s));
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
Caesar Cipher is a substitution method where each letter in plain text is
shifted to certain number of places down or up the alphabet.

RESULT:
The Java program to implement Caesar Cipher was executed
successfully.

Roll Number:2127210501149 Page No.:


B) Implementation of Playfair Cipher.

AIM:
To write a java program to implement Playfair Cipher.

ALGORITHM:

1) Start
2) Input the message and key from user, replace ‘J’ with ‘Z’ wherever present.
3) Form a 5x5 matrix, populate the matrix first with unique characters from key.
4) Fill the rest of the cells with alphabetical order of characters except J.
5) Using the matrix & map, get the corresponding character for each pair of
characters in message.
6) Return the encrypted string
7) Stop.

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)


{
// convert all the characters to lowercase
this.key = key.toLowerCase();

this.plainText = plainText.toLowerCase();
}
public void cleanPlayFairKey()
{
LinkedHashSet<Character> set
= new LinkedHashSet<Character>();

Roll Number:2127210501149 Page No.:


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;
}
public 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));
}
String 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;
}
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]));

public String formatPlainText()


{
String message = "";

Roll Number:2127210501149 Page No.:


int len = plainText.length();

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


{
if (plainText.charAt(i) == 'j')
message += 'i';
else
message += plainText.charAt(i);
}
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);
}

if (len % 2 == 1)
message += 'x'; // dummy character

return message;
}

// function to group every two characters


public 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 table


public int[] getCharPos(char ch)
{
int[] keyPos = new int[2];

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


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

Roll Number:2127210501149 Page No.:


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


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


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

// if both the characters are in the same column


else 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 columns
else {
int temp = ch1Pos[1];
ch1Pos[1] = ch2Pos[1];
ch2Pos[1] = temp;
}

Roll Number:2127210501149 Page No.:


// 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 Main {


public static void main(String[] args)
{
System.out.println("Example-1\n");

String key1 = "Problem";


String plainText1 = "Playfair";

System.out.println("Key: " + key1);


System.out.println("PlainText: " + plainText1);

Playfair pfc1 = new Playfair(key1, plainText1);


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

String encText1 = pfc1.encryptMessage();


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

}
}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
Play Phar Cipher is a digraph substitution cipher where each
pair of letters in plain text are mapped to each pair of letters in Cipher text based on
5x5 grid.

RESULT:
The Java program to implement Playfair Cipher was executed
successfully.

Roll Number:2127210501149 Page No.:


C) Implementation of Hill Cipher .

AIM:
To write a java program to find to implement Hill Cipher.

ALGORITHM:

1) Start
2) Choose an n * n invertible key matrix K .
3) Convert plaintext letters to numerical values (A=0, B=1, ..., Z=25).
4) Split numerical plaintext into vectors of size n .
5) Multiply each plaintext vector P by the key matrix K , using C = (K * P)mod
26.
6) Convert the resulting numerical values back to letters to get the ciphertext.
7) Stop.

PROGRAM:

class Main
{
static void getKeyMatrix(String key, int keyMatrix[][])
{
int k = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
keyMatrix[i][j] = (key.charAt(k)) % 65;
k++;
}
}
}

static void encrypt(int cipherMatrix[][],


int keyMatrix[][],
int messageVector[][])
{
int x, i, j;
for (i = 0; i < 3; i++)

Roll Number:2127210501149 Page No.:


{
for (j = 0; j < 1; j++)
{
cipherMatrix[i][j] = 0;

for (x = 0; x < 3; x++)


{
cipherMatrix[i][j] +=
keyMatrix[i][x] * messageVector[x][j];
}

cipherMatrix[i][j] = cipherMatrix[i][j] % 26;


}
}
}
static void HillCipher(String message, String key)
{
int [][]keyMatrix = new int[3][3];
getKeyMatrix(key, keyMatrix);

int [][]messageVector = new int[3][1];

// Generate vector for the message


for (int i = 0; i < 3; i++)
messageVector[i][0] = (message.charAt(i)) % 65;

int [][]cipherMatrix = new int[3][1];

encrypt(cipherMatrix, keyMatrix, messageVector);

String CipherText="";

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


CipherText += (char)(cipherMatrix[i][0] + 65);

// Finally print the ciphertext


System.out.print(" Ciphertext:" + CipherText);
}

public static void main(String[] args)


{
// Get the message to be encrypted
String message = "ACT";

Roll Number:2127210501149 Page No.:


// Get the key
String key = "GYBNQKURP";

System.out.println("Message = "+ message);


System.out.println("Key = "+ key);

HillCipher(message, key);
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
Hill cipher is a polygraphic substitution cipher based on linear
algebra. In encryption, each block is multiplied by invertible matrix and to decrypt
each block is multiplied by inverse of matrix used for decryption.

RESULT:
The Java program to implement Hill Cipher was executed
successfully.

Roll Number:2127210501149 Page No.:


D) Implementation of Vigenere Cipher.

AIM:
To write a java program to implement Vigenere Cipher .

ALGORITHM:

1) Start
2) Read the Plain Text and key from user .
3) Repeat key until it equals plain text length .
4) Encryption : (P+K) % 26 .
5) Decryption : (C-K)%26
6) Stop.

PROGRAM:

class Main
{
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 cipherText(String str, String key)
{
String cipher_text="";

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


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

Roll Number:2127210501149 Page No.:


// convert into alphabets(ASCII)
x += 'A';

cipher_text+=(char)(x);
}
return cipher_text;
}
static String originalText(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;

// convert into alphabets(ASCII)


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

// This function will convert the lower case character to Upper case
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;
}

public static void main(String[] args)


{
String Str = "WELCOME";
String Keyword = "HI";

Roll Number:2127210501149 Page No.:


String str = LowerToUpper(Str);
String keyword = LowerToUpper(Keyword);

String key = generateKey(str, keyword);


String cipher_text = cipherText(str, key);
System.out.println("Message ="+ str);

System.out.println("Ciphertext : "
+ cipher_text + "\n");

System.out.println("Original/Decrypted Text : "


+ originalText(cipher_text, key));
}
}

SAMPLE INPUT AND OUTPUT:

INFERENCE:
A poly alphabetic substitution of encrypting alphabets by using
keywords to shift the letters in plain text cyclically.

RESULT:
The Java program to implement Vigenere Cipher was executed
successfully.

Roll Number:2127210501149 Page No.:


E) Implementation of one time pad algorithm.

AIM:
To write a java program to implement One Time Pad Algorithm.

ALGORITHM:

1) Start.
2) Get the message.
3) Generate a key randomly that corresponds to the message size.
4) For Encryption, traverse each character, transform them by moving up the
key positions, and round off if necessary.
5) For Decryption, traverse each character, transform them by moving down
the key positions, and round off if necessary.
6) Stop.

PROGRAM:

import java.io.*;
public class Main {
public static String stringEncryption(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;
}
}
for (int i = 0; i < key.length(); i++) {
int x = cipher[i] + 'A';
cipherText += (char)x;

Roll Number:2127210501149 Page No.:


}
return cipherText;
}
public static String stringDecryption(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)
{
// Declaring plain text
String plainText = "Hello";
String key = "MONEY";

String encryptedText = stringEncryption(


plainText.toUpperCase(), key.toUpperCase());

System.out.println( "Message - "+ stringDecryption(encryptedText,


key.toUpperCase()));

System.out.println("Cipher Text - " + encryptedText);


}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
One time pad provides perfect secrecy, where each bit or character
in plain text is XOR with corresponding key of same length The key used only once
and need not be repeated.

RESULT:
The Java program to implement One Time Pad (OTP) Algorithm
was executed successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
TRANSPOSITIONAL CIPHERS

A) Implementation of Rail fence using c/c++/Java.

AIM:
To implement the Rail fence using Java.

ALGORITHM:

1) Start.
2) Read the String
3) Encryption
For rail value = 2
Rail 1 : Even Position
Rail 2 : Odd Position Concatenate to get Cipher Text
4) Decryption
If even length
val = Math.ceil(ct.length()/depth)
len = ct.length()-1
i = (i+val)%len

If odd length
val = Math.ceil(ct.length()/depth)
len = ct.length()
i = (i+val)%len
5) Stop.

Roll Number:2127210501149 Page No.:


PROGRAM:

import java.util.Arrays;
class Main {
public static String encryptRailFence(String text,int key)
{

char[][] rail = new char[key][text.length()];

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


Arrays.fill(rail[i], '\n');

boolean dirDown = false;


int row = 0, col = 0;

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

if (row == 0 || row == key - 1)


dirDown = !dirDown;

// fill the corresponding alphabet


rail[row][col++] = text.charAt(i);

// find the next row using direction flag


if (dirDown)
row++;
else
row--;
}

StringBuilder result = new StringBuilder();


for (int i = 0; i < key; i++)
for (int j = 0; j < text.length(); j++)
if (rail[i][j] != '\n')
result.append(rail[i][j]);

return result.toString();
}
public static String decryptRailFence(String cipher,int key)
{

Roll Number:2127210501149 Page No.:


// create the matrix to cipher plain text
// key = rows , length(text) = columns
char[][] rail = new char[key][cipher.length()];

// filling the rail matrix to distinguish filled


// spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');

// to find the direction


boolean dirDown = true;

int row = 0, col = 0;

// mark the places with '*'


for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

// place the marker


rail[row][col++] = '*';

// find the next row using direction flag


if (dirDown)
row++;
else
row--;
}

// now we can construct the fill the rail matrix


int index = 0;
for (int i = 0; i < key; i++)
for (int j = 0; j < cipher.length(); j++)
if (rail[i][j] == '*'
&& index < cipher.length())
rail[i][j] = cipher.charAt(index++);

StringBuilder result = new StringBuilder();

row = 0;
col = 0;

Roll Number:2127210501149 Page No.:


for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;

// place the marker


if (rail[row][col] != '*')
result.append(rail[row][col++]);

// find the next row using direction flag


if (dirDown)
row++;
else
row--;
}

return result.toString();
}

// driver program to check the above functions


public static void main(String[] args)
{

// Encryption
String s="welcome";
System.out.println("Message = "+s);
System.out.println("Cipher Text: ");
System.out.println(encryptRailFence(s, 2));

}
}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:

Railfence Cipher is a form of transpositional Cypher, where plaintexts


written diagonally in a zigzag pattern across multiple rails, and then read of
horizontally to create the ciphertext. To decode ,the zigzag pattern is
reconstructed and read character in original order.

RESULT:
Thus the Java program to implement Rail Fence Cipher was
executed successfully.

Roll Number:2127210501149 Page No.:


B) Implementation of row & Column Transformation cipher using c/c++/Java.

AIM:
To implement the Row-Column Transformation Cipher using Java.

ALGORITHM:

1) Start.
2) Read string and key
3) No of columns = key size
4) Store Plain text in Row wise
5) Read Plain text in column wise depends on key gives Cipher Text
6) Create another matrix to store cipher text characters based on key
7) Read Cipher Text Characters column wise gives Plain Text back
8) Stop.

PROGRAM:

import java.util.*;

public class Main {


// Key for Columnar Transposition
static final String key = "HACK";
static Map<Character, Integer> keyMap = new HashMap<>();

static void setPermutationOrder() {


// Add the permutation order into the map
for (int i = 0; i < key.length(); i++) {
keyMap.put(key.charAt(i), i);
}
}

static String encryptMessage(String msg) {


int row, col;
StringBuilder cipher = new StringBuilder();

col = key.length();

Roll Number:2127210501149 Page No.:


row = (int) Math.ceil((double) msg.length() / col);

char[][] matrix = new char[row][col];

for (int i = 0, k = 0; i < row; i++) {


for (int j = 0; j < col; ) {
if (k < msg.length()) {
char ch = msg.charAt(k);
if (Character.isLetter(ch) || ch == ' ') {
matrix[i][j] = ch;
j++;
}
k++;
} else {
/* Add padding character '_' */
matrix[i][j] = '_';
j++;
}
}
}

for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) {


int columnIndex = entry.getValue();
for (int i = 0; i < row; i++) {
if (Character.isLetter(matrix[i][columnIndex]) || matrix[i][columnIndex] == '
' || matrix[i][columnIndex] == '_') {
cipher.append(matrix[i][columnIndex]);
}
}
}

return cipher.toString();
}

static String decryptMessage(String cipher) {

int col = key.length();

int row = (int) Math.ceil((double) cipher.length() / col);


char[][] cipherMat = new char[row][col];
int k = 0;
for (int j = 0; j < col; j++) {
for (int i = 0; i < row; i++) {
cipherMat[i][j] = cipher.charAt(k);

Roll Number:2127210501149 Page No.:


k++;
}
}

int index = 0;
for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) {
entry.setValue(index++);
}

char[][] decCipher = new char[row][col];


for (int l = 0; l < key.length(); l++) {
int columnIndex = keyMap.get(key.charAt(l));
for (int i = 0; i < row; i++) {
decCipher[i][l] = cipherMat[i][columnIndex];
}
}

StringBuilder msg = new StringBuilder();


for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (decCipher[i][j] != '_') {
msg.append(decCipher[i][j]);
}
}
}

return msg.toString();
}

public static void main(String[] args) {


String msg = "Geeks for Geeks";
setPermutationOrder();
System.out.println("MESSAGE : " +msg);
String cipher = encryptMessage(msg);
System.out.println("Encrypted : " + cipher);
System.out.println("Decrypted : " + decryptMessage(cipher));
}
}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
The row column transformation rearranges the character of plain
text by writing into a grid of specified dimension, then reading the column in
particular order to form the cipher text. Decoding involves the reconstruction of with
and reading the rows to give the original message.

RESULT:
Thus the Java program to implement row column transformation
was executed successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
S-DES ALGORITHM

Implementation of SDES Algorithm using c/c++/Java.

AIM:
To implement the S-DES Algorithm using Java.

ALGORITHM:

1) Start.
2) Key Generation
Generate two sub keys for rounds using the 10 bit master key
3) Encryption
* The 8 bit Plain Text is converted into 8 bit Cipher Text in Two rounds
* Apply Initial Permutation
* In Round Function , use of Expansion Permutation (EP) , Sbox , P4
which processes PT
* Apply Inverse Initial Permutation

4) Decryption
* The 8 bit CipherText is converted into 8 bit PlainText in Two rounds
* It is same as Encryption , only difference is keys are interchanged in
rounds
5) Stop.

Roll Number:2127210501149 Page No.:


PROGRAM:

import java.io.*;
public class Main {
// 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 } };

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


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

Roll Number:2127210501149 Page No.:


}

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

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


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

Roll Number:2127210501149 Page No.:


ar[i] = ar[i + 1];
}
ar[ar.length - 1] = temp;
n--;
}
return ar;
}

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

Roll Number:2127210501149 Page No.:


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

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

Roll Number:2127210501149 Page No.:


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

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


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

int[] decryption(int[] ar)


{

Roll Number:2127210501149 Page No.:


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)


{

Main obj = new Main();

obj.key_generation(); // call to key generation


// function

// int []plaintext= {1,0,1,0,0,1,0,1};


int[] plaintext = {
1, 0, 0, 1, 0, 1, 1, 1
}; // extra example for checking purpose

System.out.println();
System.out.println("Your plain Text is :");
for (int i = 0; i < 8; i++) // printing the
// plaintext
System.out.print(plaintext[i] + " ");

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

System.out.println();
System.out.println(

Roll Number:2127210501149 Page No.:


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

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
In S-DES Algorithm, a random key is used to encrypt plain text
into ciphertext using symmetric encryption ensures security during transmission of
data by using same key to decrypt ciphertext back, it provides the original data only
authorised users access the data.

RESULT:
Thus, the Java program to implement sdes algorithm was executed
successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
RSA ALGORITHM

Implementation of RSA Algorithm using c/c++/Java

AIM:
To implement the RSA Algorithm using Java.

ALGORITHM:

1) Start
2) Read two very large prime numbers (p,q)
3) Calculate n = p * q .
4) Calculate the Euler Totient Function as phi = (p-1)*(q-1)
5) Calculate the public key e such that it is co-prime to phi(n) and private key d
such that e*d mod phi(n) = 1
6) Cipher Text , C = P^e(mod n) .
7) Plain Text , P = C^d(mod n).
8) Stop.

PROGRAM:

import java.math.*;
import java.util.*;

class Main {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;

int msg = 12;


double c;
BigInteger msgback;

p = 3;

Roll Number:2127210501149 Page No.:


q = 11;
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);

for (e = 2; e < z; e++) {


// e is for public key exponent
if (gcd(e, z) == 1) {
break;
}
}
System.out.println("the value of e = " + e);
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);
// d is for private key exponent
if (x % e == 0) {
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
System.out.println("Encrypted message is : " + 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("Decrypted message is : "
+ msgback);
}

static int gcd(int e, int z)


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

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
The RSA Algorithm encrypts and decrypts data using a pair of keys
derived from very large prime numbers. The security relies on the difficulty of
factoring the product of this prime numbers.

RESULT:
Thus the Java program to implement RSA algorithm was executed
successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
DIFFIEE-HELLMAN EXCHANGE ALGORITHM

Implementation of Diffiee-Hellman Exchange Algorithm.

AIM:
To implement Diffiee-Hellman Exchange Algorithm using Java.

ALGORITHM:

1) Start
2) Choose prime number (p) and its primitive root (alpha)
3) Read Private Key of A
4) Calculate Public Key of A using Math.pow(alpha, privateA))% p
5) Read Private Key of B
6) Calculate Public Key of B using Math.pow(alpha, privateB)% p
7) Generate key at User A Math.pow(publicB, privateA)%p
8) Generate key at User B Math.pow(publicA, privateB)%p
9) Stop

PROGRAM:

import java.math.BigInteger;
import java.util.*;
public class Main
{
public static BigInteger findPrimitiveRoot(BigInteger p) {
ArrayList<BigInteger> list = new ArrayList<>();
for (BigInteger i= BigInteger.valueOf(2); i.compareTo(p) < 0;
i=i.add(BigInteger.ONE))
{
boolean isPrimitiveRoot = true;
for (BigInteger j = BigInteger.ONE; j.compareTo(p.subtract(BigInteger.ONE)) <= 0; j
= j.add(BigInteger.ONE))

Roll Number:2127210501149 Page No.:


{
BigInteger mod = i.modPow(j, p);
if (list.contains(mod)) {
isPrimitiveRoot = false;
break;
}
list.add(mod);
}
if (isPrimitiveRoot) {
BigInteger n = p.subtract(BigInteger.ONE); //int n = p-1
BigInteger sum = n.multiply(n.add(BigInteger.ONE)).divide(BigInteger.valueOf(2));
BigInteger ls = BigInteger.ZERO;
for (BigInteger ele : list) {
ls = ls.add(ele);
}
if (ls.equals(sum)) {
return i;
}
}
list.clear();
}
return BigInteger.valueOf(-1);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Prime Number");
int p = sc.nextInt();
BigInteger prim = findPrimitiveRoot(BigInteger.valueOf(p));
int alpha = prim.intValue();
System.out.println("Enter Private Key for User - A");
int priA = sc.nextInt();
int pubA = ((int)Math.pow(alpha, priA))% p;
System.out.println("Enter Private Key for User - B");
int priB = sc.nextInt();
int pubB = ((int)Math.pow(alpha, priB))% p;
int keyA = ((int)Math.pow(pubB, priA))%p;
int keyB = ((int)Math.pow(pubA, priB))%p;
System.out.println("Keys = " + keyA + ":" + keyB);
}
}

Roll Number:2127210501149 Page No.:


SAMPLE INPUT AND OUTPUT:

INFERENCE:
In Diffiee-Hellman algorithm even if an attacker intercepts the
public key, they cannot easily derive the shared secret key due to the complexity of
computing discrete logarithms.

RESULT:
Thus the java program to implement Diffiee-Hellman was executed
successfully.

Roll Number:2127210501149 Page No.:


CS18713 – SECURITY PRACTICES LABORATORY

EX.NO:
DATE:
ELGAMAL DIGITAL SIGNATURE

AIM:
To implement Elgamal digital signature algorithm using Java.

ALGORITHM:

1) Start.
2) Select a Prime number (q) and find its primitive root
3) Generate random integer Xa (1,q-1)
4) Calculate Ya = (primitive_root)^Xa mod q
5) Generate hash code for message m [1,q-1]
6) Generate random k [1,q-1] and gcd(k,q-1)=1
7) Create Signatures
S1 = (primitive_root)^Xa mod q
S2 = K-1(m-XaS1) mod q-1
8) Verify Signatures
V1 = (primitive_root)^m mod q
V2 = (Ya)^S1 (S1)^S2 mod q *
9) If V1==V2 means , Signature is Valid
10) Stop.

Roll Number:2127210501149 Page No.:


PROGRAM:

import java.math.BigInteger;
import java.util.*;
public class Main {
public static BigInteger findPrimitiveRoot(BigInteger p) {
ArrayList<BigInteger> list = new ArrayList<>();
for (BigInteger i = BigInteger.valueOf(2); i.compareTo(p) < 0; i =
i.add(BigInteger.ONE))
{
boolean isPrimitiveRoot = true;
for (BigInteger j = BigInteger.ONE; j.compareTo(p.subtract(BigInteger.ONE)) <= 0; j
=
j.add(BigInteger.ONE)) {
BigInteger mod = i.modPow(j, p);
if (list.contains(mod)) {
isPrimitiveRoot = false;
break;
}
list.add(mod);
}
if (isPrimitiveRoot) {
BigInteger n = p.subtract(BigInteger.ONE); //int n = p-1
BigInteger sum = n.multiply(n.add(BigInteger.ONE)).divide(BigInteger.valueOf(2));
BigInteger ls = BigInteger.ZERO;
for (BigInteger ele : list) {
ls = ls.add(ele);
}
if (ls.equals(sum)) {
return i;
}
}
list.clear();
}
return BigInteger.valueOf(-1);
}
static int t1 = 0,t2=1;
static int t,q,r;
public static int inverseModulo(int r1,int r2)
{
if(r2==0)
return t1;

Roll Number:2127210501149 Page No.:


q = r1/r2;
r = r1%r2;
t = t1-t2*q;
r1 = r2;
r2 = r;
t1 = t2;
t2 = t;
return inverseModulo(r1, r2);
}
public static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any prime number");
int p = sc.nextInt();
BigInteger prim = findPrimitiveRoot(BigInteger.valueOf(p));
int alpha = prim.intValue();
System.out.println("Its primitive root = " + alpha);
System.out.println("Select Private key (1,q-1)");
int Xa = sc.nextInt();
long Ya = ((long)Math.pow(alpha, Xa))%p;
System.out.println("Enter hash [0,q-1]");
int m = sc.nextInt();
System.out.println("Choose Random Integer k - [0,q-1] & gcd(k,q-1)=1");
int answer = 0;
int k = 0;
while(answer!=1)
{
System.out.println("Enter Value of K");
k = sc.nextInt();
answer = gcd(p-1, k);
}
int kinv = inverseModulo(p-1,k);
if(kinv<0)
kinv = (p-1)+kinv;
long s1 = ((long)Math.pow(alpha, k))% p;
long temp = kinv*(m-Xa*s1);
long s2 = temp%(p-1);
if(s2<0)

Roll Number:2127210501149 Page No.:


s2 = s2+(p-1);
System.out.println("Signatures = " + s1 + ":" + s2);
long v1 = ((long)Math.pow(alpha, m))% p;
long v2 = (((long)Math.pow(Ya, s1))*((long)Math.pow(s1, s2)))% p;
System.out.println(v1+":"+v2);
sc.close();
}
}

SAMPLE INPUT AND OUTPUT:

Enter any prime number : 17


Select Private key (1,q-1) : 12
Enter hash [0,q-1] : 13
Choose Random Integer k - [0,q-1] & gcd(k,q-1)=1
Enter Value of K : 3
Signatures = 10:7
12:12

INFERENCE:
ElGamal digital signature is a cryptographic algorithm based on
the ElGamal encryption scheme, relying on the difficulty of solving discrete
logarithms. It involves signing a message using a private key and verifying the
signature with a corresponding public key.Thus the security of the signature relies on
the difficulty of solving the discrete logarithm problem within finite fields.

RESULT:
Thus the java program to implement Elgamal digital signature
algorithm was executed successfully.

Roll Number:2127210501149 Page No.:

You might also like