Nothing Special   »   [go: up one dir, main page]

Mca Cns Record

Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

1

Jawaharlal Nehru Technological University, Kakinada


University College of Engineering
Vizianagaram
Department Of Information Technology

MCA V SEMESTER
CRYPTOGRAPHY AND NETWORK
SECURITY LAB MANUAL

PREPARED BY
Mr W.ANIL
B.Tech, M.Tech(PhD)
Assistant Professor in IT
2

System Spefications

Operating system : Windows / Linux

Softwares / Compilers : Dev C, C++, Java, Putty, Vi Editor

Processor Intel(R) Core(TM) : Memory 4GB RAM

Prerequisites : JAVA Programming,C,C++


3

MCA V Semester
Cryptography and Network Security Lab
(Lab Manual)
R19
Course Objectives:
➢ To learn basic understanding of cryptography, how it has evolved, and some key encryption

techniques used today.

➢ To understand and implement encryption and decryption using Ceaser Cipher, Substitution

Cipher, Hill Cipher.

Course Outcomes: At the end of the course, student will be able to


➢ Apply the knowledge of symmetric cryptography to implement encryption and decryption

using Ceaser Cipher, Substitution Cipher, Hill Cipher

➢ Demonstrate the different algorithms like DES, BlowFish, and Rijndael, encrypt the text

“Hello world” using Blowfish Algorithm.

➢ Analyze and implement public key algorithms like RSA, Diffie-Hellman Key Exchange

mechanism, the message digest of a text using the SHA-1


algorithm
4

INDEX

S.NO DATE EXPERIMENT P.NO MARKS

1. A. Program to perform XOR operator with 0 and with 1-4


string “HELLO WORLD” .
B. Program to perform AND , XOR operator with 127 and
with string “HELLO WORLD”.

2. Program to encrypt message PAY using Hill cipher with plain 5


17 17 5
text K=21
18 21
2 2 19
3. A. Java program to perform encryption and decryption using 6-59
following algorithms
A. Ceaser cipher B. Substitution cipher
B. Hill cipher.
B.Program to implement Ceaser cipher.
C. Program to Affine cipher with equation c=3x+12.
D. Program to implement Playfair cipher.
E. Program to implement Polyalphabetic cipher.
F. Program to implement Autokey cipher.
G. Program to implement Hill cipher.
H. Program to implement Rail fence technique.
I. Program to implement simple columnar
Transposition technique.
J. Program to implement Advanced columnar
Transposition technique.

4. A. Program to implement DES algorithm. 60-67


B. Program to implement Blowfish algorithm.

5. A. Program to implement Rijndael algorithm. 68-73


B. RC4 logic to encrypt the text “HELLO
WORLD” using
Blowfish
5

6. A. Program to implement Euclidean algorithm. 74-77


B. Program to implement Advanced Euclidean algorithm.
A. Program to implement RSA algorithm.
B. Program to implement Diffie key exchange algorithm.

7. A. calculate the message digest a text using SHA-1 algorithm. 78-89


B. calculate the message digest a text using MDS algorithm.
1

WEEK-1
AIM: Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should XOR each character in this string with 0 and display the
result.
Description: Here, we have two variables, str is a string variable and ptr is a character
pointer, that will point to the string variable str. First of all, we are reading string in
str and then assigning the base address of str to the character pointer ptr by using
ptr=str or it can also be done by using ptr=&str[0].And, finally we are printing the
string character by character until NULL not found. Characters are printing by the
pointer *ptr.

PROGRAM:

#include<stdlib.h>

main() { char

str[]="Hello World";

char str1[11]; int i,len;

len=strlen(str);

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

str1[i]=str[i]^0;

printf("%c",str1[i]);

printf("\n");

}
2

Output:
3

AIM: Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should AND or and XOR each character in this string with 127
and display the result.

Description: Here, we have two variables, str is a string variable and ptr is a character
pointer, that will point to the string variable str. First of all, we are reading string in
str and then assigning the base address of str to the character pointer ptr
ptr = &str[0]
by using ptr=str or it can also be done by using.And, finally we are
printing the string character by character until NULL not found. Characters are
printing by the pointer *ptr.

PROGRAM

#include <stdio.h>

#include<stdlib.h>

void main() { char

str[]="Hello World";

char str1[11]; char

str2[11]=str[]; int

i,len; len = strlen(str);

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

str1[i]=str[i]&127;

printf("%c",str1[i]); }
4

printf("\n");

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

){

str3[i]=str2[i]^127;

printf("%c",str3[i]);

printf("\n");

Output:
5

WEEK-2:
Aim: Encrypt the message “PAY” using hillcipher with the following keymatrix and
show
17 17 5
the decryption to formulate original
plaintext K=21 18 21
2 2 19
Description:
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.

The matrix used for encryption is the cipher key, and it should be chosen randomly
from the set of invertible n × n matrices (modulo

1 11 12 13 1 26).
2 = 21 22 23 2
mod26
3 31 32 33 3

17 17 5
Given, K =21 18 21
2 2 19
Encryption:
The first three letters “PAY” of the plaintext are
17 17 5 21 15 375 represented by the vector
18 21 0 = 819
mod26
2 2 19 24 486
11
= 13 = LNS
18

Decryption:
P = K⁻ⁱC mod26
4 9 15
K⁻ⁱ = 15 17 6
24 0 17
6

11
C = 13
18
4 9 15 11
P = 15 17 6 13 mod26
24 0 17 18
431 15
= 494 mod26 = 0
570 24
WEEK-3
Aim: Write a C/JAVA program to perform encryption an decryption using

following algorithms Ceaser Cipher

Description:

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.

The encryption can be represented using modular arithmetic by first transforming the
letters into numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of
a letter by a shift n can be described mathematically as.

E_n(x)=(x+n)mod\ 26 (Encryption Phase with shift n)


D_n(x)=(x-n)mod\ 26 (Decryption Phase with shift n)
TEST CASE:
Test Case Functionalit Test Data Expected Observed Positive/Nega
y tive

TC1 Encryption Plaintext – Cipher text – Cipher text – Positive


And AFFINE UBBAHK UBBAHK
Decryption CIPHER CAPJKX CAPJKX
Plaintext – Plaintext –
AFFINE AFFINE
CIPHER CIPHER
Program:

class CaesarCipher { public static StringBuffer

encrypt(String text, int shift) { StringBuffer result

= new StringBuffer(); for (int i = 0; i <


7

text.length(); i++) { if

(Character.isUpperCase(text.charAt(i))) {

char ch = (char) (((int) text.charAt(i) +

shift - 65) % 26 + 65);

result.append(ch); } else { char ch

= (char) (((int) text.charAt(i) +

shift - 97) % 26 + 97);

result.append(ch);

return result; } public static StringBuffer

decrypt(String cipher, int shift) { StringBuffer result

= new StringBuffer(); for (int i = 0; i <

cipher.length(); i++) { if

(Character.isUpperCase(cipher.charAt(i))) { char ch

= (char) (((int) cipher.charAt(i) + shift - 65) % 26 +

65);

result.append(ch); } else { char ch =

(char) (((int) cipher.charAt(i) + shift

- 97) % 26 + 97);

result.append(ch);

}
8

return result; } public static void

main(String[] args) {

String originalText =

"ATTACKATONCE"; int shiftCount = 1;

System.out.println("Caesar Cipher Example");

System.out.println("Encryption");

System.out.println("Text : " + originalText);

System.out.println("Shift : " + shiftCount);

String cipher = encrypt(originalText, shiftCount).toString();

System.out.println("Encrypted Cipher: " + cipher);

System.out.println("Decryption");

System.out.println("Encrypted Cipher: " + cipher);

System.out.println("Shift : " + shiftCount);

String decryptedPlainText = decrypt(cipher, 26 - shiftCount).toString();

System.out.println("Decrypted Plain Text : " + decryptedPlainText);

}}

Output:

Substitution Cipher
9

Description:

In a Substitution cipher, any character of plain text from the given fixed set of
characters is substituted by some other character from the same set depending on a
key. For example with a shift of 1, A would be replaced by B, B would become C,
and so on.

Special case of Substitution cipher is known as Caesar cipher where the key is taken
as 3.

TEST CASE:
Test Case Functionality Test Data Expected Observed Positive/Negative
TC1 Encryption Plaintext – Ciphertext- Ciphertext- Positive
And WORLD ASVPH ASVPH
Decryption Key – 4 Plaintext- Plaintext-
WORLD WORLD
Program:

import java.util.*;

class Sub{

public static void main

(String[]args) {

Scanner s=new

Scanner(System.in); String s1;

char arr[],arr_2[];

System.out.println("Enter the encrypted

text:"); s1=s.nextLine(); int

i,j=0,counter=0; arr=s1.toCharArray();

arr_2=new char[arr.length];

for(i=0;i<arr.length;i++)
10

{
int value=(int)arr[i]; if(value<65 ||

(value>90 && value<97)){

if(value==32) arr_2[j++]=' '; else

continue; } else{ value=value-7;

if(value<97 && value>89)

value=value+26; if(value<65)

value=value+26;

arr_2[j++]=(char)val

ue; counter=1; } }

if(counter!=1){

System.out.println("No hidden message");

System.exit(0);

System.out.println("Decrypted text:");

for(i=0;i<arr_2.length;i++){ System.out.print(arr_2[i]);

}
11

Output:

Hill Cipher

Description:

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.The matrix used for
encryption is the cipher key, and it should be chosen randomly from the set of
invertible n × n matrices (modulo 26).

TEST CASE:
Test Functionalit Test Data Expected Observed Positive/Ne
Case y gative

TC1 Encryption Plaintext – ACT Ciphertext- Ciphertext – POH Positive


And Key - POH Plaintext - ACT
Decryption GYBNQKURP Plaintext - ACT
Program:

import java.util.*; import

java.io.BufferedReader; import
12

java.io.IOException; import

java.io.InputStreamReader;

public class HillCipherExample {

int[] lm; int[][]

km; int[] rm;

static int

choice; int [][]

invK;

public void performDivision(String temp, int s)

{ while (temp.length()

> s)

String line = temp.substring(0, s);

temp = temp.substring(s,

temp.length()); calLineMatrix(line);

if(choice ==1){

multiplyLineByKey(line.length());

}else{

multiplyLineByInvKey(line.length());
13

showResult(line.length(

)); } if (temp.length()

== s){

if(choice ==1){

calLineMatrix(temp);

multiplyLineByKey(temp.length(

)); showResult(temp.length());

else{

calLi

neM

atrix(

temp

);

this.

multi

plyLi

neBy

InvK

ey(te
14

mp.le

ngth(

));

show

Resu

lt(te

mp.le

ngth(

));

} } else if (temp.length() < s) { for

(int i = temp.length(); i < s; i++)

temp = temp + 'x'; if(choice ==1){

calLineMatrix(temp);

multiplyLineByKey(temp.length())

; showResult(temp.length()); }

else{ calLineMatrix(temp);

multiplyLineByInvKey(temp.lengt

h()); showResult(temp.length());

} } public void calKeyMatrix(String key,

int len)
15

{ km = new

int[len][len]; int k =

0; for (int i = 0; i <

len; i++) { for (int j

= 0; j < len; j++) {

km[i][j] = ((int)

key.charAt(k)) - 97;

k++; }

public void calLineMatrix(String line)

{ lm = new int[line.length()];

for (int i = 0; i < line.length();

i++)

{ lm[i] = ((int) line.charAt(i))

- 97;

} } public void

multiplyLineByKey(int len)

{ rm = new int[len];

for (int i = 0; i < len;

i++)
16

{
for (int j = 0; j < len; j++) { rm[i] +=

km[i][j] * lm[j]; } rm[i] %= 26; } }

public void multiplyLineByInvKey(int

len)

rm = new int[len]; for (int i

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

= 0; j < len; j++) { rm[i] +=

invK[i][j] * lm[j]; } rm[i]

%= 26; } } public void

showResult(int len) { String

result = ""; for (int i = 0; i <

len; i++)

{ result += (char) (rm[i] +

97); }

System.out.print(result); } public int

calDeterminant(int A[][], int N)

{ int resultOfDet; switch (N) { case 1:

resultOfDet = A[0][0]; break; case 2:

resultOfDet = A[0][0] * A[1][1] - A[1][0] *


17

A[0][1]; break; default: resultOfDet = 0; for (int

j1 = 0; j1 < N; j1++)

{ int m[][] = new int[N - 1][N

- 1]; for (int i = 1; i < N; i++)

{ int j2 = 0; for (int j = 0; j <

N; j++)
18

{ if (j == j1) continue; m[i - 1][j2] = A[i][j]; j2++; }

} resultOfDet += Math.pow(-1.0, 1.0 + j1 + 1.0) *

A[0][j1]

* calDeterminant(m, N - 1);

} break; }

return

resultOfDet; }

public void cofact(int num[][], int f)

int b[][], fac[][]; b

= new int[f][f]; fac

= new int[f][f]; int

p, q, m, n, i, j; for

(q = 0; q < f; q++)

{ for (p 0; p < f;

p++)

{
m = 0; n = 0; for

(i = 0; i < f; i++) {

for (j = 0; j < f;

j++) { b[i][j] = 0;
19

if (i != q && j !=

p) { b[m][n] =

num[i][j]; if (n <

(f - 2)) n++;

else

{n=

0;

m++

;}

} } fac[q][p] = (int) Math.pow(-1, q + p) *

calDeterminant(b, f - 1);

trans(fac, f);
}

void trans(int fac[][], int

r) {

int i, j; int b[][], inv[][]; b =

new int[r][r]; inv = new

int[r][r]; int d =

calDeterminant(km, r); int


20

mi = mi(d % 26); mi %=

26; if (mi < 0) mi += 26;

for (i = 0; i < r; i++) { for (j

= 0; j < r; j++) {

b[i][j] = fac[j][i];

} } for (i = 0; i <

r; i++) { for (j 0; j

< r; j++) {

inv[i][j] = b[i][j] %

26; if (inv[i][j] < 0)

inv[i][j] += 26;

inv[i][j] *= mi;

inv[i][j] %= 26; } }

invK = inv;

public int mi(int d) { int

q, r1, r2, r, t1, t2, t; r1 =

26; r2 = d; t1 = 0; t2 =

1; while (r1 != 1 && r2

!= 0) { q = r1 / r2; r = r1
21

% r2; t = t1 - (t2 * q); r1

= r2;

r2 = r; t1 = t2;

t2 = t; }

return (t1 +

t2); }

public void matrixtoinvkey(int inv[][], int n)

{ String invkey = ""; for (int i

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

0; j < n; j++) { invkey +=

(char) (inv[i][j] + 97);

System.out.print(invkey); } public

boolean check(String key, int len)

{ calKeyMatrix(key, len); int

d calDeterminant(km,

len);

d = d % 26;
if (d == 0)

{
22

System.out.println("Key is not invertible");

return false;

} else if (d % 2 == 0 || d % 13

== 0)

System.out.println("Key is not

invertible"); return false; }

else {

return

true;

public static void main(String args[]) throws IOException

HillCipherExample obj = new HillCipherExample();

BufferedReader in = new BufferedReader(new

InputStreamReader(System.in)); System.out.println("Menu:\n1:

Encryption\n2: Decryption"); choice = Integer.parseInt(in.readLine());

System.out.println("Enter the line: ");

String line = in.readLine();


Regulation:R17

System.out.println("Enter the key: "); String

key = in.readLine(); double sq =

Math.sqrt(key.length()); if (sq != (long) sq)

System.out.println("Cannot Form a square matrix"); else

{ int size = (int) sq; if (obj.check(key, size))

System.out.println("Result:"); obj.cofact(obj.km,

size); obj.performDivision(line, size);

} }}}

Output:

2. Aim: Write a C/JAVA program to implement Ceaser Cipher.

Description:
Regulation:R17

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.

The encryption can be represented using modular arithmetic by first transforming the letters into
numbers, according to the scheme, A = 0, B = 1,…, Z = 25. Encryption of a letter by a shift n
can be described mathematically as.

E_n(x)=(x+n)mod\ 26 (Encryption Phase with shift n) D_n(x)=(x-n)mod\ 26


(Decryption Phase with shift n)
Tes Functional Test Data Expected Observed Positive/Nega
t ity tive

Cas
e

TC Encryption Plaintext – Ciphertext – Ciphertext – Positive


1 And ATTACKATO EXXEGOEXSR EXXEGOEXSR
Decryption NCE GI GI
Shift - 4 Plaintext - Plaintext -
ATTACKATO ATTACKATO
NCE NCE
Program:

class CaesarCipher { public static StringBuffer

encrypt(String text, int shift) { 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) + shift - 65) % 26 + 65);

result.append(ch); } else { char ch = (char)

(((int) text.charAt(i) + shift - 97) % 26 + 97);

result.append(ch);
Regulation:R17

return result; } public static StringBuffer decrypt(String cipher,

int shift) { StringBuffer result = new StringBuffer(); for (int i =

0; i < cipher.length(); i++) { if

(Character.isUpperCase(cipher.charAt(i))) { char ch = (char)

(((int) cipher.charAt(i) + shift - 65) % 26 + 65);

result.append(ch); } else { char ch = (char)

(((int) cipher.charAt(i) + shift - 97) % 26 + 97);

result.append(ch);

return result;

}
public static void main(String[] args) {

String originalText = "ATTACKATONCE"; int

shiftCount = 1;

System.out.println("Caesar Cipher Example");

System.out.println("Encryption");

System.out.println("Text : " + originalText);

System.out.println("Shift : " + shiftCount);

String cipher = encrypt(originalText, shiftCount).toString();


Regulation:R17

System.out.println("Encrypted Cipher: " + cipher);

System.out.println("Decryption");

System.out.println("Encrypted Cipher: " + cipher);

System.out.println("Shift : " + shiftCount);

String decryptedPlainText = decrypt(cipher, 26 - shiftCount).toString();

System.out.println("Decrypted Plain Text : " + decryptedPlainText);

}}

Output:

Week-3 iii) Aim: Write a C/JAVA program for AFFINE CIPHER with equation c =

3x + 12

Description:

The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an
alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function,
and converted back to a letter. The formula used means that each letter encrypts to one other
letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule
governing which letter goes to which.
Regulation:R17

The whole process relies on working modulo m (the length of the alphabet used). In the affine
cipher, the letters of an alphabet of size m are first mapped to the integers in the range 0 … m-
1.

The ‘key’ for the Affine cipher consists of 2 numbers, we’ll call them a and b. The following
discussion assumes the use of a 26 character alphabet (m = 26). a should be chosen to be
relatively prime to m (i.e. a should have no factors in common with m).

TEST CASE:
Test Case Functionalit Test Data Expected Observed Positive/Nega
y tive

TC1 Encryption Plaintext – Cipher text – Cipher text – Positive


And AFFINE UBBAHK UBBAHK
Decryption CIPHER CAPJKX CAPJKX
Plaintext – Plaintext –
AFFINE AFFINE
CIPHER CIPHER
Program:

public class CGF { static int a = 17; static int b

= 20; static String encryptMessage(char[] msg)

{
String cipher = &quot;&quot;; for (int i =

0; i &lt; msg.length; i++)

{ if (msg[i] != &#39; &#39;)

{ cipher = cipher

+ (char) ((((a * (msg[i] - &#39;A&#39;)) + b) % 26) + &#39;A&#39;);

} else { cipher += msg[i];


Regulation:R17

} } return cipher; } static String

decryptCipher(String cipher)

String msg = &quot;&quot;; int

a_inv = 0; int flag = 0; for (int i = 0;

i &lt; 26; i++)

{ flag = (a * i) % 26; if

(flag == 1)

{
a_inv = i;

} } for (int i = 0; i &lt; cipher.length(); i++)

{ if (cipher.charAt(i) != &#39; &#39;)

{ msg = msg + (char) (((a_inv *

((cipher.charAt(i) + &#39;A&#39; - b)) % 26)) + &#39;A&#39;);

else { msg += cipher.charAt(i);

} } return msg; } public static void

main(String[] args)

String msg = &quot;AFFINE CIPHER&quot;;

String cipherText = encryptMessage(msg.toCharArray());

System.out.println(&quot;Encrypted Message is : &quot; + cipherText);


Regulation:R17

System.out.println(&quot;Decrypted Message is: &quot; + decryptCipher(cipherText));

}}
Output
Regulation:R17

Week-3:

iv) Aim: Write a C/JAVA program to implement Playfair cipher with key ldrp

Description:

The Playfair Cipher is a manual symmetric encryption cipher invented in 1854 by Charles
Wheatstone, however it’s name and popularity came from the endorsement of Lord Playfair.

The Playfair cipher encrypts pairs of letters (digraphs), instead of single letters as is the case
with simpler substitution ciphers such as the Caesar Cipher. Frequency analysis is still possible
on the Playfair cipher, however it would be against 600 possible pairs of letters instead of 26
different possible letters. For this reason the Playfair cipher is much more secure than older
substitution ciphers, and it’s use continued up until WWII.

The playfair cipher starts with creating a key table. The key table is a 5×5 grid of letters that
will act as the key for encrypting your plaintext. Each of the 25 letters must be unique and one
letter of the alphabet (usually Q) is omitted from the table (as there are 25 spots and 26 letters in
the alphabet).

TEST CASE:
Test Functionality Test Data Expected Observed Positive/Negati
Case ve

TC1 Encryption Plaintext - ldrp Cipher text – Cipher text – Positive


And Key – heyu kbzt kbzt
Decryption Plaintext - heyu Plaintext - heyu
Program:

package com.sanfoundry.setandstring;

import java.util.Scanner; public class

PlayfairCipherEncryption

{ private String KeyWord = new String(); private

String Key = new String(); private char


Regulation:R17

matrix_arr[][] = new char[5][5]; public void

setKey(String k) {

String K_adjust = new String(); boolean

flag = false; K_adjust = K_adjust +

k.charAt(0); for (int i = 1; i &lt; k.length();

i++)

{ for (int j = 0; j &lt; K_adjust.length(); j++)

{ if (k.charAt(i) == K_adjust.charAt(j))

{ flag = true; } } if (flag == false)

K_adjust = K_adjust + k.charAt(i); flag =

false; }

KeyWord = K_adjust; }

public void KeyGen() {

boolean flag = true; char

current;

Key = KeyWord; for (int i = 0; i &lt; 26; i++) {

current = (char) (i + 97); if (current ==

&#39;j&#39;) continue; for (int j = 0; j &lt;

KeyWord.length(); j++)

{ if (current == KeyWord.charAt(j))
Regulation:R17

{ flag = false; break;

if (flag)

Key = Key + current; flag =

true; }

System.out.println(Key);

matrix(); } private void matrix()

{ int counter = 0;

for (int i = 0; i &lt; 5; i++)

{ for (int j = 0; j &lt; 5; j++)

{ matrix_arr[i][j] = Key.charAt(counter);

System.out.print(matrix_arr[i][j] + &quot; &quot;);

counter++; }

System.out.println();

} } private String format(String old_text)

{ int i = 0; int len = 0; String text = new

String(); len = old_text.length(); for (int tmp

= 0; tmp &lt; len; tmp++)

{ if (old_text.charAt(tmp) == &#39;j&#39;)

{ text = text + &#39;i&#39;;


Regulation:R17

else
text = text + old_text.charAt(tmp);

} len = text.length(); for (i = 0; i &lt;

len; i = i + 2)

{ if (text.charAt(i + 1) == text.charAt(i))

{ text = text.substring(0, i + 1) + &#39;x&#39; + text.substring(i + 1);

} } return text; }

private String[] Divid2Pairs(String new_string)

String Original = format(new_string); int

size = Original.length(); if (size % 2 != 0) {

size++;

Original = Original + &#39;x&#39;;

String x[] = new String[size / 2]; int

counter = 0;

for (int i = 0; i &lt; size / 2; i++)

{ x[i] = Original.substring(counter, counter + 2);

counter = counter + 2; } return x; } public int[]

GetDiminsions(char letter)
Regulation:R17

{ int[] key = new int[2]; if (letter

== &#39;j&#39;) letter =

&#39;i&#39;; for (int i = 0; i &lt;

5; i++) { for (int j = 0; j &lt; 5; j++)

{ if (matrix_arr[i][j] == letter)

{ key[0] = i; key[1]

= j; break; }

}
return key; } public String encryptMessage(String

Source)

String src_arr[] = Divid2Pairs(Source); String

Code = new String(); char one; char two; int

part1[] = new int[2]; int part2[] = new int[2];

for (int i = 0; i &lt; src_arr.length; i++)

{ two =

src_arr[i].charAt(1); part1 =

GetDiminsions(one); part2 =

GetDiminsions(two); if (part1[0] ==

part2[0]) { if (part1[1] &lt; 4)


Regulation:R17

part1[1]++; else part1[1] = 0; if

(part2[1] &lt; 4) part2[1]++;

else part2[1] = 0; } else if (part1[1]

== part2[1])

{ if (part1[0] &lt; 4)

part1[0]++; else part1[0] =

0; if (part2[0] &lt; 4)

part2[0]++; else part2[0] =

0; }

else { int temp = part1[1];

part1[1] = part2[1]; part2[1]

= temp;

Code = Code + matrix_arr[part1[0]][part1[1]]

+ matrix_arr[part2[0]][part2[1]];

} return Code; }

public static void

main(String[] args)

PlayfairCipherEncryption x = new PlayfairCipherEncryption();

Scanner sc = new Scanner(System.in);


Regulation:R17

System.out.println("Enter a keyword:"); String

keyword = sc.next();

x.setKey(keyword);

x.KeyGen();

System.out.println(&quot;Enter word to encrypt: (Make sure length of message is

even)&quot;);

String key_input = sc.next(); if

(key_input.length() % 2 == 0)

System.out.println(&quot;Encryption: &quot; + x.encryptMessage(key_input));

else

System.out.println(&quot;Message length should be even&quot;);

sc.close();

}}
Output:
Regulation:R17
Regulation:R17

v. Aim :Write a C/Java program to implement polyalphabetic cipher.

Description:

A polyalphabetic cipher is any cipher based on substitution, using multiple substitution


alphabets .The encryption of the original text is done using the Vigenère square or Vigenère
table.

The table consists of the alphabets written out 26 times in different rows, each alphabet shifted
cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar
Ciphers.

At different points in the encryption process, the cipher uses a different alphabet from one of the
rows.

The alphabet used at each point depends on a repeating keyword.

TEST CASE:
Test Functionalit Test Data Expected Observed Positive/Nega
Case y tive

TC1 Encryption Plaintext - Cipher text – Cipher text – positive


And GEEKSFOR GCYCZFMLYLE GCYCZFMLYLE
Decryption GEEKS IM IM
Plaintext - Plaintext -
GEEKSFORGEE GEEKSFORGEE
KS KS
Program: class GFG { static String

generateKey(String str, String key)

{ int x = str.length(); for

(int i = 0; ; i++)

{
if (x == i) i = 0;
Regulation:R17

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

{ int x = (str.charAt(i) + key.charAt(i)) %26; 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++)

{
int x = (cipher_text.charAt(i) - key.charAt(i) + 26) %26; x +=

'A';

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

public static void main(String[] args)

String str = "GEEKSFORGEEKS";

String keyword = "AYUSH";


Regulation:R17

String key = generateKey(str, keyword);

String cipher_text = cipherText(str, key);

System.out.println("Ciphertext : "

+ cipher_text + "\n");

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

+ originalText(cipher_text, key));

}}

Output:

6. Aim: Write a C or Java program to implement Auto Key Cipher.


Description: Autokey Cipher is a polyalphabetic substitution cipher. It is closely related to the
Vigenere cipher but uses a different method of generating the key. It was invented by Blaise de
Vigenere in 1586. In general, more secure than the Vigenere cipher.
Regulation:R17

TEST CASE:
Test Functionality Test Data Expected Observed Positive/Negative
Case
TC1 Encryption And Plaintext - Cipher text Cipher text Positive
Decryption HELLO – ULPWZ – ULPWZ
Plaintext - Plaintext -
HELLO HELLO
Program:
import java.lang.*; import java.util.*; public class AutoKey { private static final
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void
main(String[] args)
{
String msg = "HELLO"; String key =
"N";
if (key.matches("[-+]?\\d*\\.?\\d+")) key = "" +
alphabet.charAt(Integer.parseInt(key));
String enc = autoEncryption(msg, key);
System.out.println("Plaintext : " + msg);
System.out.println("Encrypted : " + enc);
System.out.println("Decrypted : " + autoDecryption(enc, key));
} public static String autoEncryption(String msg, String key)
{ int len = msg.length(); String newKey =
key.concat(msg);
Regulation:R17

newKey = newKey.substring(0, newKey.length() - key.length());


String encryptMsg = ""; for (int x = 0; x < len; x++) {
int first = alphabet.indexOf(msg.charAt(x)); int second =
alphabet.indexOf(newKey.charAt(x)); int total = (first +
second) % 26; encryptMsg += alphabet.charAt(total);
} return encryptMsg; }

public static String autoDecryption(String msg, String key)


{
String currentKey = key;
String decryptMsg = "";
// applying decryption algorithm for (int x = 0; x <
msg.length(); x++) { int get1 =
alphabet.indexOf(msg.charAt(x)); int get2 =
alphabet.indexOf(currentKey.charAt(x)); int total = (get1
- get2) % 26; total = (total < 0) ? total + 26 : total;
decryptMsg += alphabet.charAt(total); currentKey +=
alphabet.charAt(total);
}return decryptMsg;
}}
Output:
Regulation:R17

7. Aim: Write a C or Java Program to implement Hill Cipher.

Description: 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.

The matrix used for encryption is the cipher key, and it should be chosen randomly from the set
of invertible n × n matrices.

TEST CASE:
Test Functionality Test Data Expected Observed Positive/Negative
Case
TC1 Encryption Plaintext – Ciphertext- Ciphertext Positive
And ACT POH – POH
Decryption Key - Plaintext - Plaintext -
GYBNQKURP ACT ACT
Program: class GFG

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


Regulation:R17

// Following function encrypts the message static

void encrypt(int cipherMatrix[][], int

keyMatrix[][], int messageVector[][]) { int x, i, j;

for (i = 0; i < 3; i++) { for (j =

0; j < 1; j++) {

cipherMatrix[i][j] = 0;

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


{ cipherMatrix[i][j] += keyMatrix[i][x] *

messageVector[x][j];

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

}}

static void HillCipher(String message, String key)


Regulation:R17

// Get key matrix from the key string int

[][]keyMatrix = new int[3][3];

getKeyMatrix(key, keyMatrix);

int [][]messageVector = new int[3][1]; 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);
System.out.print(" Ciphertext:" + CipherText);
} public static void main(String[] args)
{
// Get the message to be encrypted
String message = "ACT";
Regulation:R17

// Get the key


String key = "GYBNQKURP";

HillCipher(message, key);
}
}
Output:

8. Aim: Write a C or Java program to implement Rail Fence technique.


Description: 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.
Examples:
Encryption
Input : "GeeksforGeeks "
Key = 3
Output : GsGsekfrek eoe
Decryption
Input : GsGsekfrek eoe
Key = 3
Output :"GeeksforGeeks "
Regulation:R17

Encryption
Input : "defend the east wall"
Key = 3
Output : dnhaweedtees alf tl
Decryption
Input : dnhaweedtees alf tl
Key = 3
Output : defend the east wall
TEST CASE:
Test Functionalit Test Data Expected Observed Positive/Negative
Case y

TC1 Encryption Plaintext – HEY Cipher text- Cipher text- Positive


And Key level - 2 HYE HYE
Decryption Plaintext - HEY Plaintext - HEY
Program:
import java.io.*; class
RailFence
{
public static void main(String[] args) throws IOException
{
String plaintxt,ciphertxt; int i,j,k;
System.out.println("Enter the message to be encrypted\n");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
plaintxt=br.readLine(); int len=plaintxt.length();
String s1="",s2="",temp=""; for(i=0;i<len;i++) {
if(plaintxt.charAt(i)!=' ') temp=temp+plaintxt.charAt(i);
} for(i=0;i<temp.length();i++)
{ if(i%2==0)
s1=s1+temp.charAt(i); else
s2=s2+temp.charAt(i);
} ciphertxt=s1.concat(s2);
Regulation:R17

System.out.println("Ciphertext : "+ciphertxt);
plaintxt=""; if(ciphertxt.length()%2==0)
j=ciphertxt.length()/2; else
j=ciphertxt.length()/2+1; k=j; for(i=0;i<k;i++,j++)
{
plaintxt+=ciphertxt.charAt(i); plaintxt+=ciphertxt.charAt(j);
}
System.out.println("Plaintext: "+plaintxt);
}}
Output:
Regulation:R17

9. Aim: Write a C or Java Program to implement Simple Columner Transposition technique.


Description: Given a plain-text message and a numeric key, cipher/de-cipher the given text
using Columnar Transposition Cipher
The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence
Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the
ciphertext off in columns one by one.
Examples:
Encryption
Input : Geeks for Geeks
Key = HACK
Output : e kefGsGsrekoe_
Decryption
Input : e kefGsGsrekoe_
Key = HACK
Output : Geeks for Geeks

Encryption
Input : Geeks on work
Key = HACK
Output : e w_eoo_Gs kknr_
Decryption
Input : e w_eoo_Gs kknr_
Key = HACK
Output : Geeks on work TEST
CASE:
Test Functionalit Test Data Expected Observed Positive/Nega
Case y tive

TC1 Encryption Plaintext – Cipher text – Cipher text – positive


And NETWOR TSIXNRUXWETX TSIXNRUXWETX
Decryption KSECURI OCYXEKRX OCYXEKRX
TY Plaintext - Plaintext -
Key 31452 NETWORKSECUR NETWORKSECUR
ITY ITY
Program:
Regulation:R17

import java.util.*; class simpleColumnar{ public


static void main(String sap[]){ Scanner sc = new
Scanner(System.in);

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


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

/* columnCount would keep track of columns */ int


columnCount = key.length();

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


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

/*plainText and cipherText would be array containing ASCII values for respective
alphabets */ int plainText[][] = new int[rowCount][columnCount]; int cipherText[][] =
new int[rowCount][columnCount];

/*Encryption Process*/
System.out.print("\n-----Encryption-----\n"); cipherText = encrypt(plainText,
cipherText, message, rowCount, columnCount, key);

// prepare final string String ct = "";


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

/*Decryption Process*/
System.out.print("\n\n\n-----Decryption-----\n");

plainText = decrypt(plainText, cipherText, ct, rowCount, columnCount, key);

// prepare final string String pt = "";


for(int i=0; i<rowCount; i++)
{ for(int j=0; j<columnCount; j++)
{ if(plainText[i][j] == 0) pt = pt +
"";
else{ pt = pt + (char)plainText[i][j];
}
}
}
System.out.print("\nPlain Text: " + pt);

System.out.println();
}

static int[][] encrypt(int plainText[][], int cipherText[][], String message, int rowCount,
int columnCount, String key){
int i,j;
int k=0;

/* here array would be filled row by row */ for(i=0;


i<rowCount; i++)
{ for(j=0; j<columnCount; j++)
{
/* terminating condition...as string length can be smaller than 2-D array */
if(k < message.length()) {
/* respective ASCII characters would be placed */
plainText[i][j] = (int)message.charAt(k); k++; }
else
Regulation:R17

{ break;
}
}
}

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


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

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


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

static int[][] decrypt(int plainText[][], int cipherText[][], String message, int rowCount,
int columnCount, String key){
int i,j;
int k=0;

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


Regulation:R17

{ int currentCol= ( (int)key.charAt(i) - 48 ) -1;


for(j=0; j<rowCount; j++)
{ plainText[j][currentCol] = cipherText[j][i];
}
}

System.out.print("Plain Array(read row by row): \n");


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

return plainText;
}}
Output:

WEEK-4

AIM:- write a c/java program to implement DES algorithm DESCRIPTION:

The Data Encryption Standard (DES) is a symmetric-key block cipher published by the
National Institute of Standards and Technology (NIST).
Regulation:R17

DES is an implementation of a Feistel Cipher. It uses 16 round Feistel structure. The block size
is 64-bit. Though, key length is 64-bit, DES has an effective key length of 56 bits, since 8 of the
64 bits of the key are not used by the encryption algorithm

Since DES is based on the Feistel Cipher, all that is required to specify DES is −

• Round function
• Key schedule

• Any additional processing − Initial and final permutation

DES ANALYSIS:

The DES satisfies both the desired properties of block cipher. These two properties make cipher
very strong.

• Avalanche effect − A small change in plaintext results in the very great change in the
ciphertext.

• Completeness − Each bit of ciphertext depends on many bits of plaintext.

During the last few years, cryptanalysis have found some weaknesses in DES when key selected
are weak keys. These keys shall be avoided.

DES has proved to be a very well designed block cipher. There have been no significant
cryptanalytic attacks on DES other than exhaustive key search.
TEST CASE:
Te Functi Test data Expected Observed Positive/N
st nality egative

C
as
e
Regulation:R17

T DES Message=0123456 Key=133457799B Key=133457799B Positive


C encrypt 789ABCDEF BCDFF1 BCDFF1
1 ion and
decrypt Encrypted Encrypted
ion message=85E813 message=85E813
540F0AB405 540F0AB405

PROGRAM:
import javax.swing.*; import
java.security.SecureRandom; import
javax.crypto.Cipher; import
javax.crypto.KeyGenerator; import
javax.crypto.SecretKey; import
javax.crypto.spec.SecretKeySpec; import
java.util.Random ; public class DES { byte[]
skey = new byte[1000]; String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage; public
DES()
{
try
{ generateSymmetricKey();
inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");
byte[] ibyte = inputMessage.getBytes(); byte[] ebyte=encrypt(raw, ibyte); String
encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte); String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);

JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);


} catch(Exception e)
{
Regulation:R17

System.out.println(e);
} } void generateSymmetricKey() { try
{
Random r = new Random(); int num =
r.nextInt(10000); String knum =
String.valueOf(num); byte[] knumb =
knum.getBytes();
skey=getRawKey(knumb); skeyString =
new String(skey);
System.out.println("DES Symmetric key = "+skeyString);
} catch(Exception e)
{
System.out.println(e);
} } private static byte[] getRawKey(byte[] seed) throws Exception
{
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed); kgen.init(56, sr);
SecretKey skey = kgen.generateKey(); raw =
skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws
Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[]
encrypted = cipher.doFinal(clear); return encrypted; } private
static byte[] decrypt(byte[] raw, byte[] encrypted) throws
Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw,
Regulation:R17

"DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted); return
decrypted; }
public static void main(String args[]) {

DES des = new DES();

}}
OUTPUT:

AIM:
write a c/java program to implement the blowfish algorithm logic.Generate sub key and s-box
from the given 32 –bit key by blowfish DESCRIPTION:
Blowfish is an encryption technique designed by Bruce Schneier in 1993 as an alternative to
DES Encryption Technique. It is significantly faster than DES and provides a good encryption
rate with no effective cryptanalysis technique found to date. It is one of the first, secure block
cyphers not subject to any patents and hence freely available for anyone to use.
1. blockSize: 64-bits
2. keySize: 32-bits to 448-bits variable size
3. number of subkeys: 18 [P-array]
4. number of rounds: 16
5. number of subsitution boxes: 4 [each having 512 entries of 32-bits each]
Regulation:R17

The entire encryption process can be elaborated as:

TEST CASE:
Test Functionality Test Expected Observed Positive/N
Case Data egative

TC1 Blowfish Message Positive


Key=133477754GHS Key=133477754GHSD
algorithm =123456
DFF1 FF1
789ABC
DEFG Encrypted Encrypted
message=4E381T540U message=4E381T540U
0AF805 0AF805
PROGRAM:
import javax.swing.*; import
java.security.SecureRandom; import
javax.crypto.Cipher; import
javax.crypto.KeyGenerator; import
javax.crypto.SecretKey; import
javax.crypto.spec.SecretKeySpec; import
Regulation:R17

java.util.Random ; public class Blowfish {


byte[] skey = new byte[1000]; String
skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;

public Blowfish() { try {


generateSymmetricKey();

inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");


byte[] ibyte = inputMessage.getBytes(); byte[] ebyte=encrypt(raw, ibyte); String
encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);

byte[] dbyte= decrypt(raw,ebyte); String


decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);

JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);


} catch(Exception e) {
System.out.println(e);
}

} void generateSymmetricKey() { try {


Random r = new Random(); int num =
r.nextInt(10000); String knum =
String.valueOf(num); byte[] knumb =
knum.getBytes();
skey=getRawKey(knumb); skeyString =
new String(skey);
System.out.println("Blowfish Symmetric key = "+skeyString);
Regulation:R17

} catch(Exception e) {
System.out.println(e); } }
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator
kgen = KeyGenerator.getInstance("Blowfish"); SecureRandom sr =
SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed);
kgen.init(128, sr); // 128, 256 and 448 bits may not be available
SecretKey skey = kgen.generateKey(); raw = skey.getEncoded();
return raw; }
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted =
cipher.doFinal(clear); return encrypted; }

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {


SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted =
cipher.doFinal(encrypted); return decrypted; }
public static void main(String args[]) {
Blowfish bf = new Blowfish();
}}
OUTPUT:
Regulation:R17

WEEK-5

AIM: Write a C/JAVA program to implement the Rijndael algorithm logic

DESCRIPTION:
Rijndael (pronounced rain-dahl) is the algorithm that has been selected by the U.S. National
Institute of Standards and Technology (NIST) as the candidate for the Advanced Encryption
Standard (AES). It was selected from a list of five finalists, that were themselves selected from
Regulation:R17

an original list of more than 15 submissions. Rijndael will begin to supplant the Data
Encryption Standard (DES) - and later Triple DES - over the next few years in many
cryptography applications. The algorithm was designed by two Belgian cryptologists, Vincent
Rijmen and Joan Daemen, whose surnames are reflected in the cipher's name.

Rijndael has its origins in Square, an earlier collaboration between the two cryptologists.

The Rijndael algorithm is a new generation symmetric block cipher that supports key sizes of
128, 192 and 256 bits, with data handled in 128-bit blocks - however, in excess of AES design
criteria, the block sizes can mirror those of the keys. Rijndael uses a variable number of rounds,
depending on key/block sizes, as follows:
9 rounds if the key/block size is 128 bits
11 rounds if the key/block size is 192 bits
13 rounds if the key/block size is 256 bits
T Func Inp Expected Output Observed Output Positiv
e tiona ut e/Nega
lity
st tive
C
a
s
e

T Impl AE dcc825d3fb18b0b64af7fe4d2 dcc825d3fb18b0b64af7fe4d2 Positiv


S e9e25775663fdeeb83e378346 e9e25775663fdeeb83e378346 e
C emen
1 ting 1693a69f6413b8 1693a69f6413b8
st
Rijnd
il
ael
algor l
ithm
ro
ck
s!
!
PROGRAM:

import java.secuity.*; import


javax.crpto.*; import
Regulation:R17

javax.crypto.sec.*; import
java.io.*; public classAES {
public static String asHex (byte buf[]) {

StringBuffer strbuf = new StringBuffer(buf.length *


2); int i; for (i = 0; i
< buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); }
return strbuf.toString(); }

public static void main(String[] args) throws Exception

{ String message="AES still rocks!!";

// Get the KeyGenerator

KeyGenerator kgen = KeyGenerator.getInstance("AES");


kgen.init(128); // 192 and 256 bits may not be available //
Generate the secret key specs.

SecretKey skey = kgen.generateKey();


byte[] raw = skey.getEncoded();

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

// Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());


Regulation:R17

System.out.println("encrypted string: " + asHex(encrypted));

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

byte[] original = cipher.doFinal(encrypted);

String originalString = new String(original);

System.out.println("Original string: " + originalString + " " + asHex(original));


}
}
OUTPUT:
Regulation:R17

2 Write the RC4 logic in java using java cryptography; encrypt the text “Hello World” using
Blowfish. Create your own key using java key tool.

DESCRIPTION:

RC4– this algorithm is used to create pseudo-random stream of bits (a key-stream). As with any
stream cipher, keystreams can be used for encryption.

A stream cipher is a symmetric key cipher where plaintext digits one at a time are XORed with
corresponding digits of pseudorandom stream of bits (keystream) to create encrypted message
i.e. ciphertext.
RC4 is mostly used in protocols such as :

1) Secure Socket Layer (SSL) to establish an encrypted link between a web server and a
browser to ensure all data transmitted remain private and generally used by many websites to
protect their online transaction with their customers.

2) Wired Equivalent Privacy (WEP) security protocol to provide security and privacy to
wireless networks(e.g. Wi-Fi) comparable to as in Wired Network (LAN).

Blowfish is also an encryption technique which is replacement to DES algorithm and that is
very powerful ammunition against hackers and cyber-criminals. It is utilized in a wide array of
products like in performance-constrained environments such as embedded systems, secure E-
mail encryption tools, backup software, password management tools.
Test Functionality Input Expected Output Observed Output Positive/Negative
Case

TC1 Encrypting Java Zhi(5Oï˜çê–½-ÕH Zhi(5Oï˜çê–½-ÕH Positive


text using Program
Blowfish

PROGRAM:

import javax.crypto.Cipher; import

javax.crypto.KeyGenerator; import javax.crypto.SecretKey;


Regulation:R17

import javax.swing.JOptionPane; public class

BlowFishCipher{ public static void main(String[]args)

throws Exception{

//create a keygenerator based upon the

KeyGenerator keygenerator= KeyGenerator.getInstance("Blowfish"); //create a key

SecretKey secretkey=keygenerator.generateKey();
//create a cipher based upon

Blowfish Cipher cipher=Cipher.getInstance("Blowfish");

//initialise cipher to with secretkey cipher.init(Cipher.ENCRYPT_MODE,secretkey);

//get the text to encrypt

String inputText = "Hello world";

//encrypt message byte[]

encrypted=cipher.doFinal(inputText.getBytes()); //re-

initialise the cipher to be in decrypt mode

cipher.init(Cipher.DECRYPT_MODE,secretkey);

//decrypt message byte[]

decrypted=cipher.doFinal(encrypted);

//and display the results

System.out.println("Original String: " + inputText);

System.out.println("Encrypted: " + new String(encrypted)); System.out.println("Decrypted: " +


new String(decrypted));
Regulation:R17

}}

OUTPUT:

WEEK-6

Aim: Write C/JAVA program to implement Euclidean Algorithm.


Description:
GCD of two numbers is the largest number that divides both of them. A simple way to find
GCD is to factorize both numbers and multiply common prime factors.
Basic Euclidean Algorithm for GCD
The algorithm is based on the below facts.
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.
Now instead of subtraction, if we divide the smaller number, the algorithm stops when we find
remainder 0.
Time Complexity: O(Log min(a, b)) TEST
CASE:
Test Case Functionality Test Data Expected Observed Positive/Negative
TC1 Finding GCD of two A=10 GCD=5 GCD=5 positive
numbers B=15
JAVA CODE:
class Euclidean {
// extended Euclidean Algorithm public
static int gcd(int a, int b)
{ if (a == 0) return
b;

return gcd(b % a, a); }


Regulation:R17

// Driver Program public static void


main(String[] args)
{ int a = 10, b = 15, g; g =
gcd(a, b);
System.out.println("GCD(" + a + ", " + b + ") = " + g);

a = 35; b = 10; g =
gcd(a, b);
System.out.println("GCD(" + a + ", " + b + ") = " + g);

a = 31; b = 2; g =
gcd(a, b);
System.out.println("GCD(" + a + ", " + b + ") = " + g);
}
}

OUTPUT:
Regulation:R17

Aim: Write C/JAVA program to implement Extended Euclidean Algorithm.


Description:
Advanced Euclidean algorithm also finds integer coefficients x and y such that:
ax + by = gcd(a, b)
The advanced Euclidean algorithm updates results of gcd(a, b) using the results calculated by
recursive call gcd(b%a, a). Let values of x and y calculated by the recursive call be x1 and y1. x
and y are updated using the below expressions.
It is used for finding the greatest common divisor of two positive integers a and b and writing
this greatest common divisor as an integer linear combination of a and b .
x = y1 - ⌊ b/a⌋ * x1 y = x1
TEST CASE:
Test Case Functionality Test Data Expected Observed Positive/Negative
TC1 Finding GCD of two A=35 GCD=5 GCD=5 positive
numbers B=15
JAVA CODE:
class extendedEuclidean { // extended Euclidean
Algorithm public static int gcdExtended(int a, int b, int x,
int y)
{ // Base Case if (a
== 0) { x = 0; y = 1;
return b; }

int x1 = 1, y1 = 1; // To store results of recursive call int gcd


= gcdExtended(b % a, a, x1, y1);

// Update x and y using results of recursive


// call
x = y1 - (b / a) * x1; y = x1;

return gcd; }

// Driver Program public static void


main(String[] args)
Regulation:R17

{ int x = 1, y = 1; int a = 35, b = 15;


int g = gcdExtended(a, b, x, y);
System.out.print("gcd(" + a + ", " + b
+ ") = " + g);

}
}

OUTPUT:

Aim: Java program to implement RSA Algoithm.


Description:
Regulation:R17

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.
Mechanism:
Select two prime no's. Suppose P = 53 and Q = 59. Now
First part of the Public key : n = P*Q = 3127.
We also need a small exponent say e :
But e Must be an integer.
Not be a factor of n.
1 < e < Φ(n) [Φ(n) is discussed below], Let us now consider it to be equal to 3.
Our Public Key is made of n and e >>
Generating Private Key :
We need to calculate Φ(n) : Such that Φ(n) = (P-1)(Q-1) so, Φ(n) = 3016
Now calculate Private Key, d : d = (k*Φ(n) + 1) / e for some integer k For k = 2, value of d is
2011.
Now we are ready with our – Public Key ( n = 3127 and e = 3) and Private Key(d = 2011) Now
we will encrypt “HI” :
Convert letters to numbers : H = 8 and I = 9
Thus Encrypted Data c = 89e mod n. Thus our Encrypted Data comes out to be 1394 Now
we will decrypt 1394 :
Decrypted Data = cd mod n. Thus our Encrypted Data comes out to be 89 8 =
H and I = 9 i.e. "HI".

TEST CASE:
Test Functionality Test Data Expected Observed Positive/Negative
Case
TC1 Encryption and p=3 q=11 Encryptedmsg=18 Encryptedmsg=18 positive
decryption message=45678 Decryptedmsg=6 Decryptedmsg=6

PROGRAM:
import java.math.*;
class RSA {
public static void main(String args[])
Regulation:R17

{ int p, q, n, z, d = 0, e, i;

// The number to be encrypted and decrypted int


msg = 12; double c; BigInteger msgback;

// 1st prime number p p = 3;

// 2nd prime number q 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 =
Regulation:R17

(C.pow(d)).mod(N); System.out.println("Derypted message


is : "
+ msgback);
}
static int gcd(int e, int z)
{ if (e == 0) return
z; else
return gcd(z % e, e);
}
}

OUTPUT:

Aim: Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
Description:
This algorithm is used to exchange the secret key between the sender and the receiver.
This algorithm facilitates the exchange of secret key without actually transmitting it.
Algorithm-
Let-
Private key of the sender = Xs
Regulation:R17

Public key of the sender = Ys


Private key of the receiver = Xr
Public key of the receiver = Yr
Using Diffie Hellman Algorithm, the key is exchanged in the following stepsStep-01:
One of the parties choose two numbers ‘a’ and ‘n’ and exchange with the other party.
‘a’ is the primitive root of prime number ‘n’.
After this exchange, both the parties know the value of ‘a’ and ‘n’.
Step-02:
Both the parties already know their own private key.
Both the parties calculate the value of their public key and exchange with each other.
Sender calculate its public key as-
Ys = aXs mod n
Receiver calculate its public key as-
Yr = aXr mod n
Step-03:
Both the parties receive public key of each other.
Now, both the parties calculate the value of secret key.
Sender calculates secret key as-
Secret key = (Yr)Xs mod n
Receiver calculates secret key as-
Secret key = (Ys)Xr mod nFinally, both the parties obtain the same value of secret key.

TEST CASE:
Test Case Functionality Test Data Expected Observed Positive/Negative
TC1 Finding secret key p=7 Secret key=1 Secret key=1 positive
g=17
a=6
b=4

PROGRAM:
import java.util.*;

class DiffeHellman
{ public static void main(String args[])
{
Regulation:R17

Scanner sc=new Scanner(System.in);


System.out.println("Enter modulo(p)"); int
p=sc.nextInt(); System.out.println("Enter
primitive root of "+p); int g=sc.nextInt();
System.out.println("Choose 1st secret no(Alice)"); int
a=sc.nextInt();
System.out.println("Choose 2nd secret no(BOB)"); int
b=sc.nextInt();

int A = (int)Math.pow(g,a)%p; int B =


(int)Math.pow(g,b)%p;

int S_A = (int)Math.pow(B,a)%p; int S_B


=(int)Math.pow(A,b)%p;

if(S_A==S_B)
{
System.out.println("A and B can communicate with each other!!!");
System.out.println("They share a secret no = "+S_A);
}
else
{
System.out.println("A and B cannot communicate with each other!!!");
}}}
Regulation:R17

OUTPUT:

WEEK-7

AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA
DESCRIPTION: SHA-1 or Secure Hash Algorithm 1 is a cryptographic hash function which
takes an input and produces a 160-bit (20-byte) hash value. This hash value is known as a
message digest. This message digest is usually then rendered as a hexadecimal number which is
40 digits long. It is a U.S. Federal Information Processing Standard and was designed by the
United States National Security Agency.
SHA-1 is now considered insecure since 2005. Message Digest Class provides following
cryptographic hash function to find hash value of a text as follows:
MD2
MD5
SHA-1
SHA-224
SHA-256
SHA-384
SHA-512
SHA1
Test Functionality Testdata Expected Observed Positive/
case (Plain Negative
Text)
Regulation:R17

TC1 Encryption ““ DA39A3EE5E6B4B0D32 DA39A3EE5E6B4B0D325 Positive


55BFEF95601890AFD80 5BFEF95601890AFD8070
709 9
TC2 Encryption abc A9993E364706816ABA3 A9993E364706816ABA3E Positive
E25717850C26C9CD0D8 25717850C26C9CD0D89D
9D
TC3 Encryption abcdefghi 32D10C7B8CF96570CA0 32D10C7B8CF96570CA04 Positive
jklmnopqr 4CE37F2A19D84240D3A CE37F2A19D84240D3A89
stuvwxyz
89
PROGRAM:

import java.security.*; public class

SHA1 { public static void main(String[]

a)

try

MessageDigest md = MessageDigest.getInstance("SHA1");

System.out.println("Message digest object info: ");

System.out.println(" Algorithm = " +md.getAlgorithm()); System.out.println(" Provider = "


+md.getProvider());

System.out.println(" ToString = " +md.toString());

String input = ""; md.update(input.getBytes()); byte[]

output = md.digest();

System.out.println();

System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));

input = "abc"; md.update(input.getBytes()); output = md.digest();

System.out.println();
Regulation:R17

System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));

input = "abcdefghijklmnopqrstuvwxyz"; md.update(input.getBytes());

output = md.digest();

System.out.println();

System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));

System.out.println("");

} catch (Exception e) {

System.out.println("Exception: " +e);

} } public static String bytesToHex(byte[] b)

char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

StringBufferbuf = new StringBuffer(); for (int j=0; j<b.length;j++)

{ buf.append(hexDigit[(b[j] >> 4) & 0x0f]);


buf.append(hexDigit[b[j] & 0x0f]); }
}
returnbuf.toString(); }

OUTPUT:
Regulation:R17

AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
DESCRIPTION: Message Digest is used to ensure the integrity of a message transmitted over
an insecure channel (where the content of the message can be changed). The message is passed
through a Cryptographic hash function. This function creates a compressed image of the
message called Digest.
Lets assume, Alice sent a message and digest pair to Bob. To check the integrity of the message
Bob runs the cryptographic hash function on the received message and gets a new digest. Now,
Bob will compare the new digest and the digest sent by Alice. If, both are same then Bob is sure
that the original message is not changed.
MD5
Test Functionality Testdata Expected Observed Positive/
case (Plain Negative
Text)
TC1 Encryption ““ D41D8CD98F00B204E98 D41D8CD98F00B204E980 Positive
00998ECF8427E 0998ECF8427E
TC2 Encryption abc 900150983CD24FB0D69 900150983CD24FB0D696 Positive
63F7D28E17F72 3F7D28E17F72
TC3 Encryption abcdefghi C3FCD3D76192E4007DF C3FCD3D76192E4007DF Positive
jklmnopqr B496CCA67E13B B496CCA67E13B
stuvwxyz

PROGRAM:

import java.security.*; public class MD5

{ public static void main(String[] a)

try

MessageDigest md = MessageDigest.getInstance("MD5");

System.out.println("Message digest object info: ");

System.out.println(" Algorithm = " +md.getAlgorithm());


Regulation:R17

System.out.println(" Provider = " +md.getProvider());

System.out.println(" ToString = " +md.toString());

String input = ""; md.update(input.getBytes()); byte[]

output = md.digest(); System.out.println();

System.out.println("MD5(\""+input+"\") = "

+bytesToHex(output)); input = "abc";

md.update(input.getBytes()); output = md.digest();

System.out.println();

System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));

input = "abcdefghijklmnopqrstuvwxyz"; md.update(input.getBytes());

output = md.digest();

System.out.println();

System.out.println("MD5(\"" +input+"\") = " +bytesToHex(output)); System.out.println("");

} catch (Exception e)

System.out.println("Exception: " +e); } } public

static String bytesToHex(byte[] b)

char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

StringBufferbuf = new StringBuffer(); for (int j=0; j<b.length;j++)

{ buf.append(hexDigit[(b[j] >> 4) & 0x0f]);

buf.append(hexDigit[b[j] & 0x0f]);


Regulation:R17

} return buf.toString(); } }

OUTPUT:

You might also like