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

Cns Lab Main

The document contains 6 programming questions related to encryption algorithms. It includes programs to perform XOR and AND/OR/XOR operations on strings. It also includes programs to implement Caesar cipher, substitution cipher, Hill cipher, DES algorithm, Blowfish algorithm and Rijndael algorithm for encryption and decryption. The programs take an input string, encrypt it using the specified algorithm and encryption key and display the encrypted output. They then decrypt the encrypted string and display the original string.

Uploaded by

Prakash Raj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
179 views

Cns Lab Main

The document contains 6 programming questions related to encryption algorithms. It includes programs to perform XOR and AND/OR/XOR operations on strings. It also includes programs to implement Caesar cipher, substitution cipher, Hill cipher, DES algorithm, Blowfish algorithm and Rijndael algorithm for encryption and decryption. The programs take an input string, encrypt it using the specified algorithm and encryption key and display the encrypted output. They then decrypt the encrypted string and display the original string.

Uploaded by

Prakash Raj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

EXPERIMENT 1

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.

PROGRAM:
#include<stdlib.h>
main()
{
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf("\n");
}
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.

PROGRAM:
#include <stdio.h>
#include<stdlib.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) | (str[i]^127);
printf("%d",str1[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str2[i] = (str[i]&127) & (str[i]^127);
printf("%d",str2[i]);
}
printf("\n");
}

OUTPUT:
127127127127127127127127127127127
00000000000

3. 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 {

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


String str = "Hello World";
int key=5;

String encrypted = encrypt(str, key);


System.out.println("\nEncrypted String is: " +encrypted);
String decrypted = 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++) {
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:
Encrypted String is: Mjqqt Btwqi

Decrypted String is: Hello World

b) Substitution Cipher
PROGRAM:
import java.io.*;
import java.util.*;
public class SubstitutionCipher {
public static void main(String[] args) throws IOException {
String str = "hello world";
String a = "abcdefghijklmnopqrstuvwxyz ";
String b = "zyxwvutsrqponmlkjihgfedcba ";

String encrypt = "";


String decrypt = "";
char c;
for(int i=0;i<str.length();i++)
{
c = str.charAt(i);
int j = a.indexOf(c);
encrypt = encrypt+b.charAt(j);
}
System.out.println("The encrypted data is: " +encrypt);
for(int i=0;i<str.length();i++)
{
c = encrypt.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
System.out.println("The decrypted data is: " +decrypt);
}
}

OUTPUT:
The encrypted data is: svool dliow
The decrypted data is: hello world
c) Hill Cipher
PROGRAM:
import java.io.*;
import java.util.*;
import java.io.*;
public class HillCipher {
static int[][] decrypt = new int[3][1];
static int[][] b = new int[3][3];
static int[][] mes = new int[3][1];
static int[][] res = new int[3][1];
static int a[][] = {{1,2,3},{0,1,4},{5,6,0}};
public static void main(String[] args) throws IOException {
getkeymes();
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 {
String msg = "cse";
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
}
public static void inverse() {
int p, q;
int[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextint();
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("\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:
Encrypted string is : yio

Inverse Matrix is :
-24 18 5
20 -15 -4
-5 4 1
Decrypted string is : cse

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

PROGRAM:
import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Random ;

public class DES {

byte[] skey = new byte[1000];

String skeyString;

static byte[] raw;

String inputMessage,encryptedData,decryptedMessage;
public DES() {

try {

generateSymmetricKey();

inputMessage= "CSE-D";

byte[] ibyte = inputMessage.getBytes();

byte[] ebyte=encrypt(raw, ibyte);

String encryptedData = new String(ebyte);

System.out.println("Encrypted message "+encryptedData);

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

String decryptedMessage = new String(dbyte);

System.out.println("Decrypted message "+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();

OUTPUT:

DES Symmetric key = Ly�aTp�

Encrypted message ��߸��/

Decrypted message CSE-D

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

PROGRAM:

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Random ;
public class BLOWFISH {

byte[] skey = new byte[1000];

String skeyString;

static byte[] raw;

String inputMessage,encryptedData,decryptedMessage;

public BLOWFISH() {

try {

generateSymmetricKey();

inputMessage= "CSE-D";

byte[] ibyte = inputMessage.getBytes();

byte[] ebyte=encrypt(raw, ibyte);

String encryptedData = new String(ebyte);

System.out.println("Encrypted message "+encryptedData);

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

String decryptedMessage = new String(dbyte);

System.out.println("Decrypted message "+decryptedMessage);

catch(Exception e) {

System.out.println(e);
}

void generateSymmetricKey() {

try {

Random r = new Random();

int num = r.nextInt(10000);

String knum = String.valueOf(num);

byte[] knumb = knum.getBytes();

skey=getRawKey(knumb);

skeyString = new String(skey);

System.out.println("BLOWFISH Symmetric key = "+skeyString);

catch(Exception e) {

System.out.println(e);

private static byte[] getRawKey(byte[] seed) throws Exception {

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

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

sr.setSeed(seed);

kgen.init(32, 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, "BLOWFISH");

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

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

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

return encrypted;

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

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

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

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

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

return decrypted;

public static void main(String args[]) {

BLOWFISH blowfish = new BLOWFISH();

OUTPUT:

BLOWFISH Symmetric key = ��4~


Encrypted message Z�����0!
Decrypted message CSE-D
6. Write a C/JAVA program to implement the Rijndael algorithm logic.

PROGRAM:

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Random ;

public class AES {

byte[] skey = new byte[1000];

String skeyString;

static byte[] raw;

String inputMessage,encryptedData,decryptedMessage;

public AES() {

try {

generateSymmetricKey();

inputMessage= "CSE-D";

byte[] ibyte = inputMessage.getBytes();

byte[] ebyte=encrypt(raw, ibyte);

String encryptedData = new String(ebyte);

System.out.println("Encrypted message "+encryptedData);


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

String decryptedMessage = new String(dbyte);

System.out.println("Decrypted message "+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("AES Symmetric key = "+skeyString);

catch(Exception e) {

System.out.println(e);

}
}

private static byte[] getRawKey(byte[] seed) throws Exception {

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

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

sr.setSeed(seed);

kgen.init(128, 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, "AES");

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

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, "AES");

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

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

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

return decrypted;

public static void main(String args[]) {


AES aes = new AES();

OUTPUT:
AES Symmetric key = "��漡�r69Qf2w�
Encrypted message �\I��u�L,g�*�
Decrypted message CSE-D

7. Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello world”
using Blowfish.

PROGRAM:

// RC4 key generation with Blowfish encryption

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Random ;

public class BLOWFISH {

byte[] skey = new byte[1000];

String skeyString;

static byte[] raw;

String inputMessage,encryptedData,decryptedMessage;

public BLOWFISH() {
try {

generateSymmetricKey();

inputMessage= " CSED ";

byte[] ibyte = inputMessage.getBytes();

byte[] ebyte=encrypt(raw, ibyte);

String encryptedData = new String(ebyte);

System.out.println("Encrypted message "+encryptedData);

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

String decryptedMessage = new String(dbyte);

System.out.println("Decrypted message "+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("RC4 Symmetric key = "+skeyString);

catch(Exception e) {

System.out.println(e);

private static byte[] getRawKey(byte[] seed) throws Exception {

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

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

sr.setSeed(seed);

kgen.init(40, 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, "BLOWFISH");

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

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

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

return encrypted;
}

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

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

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

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

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

return decrypted;

public static void main(String args[]) {

BLOWFISH blowfish = new BLOWFISH();

OUTPUT:

RC4 Symmetric key = �^•


Encrypted message ���9�If
Decrypted message CSED

8) Write a Java program to implement RSA algorithm.

PROGRAM:
import java.util.*;
import java.math.*;

public class RSA


{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int p,q,n,z,d=0,e,i;
System.out.print("Enter the number to be encrypted and decrypted: ");
int msg=sc.nextInt();
int c;
BigInteger msgback;
System.out.print("Enter 1st prime number p: ");
p=sc.nextInt();
System.out.print("Enter 2nd prime number q: ");
q=sc.nextInt();

n=p*q;
z=(p-1)*(q-1);

for(e=2;e<z;e++)
{
if(gcd(e,z)==1)
{
break;
}
}

System.out.print("Public key (e,n): ");


System.out.println("("+e+","+n+")");

for(i=0;i<=9;i++)
{
int x=1+(i*z);
if(x%e==0)
{
d=x/e;
break;
}
}

c=(int)(Math.pow(msg,e))%n;
System.out.print("Encrypted message is : ");
System.out.println(c);
BigInteger N = BigInteger.valueOf(n);
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.print("Derypted message is : ");
System.out.println(msgback);

}
static int gcd(int e, int z)
{
if(e==0)
return z;
else
return gcd(z%e,e);
}
}
OUTPUT:
Enter the number to be encrypted and decrypted: 24
Enter 1st prime number p: 5
Enter 2nd prime number q: 11
Public key (e,n): (3,55)
Encrypted message is : 19
Derypted message is : 24

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


JavaScript.

PROGRAM:
<html>

<body>

<script>

var q,g,a, b;

p=prompt("Enter the p value");

g=prompt("Enter the Alpha value - Primitive Root of p");

a=prompt("Enter the Private key of Alice");

b=prompt("Enter the Private key of Bob");


q=parseInt(p);

alpha=parseInt(g);

Xa=parseInt(a);

Xb=parseInt(b);

Ya = Math.pow(alpha,Xa)%q;

Yb = Math.pow(alpha,Xb)%q;

K_A = Math.pow(Yb,Xa)%q;

K_B = Math.pow(Ya,Xb)%q;

if(K_A==K_B)

document.writeln("ALice and Bob can communicate with each other!!!


<br> Secret Key K:");

document.writeln(K_A);

else

alert("ALice and Bob cannot communicate with each other!!! <br> Please
enter correct alpha value(Primitive root of P)" );

</script>

</body>

</html>

OUTPUT:

Enter the p value 23


Enter the Alpha value - Primitive Root of p 5

Enter the Private key of Alice 6

Enter the Private key of Bob 15

ALice and Bob can communicate with each other!!!

Secret Key K: 2

10. 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[] args) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
String input = "abc";
md.update(input.getBytes());
byte[] 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:
SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz") =
32D10C7B8CF96570CA04CE37F2A19D84240D3A89

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

PROGRAM:

import java.security.*;
public class MD5
{
public static void main(String[] args) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
String input = "abc";
md.update(input.getBytes());
byte[] 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(); }
}

OUTPUT:
MD5("abc") = 900150983CD24FB0D6963F7D28E17F72
MD5("abcdefghijklmnopqrstuvwxyz") = C3FCD3D76192E4007DFB496CCA67E13B

You might also like