Cns Lab Manual k.durga

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

SRK INSTITUTE OF TECHNOLOGY

Approved by AICTE, Affiliated to JNTUK, Kakinada


(ISO 9001:2015 Certified Institution)
Department of Computer Science and Engineering

CRYPTOGRAPHY NETWORK SECURITY


LAB MANUAL

(III B.Tech II Sem R20 Regulation)

Enikepadu, Vijayawada 521108

Prepared by

K.Durgabhavani
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

List of Experiments:
1. 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 displays the result.
2. 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
3. Write a Java program to perform encryption and decryption using the following algorithms:
a) Ceaser Cipher b) Substitution Cipher c) Hill Cipher
4. Write a Java program to implement the DES algorithm logic
5. Write a C/JAVA program to implement the BlowFish algorithm logic.
6. Write a C/JAVA program to implement the Rijndael algorithm logic.
7. Using Java Cryptography, encrypt the text “Hello world” using BlowFish. Create your own
key using Java key tool.
8. Write a Java program to implement RSA Algorithm
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
Consider the end user as one of the parties (Alice) and the JavaScript application as other party
(bob).
10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

content beyond the syllabus


1. Calculate the message digest of a text using the MD-5 algorithm in JAVA
2. To implement the Vigenere Cipher substitution technique using C program.
1. 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 displays the result?

Source code:
#include<stdlib.h
>
#include<conio.h
>
#include<string.h>
#include<stdio.h>
void 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");
getch();
}
Output:

2. 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 displays
the result?
Source code:
#include<stdlib.h
>
#include<conio.h
>
#include<string.h>
#include<stdio.h>
void main()
{
char str[]="Hello World";
char str1[11];
char str2[11];
int i,len;
len=strlen(str)
;
for(i=0;i<len;i++)
{
str1[i]=str[i]&127;
printf("%c",str1[i])
;
}
printf("\n");
for(i=0;i<len;i+
+)
{
str2[i]=str[i]^127;
printf("%c",str2[i])
;
}
printf("\
n");
getch();
}
Output:

3. Write a Java program to perform encryption and decryption using the


followingalgorithms:
a. Ceaser cipher
b. Substitution cipher
c. Hill cipher

a. Ceaser cipher:-
source code:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Scanner;

public class CeaserCipher

static Scanner sc=new Scanner(System.in);

static BufferedReader br=new


BufferedReader(new
InputStreamReader(System.in));
public static void main(String[] args) throws IOException

System.out.println("Enter any

string:"); String str=br.readLine();

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

int key=sc.nextInt();

String encrypted=encrypt(str,key); System.out.println("\

n Encrypted string is:"+encrypted); String

decrypted=decrypt (encrypted,key);

System.out.println("\n Decrypted string

is:"+decrypted); System.out.println("\n");

public static String encrypt(String str,int key)

String encrypted=" ";

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

int c=str.charAt(i);

if(Character.isUpperCase(c)

c=c+(key

%26); if(c>'Z')

c=c-26;

else if(Character.isLowerCase(c))
{

c=c+(key

%26); if(c>'z')

c=c-26;

encrypted+=(char)c;

return encrypted;

public static String decrypt(String str,int key)

String decrypted=" ";

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

int c=str.charAt(i);

if(Character.isUpperCase(c)

c=c-(key%26);

if(c<'A'

c=c+26;

else if(Character.isLowerCase(c))

c=c-(key%26);

if(c<'a')
c=c+26;

decrypted+=(char)c;

return decrypted;

Output:

b. substitution cipher source code:


source code:
import java.io.*;
import java.util.*;

public class SubstitutionCipher

static Scanner sc=new Scanner(System.in);

static BufferedReader br= new BufferedReader(new


InputStreamReader(System.in));

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

String

a="abcdefghijklmnopqrstuvwxyz"; String

b="zyxwvutsrqponmlkjihgfedcba";

System.out.print("Enter any string");

String str=br.readLine();

String

decrypt=""; char
c;

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


{

c=str.charAt(i);

int j= a.indexOf(c);

decrypt= decrypt+b.charAt(j);

System.out.println("The encrypted data is:"+decrypt);

}
Output:

c) Hill cipher
Hill cipher

Hill cipher is a poly graphic 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-componentvector)
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).
source code:

class H

{
// Following function generates the

// key matrix for the key string

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

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

// Function to implement Hill Cipher


static void HillCipher(String message, String key)

// Get key matrix from the key string

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

getKeyMatrix(key, keyMatrix);

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

// Generate vector for the message

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

messageVector[i][0] = (message.charAt(i)) % 65;

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

// Following function generates

// the encrypted vector

encrypt(cipherMatrix, keyMatrix, messageVector);

String CipherText="";

// Generate the encrypted text from

// the encrypted vector

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

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


// Finally print the ciphertext System.out.print("

Ciphertext:" + CipherText);

public static void main(String[] args)

// Get the message to be

encryptedString message = "SAF";

// Get the key

String key = "CIPHERING";

HillCipher(message, key);

Output:
4. Write a java program to implement DES algorithm logic
Source code:

import java.util.*;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class DES

private static final String UNICODE_FORMAT = "UTF8";

public static final String DESEDE_ENCRYPTION_SCHEME =


"DESede"
;
private KeySpec myKeySpec;

private SecretKeyFactory mySecretKeyFactory;

private Cipher cipher;

byte[] keyAsBytes;

private String myEncryptionKey;

private String

myEncryptionScheme; SecretKey

key;

static BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

public DES() throws Exception


{

// TODO code application logic here myEncryptionKey=

"ThisIsSecretEncryptionKey";

myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
keyAsBytes =myEncryptionKey.getBytes(UNICODE_FORMAT);

myKeySpec= new

DESedeKeySpec(keyAsBytes);

mySecretKeyFactory =
SecretKeyFactory.getInstance(myEncryptionScheme);

cipher = Cipher.getInstance(myEncryptionScheme);

key = mySecretKeyFactory.generateSecret(myKeySpec);

public String encrypt(String unencryptedString)

String encryptedString = null;try {

cipher.init(Cipher.ENCRYPT_MODE,

key);

byte[] plainText =
unencryptedString.getBytes(UNICODE_FORMAT)
;

byte[] encryptedText = cipher.doFinal(plainText);

BASE64Encoder base64encoder = new BASE64Encoder();

encryptedString = base64encoder.encode(encryptedText);

catch (Exception e)

e.printStackTrace();

return encryptedString;

public String decrypt(String encryptedString)


{

String decryptedText=null;try

cipher.init(Cipher.DECRYPT_MODE, key);

BASE64Decoder base64decoder = new BASE64Decoder();

byte[] encryptedText =
base64decoder.decodeBuffer(encryptedString)
;

byte[] plainText =

cipher.doFinal(encryptedText); decryptedText=

bytes2String(plainText);

catch (Exception e)

e.printStackTrace();

return decryptedText;

private static String bytes2String(byte[] bytes)

StringBuffer stringBuffer = new StringBuffer();

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

stringBuffer.append((char) bytes[i]);

}
return stringBuffer.toString();

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

System.out.print("Enter the

string: ");

DES myEncryptor= new

DES();

String stringToEncrypt = br.readLine();

String encrypted = myEncryptor.encrypt(stringToEncrypt);

String decrypted = myEncryptor.decrypt(encrypted);

System.out.println("\nString To Encrypt:

"+stringToEncrypt);

System.out.println("\nEncrypted Value : " +encrypted);

System.out.println("\nDecrypted Value : " +decrypted);

System.out.println("");

Output:
5. Write a java program to implement the Blow Fish algorithm logic?

Source code:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.swing.JOptionPane;

public class BlowFishCipher

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

// create a key generator based upon the Blowfish cipher

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 secret key


cipher.init(Cipher.ENCRYPT_MODE, secretkey);

// get the text to encrypt

String inputText = "Hai

cse";

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

Output:
6. Write a java program to implement the Rijndael algorithm logic?

Import javax.crypto.*;
import javax.crypto.spec.*;
class Rijndael
{
private 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());
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 in Hexadecimal: " +
asHex(original)); System.out.println("Original string : " +
originalString);
}
}
output

7. Using java cryptography, encrypt the text “Hello world” using BlowFish. Create
your ownkey using java key tool?

Source code:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.swing.JOptionPane;

public class BlowFishCipher


{

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

// create a key generator based upon the Blowfish cipher

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 secret key

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

}
output

8. Write a java program to implement RSA algorithm?

Source code:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.math.*;

import java.util.Random;
import java.util.Scanner;

public class RSA

static Scanner sc = new Scanner(System.in);

public static void main(String[] args)

// TODO code application logic here

System.out.print("Enter a Prime number: ");

BigInteger p = sc.nextBigInteger();

// Here's one prime number..

System.out.print("Enter another prime number: ");

BigInteger q = sc.nextBigInteger();

// ..and another.

BigInteger n = p.multiply(q);

BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

BigInteger e = generateE(n2);

BigInteger d = e.modInverse(n2);

// Here's the multiplicative inverse

System.out.println("Encryption keys are: " + e + ", " + n);

System.out.println("Decryption keys are: " + d + ", " +

n);

private static BigInteger generateE(BigInteger fiofn)

int y,
intGCD;

BigInteger e;
BigInteger gcd;

Random x = new Random();

do {

y = x.nextInt(fiofn.intValue()-1);

String z = Integer.toString(y);

e = new BigInteger(z);

gcd = fiofn.gcd(e);

intGCD = gcd.intValue();

while(y <= 2 || intGCD != 1);

return e;

Output:
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and
Javascript. Consider end user as one of the parties(Alice) and the Java script application
as other party(bob)?

Source code:

import java.util.*;

class DiffieHellman

public static void main(String[] args)

long P, G, x, a, y, b, ka, kb;

// create Scanner class object to take input from user

Scanner sc = new Scanner(System.in);

System.out.println("Both the users should be agreed upon the public keys G and P");

// take inputs for public keys from the user

System.out.println("Enter value for public key G:");

G = sc.nextLong();

System.out.println("Enter value for public key

P:"); P = sc.nextLong();

// get input from user for private keys a and b selected by User1 and User2

System.out.println("Enter value for private key a selected by user1:");


a = sc.nextLong();

System.out.println("Enter value for private key b selected by user2:");

b = sc.nextLong();

// call calculatePower() method to generate x and y

keys x = calculatePower(G, a, P);

y = calculatePower(G, b, P);

// call calculatePower() method to generate ka and kb secret keys after the exchange
of x and y keys

// calculate secret key for User1

ka = calculatePower(y, a, P);

// calculate secret key for User2

kb = calculatePower(x, b, P);

// print secret keys of user1 and user2

System.out.println("Secret key for User1 is:" + ka);

System.out.println("Secret key for User2 is:" + kb);

// create calculatePower() method to find the value of x ^ y mod P

private static long calculatePower(long x, long y, long P)

long result = 0;

if (y == 1)

return x;

else
{

result = ((long)Math.pow(x, y)) % P;

return result;

Output:

10. Calculate the message digest of a text using the SHA-1 algorithm in Java?
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();
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'};
StringBuffer buf = 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
content beyond the syllabus
1. Calculate the message digest of a text using the MD-5 algorithm in JAVA
In cryptography, MD5 (Message Digest version 5) and SHA (Secure Hash Algorithm) are two well-known
message digest algorithms. They are also referred as cryptographic hash functions, which take arbitrary-sized
data as input (message) and produce a fixed-length hash value. One of the most important properties of hash
functions is, it’s infeasible to generate a message that has a given hash (secure one-way). Hash functions are
frequently used to check data integrity such as checking integrity of a downloaded file against its publicly-
known hash value. Another common usage is to encrypt user’s password in database.
The Java platform provides two implementation of hashing functions:
MD5 (produces 128-bit hash value), SHA-1 (160-bit) and SHA-2 (256-bit)

Source code:

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

// Java program to calculate MD5 hash value


public class MD5 {
public static String getMd5(String input)
{
try {

// Static getInstance method is called with hashing MD5


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

// digest() method is called to calculate message digest


// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation


BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value


String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}

// For specifying wrong message digest algorithms


catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
String s = "GeeksForGeeks";
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
}
}
2. Toimplement the Vigenere Cipher substitution technique using C
program.

ALGORITHM:

STEP-1: Arrange the alphabets in row and column of a 26*26 matrix.


STEP-2: Circulate the alphabets in each row to position left such that the first letter
is attached to last.
STEP-3: Repeat this process for all 26 rows and construct the final key matrix.
STEP-4: The keyword and the plain text is read from the user.
STEP-5: The characters in the keyword are repeated sequentially so as to
match with that of the plain text.
STEP-6: Pick the first letter of the plain text and that of the keyword as the row
indices and column indices respectively.
STEP-7: The junction character where these two meet forms the cipher character.
STEP-8: Repeat the above steps to generate the entire cipher text.
PROGRAM: (Vigenere Cipher)

#include <stdio.h>
#include<conio.h>
#include <ctype.h>
#include <string.h>
void encipher();
void decipher();
void main()
{
int choice;
clrscr();
while(1)
{
printf("\n1. Encrypt Text");
printf("\t2. Decrypt Text");
printf("\t3. Exit"); printf("\n\
nEnter Your Choice : ");
scanf("%d",&choice);
if(choice == 3)
exit(0);
else if(choice == 1)
encipher();
else if(choice == 2)
decipher();
else
printf("Please Enter Valid Option.");
}
}
void encipher()
{
unsigned int i,j;
char input[50],key[10];
printf("\n\nEnter Plain Text: ");
scanf("%s",input);
printf("\nEnter Key Value:
"); scanf("%s",key);
printf("\nResultant Cipher Text: ");
for(i=0,j=0;i<strlen(input);i++,j++)
{
if(j>=strlen(key))
{ j=0;
}
printf("%c",65+(((toupper(input[i])-65)+(toupper(key[j])-
65))%26));
}}
void decipher()
{
unsigned int i,j;
char input[50],key[10];
int value;
printf("\n\nEnter Cipher Text: ");
scanf("%s",input); printf("\n\
nEnter the key value: ");
scanf("%s",key);
for(i=0,j=0;i<strlen(input);i++,j++)
{
if(j>=strlen(key))
{ j=0; }
value = (toupper(input[i])-64)-(toupper(key[j])-64);
if( value < 0)
{ value = value * -1;
}
printf("%c",65 + (value % 26));
}}

Output:

You might also like