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

CRYPTOGRAPHY AND NETWORK SECURITY LAB MANUAL

The document contains a series of programming exercises focused on cryptography and network security, including implementations of various encryption algorithms such as XOR, AND, Ceaser cipher, Substitution cipher, Hill cipher, DES, Blowfish, Rijndael (AES), RSA, and Diffie-Hellman key exchange. Each exercise provides code examples in C or Java, demonstrating how to encrypt and decrypt messages using the specified algorithms. The document serves as a lab manual for students to practice and understand cryptographic techniques.

Uploaded by

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

CRYPTOGRAPHY AND NETWORK SECURITY LAB MANUAL

The document contains a series of programming exercises focused on cryptography and network security, including implementations of various encryption algorithms such as XOR, AND, Ceaser cipher, Substitution cipher, Hill cipher, DES, Blowfish, Rijndael (AES), RSA, and Diffie-Hellman key exchange. Each exercise provides code examples in C or Java, demonstrating how to encrypt and decrypt messages using the specified algorithms. The document serves as a lab manual for students to practice and understand cryptographic techniques.

Uploaded by

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

CRYPTOGRAPHY AND NETWORK SECURITY LAB MANUAL

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.
#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int 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
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.
#include<stdio.h>

#include<stdlib.h>

#include<string.h>

int main()

char str[]=" Hello World ";

char str1[11];

char str2[11];

char str3[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++)

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

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

printf("\n");

Output:-

Hello World

Hello World
3. Write a Java program to perform encryption and decryption using the following
algorithms a. Ceaser cipher b. Substitution cipher c. Hill Cipher
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);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException
{
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("\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;
}
}
b. Substitution cipher
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);
}
}
c. Hill Cipher
import java.io.*;
import java.util.*;
import java.io.*;
public class HillCipher{
static float[][] decrypt=new float[3][1];
static float[][] a=new float[3][3];
static float[][] b = new float[3][3];
static float[][] mes = new float[3][1];
static float[][] 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
{
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(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));
res[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++)
{
decrypt[i][j]=decrypt[i][j]+b[i][k]*res[k][j];
}
System.out.print("\nDecrypted string is:");
for(int i=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()
{
float p,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++)
{
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("\n Inverse 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");
}
}
}
4.Write a C/JAVA program to implement the DES algorithm logic.
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;

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

public DES() {
try {
generateSymmetricKey();

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

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


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

JOptionPane.showMessageDialog(null,"Decrypted Data
"+"\n"+decryptedMessage);
}
catch(Exception e) {
System.out.println(e);
}

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

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


SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[]) {
DES des = new DES();
}
}
5. Write a C/JAVA program to implement the Blowfish algorithm logic.
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import java.util.Base64;

public class BlowFish {

public static void main(String[] args) {


if (args.length != 2) {
System.out.println("Usage: java BlowFish <inputFile> <outputFile>");
return;
}

String inputFile = args[0];


String outputFile = args[1];

try {

KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");


keyGenerator.init(128, new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] iv = cipher.getIV();
if (iv != null) {
System.out.println("Initialization Vector of the Cipher: " +
Base64.getEncoder().encodeToString(iv));
}

// File handling with try-with-resources


try (FileInputStream fin = new FileInputStream(inputFile);
FileOutputStream fout = new FileOutputStream(outputFile);
CipherOutputStream cout = new CipherOutputStream(fout, cipher)) {

int input;
while ((input = fin.read()) != -1) {
cout.write(input);
}
}
System.out.println("\nContent of " + inputFile + ":");
readFileContent(inputFile);
System.out.println("\nContent of " + outputFile + ":");
readFileContent(outputFile);

} catch (Exception e) {
e.printStackTrace();
}
}
private static void readFileContent(String fileName) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file " + fileName + ": " + e.getMessage());
}
}
}
6. Write a C/JAVA program to implement the Rijndael algorithm logic.

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES
{
public static String asHex (byte buf[])
{
StringBuffer strbuf = new StringBuffer(buf.length *2);
int i;
for (i = 0; i < buf.length; i++)
{
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception
{
String message=" Hello AES still rocks!!";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
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: " +originalString + " " + asHex(original));
}
}
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.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;

/**
* This program demonstrates how to encrypt/decrypt input
* using the Blowfish Cipher with the Java Cryptograhpy.
*
*/
public class BlowfishCipher {

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


KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
SecretKey secretkey = keygenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
String inputText = JOptionPane.showInputDialog("Input your message: ");
byte[] encrypted = cipher.doFinal(inputText.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretkey);
byte[] decrypted = cipher.doFinal(encrypted);
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"encrypted text: " + new String(encrypted) + "\n" +
"decrypted text: " + new String(decrypted));
System.exit(0);
}
}
8. Write a Java program to implement RSA algorithm.
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)
{
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger();
System.out.print("Enter another prime number:");
BigInteger q = sc.nextBigInteger();
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);
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
}
public 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;
}
}
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
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;

public final static int XbValue = 14;

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


BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new BigInteger(Integer.toString(XaValue));
BigInteger Xb = new BigInteger(Integer.toString(XbValue));

createKey();

int bitLength = 512; // 512 bits


SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);

createSpecificKey(p, g);
}

public static void createKey() throws Exception {


KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");

kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");

DHPublicKeySpec kspec = (DHPublicKeySpec)


kfactory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("\nPublic key is:"+kspec);
}

public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception {


KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");

DHParameterSpec param = new DHParameterSpec(p, g);


kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();

KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");

DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),


DHPublicKeySpec.class);
System.out.println("\nPublic key is:"+kspec);
}
}
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();
}
}
11. Calculate the message digest of a text using the MD5 algorithm in JAVA.
import java.security.*;
public class MD5
{
public static void main(String[] a)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") = "+bytesToHex(output)); System.out.println("");
}
catch (Exception e)
{
System.out.println("Exception: " +e);
}
}
public static String bytesToHex(byte[] b)
{
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
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();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy