Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Cns Lab Manual 2024-25

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

IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

CNS LAB PROGRAMS

Intoduction to Lab:

Cryptography is the study and application of techniques that hide the real meaning of information
by transforming it into nonhuman readable formats and vice versa.

Cryptography is the science of encrypting or decrypting information to prevent unauthorized


access. In cryptography, you transform data and personal information to make sure only the correct
recipient can decrypt the message. As an essential aspect of modern data security, using
cryptography allows the secure storage and transmission of data between willing parties.

There are two primary aspects of cryptography, they are:

1. Encryption:Converting plain text into cipher text

2.Decryption:converting cipher text to plain text.

Applications of Cryptography:

Cryptography finds use in many areas, ranging from safety in payment portals, to secure messaging
platforms like WhatsApp. A few of those applications are as follows -

1 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Cryptography can be broadly classified into three different types -

1. Symmetric Key Cryptography

2. Asymmetric Key Cryptography

3. Hashing

1. Symmetric Key Cryptography

Symmetric key cryptography is the category where the same key is used for both the encryption
and decryption of information.

Example:

2 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Symmetric key algorithms use one of the two types of Ciphers -

 Stream Ciphers - The plaintext is converted to ciphertext bit-by-bit, one at a time.

 Block Ciphers - The plaintext is broken down into blocks/chunks of data encrypted
individually and later chained together.

The most widely used Symmetric Key Algorithms are AES (Advanced Encryption Standard),
DES (Data Encryption Standard), 3DES (Triple DES), Twofish, etc.

2. Asymmetric Key Cryptography

In asymmetric key cryptography, there are two keys at play. A public key and a private key. The
public key is used to encrypt the data pre-transit, and the private key is used to decrypt the data
post-transit.

Example:

3 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

RSA encryption is the most widely used asymmetric encryption standard today. Named after its
founders (Rivest, Shamir, and Adleman), it uses block ciphers that separate the data into blocks
and obscure the information.

3. Hashing

Hashing is the branch of cryptography that scrambles data beyond recognition. However, unlike
symmetric and asymmetric key cryptography, hashing isn’t designed to be reversible. It gives an
output of a fixed size, known as the hash value of the original data.

You can use hash functions to scramble the data. They are not reversible and the output size of a
hash function is always the same, irrespective of the size of the plaintext.

Cryptography Primitives

Cryptography primitives are nothing but the tools and techniques in Cryptography that can be
selectively used to provide a set of desired security services −

 Encryption

 Hash functions

 Message Authentication codes (MAC)

 Digital Signatures

The following table shows the primitives that can achieve a particular security service on their
own

4 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program1:XOR a string with a Zero

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.

PROGRAM:

#include <stdio.h>

int main() {

// Define the string

char *str = "Hello World";

// Loop through each character of the string

for (int i = 0; str[i] != '\0'; i++) {

// XOR each character with 0 (which doesn't change the character)

char result = str[i] ^ 0;

// Print the result (which should be the same as the original character)

printf("%c", result);

printf("\n"); // New line for better output formatting

return 0;

Output:

Hello World

5 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program2.XOR a string with a 127

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.

PROGRAM:

#include <stdio.h>

int main() {

// Define the string

char *str = "Hello World";

printf("Original String: %s\n", str);

// Perform AND and XOR operations on each character of the string

printf("\nAfter AND with 127:\n");

for (int i = 0; str[i] != '\0'; i++) {

char and_result = str[i] & 127;

printf("%c ", and_result); // Print the result after AND operation

printf("\nAfter XOR with 127:\n");

for (int i = 0; str[i] != '\0'; i++) {

char xor_result = str[i] ^ 127;

printf("%c ", xor_result); // Print the result after XOR operation

6 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

printf("\n");

return 0;

Explanation:

1. String Definition: We define a string str with the value "Hello World".

2. AND Operation: We loop through each character in the string, apply the bitwise AND
(&) operation with 127 (binary: 01111111), and print the result.

3. XOR Operation: We then apply the bitwise XOR (^) operation with 127 and print the
result.

4. Display: Both results are printed character by character, separated by spaces.

Bitwise Operations:

 AND with 127 (& 127): The binary value 127 is 01111111 (7 bits set to 1 and the 8th bit
set to 0), which essentially keeps the lower 7 bits of each character unchanged, clearing
the 8th bit (if it was set).

 XOR with 127 (^ 127): The XOR operation toggles the 7 lower bits of each character, so
characters will be changed depending on their original values.

Output:

Original String: Hello World

After AND with 127:

Hello World

After XOR with 127:

? `j j p E d q j p

7 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program3.Encryption & Decryption using Cipher Algorithms

AIM: Write a Java program to perform encryption and decryption using the following
algorithms:

a) Ceaser Cipher

b) Substitution Cipher

c) Hill Cipher

a) i).Ceaser Cipher Implementation:

It is introduced by Julius cipher.It is one of the simplest and most used encryption techniques.
In this technique, each letter of the given text is replaced by a letter of some fixed number of
positions down the alphabet.

For example, with a shift of 1, X would be replaced by Y, Y would become Z, and so on. Julius
Caesar was the first one who used it for communicating with his officials. Based on his name,
this technique was named as Caesar Cipher technique.

An integer value is required to cipher a given text. The integer value is known as shift, which
indicates the number of positions each letter of the text has been moved down.

ABCDEFGHIJKLMNOPQRSTUVWXYZ

DEFGHIJKLMNOPQRSTUVWXYZABC

1.Encryption :

It’s a process of encoding a message using an encryption algorithm that can only be accessed via
an authorized person.

2.Decryption :

It’s the process of converting an encrypted message to its original form.

3.Plaintext :

The message which needs to get to the end user, might or might not be formatted.

4.Ciphertext :

The text that results after an encryption algorithm is applied to the plaintext.

5.Shift :

Integer between 0-25 0−25 which tells us the number of shifts to be applied on a character.

8 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program:

import java.util.Scanner;

public class CaesarCipher {

// Method to encrypt the text using Caesar Cipher

public static String encrypt(String text, int shift) {

StringBuilder encrypted = new StringBuilder();

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

char c = text.charAt(i);

// Encrypt uppercase letters

if (Character.isUpperCase(c)) {

c = (char) (((c - 'A' + shift) % 26) + 'A');

// Encrypt lowercase letters

else if (Character.isLowerCase(c)) {

c = (char) (((c - 'a' + shift) % 26) + 'a');

encrypted.append(c);

return encrypted.toString();

// Method to decrypt the text using Caesar Cipher

public static String decrypt(String text, int shift) {

StringBuilder decrypted = new StringBuilder();

9 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

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

char c = text.charAt(i);

// Decrypt uppercase letters

if (Character.isUpperCase(c)) {

c = (char) (((c - 'A' - shift + 26) % 26) + 'A');

// Decrypt lowercase letters

else if (Character.isLowerCase(c)) {

c = (char) (((c - 'a' - shift + 26) % 26) + 'a');

decrypted.append(c);

return decrypted.toString();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Get user input for message and shift value

System.out.print("Enter the message: ");

String message = scanner.nextLine();

System.out.print("Enter the shift key: ");

int shift = scanner.nextInt();

// Encrypt the message

String encryptedMessage = encrypt(message, shift);

System.out.println("Encrypted Message: " + encryptedMessage);

10 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

// Decrypt the message

String decryptedMessage = decrypt(encryptedMessage, shift);

System.out.println("Decrypted Message: " + decryptedMessage);

scanner.close();

Output:

11 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

b).Substitution Cipher Implementation:

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.

Program:

import java.io.*;

import java.util.Scanner;

public class SubstitutionCipher {

public static String encrypt(String text) {

String key = "qwertyuiopasdfghjklzxcvbnm"; // Substitution key

StringBuilder encrypted = new StringBuilder();

for (char c : text.toCharArray()) {

if (Character.isLowerCase(c))

encrypted.append(key.charAt(c - 'a'));

else if (Character.isUpperCase(c))

encrypted.append(Character.toUpperCase(key.charAt(c - 'A')));

else encrypted.append(c);

return encrypted.toString();

public static String decrypt(String text) {

String key = "qwertyuiopasdfghjklzxcvbnm"; // Substitution key

String alphabet = "abcdefghijklmnopqrstuvwxyz";

StringBuilder decrypted = new StringBuilder();

for (char c : text.toCharArray()) {

if (Character.isLowerCase(c))

12 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

decrypted.append(alphabet.charAt(key.indexOf(c)));

else if (Character.isUpperCase(c))

decrypted.append(Character.toUpperCase(alphabet.charAt(key.indexOf(Character.toLowerCase(
c)))));

else decrypted.append(c);

return decrypted.toString();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter message: ");

String message = sc.nextLine();

String encrypted = encrypt(message);

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

String decrypted = decrypt(encrypted);

System.out.println("Decrypted: " + decrypted);

sc.close();

Output:

13 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

c)Hill Cipher Implementation:

In classical cryptography, the hill cipher is a polygraphic substitution cipher based on Linear
Algebra. It was invented by Lester S. Hill in the year 1929. In simple words, it is a cryptography
algorithm used to encrypt and decrypt data for the purpose of data security.

The algorithm uses matrix calculations used in Linear Algebra. It is easier to understand if we
have the basic knowledge of matrix multiplication, modulo calculation, and the inverse
calculation of matrices.

In hill cipher algorithm every letter (A-Z) is represented by a number moduli 26. Usually, the
simple substitution scheme is used where A = 0, B = 1, C = 2…Z = 25 in order to use 2x2 key
matrix.

1.Encryption:

To encrypt the text using hill cipher, we need to perform the following operation.

E(K, P) = (K * P) mod 26

Where K is the key matrix and P is plain text in vector form. Matrix multiplication of K and P
generates the encrypted ciphertext.

2. Decryption:

To encrypt the text using hill cipher, we need to perform the following operation.

D(K, C) = (K-1 * C) mod 26

Where K is the key matrix and C is the ciphertext in vector form. Matrix multiplication of inverse
of key matrix K and ciphertext C generates the decrypted plain text.

Program:

import java.util.ArrayList;

import java.util.Scanner;

public class HillCipherExample {

//method to accept key matrix

private static int[][] getKeyMatrix() {

Scanner sc = new Scanner(System.in);

14 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

System.out.println("Enter key matrix:");

String key = sc.nextLine();

//int len = key.length();

double sq = Math.sqrt(key.length());

if (sq != (long) sq) {

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

int len = (int) sq;

int[][] keyMatrix = new int[len][len];

int k = 0;

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

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

keyMatrix[i][j] = ((int) key.charAt(k)) - 97;

k++;

return keyMatrix;

// Below method checks whether the key matrix is valid (det=0)

private static void isValidMatrix(int[][] keyMatrix) {

int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0];

15 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

// If det=0, throw exception and terminate

if(det == 0) {

throw new java.lang.Error("Det equals to zero, invalid key matrix!");

// This method checks if the reverse key matrix is valid (matrix mod26 = (1,0,0,1)

private static void isValidReverseMatrix(int[][] keyMatrix, int[][] reverseMatrix) {

int[][] product = new int[2][2];

// Find the product matrix of key matrix times reverse key matrix

product[0][0] = (keyMatrix[0][0]*reverseMatrix[0][0] + keyMatrix[0][1] *


reverseMatrix[1][0]) % 26;

product[0][1] = (keyMatrix[0][0]*reverseMatrix[0][1] + keyMatrix[0][1] *


reverseMatrix[1][1]) % 26;

product[1][0] = (keyMatrix[1][0]*reverseMatrix[0][0] + keyMatrix[1][1] *


reverseMatrix[1][0]) % 26;

product[1][1] = (keyMatrix[1][0]*reverseMatrix[0][1] + keyMatrix[1][1] *


reverseMatrix[1][1]) % 26;

// Check if a=1 and b=0 and c=0 and d=1

// If not, throw exception and terminate

if(product[0][0] != 1 || product[0][1] != 0 || product[1][0] != 0 || product[1][1] != 1) {

throw new java.lang.Error("Invalid reverse matrix found!");

// This method calculates the reverse key matrix

private static int[][] reverseMatrix(int[][] keyMatrix) {

16 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

int detmod26 = (keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1][0]) %


26; // Calc det

int factor;

int[][] reverseMatrix = new int[2][2];

// Find the factor for which is true that

// factor*det = 1 mod 26

for(factor=1; factor < 26; factor++)

if((detmod26 * factor) % 26 == 1)

break;

// Calculate the reverse key matrix elements using the factor found

reverseMatrix[0][0] = keyMatrix[1][1] * factor % 26;

reverseMatrix[0][1] = (26 - keyMatrix[0][1]) * factor % 26;

reverseMatrix[1][0] = (26 - keyMatrix[1][0]) * factor % 26;

reverseMatrix[1][1] = keyMatrix[0][0] * factor % 26;

return reverseMatrix;

// This method echoes the result of encrypt/decrypt

private static void echoResult(String label, int adder, ArrayList<Integer> phrase) {

int i;

System.out.print(label);

17 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

// Loop for each pair

for(i=0; i < phrase.size(); i += 2) {

System.out.print(Character.toChars(phrase.get(i) + (64 + adder)));

System.out.print(Character.toChars(phrase.get(i+1) + (64 + adder)));

if(i+2 <phrase.size()) {

System.out.print("-");

System.out.println();

// This method makes the actual encryption

public static void encrypt(String phrase, boolean alphaZero)

int i;

int adder = alphaZero ? 1 : 0; // For calclulations depending on the alphabet

int[][] keyMatrix;

ArrayList<Integer> phraseToNum = new ArrayList<>();

ArrayList<Integer> phraseEncoded = new ArrayList<>();

// Delete all non-english characters, and convert phrase to upper case

phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();

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

if(phrase.length() % 2 == 1) {

phrase += "Q";

18 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

// Get the 2x2 key matrix from sc

keyMatrix = getKeyMatrix();

// Check if the matrix is valid (det != 0)

isValidMatrix(keyMatrix);

// Convert characters to numbers according to their

// place in ASCII table minus 64 positions (A=65 in ASCII table)

// If we use A=0 alphabet, subtract one more (adder)

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

phraseToNum.add(phrase.charAt(i) - (64 + adder));

// Find the product per pair of the phrase with the key matrix modulo 26

// If we use A=1 alphabet and result is 0, replace it with 26 (Z)

for(i=0; i < phraseToNum.size(); i += 2) {

int x = (keyMatrix[0][0] * phraseToNum.get(i) + keyMatrix[0][1] *


phraseToNum.get(i+1)) % 26;

int y = (keyMatrix[1][0] * phraseToNum.get(i) + keyMatrix[1][1] *


phraseToNum.get(i+1)) % 26;

phraseEncoded.add(alphaZero ? x : (x == 0 ? 26 : x ));

phraseEncoded.add(alphaZero ? y : (y == 0 ? 26 : y ));

// Print the result

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

19 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

// This method makes the actual decryption

public static void decrypt(String phrase, boolean alphaZero)

int i, adder = alphaZero ? 1 : 0;

int[][] keyMatrix, revKeyMatrix;

ArrayList<Integer> phraseToNum = new ArrayList<>();

ArrayList<Integer> phraseDecoded = new ArrayList<>();

// Delete all non-english characters, and convert phrase to upper case

phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();

// Get the 2x2 key matrix from sc

keyMatrix = getKeyMatrix();

// Check if the matrix is valid (det != 0)

isValidMatrix(keyMatrix);

// Convert numbers to characters according to their

// place in ASCII table minus 64 positions (A=65 in ASCII table)

// If we use A=0 alphabet, subtract one more (adder)

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

phraseToNum.add(phrase.charAt(i) - (64 + adder));

// Find the reverse key matrix

revKeyMatrix = reverseMatrix(keyMatrix);

// Check if the reverse key matrix is valid (product = 1,0,0,1)

20 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

isValidReverseMatrix(keyMatrix, revKeyMatrix);

// Find the product per pair of the phrase with the reverse key matrix modulo 26

for(i=0; i < phraseToNum.size(); i += 2) {

phraseDecoded.add((revKeyMatrix[0][0] * phraseToNum.get(i) + revKeyMatrix[0][1] *


phraseToNum.get(i+1)) % 26);

phraseDecoded.add((revKeyMatrix[1][0] * phraseToNum.get(i) + revKeyMatrix[1][1] *


phraseToNum.get(i+1)) % 26);

// Print the result

echoResult("Decoded phrase: ", adder, phraseDecoded);

//main method

public static void main(String[] args) {

String opt, phrase;

byte[] p;

Scanner sc = new Scanner(System.in);

System.out.println("Hill Cipher Implementation (2x2)");

System.out.println("-------------------------");

System.out.println("1. Encrypt text (A=0,B=1,...Z=25)");

System.out.println("2. Decrypt text (A=0,B=1,...Z=25)");

System.out.println("3. Encrypt text (A=1,B=2,...Z=26)");

System.out.println("4. Decrypt text (A=1,B=2,...Z=26)");

System.out.println();

System.out.println("Type any other character to exit");

21 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

System.out.println();

System.out.print("Select your choice: ");

opt = sc.nextLine();

switch (opt)

case "1":

System.out.print("Enter phrase to encrypt: ");

phrase = sc.nextLine();

encrypt(phrase, true);

break;

case "2":

System.out.print("Enter phrase to decrypt: ");

phrase = sc.nextLine();

decrypt(phrase, true);

break;

case "3":

System.out.print("Enter phrase to encrypt: ");

phrase = sc.nextLine();

encrypt(phrase, false);

break;

case "4":

System.out.print("Enter phrase to decrypt: ");

phrase = sc.nextLine();

22 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

decrypt(phrase, false);

break;

Output:

23 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

4. Write a C/JAVA program to implement the DES algorithm logic.

DES stands for Data Encryption Standard. It is a symmetric-key block cipher algorithm used to
encrypt and decrypt data. It is developed by the IBM team in early 1970. It accepts the plaintext
in 64-bit blocks and changes it into the ciphertext that uses the 64-bit keys to encrypt the data. The
algorithm uses the same key to encrypt and decrypt the data.

It is based on LUCIFER (also known as Feistel block cipher algorithm) which is a direct
predecessor of the DES algorithm. It is developed by eminent scholar and researcher Horst
Feistel at IBM. It provides high security by using a 128-bit key block and a 128-bit block size. The
DES algorithm uses the 16 rounds of the Feistel structure. The structure uses a unique key for each
round. Finally, in 1976, it was approved by the federal encryption standard.

24 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program:

import java.awt.datatransfer.StringSelection;

import java.io.DataInputStream;

/*

* Link For reference: https://www.brainkart.com/article/Simplified-Data-Encryption-Standard-


(S-DES)_8343/

public class SDES {

public int K1,K2;

//Note: below matrics will be provided in lab(PICT)..

//For performing P10 permutation

public static final int P10[] = { 3, 5, 2, 7, 4, 10, 1, 9, 8, 6};

public static final int P10max = 10;

//10 to 8 bit permutation

public static final int P8[] = { 6, 3, 7, 4, 8, 5, 10, 9};

public static final int P8max = 10;

public static final int P4[] = { 2, 4, 3, 1};

public static final int P4max = 4;

//Performing initial permutaion

public static final int IP[] = { 2, 6, 3, 1, 4, 8, 5, 7};

public static final int IPmax = 8;

//performing final permuttaion(Inverse of initial permutation)

public static final int IPI[] = { 4, 1, 3, 5, 7, 2, 8, 6};

public static final int IPImax = 8;

//expansion/permutation operation:Used in F1 Function

public static final int EP[] = { 4, 1, 2, 3, 2, 3, 4, 1};

25 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

public static final int EPmax = 4;

public static final int S0[][] = {{ 1, 0, 3, 2},{ 3, 2, 1, 0},{ 0, 2, 1,

3},{ 3, 1, 3, 2}};

public static final int S1[][] = {{ 0, 1, 2, 3},{ 2, 0, 1, 3},{ 3, 0, 1,

2},{ 2, 1, 0, 3}};

/*

* Generic Function to perform all permutations

*/

public static int permute(int x, int p[], int pmax) {

int y=0;

//System.out.println(Integer.toBinaryString(x));

/*

String binary=Integer.toBinaryString(x);

StringBuffer br=new StringBuffer(new String(new char[10]).replace("\0", "0"));

*/

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

// br.setCharAt(i, binary.charAt(p[i]-1));

y=y<<1;

y=y|(x>>(pmax-p[i]))&1;

//System.out.println("Final :"+Integer.toBinaryString(y));

return y;

public static int F( int R, int K)

26 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

int t = permute( R, EP, EPmax) ^ K;

int t0 = (t >> 4) & 0xF;

int t1 = t & 0xF;

t0 = S0[ ((t0 & 0x8) >> 2) | (t0 & 1) ][ (t0 >> 1) & 0x3 ];

t1 = S1[ ((t1 & 0x8) >> 2) | (t1 & 1) ][ (t1 >> 1) & 0x3 ];

t = permute( (t0 << 2) | t1, P4, P4max);

return t;

public static int fK( int m, int K)

int L = (m >> 4) & 0xF;

int R = m & 0xF;

return ((L ^ F(R,K)) << 4) | R;

public static int SW( int x)

return ((x & 0xF) << 4) | ((x >> 4) & 0xF);

/*

* Ciphertext = IP-1 (fK2 (SW (fk1 (IP (plaintext))))

*/

public byte encrypt( int m)

27 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

System.out.println("\nEncryption Process Starts........\n\n");

m = permute( m, IP, IPmax);

System.out.print("\nAfter Initial Permutation(IP) : ");

printData( m, 8);

m = fK( m, K1);

System.out.print("\nbefore Swap : ");

printData( m, 8);

m = SW( m);

System.out.print("\nAfter Swap : ");

printData( m, 8);

m = fK( m, K2);

System.out.print("\nbefore IP inverse : ");

printData( m, 8);

m = permute( m, IPI, IPImax);

return (byte) m;

/*

* Plaintext = IP-1 (fK1 (SW (fk2 (IP (ciphertext)))))

*/

public byte decrypt( int m)

System.out.println("\nDecryption Process Starts........\n\n");

printData( m, 8);

28 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

m = permute( m, IP, IPmax);

System.out.print("\nAfter Permutation : ");

printData( m, 8);

m = fK( m, K2);

System.out.print("\nbefore Swap : ");

printData( m, 8);

m = SW( m);

System.out.print("\nAfter Swap : ");

printData( m, 8);

m = fK( m, K1);

System.out.print("\nBefore Extraction Permutation : ");

printData( m, 4);

m = permute( m, IPI, IPImax);

System.out.print("\nAfter Extraction Permutation : ");

printData( m, 8);

return (byte) m;

public static void printData( int x, int n)

int mask = 1 << (n-1);

while( mask > 0)

System.out.print( ((x & mask) == 0) ? '0' : '1');

mask >>= 1;

29 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

/*

* K1 = P8 (Shift_1 (P10 (Key)))

K2 = P8 (Shift_2 (shift_1 (P10 (Key))))

*/

public SDES( int K) //COnstructor generates key k1 & k2 used for encyption

K = permute( K, P10, P10max);

int t1 = (K >> 5) & 0x1F;

int t2 = K & 0x1F;

t1 = ((t1 & 0xF) << 1) | ((t1 & 0x10) >> 4);

t2 = ((t2 & 0xF) << 1) | ((t2 & 0x10) >> 4);

K1 = permute( (t1 << 5)| t2, P8, P8max);

t1 = ((t1 & 0x7) << 2) | ((t1 & 0x18) >> 3);

t2 = ((t2 & 0x7) << 2) | ((t2 & 0x18) >> 3);

K2 = permute( (t1 << 5)| t2, P8, P8max);

@SuppressWarnings("deprecation")

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

DataInputStream inp=new DataInputStream(System.in);

System.out.println("Enter the 10 Bit Key :"); //1011011010

int K = Integer.parseInt(inp.readLine(),2);

30 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

SDES A = new SDES( K);

System.out.println("Enter the 8 Bit message To be Encrypt : ");

int m = Integer.parseInt(inp.readLine(),2); //10110110

System.out.print("\nKey K1: ");

SDES.printData( A.K1, 8);

System.out.print("\nKey K2: ");

SDES.printData( A.K2, 8);

m = A.encrypt( m);

System.out.print("\nEncrypted Message: ");

SDES.printData( m, 8);

m = A.decrypt( m);

System.out.print("\nDecrypted Message: ");

SDES.printData( m, 8);

31 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Output:

32 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

5. Write a C/JAVA program to implement the Blowfish algorithm logic.

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 substitution boxes: 4 [each having 512 entries of 32-bits each]

Program:

import java.io.UnsupportedEncodingException;

import java.nio.charset.Charset;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.util.Base64;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.spec.SecretKeySpec;

/**

* This program demonstrates how to encrypt/decrypt

* input using the Blowfish

* Cipher with the Java Cryptography.

33 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

*/

public class BlowfishDemo {

public String encrypt(String password, String key) throws

NoSuchAlgorithmException, NoSuchPaddingException,

InvalidKeyException, IllegalBlockSizeException,

BadPaddingException, UnsupportedEncodingException {

byte[] KeyData = key.getBytes();

SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");

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

cipher.init(Cipher.ENCRYPT_MODE, KS);

String encryptedtext = Base64.getEncoder().

encodeToString(cipher.doFinal(password.getBytes("UTF-8")));

return encryptedtext;

public String decrypt(String encryptedtext, String key)

throws NoSuchAlgorithmException, NoSuchPaddingException,

InvalidKeyException, IllegalBlockSizeException,

BadPaddingException {

byte[] KeyData = key.getBytes();

SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");

byte[] ecryptedtexttobytes = Base64.getDecoder().

decode(encryptedtext);

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

34 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

cipher.init(Cipher.DECRYPT_MODE, KS);

byte[] decrypted = cipher.doFinal(ecryptedtexttobytes);

String decryptedString =

new String(decrypted, Charset.forName("UTF-8"));

return decryptedString;

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

final String password = "Knf@123";

final String key = "knowledgefactory";

System.out.println("Password: " + password);

BlowfishDemo obj = new BlowfishDemo();

String enc_output = obj.encrypt(password, key);

System.out.println("Encrypted text: " + enc_output);

String dec_output = obj.decrypt(enc_output, key);

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

}}

Output:

35 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

6. Write a C/JAVA program to implement the Rijndael algorithm logic.

The AES Encryption algorithm (also known as the Rijndael algorithm) is a symmetric block
cipher algorithm with a block/chunk size of 128 bits.

It is not a Feistel cipher. – It works in parallel over the whole input block.

• Designed to be efficient both in hardware and software across a

variety of platforms.

• It’s a block cipher which works iteratively

• Block size: 128 bit (but also 192 or 256 bit)

• Key length: 128, 192, or 256 bit

• Number of rounds: 10, 12 o 14

• Key scheduling: 44, 52 or 60 subkeys having length = 32 bit

Each round (except the last one) is a uniform and parallel composition

of 4 steps

• SubBytes (byte-by-byte substitution using an S-box)

• ShiftRows (a permutation, which cyclically shifts the last three rows in the State)

• MixColumns (substitution that uses Galois Fields, corps de Galois, GF(28) arithmetic)

• AddRound key (bit-by- bit XOR with an expanded key)

36 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Program:

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.PBEKeySpec;

import javax.crypto.spec.SecretKeySpec;

import java.nio.charset.StandardCharsets;

import java.security.InvalidAlgorithmParameterException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.KeySpec;

import java.util.Base64;

import javax.crypto.BadPaddingException;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

public class AESExample

/* Private variable declaration */

private static final String SECRET_KEY = "123456789";

private static final String SALTVALUE = "abcdefg";

/* Encryption Method */

public static String encrypt(String strToEncrypt)

37 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

try

/* Declare a byte array. */

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

IvParameterSpec ivspec = new IvParameterSpec(iv);

/* Create factory for secret keys. */

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

/* PBEKeySpec class implements KeySpec interface. */

KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(),


SALTVALUE.getBytes(), 65536, 256);

SecretKey tmp = factory.generateSecret(spec);

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

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);

/* Retruns encrypted value. */

return Base64.getEncoder()

.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));

catch (InvalidAlgorithmParameterException | InvalidKeyException |


NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException |
IllegalBlockSizeException | NoSuchPaddingException e)

System.out.println("Error occured during encryption: " + e.toString());

return null;

38 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

/* Decryption Method */

public static String decrypt(String strToDecrypt)

try

/* Declare a byte array. */

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

IvParameterSpec ivspec = new IvParameterSpec(iv);

/* Create factory for secret keys. */

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

/* PBEKeySpec class implements KeySpec interface. */

KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(),


SALTVALUE.getBytes(), 65536, 256);

SecretKey tmp = factory.generateSecret(spec);

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

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);

/* Retruns decrypted value. */

return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));

catch (InvalidAlgorithmParameterException | InvalidKeyException |


NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException |
IllegalBlockSizeException | NoSuchPaddingException e)

System.out.println("Error occured during decryption: " + e.toString());

39 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

return null;

/* Driver Code */

public static void main(String[] args)

/* Message to be encrypted. */

String originalval = "AES Encryption";

/* Call the encrypt() method and store result of encryption. */

String encryptedval = encrypt(originalval);

/* Call the decrypt() method and store result of decryption. */

String decryptedval = decrypt(encryptedval);

/* Display the original message, encrypted message and decrypted message on the console.
*/

System.out.println("Original value: " + originalval);

System.out.println("Encrypted value: " + encryptedval);

System.out.println("Decrypted value: " + decryptedval);

Output:

40 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

7. Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello world”
using Blowfish. Create your own key using Java key tool.

RC4 is a symmetric stream cipher and variable key length algorithm. This symmetric key
algorithm is used identically for encryption and decryption such that the data stream is
simply XORed with the generated key sequence. The algorithm is serial as it requires successive
exchanges of state entries based on the key sequence. The algorithm works in two phases:

Key Scheduling Algorithm(KSA):

 It is used to generate a State array by applying a permutation using a variable-length key


consisting of 0 to 256 bytes.

 The state vector is identified as S[0], S[1]…. S[255] is initialized with {0, 1, 2, …, 255}.
The key K[0], K[1], …., K[255] can be of any length from 0 to 256 bytes and is used to
initialize permutation S. Each K[I] and S[I] is a byte.

 K is a temporary array if the length of the key is 256 bytes copy it to K else after copying
the remaining positions of K are filled with repeated Key Values until full.

Program:

import java.io.*;

class rc4

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

int temp=0;

String ptext;

String key;

int s[]=new int[256];

int k[]=new int[256];

DataInputStream in=new DataInputStream(System.in);

System.out.print(“\nENTER PLAIN TEXT\t”);

ptext=in.readLine();

41 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

System.out.print(“\n \nENTER KEY TEXT\t\t”);

key=in.readLine();

char ptextc[]=ptext.toCharArray();

char keyc[]=key.toCharArray();

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

int decrypt[]=new int[ptext.length()];

int ptexti[]=new int[ptext.length()];

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

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

ptexti[i]=(int)ptextc[i]; }

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

keyi[i]=(int)keyc[i]; }

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

s[i]=i;

k[i]=keyi[i%key.length()]; }

int j=0;

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

j=(j+s[i]+k[i])%256;

temp=s[i];

s[i]=s[j];

s[j]=temp; }

int i=0;

j=0;

int z=0;

for(int l=0;l<ptext.length();l++) {

42 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

i=(l+1)%256;

j=(j+s[i])%256;

temp=s[i];

s[i]=s[j];

s[j]=temp;

z=s[(s[i]+s[j])%256];

cipher[l]=z^ptexti[l];

decrypt[l]=z^cipher[l];

System.out.print(“\n\nENCRYPTED:\t\t”);

display(cipher);

System.out.print(“\n\nDECRYPTED:\t\t”);

display(decrypt);

static void display(int disp[])

char convert[]=new char[disp.length];

for(int l=0;l<disp.length;l++)

convert[l]=(char)disp[l];

System.out.print(convert[l]);

} /*

43 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Output:

44 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

8. Write a Java program to implement RSA algorithm.

RSA or Rivest–Shamir–Adleman is an algorithm employed by modern computers to encrypt and


decrypt messages. It is an asymmetric cryptographic algorithm. Asymmetric means that there are
two different keys. This is also called public-key cryptography because one among the keys are
often given to anyone. The other is the private key which is kept private. The algorithm is
predicated on the very fact that finding the factors of an outsized number is difficult: when the
factors are prime numbers, the matter is named prime factorization. It is also a key pair (public and
personal key) generator.

Example:

Generating Public Key

1. Select two prime no's. Suppose P = 53 and Q = 59.

Now First part of the Public key : n = P*Q = 3127.

2. 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.

The public key has been made of n and e

Generating Private Key

1. We need to calculate Φ(n) :

Such that Φ(n) = (P-1)(Q-1)

so, Φ(n) = 3016

2. Now calculate Private Key, d :

d = (k*Φ(n) + 1) / e for some integer k

3. For k = 2, value of d is 2011.

The private key has been made of d

45 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

1. Consider two prime numbers p and q.

2. Compute n = p*q

3. Compute ϕ(n) = (p – 1) * (q – 1)

4. Choose e such gcd(e , ϕ(n) ) = 1

5. Calculate d such e*d mod ϕ(n) = 1

6. Public Key {e,n} Private Key {d,n}

7. Cipher text C = Pe mod n where P = plaintext

8. For Decryption D = Dd mod n where D will refund the plaintext.

Program:

// Java Program to Implement the RSA Algorithm

import java.math.*;

import java.util.*;

class RSA {

public static void main(String args[])

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;

46 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

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

47 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

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

}}

Output:

48 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.

The Diffie-Hellman algorithm was first published in 1976, and it has become a staple for any kind of
cryptography. Whenever we use cryptography, we usually need to have a symmetric key, and to get that,
we have to perform some kind of Diffie-Hellman.

Step by Step Explanation


Alice Bob

Public Keys available = P, G Public Keys available = P, G

Private Key Selected = a Private Key Selected = b

Exchange of generated keys takes place

Key received = y key received = x

Generated Secret Key = Generated Secret Key =

Algebraically, it can be shown that

Users now have a symmetric secret key to encrypt


Example:

Step 1: Alice and Bob get public numbers P = 23, G = 9

Step 2: Alice selected a private key a = 4 and

Bob selected a private key b = 3

Step 3: Alice and Bob compute public values

Alice: x =(9^4 mod 23) = (6561 mod 23) = 6

49 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Bob: y = (9^3 mod 23) = (729 mod 23) = 16

Step 4: Alice and Bob exchange public numbers

Step 5: Alice receives public key y =16 and

Bob receives public key x = 6

Step 6: Alice and Bob compute symmetric keys

Alice: ka = y^a mod p = 65536 mod 23 = 9

Bob: kb = x^b mod p = 216 mod 23 = 9

Step 7: 9 is the shared secret.

Program:

Index.html:

<!DOCTYPE HTML>

<html>

<body>

<h1>Diffie Hellman</h1>

<br>

<br>

<div id="generate-shared-key">

Prime<input type="number" id="shared-prime" />

Base<input type="number" id="shared-base" />

Integer<input type="number" id="shared-integer" />

</div>

<br>

<br>

<div >

Public key<input type="number" id="shared-key" disabled="true" />

</div>

50 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

<br>

<br>

<div id="generate-secret-key">

<div >

Prime<input type="number" id="secret-prime" />

Integer<input type="number" id="secret-integer" />

Public Key Pair<input type="number" id="secret-shared" />

</div >

<div>

<br>

<br>

Secret key<input type="number" id="secret-key" disabled="true" />

</div>

</div>

<script src="js/jquery.min.js"></script>

<script src="js/diffie-hellman.js"></script>

</body>

</html>

Diffie-hellman.js:

var diffieHellman = {

getPKDH: function(prime, base, integer){

return Math.pow(base, integer) % prime;

},

getSKDH: function(prime, integer, public_key){

return Math.pow(public_key, integer) % prime;

},

51 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

$(document).ready(function() {

var apps = {

unit_testing: function(prime,base,a,b){

var public_key_a = diffieHellman.getPKDH(prime,base,a);

var public_key_b = diffieHellman.getPKDH(prime,base,b);

var s1 = diffieHellman.getSKDH(prime,a,public_key_b);

var s2 = diffieHellman.getSKDH(prime,b,public_key_a);

},

generatePublicKey: function(){

var shared_prime = $('#shared-prime').val();

var shared_base = $('#shared-base').val();

var shared_integer = $('#shared-integer').val();

$('#shared-key').val(diffieHellman.getPKDH(shared_prime,shared_base,shared_integer));

},

generateSharedSecret: function(){

var secret_prime = $('#secret-prime').val();

var secret_integer = $('#secret-integer').val();

var secret_shared = $('#secret-shared').val();

$('#secret-
key').val(diffieHellman.getSKDH(secret_prime,secret_integer,secret_shared));

},

};

$('#shared-prime, #shared-base, #shared-integer').change(apps.generatePublicKey);

$('#secret-prime, #secret-integer, #secret-shared').change(apps.generateSharedSecret);

});

52 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

Output:

53 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

SHA is an abbreviation for Secure Hash Algorithm. In Java SHA and is one of the most
prevalent cryptographic hash functions. A cryptographic hash can be used to create a text signature
or data file. Now, SHA is nothing but a cryptographic hash function that takes input as much as
20 bytes long and returns a hexadecimal hash value which is approximately 40 digits in length.
The SHA-256 algorithm is capable of producing nearly a unique, non-static 256-bit (i.e., 32-byte)
hash value. But the point to remember is that this function is only a one-way function, i.e., the
result it produces cannot be decrypted back to its original value.

Java provides a class named MessageDigest which belongs to the package java.security. This
class supports algorithms such as SHA-1, SHA 256, MD5 algorithms to convert an arbitrary
length message to a message digest.

To convert a given message to a message digest, follow the steps given below −

Step 1: Create a MessageDigest object

The MessageDigest class provides a method named getInstance(). This method accepts a String
variable specifying the name of the algorithm to be used and returns a MessageDigest object
implementing the specified algorithm.

Create MessageDigest object using the getInstance() method as shown below.

MessageDigest md = MessageDigest.getInstance("SHA-256");

Step 2: Pass data to the created MessageDigest object

54 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

After creating the message digest object, you need to pass the message/data to it. You can do so
using the update() method of the MessageDigest class, this method accepts a byte array
representing the message and adds/passes it to the above created MessageDigest object.

md.update(msg.getBytes());

Step 3: Generate the message digest

You can generate the message digest using the digest() method od the MessageDigest class this
method computes the hash function on the current object and returns the message digest in the
form of byte array.

Generate the message digest using the digest method.

byte[] digest = md.digest();

Program:

import java.security.MessageDigest;

import java.util.Scanner;

public class MessageDigestExample {

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

//Reading data from user

Scanner sc = new Scanner(System.in);

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

String message = sc.nextLine();

//Creating the MessageDigest object

MessageDigest md = MessageDigest.getInstance("SHA-256");

//Passing data to the created MessageDigest Object

md.update(message.getBytes());

//Compute the message digest

byte[] digest = md.digest();

System.out.println(digest);

55 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

//Converting the byte array in to HexString format

StringBuffer hexString = new StringBuffer();

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

hexString.append(Integer.toHexString(0xFF & digest[i]));

System.out.println("Hex format : " + hexString.toString());

Output:

Enter the message:

Hello how are you

[B@55f96302

Hex format: 2953d33828c395aebe8225236ba4e23fa75e6f13bd881b9056a3295cbd64d3

56 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

11. Calculate the message digest of a text using the MD5 algorithm in JAVA.

MD5 (Message Digest Method 5) is a cryptographic hash algorithm used to generate a 128-bit
digest from a string of any length. It represents the digests as 32 digit hexadecimal numbers.

The digest size is always 128 bits, and thanks to hashing function guidelines, a minor change in
the input string generate a drastically different digest. This is essential to prevent similar hash
generation as much as possible, also known as a hash collision.

Program:

import java.security.*;

public class MD5 {

public static void main(String[] a) {

// TODO code application logic here

57 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

try {

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

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

58 | Page Mr.V.Manikyala Rao,Assistant Professor


IV-I CNS LAB MANUAL DEPARTMENT OF CSE,MRIT

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

return buf.toString(); } }

Output:

Message digest object info:

Algorithm = MD5

Provider = SUN version 1.6

ToString = MD5 Message Digest from SUN, <initialized> MD5("") =

D41D8CD98F00B204E9800998ECF8427E MD5("abc") =

900150983CD24FB0D6963F7D28E17F72 MD5("abcdefghijklmnopqrstuvwxyz")

= C3FCD3D76192E4007DFB496CCA67E13B

59 | Page Mr.V.Manikyala Rao,Assistant Professor

You might also like