KEMBAR78
Cns Lab Manual | PDF | Cipher | Cryptography
0% found this document useful (0 votes)
5 views23 pages

Cns Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

Cns Lab Manual

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

SHRI SHANKARPRASAD AGNIHOTRI COLLEGE OF

ENGINEERING, WARDHA
Department of Computer Science and Engineering
LABORATORY MANUAL

Session:- 2024-25
(Winter- 2024)

Name of Faculty: Prof. N. B. Vairagade

Subject: Cryptography and Network Security Subject Code:

Semester: VII SEMESTER Section: CSE

Index
Sr. Name of Practical Page No.
No.
1 Write a C program that contains a string(char pointer) with a value \Hello World. The programs
should XOR each character in this string with 0 and display 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 Java program to implement RSA Algorithm

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

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

9 Write the RC4 logic in Java Using Java Cryptography, encrypt the text “Hello world” using
Blowfish. Create your own key using Java key tool.
10 Calculate the message digest of a text using the MD5 algorithm in JAVA.

1
PRACTICAL NO: 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 an display the result.

PROGRAM :

#include<stdio.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");
}

OUTPUT: Hello World Hello World

RESULT:Thus we have successfully executed Hello World program


Should XOR each character in this string with 0 an display the result.

2
PRACTICAL NO: 2

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> #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]);
}
printf("\n");
for(i=0;i<len;i++)
{
str3[i]=str2[i]^127; printf("%c",str3[i]);
}
printf("\n");
}

OUTPUT : Hello World

Hello World

Hello World

RESULT: Thus we have successfully executed AND or and XOR each character in this string
with 127

3
PRACTICAL NO: 3

AIM: Write a Java program to perform encryption and decryption using the
following algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher

PROGRAM:

a) Ceaser Cipher

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);
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));pu
blic static void main(String[] args) throws IOException {
// TODO code application logic here
System.out.print("Enter any String: "); String str = br.readLine(); System.out.print("\
nEnter the Key: ");
int key = sc.nextInt();
String encrypted = encrypt(str, key); System.out.println("\nEncrypted String is: "
+encrypted);
Stringdecrypted=decrypt(encrypted, key); System.out.println("\nDecrypted 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++)
{

4
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')

5
}
c = c + 26;
}

Output:

Enterany String: HelloWorld Enter the Key: 5


Encrypted String is: MjqqtBtwqi DecryptedStringis: HelloWor

b) Substitution Cipher

PROGRAM:

import java.io.*; import java.util.*;


public class SubstitutionCipher
{
static Scanner sc = new Scanner(System.in);
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in))
;public static void main(String[] args) throws IOException
{
// TODO code application logic here String a
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);
}

6
System.out.println("The encrypted data is: " +decrypt);
}
}
Output:
Enter any string: aceho
The encrypted data is: zxvsl

c) Hill Cipher

PROGRAM:

import java.io.*; import java.util.*;


import java.io.*; public class HillCipher { staticfloat[][] decrypt= newfloat[3][1];
staticfloat[][] a= newfloat[3][3];
static float[][]b=newfloat[3][3]; staticfloat[][] mes=newfloat[3][1]; staticfloat[][]res=
new float[3][1];
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
//TODOcode applicationlogic here getkeymes(); for(int i=0;i<3;i++)
for(int j=0;j<1;j++) (int k=0;k<3;k++) {
res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}
System.out.print("\nEncrypted string is : "); for(int i=0;i<3;i++)
{ System.out.print((char)(res[i][0]%26+97)); [i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++) for(int j=0;j<1;j++) for(int k=0;k<3;k++)

7
{
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; } System.out.print("\nDecrypted string
is : ");

8
for(inti =0;i<3;i++)
{
System.out.print((char)(decrypt[i][0]% 26+97));
}
System.out.print("\n");
}
public static void getkeymes() throws IOException
{
System.out.println("Enter 3x3 matrix for key (It should be inversible): "); for(int
i=0;i<3;i++)
for(int j=0;j<3;j++) a[i][j]= sc.nextFloat();
System.out.print("\nEnter a 3 letter string: "); String msg = br.readLine();
for(int i=0;i<3;i++) mes[i][0]
= msg.charAt(i)-97;
}
public static void inverse()
{
floatp,q; float[][] c= a;
for(int i=0;i<3;i++) for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat(); if(i==j)
b[i][j]=1; else b[i][j]=0;
}
for(int k=0;k<3;k++)
{
for(int i=0;i<3;i++)
{

9
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++)
{
if(i!=k)
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] =b[i][j]*q-p*b[k][j];
}}}}
for(int i=0;i<3;i++) for(int j=0;j<3;j++)
{ b[i][j] = b[i][j]/c[i][i]; }
System.out.println(""); System.out.println("\nInverse Matrix is : "); for(int i=0;i<3;i+
+) { for(int j=0;j<3;j++) System.out.print(b[i][j] + " ");
System.out.print("\n"); }
}}

Output:

Entera3letterstring: hai Encrypted string is :fdx Inverse Matrix is: 0.083333336


0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is: hai

RESULT: Thus we have successfully executed encryption and decryption

10
PRACTICAL NO: 4

AIM: Write a Java program to implement the DES algorithm logic.

PROGRAM:

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";
privateKeySpecmyKeySpec;
privateSecretKeyFactorymySecretKeyFactory;
private Cipher cipher; byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme; key;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
publicDES()throws Exception{
// TODO code application logic here my

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

12
{ e.printStackTrace();} returndecryptedText; }
private static String bytes2String(byte[] bytes)
{ StringBufferstringBuffer =new StringBuffer(); for (int i
= 0; i <bytes.length;
i++) { stringBuffer.append((char) bytes[i]); } returnstringBuffer.toString(); }
public static void main(String args []) throws Exception
{ System.out.print("Enter the string: "); DES myEncryptor= new DES();
String stringToEncrypt = br.readLine();
}
}

OUTPUT:

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("");
Enterthestring:WelcomeString To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg= Decrypted Value: Welcome

RESULT: Thus we have successfully executed DES algorithm

13
PRACTICAL NO: 5

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

PROGRAM:
import java.io.*;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.Key; import
javax.crypto.Cipher;
import javax.crypto.CipherOutputStream; import javax.crypto.KeyGenerator; import
sun.misc.BASE64Encoder; public class BlowFish{
public static void main(String[] args) throws Exception {
// TODO code application logic here KeyGeneratorkeyGenerator
=KeyGenerator.getInstance("Blowfish"); keyGenerator.init(128); KeysecretKey =
keyGenerator.generateKey();
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey); BASE64Encoder encoder = new
BASE64Encoder();
byte iv[] = cipherOut.getIV(); if (iv != null) {
System.out.println("Initialization Vectorofthe Cipher:" + encoder.encode(iv)); } FileInputStream fin=
new FileInputStream("inputFile.txt"); FileOutputStreamfout = new FileOutputStream("outputFile.txt");
CipherOutputStreamcout = new CipherOutputStream(fout, cipherOut); intinput
= 0;
while ((input = fin.read()) != -1)
{ cout.write(input); }
fin.close(); cout.close(); } }

OUTPUT:
Initialization Vectorofthe Cipher: dI1MXzW97oQ= Contents of inputFile.txt: Hello World Contents of
outputFile.txt: ùJÖ˜ NåI“

RESULT: Thus we have successfully executed BlowFish algorithm

14
PRACTICAL NO: 6

AIM: Write a Java program to implement RSA Algoithm.


PROGRAM:

importjava.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: ");
BigIntegerp= sc.nextBigInteger();// Here'soneprimenumber.. System.out.print("Enter another prime
number: "); BigInteger q = sc.nextBigInteger(); // ..andanother.
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("Encryptionkeysare:"+e+","+ n); System.out.println("Decryption keys are: " + d + ",
" + n);
}
public static BigIntegergenerateE(BigIntegerfiofn)
{
int y, intGCD;
BigInteger e; BigInteger gcd; Random x = new Random(); do {

15
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:

Enter a Prime number: 5


Enteranotherprimenumber:11 Encryption keys are: 33, 55
Decryption keys are: 17, 55

RESULT: Thus we have successfully executed RSA Algoithm.

16
PRACTICAL NO: 7

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

PROGRAM:

import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair;


import java.security.KeyPairGenerator; import java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; public class
DiffeHellman{
public final static int pValue = 47;
public final static int gValue = 71; public final static int XaValue = 9; publicfinalstaticint XbValue= 14;
public static void main(String[] args) throws Exception
{ // TODO code application logic here
BigInteger p = new BigInteger(Integer.toString(pValue)); BigInteger g = new
BigInteger(Integer.toString(gValue)); BigIntegerXa = new BigInteger(Integer.toString(XaValue))
; BigIntegerXb = new BigInteger(Integer.toString(XbValue)); createKey(); intbitLength = 512; // 512
bits SecureRandomrnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd); g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createKey() throws Exception { KeyPairGeneratorkpg =
KeyPairGenerator.getInstance("DiffieHellman"); kpg.initialize(512);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman"); DHPublicKeySpeckspec =
(DHPublicKeySpec)

17
kfactory.getKeySpec(kp.getPublic().DHPublicKeySpec.class); System.out.println("Public key is: "
+kspec);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception
{
KeyPairGeneratorkpg = KeyPairGenerator.getInstance("DiffieHellman"); DHParameterSpecparam =
new DHParameterSpec(p, g); kpg.initialize(param);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman"); DHPublicKeySpeckspec =
(DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), DHPublicKeySpec.class);
System.out.println("\nPublic key is : " +kspec);
}
}

OUTPUT:

Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29 Public key is: javax.crypto.spec.


DHPublicKeySpec@9971a

RESULT: Thus we have successfully executed Diffie-Hellman Key Exchange mechanism using
HTML and JavaScript

18
PRACTICAL NO: 8

AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA

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

19
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:

Message digest object info: Algorithm = SHA1 Provider = SUN version 1.6 ToString = SHA1 Message
Digest from SUN, <initialized> SHA1("") = DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnop qrstuvwxyz")=32D10C7B8CF96570 CA04CE37F2A19D8424 0D3A89

RESULT: Thus we have successfully executed digest of a text using the SHA-1 algorithm in

20
PRACTICAL NO: 9

AIM: Write the RC4 logic in Java Using Java Cryptography, encrypt the text “Hello world” using
Blowfish. Create your own key using Java key tool.

PROGRAM:

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 theBlowfish cipher KeyGeneratorkeygenerator =
KeyGenerator.getInstance("Blowfish");
// create a key // 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 = JOptionPane.showInputDialog("Input your message: ");

byte[] encrypted = cipher.doFinal(inputText.getBytes());

//re-initialisetheciphertobeindecryptmode cipher.init(Cipher.DECRYPT_MODE, secretkey);


// decrypt message

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

// and display the results

JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "\nEncrypted text:"+ new


String(encrypted)+"\n"+"\nDecryptedtext:"+ new String(decrypted));
System.exit(0);
}}

OUTPUT:

Input your message: Helloworld Encrypted text: 3ooo&&(*&*4r4 Decrypted text: Hello world

Result: Thus we have successfully executed encrypt the text “Hello world” using Blowfish.

21
PRACTICAL NO: 10

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

PROGRAM:

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

22
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));
}
OUTPUT:

Input : hello world

Output : 5eb63bbbe01eeed093cb22bb8f5acdc3

Input : GeeksForGeeks

Output : e39b9c178b2c9be4e99b141d956c6ff6

RESULT: Thus we have successfully executed digest of a text using the MD5 algorithm

23

You might also like