0% found this document useful (0 votes)
50 views45 pages

Lab Note (After DSP)

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)
50 views45 pages

Lab Note (After DSP)

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/ 45

CSE-405 (Digital Signal & Image Processing)

No Problem Name
01 Write a matlab program to add two signal.

02 Write a matlab program to multiply two signal.

03 Write a matlab program to fold a signal.

04. Write a matlab program to shift a signal.

05 Write a matlab program to draw even odd signal.

06 Write a matlab program for sampling.

07 Write a matlab program for up sampling.

08 Write a matlab program for cross correlation.

09 Write a matlab program to find convolution.

10 Write a matlab program for script covariance.

11 Write a matlab program for furier series coefficient.

12 Write a matlab program to FFTransform.


1. Write a matlab program to add two signal.

Source Code:
function [ y, n ] = sigadd(x1,n1,x2,n2)
%This is a Matlab function for computing the addition of two given
%sequences
n=min(min(n1), min(n2)):max(max(n1),max(n2));
y1=zeros(1,length(n));
y2=y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))= x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))= x2;
y=y1+y2;

Figure:
2. Write a matlab program to multiply two signal.

Source Code:
function [ y, n ] = sigmul(x1,n1,x2,n2)
%This is a Matlab function for computing the addition of two given
%sequences
n=min(min(n1), min(n2)):max(max(n1),max(n2));
y1=zeros(1,length(n));
y2=y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))= x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))= x2;
y=y1.*y2; %element wise dot

Figure:
3. Write a matlab program to fold a signal.

Source Code:
function [ y, n ] = sigfold(x,m) %m time
%This is a Matlab function for computing the addition of two given
%sequences
n=-fliplr(m); %time
y=fliplr(x);

Figure:
4. Write a matlab program to shift a signal.

Source Code:
function [ y, n ] = sigshift(x,m,k)
%This is a Matlab function for shifting a Digital signal by k units
n = m+k;
y=x;
end

Figure
5. Write a matlab program to draw even odd signal.

Source Code:
function [xe,xo] = evenodd(t,x)
%This is a Matlab function for decomposing a real sequence into its even
%and odd components
%INPUTS:
% t: time index
%x: input sequence
%OUTPUTS:
%xe: even/ symmetric component
%xo:odd/ antisymmetric component

x_reverse = fliplr(x);% time reversal


xe = 0.5*(x + x_reverse); %even component
xo = 0.5*(x - x_reverse); %odd component
subplot(3,1,1);
stem(t,x);
title('Input signal x')
subplot(3,1,2);
stem(t,xe);
title('Even part');
subplot(3,1,3);
stem(t,xo);
title('Odd part');
end

Figure:
6. Write a matlab program for sampling.

Source Code:% Generate a continuous time cosine signal of 60 Hz.

clc;
close all;
clearvars;
f = 60; %Freq in Hz
tmin = -0.05;
tmax = 0.05;
np = 40000;
t = linspace(tmin, tmax, np); %Generates np points, and spacing between points is
(tmax-tmin)/np-1
x_c = cos(2*pi*f*t);
plot(t, x_c);
xlabel('t [s]');
% Saample x_c with a sampling frequency of 400 Hz
F = 1200;
T = 1/F;
nmin = ceil(tmin/T);
nmax = ceil(tmax/T);
n = nmin: nmax;
x1 = cos(2*pi*f*n*T);
hold on
plot(n*T,x1,'ro');
%hold off
% Saample x_c with a sampling frequency of 60 Hz
clear nmin, nmax,n, x1, T;
% Explain Aliasing: A high frequency cosine looks like a low frequency
% cosine
%figure (3);
F = 70;
T = 1/F;
x_c = cos(2*pi*10*t);
nmin = ceil(tmin/T);
nmax = ceil(tmax/T);
n = nmin: nmax;
x1 = cos(2*pi*f*n*T);
plot(t, x_c, 'v');
hold on
plot(n*T, x1,'ob');
hold off

Figure:
7. Write a matlab program for upsampling.

Source Code:
%Study UpSampling of a sinusoidal input sequence

clc;
close all;
clearvars;
echo on;
N = input('Input Length=' );
L = input('UpSampling Factor=');
f0 = input('Input Signal Frequency');
%Generate the input sinusoidal sequence
n = 0: N-1;
x = sin(2*pi*f0*n);

%Generate Up sampled signal y


y = zeros(1, L*length(x));
y([1:L:length(y)]) = x;
y= interp(x,L);
subplot(211);
stem(n,x);
subplot(212)
stem(y);

Figure:
8. Write a matlab program for cross correlation.

Source Code:
clc;

x =[3 11 7 0 -1 4 2];
nx = -3:3;
lag = 3;
[y,ny] = sigshift(x,nx,lag);
%y=x[n-2]
w = randn(1,length(y));
nw=ny;
[y,ny] = sigadd(y,ny, w,nw);
%y=x[n-2]+w[n]
[x,~] = sigfold(x,nx);
rxy = conv(y,x);
nrxyb = nx(1)+ny(1);
nrxyend = nx(length(x))+ny(length(y));
nrxy = nrxyb:nrxyend;
%[~, ind]= max(rxy);
%lagMax = nrxy(ind);
%subplot(1,1,1);
subplot(3,1,1);
stem(nx,x);
title('X');
subplot(3,1,2);
stem(ny,y);
title('Y');
subplot(3,1,3);
stem(nrxy, rxy);
axis([-5 10 -50 300]);
xlabel('Lag variable:l');
ylabel('rxy');
title('Cross correlation of noise sequence with a given input');

Figure:
9. Write a matlab program to find convolution.

Source Code:
clc;
close all;
clearvars;
nx = -25:25;
nh = -7:7;
x = cos(2*pi*nx/.3).*(nx>=0);
h = (cos(pi*nh/.3)+(sin(pi*nh/3)/sqrt(3))).*(nh>=0);
y = conv(h,x);
nyb = nx(1)+nh(1);
nye = nx(end)+ nh(end);
ny = nyb:nye;
plot(nx,x,'-r');
hold on
plot(nh,h,'-g');
%hold on
plot(ny,y,'--b');
title ('Plot of input X[n], impulse response h[n] and the convolution of the two Y[n]')
xlabel ('Variable n');
ylabel ('Signal amplitude')

Figure:
10.Write a matlab program for script covariance.

Source Code:
clc;
clearvars;
close all;
shft = 50;

s1 = rand(150,1);
s2 = circshift(s1,[shft 0]);% shift circulary with 0 time shifting
s = [s1 s2]; % construct a matrix of two channels

subplot(2,1,1)
plot(s1)
title('s_1')
subplot(2,1,2)
plot(s2)
title('s_2')
%hold on
%plot([shft shft],[0 1]
[c,lg] = xcov(s,'biased');

figure (2)
plot(lg,c)
legend('c_{s_1s_1}','c_{s_1s_2}','c_{s_2s_1}','c_{s_2s_2}')
%Change the normalization so that the cross-covariance and autocovariance
%sequences are unity at zero lag. Plot each sequence in its own subplot.
[c,lg] = xcov(s,'coeff');
figure(3)
for a = 1:2
for b = 1:2
nm = 2*(a-1)+b;
subplot(2,2,nm)
plot(lg,c(:,nm))
title(sprintf('c_{s_%ds_%d}',a,b))
axis([-150 150 -0.2 1])
end
end
Figure:
11. Write a matlab program for furier series coefficient.

Source Code:
%CALCULATION OF FOURIER SERIES COEFFICIENTS
clear all;
echo on;
Fs = 100e3;
dt = 1/Fs;

%GENERATING THE RECTANGULAR PULSE TRAIN


T = 1e-3; %PERIOD OF THE PULSE TRAIN
D = 0.1; %DUTY CYCLE
PW = D*T; %PULSE WIDTH
f = 1/T; %ANALOG FREQUENCY
t = -T/2:dt:T/2; %TIME INTERVAL FOR A PERIOD
n = t/dt; %INDEX FOR DATA POINTS IN A PERIOD
L = PW/dt; %DATA POINTS IN THE THE HIGH TIME

x = zeros(1,length(t)); %INITIALIZING A SINGLE RECTANGULAR PULSEATION OF A


x(find(abs(n)<=L/2)) = 1.1; %GENER SINGLE RECTANGULAR PULSE

%END OF THE RENTANGULAR PULSE TRAIN


figure(1)
subplot(2,1,1)
plot(t,x);
xlabel('Time (Seconds)')
ylabel('x(t)')
title('Continuous signal')
subplot(2,1,2)
stem(n,x)
xlabel('n')
ylabel('x(n)')
title('Discrete signal')
N = length(x);
% TOTAL NO OF DATA POINTS IN A PERIOD
Nc = N; %TOTAL NO COEFFICIENTS
if mod(Nc,2) == 0
k = -(Nc/2):(Nc/2)-1;
else

k = -(Nc-1)/2:(Nc-1)/2;
end
c = zeros(1,length(k)); %INITIALIZING FOURIER COEFFICIENTS
for i1=1:length(k)
for i2=1:length(x)
c(i1)=c(i1)+1/N*x(i2)*exp(-i*2*pi*k(i1)*n(i2)/N);

end

end
figure(2)
subplot(2,1,1)
stem(k,abs(c));
xlabel('k')
ylabel('|c_k|')
title('Fourier series coefficients c_k')
subplot(2,1,2)
stem(k,angle(c)*130/pi)
xlabel('k')
ylabel('angle(c_k)')

%START OF RECONSTRUCTION OF SIGNAL


t_remax = T/2;
t_re = -t_remax:dt:t_remax; n_re=t_re/dt; x_re=zeros(1,length(n_re)); for
i1=1:length(k)
for i2=1:length(x_re)

x_re(i2)= x_re(i2)+c(i1)*exp(i*2*pi*k(i1)*n_re(i2)/N);
end
end
%END OF RECONSTRUCTION OF SIGNAL
figure(3)
subplot(2,1,1)
stem(n_re, x_re)
xlabel('n')
ylabel('x_{reconstructed}')
title('Reconstructed signal')
subplot(2,1,2)
plot(t_re, x_re)
xlabel('t')
ylabel('x_{reconstructed}')
title('Reconstructed signal')

Figure:
12. Write a matlab program to FFTransform.

Source Code:
Fs = 1000; % Sampling frequency
T = 1/Fs; % sample time
L = 1000; % length of signal
t = (0:L-1)*T; % time vector
%sum of a 50 Hz sinusoid and a 120 Hz sinusoid
x = 0.7*sin(2*pi*50*t) + cos(2*pi*120*t);
y = x + 2*randn(size(t)); % sinusoids plus noise
subplot(2,1,1)
plot(Fs*t(1:50),y(1:50))
title ('Signal Corrupted with Zero-Mean Random Noise')
xlabel('time (milliseconds)');
NFFT = 2^nextpow2(L); %Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
subplot(2,1,2)
%Plot single-sided amplitude spectrum.
plot(f,2*abs(Y(1:NFFT/2+1)))
title ('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

Figure:
CSE-407 (Network Security)
No Problem Name
01. Perform encryption and decryption using mono-alphabetic cipher. The program should
support the following :
 Construct an input file named plaintext.txt (consisting of 1000 alphabets, without any
space or special characters)
 Encrypt the characters of plaintext.txt and store the corresponding ciphertext characters
in ciphertext.txt
 Compute the frequency of occurrence of each alphabet in both plaintext.txt and
ciphertext.txt and tabulate the results

02. Write a program to perform the following using Playfair cipher technique
 Encrypt a given message M with different keys {k1,k2,...,kn}. Print key and cipher text
pair
 Decrypt the cipher texts obtained in (i) to get back M

03. Write a program to perform the following using Hill cipher:


 Encrypt a message M with a given key matrix of size 2X2 and 3X3
 Decrypt the cipher text obtained in (i) by computing inverse of the respective key
matrix.

04. Write a program to perform encryption and decryption using transposition technique with
column permutation given as key.

05. Generate and print 48-bit keys for all sixteen rounds of DES algorithm, given a 64-bit initial
key.

06. Implement RSA algorithm using client-server concept. The program should support the
following :
 Client generates {PU, PR} and distributes PU to Server.
 Sever encrypts message M using client’s public key {PU}.
 Client decrypts the message sent by server using its private key {PR}.

07. Implement RSA algorithm to process blocks of plaintext (refer Figure 9.7 of the text book),
where plaintext is a string of characters and let the block size be two characters. (Note: assign a
unique code to each plain text character i.e., a=00, A=26). The program should support the
following.
 Accept string of characters as plaintext.
 Encryption takes plaintext and produces ciphertext characters.
 Decryption takes ciphertext characters obtained in step ii and produces corresponding
plaintext characters
 Display the result after each step
01. Perform encryption and decryption using mono-alphabetic cipher.

Source Code:
#include<bits/stdc++.h>
using namespace std;

char uniqtext[26]; // Global variable

/* read plain text from plaintext.txt file */


string readPlainText()
{
ifstream fin;
string ptext;

fin.open("plaintext.txt");
fin >> ptext;
fin.close();

return ptext;
}

/* write cipher text to ciphertext.txt file */


void writecipherText(string ctext)
{
ofstream fout;
fout.open("ciphertext.txt");
fout << ctext;
fout.close();
}

/* function to find all possible permutation */


void permute(char a[], int l, int r, vector<string>& keyspace) // keyspace is
passed by reference
{
if(l == r)
{
keyspace.push_back(a);
}
else
{
for(int i = l; i <= r; i++)
{
swap(a[l], a[i]); //inbuilt swap function
permute(a, l+1, r, keyspace);
swap(a[l], a[i]);
}
}
}

vector<string> genKeySpace(string plaintext)


{
set<char> uniqSet;
vector<string> keyspace; // contains all possible permutation of letters
in plaintext
int count = 0;

/* store all the unique letters of plain text in uniqSet */


for(int i=0; i < plaintext.length(); i++)
{
uniqSet.insert(plaintext[i]);
}

/* copy uniqSet to uniqtext char array */


for(set<char>::iterator it = uniqSet.begin(); it != uniqSet.end(); it++)
{
uniqtext[count++] = (*it);
}

permute(uniqtext, 0, strlen(uniqtext)-1, keyspace);


return keyspace;
}

/* create cipher text using key */


string encrypt(string unique, string key)
{
string plaintext = readPlainText();
string ciphertext = "";

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


{
int idx = unique.find(plaintext[i]);
ciphertext += key[idx];
}
return ciphertext;
}

/* frequency = (no of occurance of a character / length of plaintext) */


/* show frequency of all characters of plain text and cipher text */
void showFrequency(string pt , string ct)
{
map<char , int > mPlain ;
map<char , int > mCipher ;

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


{
mPlain[pt[i]]++ ;
mCipher[ct[i]]++ ;
}
cout<<"\nFrequency\t\tPlaintext Character\t\tCiphertext character"
<<endl;
cout<<"=========\t\t===================\t\t====================" <<endl;
for(int i=0 ; i<pt.length() ; i++)
{
cout<< (float)mPlain[pt[i]]/pt.length() << "\t\t\t\t" << pt[i] <<
"\t\t\t\t" << ct[i] << endl ;
}
}

int main()
{
srand(time(NULL)) ;

string plaintext = readPlainText() ;


cout<<"Plain text = \t" << plaintext << endl;

vector<string> keyspace = genKeySpace(plaintext);


string key = keyspace[rand()%keyspace.size()];

cout<<"Unique chars = \t" << uniqtext <<endl;


cout<<"Chosen key = \t" << key <<endl;

string ciphertext = encrypt(uniqtext , key) ;


writecipherText(ciphertext) ; // write ciphertext to file
showFrequency(plaintext , ciphertext) ;
}

Input & Output:


02. Write a program to perform Playfair cipher technique.

Source Code:

#include <bits/stdc++.h>
using namespace std;

typedef struct{
int row;
int col;
}position;

char mat[5][5]; // Global Variable

void generateMatrix(string key)


{
/* flag keeps track of letters that are filled in matrix */
/* flag = 0 -> letter not already present in matrix */
/* flag = 1 -> letter already present in matrix */
int flag[26] = {0};
int x = 0, y = 0;

/* Add all characters present in the key */


for(int i=0; i<key.length(); i++)
{
if(key[i] == 'j') key[i] = 'i'; // replace j with i

if(flag[key[i]-'a'] == 0)
{
mat[x][y++] = key[i];
flag[key[i]-'a'] = 1;
}
if(y==5) x++, y=0;
}

/* Add remaining characters */


for(char ch = 'a'; ch <= 'z'; ch++)
{
if(ch == 'j') continue; // don't fill j since j was replaced by i

if(flag[ch - 'a'] == 0)
{
mat[x][y++] = ch;
flag[ch - 'a'] = 1 ;
}
if(y==5) x++, y=0;
}
}

/* function to add filler letter('x') */


string formatMessage(string msg)
{
for(int i=0; i<msg.length(); i++)
{
if(msg[i] == 'j') msg[i] = 'i';
}

for(int i=1; i<msg.length(); i+=2) //pairing two characters


{
if(msg[i-1] == msg[i]) msg.insert(i, "x");
}

if(msg.length()%2 != 0) msg += "x";


return msg;
}

/* Returns the position of the character */


position getPosition(char c)
{
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
if(c == mat[i][j])
{
position p = {i, j};
return p;
}
}

string encrypt(string message)


{
string ctext = "";
for(int i=0; i<message.length(); i+=2) // i is incremented by 2 inorder
to check for pair values
{
position p1 = getPosition(message[i]);
position p2 = getPosition(message[i+1]);
int x1 = p1.row; int y1 = p1.col;
int x2 = p2.row; int y2 = p2.col;

if( x1 == x2 ) // same row


{
ctext += mat[x1][(y1+1)%5];
ctext += mat[x2][(y2+1)%5];
}
else if( y1 == y2 ) // same column
{
ctext += mat[ (x1+1)%5 ][ y1 ];
ctext += mat[ (x2+1)%5 ][ y2 ];
}
else
{
ctext += mat[ x1 ][ y2 ];
ctext += mat[ x2 ][ y1 ];
}
}
return ctext;
}

string Decrypt(string message)


{
string ptext = "";
for(int i=0; i<message.length(); i+=2) // i is incremented by 2 inorder to
check for pair values
{
position p1 = getPosition(message[i]);
position p2 = getPosition(message[i+1]);
int x1 = p1.row; int y1 = p1.col;
int x2 = p2.row; int y2 = p2.col;

if( x1 == x2 ) // same row


{
ptext += mat[x1][ --y1<0 ? 4: y1 ];
ptext += mat[x2][ --y2<0 ? 4: y2 ];
}
else if( y1 == y2 ) // same column
{
ptext += mat[ --x1<0 ? 4: x1 ][y1];
ptext += mat[ --x2<0 ? 4: x2 ][y2];
}
else
{
ptext += mat[ x1 ][ y2 ];
ptext += mat[ x2 ][ y1 ];
}
}
return ptext;
}

int main()
{
string plaintext;
cout << "Enter message : "; cin >> plaintext;

int n; // number of keys


cout << "Enter number of keys : "; cin >> n;

string key[n];
for(int i=0; i<n; i++)
{
cout<< "\nEnter key " << i+1 << " : " << key[i];
cin >> key[i];

generateMatrix(key[i]);

cout << "Key " << i+1 << " Matrix:" << endl;
for(int k=0;k<5;k++)
{
for(int j=0;j<5;j++)
{
cout << mat[k][j] << " ";
}
cout << endl;
}

cout << "Actual Message \t\t: " << plaintext << endl;

string fmsg = formatMessage(plaintext);


cout << "Formatted Message \t: " << fmsg << endl;

string ciphertext = encrypt(fmsg);


cout << "Encrypted Message \t: " << ciphertext << endl;

string decryptmsg = Decrypt(ciphertext);


cout<< "Decrypted Message \t: " << decryptmsg << endl;
}
}

Input & Output:


03. Write a program to perform the Hill cipher:

Source Code:

#include<bits/stdc++.h>
using namespace std ;

int key[3][3] ; // Global

int mod26(int x)
{
return x >= 0 ? (x%26) : 26-(abs(x)%26) ;
}

/* findDet(matrix , order_of_matrix) */
int findDet(int m[3][3] , int n)
{
int det;
if(n == 2)
{
det = m[0][0] * m[1][1] - m[0][1]*m[1][0] ;
}
else if (n == 3)
{
det = m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1]) -
m[0][1]*(m[1][0]*m[2][2] - m[2][0]*m[1][2] ) + m[0][2]*(m[1][0]*m[2][1] -
m[1][1]*m[2][0]);
}
else det = 0 ; // invalid input
return mod26(det);
}

int findDetInverse(int R , int D = 26) // R is the remainder or determinant


{
int i = 0 ;
int p[100] = {0,1};
int q[100] = {0} ; // quotient

while(R!=0)
{
q[i] = D/R ;
int oldD = D ;
D = R ;
R = oldD%R ;
if(i>1)
{
p[i] = mod26(p[i-2] - p[i-1]*q[i-2]) ;
}
i++ ;
}
if (i == 1) return 1;
else return p[i] = mod26(p[i-2] - p[i-1]*q[i-2]) ;
}
void multiplyMatrices(int a[1000][3] , int a_rows , int a_cols , int
b[1000][3] , int b_rows , int b_cols , int res[1000][3])
{
for(int i=0 ; i < a_rows ; i++)
{
for(int j=0 ; j < b_cols ; j++)
{
for(int k=0 ; k < b_rows ; k++)
{
res[i][j] += a[i][k]*b[k][j] ;
}
res[i][j] = mod26(res[i][j]) ;
}
}
}

/* Inverse = (matrix * detInverse) mod 26 */


/* findInverse(matrix , order_of_matrix , result_matrix) */
void findInverse(int m[3][3] , int n , int m_inverse[3][3] )
{
int adj[3][3] = {0};

int det = findDet(m , n); // findDet(matrix , order_of_matrix)


int detInverse = findDetInverse(det);

if(n==2)
{
adj[0][0] = m[1][1];
adj[1][1] = m[0][0];
adj[0][1] = -m[0][1];
adj[1][0] = -m[1][0];
}
else if(n==3)
{
int temp[5][5] = {0} ;
// fill the 5x5 matrix
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
temp[i][j] = m[i%3][j%3] ;
}
}
/* except first row and first column, multiply elements along rows
and place them along columns */
for(int i=1; i<=3 ; i++)
{
for(int j=1; j<=3 ; j++)
{
adj[j-1][i-1] = temp[i][j]*temp[i+1][j+1] -
temp[i][j+1]*temp[i+1][j];
}
}
}

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


{
for(int j=0; j<n ; j++)
{
m_inverse[i][j] = mod26(adj[i][j] * detInverse) ;
}
}
}

// C = PK
string encrypt(string pt, int n)
{
int P[1000][3] = {0} ; // plaintext
int C[1000][3] = {0} ; // cipher text
int ptIter = 0 ;

while(pt.length()%n != 0)
{
pt += "x" ; // pad extra x
}
int row = (pt.length())/n; // number of rows in P

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


{
for(int j=0; j<n; j++)
{
P[i][j] = pt[ptIter++]-'a' ;
}
}

// multiplyMatrices(mat_a , row_a , col_a , mat_b, row_b, col_b ,


mat_result)
multiplyMatrices(P, row , n , key , n , n , C) ;

string ct = "" ;
for(int i=0 ; i<row ; i++)
{
for(int j=0 ; j<n ;j++)
{
ct += (C[i][j] + 'a');
}
}
return ct ;
}

// P = C*(k_inverse)
string decrypt(string ct, int n)
{
int P[1000][3] = {0} ; // plaintext
int C[1000][3] = {0} ; // cipher text
int ctIter = 0 ;

int row = ct.length()/n; // number of rows in C

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


{
for(int j=0; j<n; j++)
{
C[i][j] = ct[ctIter++]-'a' ;
}
}

int k_inverse[3][3] = {0};


/* findInverse(matrix , order_of_matrix , result_matrix) */
findInverse(key, n , k_inverse);

/* multiplyMatrices(mat_a , row_a , col_a , mat_b, row_b, col_b ,


mat_result) */
multiplyMatrices(C, row , n , k_inverse , n , n , P) ;

string pt = "" ;
for(int i = 0 ; i<row ; i++)
{
for(int j=0 ; j<n ; j++)
{
pt += (P[i][j] + 'a');
}
}
return pt ;
}

int main(void)
{
string pt ;
int n ;

cout << "Enter the text to be encrypted : " ;


cin >> pt;

cout << "Enter order of key matrix : ";


cin >> n ;

cout<<"Enter key matrix: " <<endl;


for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin >> key[i][j];
}
}

cout << "\nOriginal text : " << pt << endl;


string ct = encrypt(pt, n) ;
cout << "Encrypted text : " << ct << endl;

string dt = decrypt(ct, n);


cout << "Decrypted text : " << dt << endl;
}

Input & Output:


04. Write a program to perform encryption and decryption using transposition technique with column
permutation given as key.

Source Code:

#include<bits/stdc++.h>
using namespace std ;

string encrypt(string pt , string key)


{
string ct = ""; // ciphertext
int k = 0; // plaintext iterator

int num_row = ceil((float) pt.length()/key.length());


int num_col = key.length();
char mat[num_row][num_col];

cout << "\nEncryption Matrix :" << endl;


cout << "---------------------" << endl;
for(int i=0; i<num_row ; i++)
{
for(int j=0; j<num_col; j++)
{
if(k < pt.length())
{
cout << (mat[i][j] = pt[k++]) << " ";
}
else
{
cout << (mat[i][j] = 'x') << " " ;
}
}
cout << endl;
}
for(int i=0; i<num_col; i++)
{
for(int j=0; j<num_row; j++)
{
ct += mat[j][key.find(i+'1')];
}
}
return ct;
}

string decrypt(string ct , string key)


{
string pt = ""; // plaintext
int k = 0; // ciptext iterator

int num_row = ceil((float)ct.length() / key.length());


int num_col = key.length();
char mat[num_row][num_col];
for(int i=0; i<num_col; i++)
{
for(int j=0; j<num_row; j++)
{
mat[j][key.find(i+'1')] = ct[k++];
}
}

cout << "\nDecryption Matrix :" << endl;


cout << "---------------------" << endl;
for(int i=0; i<num_row ; i++)
{
for(int j=0; j<num_col; j++)
{
cout << mat[i][j] << " ";
pt += mat[i][j];
}
cout << endl;
}
return pt;
}

int main()
{
string plaintext , key , ciphertext , decryptext;

cout << "Enter text : ";


cin >> plaintext;

cout << "Enter key : ";


cin >> key;

ciphertext = encrypt(plaintext , key);


cout << "\nEncrypted text \t: " << ciphertext << endl;

decryptext = decrypt(ciphertext , key);


cout << "\nDecrypted text \t: " << decryptext << endl;
}
Input & Output:
05. Generate and print 48-bit keys for all sixteen rounds of DES algorithm, given a 64-bit initial key.

Source Code:

#include <bits/stdc++.h>
using namespace std;

int permChoiceOne[] = {
57, 49, 41, 33, 25, 17, 9 ,
1 , 58, 50, 42, 34, 26, 18,
10, 2 , 59, 51, 43, 35, 27,
19, 11, 3 , 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7 , 62, 54, 46, 38, 30, 22,
14, 6 , 61, 53, 45, 37, 29,
21, 13, 5 , 28, 20, 12, 4 };

int permChoiceTwo[] = {
14, 17, 11, 24, 1 , 5 , 3 , 28,
15, 6 , 21, 10, 23, 19, 12, 4 ,
26, 8 , 16, 7 , 27, 20, 13, 2 ,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32 };

int leftShiftTable[] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};

string rotateSubKey(string s , int rot) // rot is the number of left shift


rotation
{
return s.substr(rot, s.length()-rot) + s.substr(0, rot) ;
}

string firstPermute(string input)


{
string res = "" ;
for(int i=0 ; i<56 ; i++)
{
res += input[permChoiceOne[i]-1];
}
return res ;
}

string secondPermute(string input)


{
string res = "" ;
for(int i=0 ; i<48 ; i++)
{
res += input[permChoiceTwo[i]-1];
}
return res ;
}
void genKeys(string left, string right)
{
ofstream fout ;
fout.open("keygen.txt"); //saving output to keygen.txt file

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


{
left = rotateSubKey(left , leftShiftTable[i]);
right = rotateSubKey(right, leftShiftTable[i]);

string key = secondPermute(left+right);

cout << "key " << i+1 << " \t: " << key << endl; // display
fout << key << endl; // save to file
}
}

int main()
{
unsigned long long hexkey;
cout << "\nEnter 64-bit key in hexadecimal(16-digits) : " ;
cin >> hex >> hexkey; // to read hex input cin >> hex >> input

string key = bitset<64>(hexkey).to_string(); // to convert hex to binary


string
cout << "Binary key (k) \t: " << key << endl;

key = firstPermute(key) ;
cout << "PC-1 key (k+) \t: " << key << endl;

cout << "\nSubKeys: " << endl;


genKeys(key.substr(0,28) , key.substr(28,28));

cout<<endl<<endl ;
}
Input & Output:
6. Implement RSA algorithm using client-server concept

Source Code:

/*Client Program*/

# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;

int connectToServer(const char* ip, int port)


{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), inet_addr(ip)};

if(connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0 ){


cout << "\nRun server program first." << endl; exit(0);
}else{
cout << "\nClient is connected to Server." << endl;
}
return sock;
}

int randInRange(int low, int high) // excluding high and low


{
return rand()%(high-(low+1)) + (low+1) ;
}

int gcd(int a, int b)


{
return b==0 ? a : gcd(b, a%b);
}

int powermod(int a, int b, int n)


{
int res = 1;
for(int i=0; i<b; i++)
{
res = (res*a) % n;
}
return res;
}

// M = C^d mod n
int decrypt(int C, int PR[2])
{
return powermod(C, PR[0], PR[1]);
}

int main()
{
char ip[50];
int port;
cout << "\nEnter server's IP address: "; cin >> ip;
cout << "Enter port : "; cin >> port;
int sock = connectToServer(ip, port);

int p,q;
cout << "\nEnter two prime numbers : "; cin >> p >> q;
int n = p * q ;
int phi = (p-1) * (q-1);

srand(time(NULL));
int e, d;
do{ e = randInRange(1, phi); } while(gcd(e,phi) != 1);

for(d=1; d<phi; d++)


{
if((d*e)%phi == 1) break;
}

int PU[2] = {e, n}; // public key


int PR[2] = {d, n}; // private key
cout << "\nPublic key , PU = {" << e << ", " << n << "}" << endl;
cout << "Private key, PR = {" << d << ", " << n << "}" << endl;

send(sock, &PU, sizeof(PU), 0); // send public key to server


cout << "\nSent Public key to server." << endl;

int C; // ciphertext
recv(sock, &C, sizeof(C), 0); // receive ciphertext from server
cout << "\nCiphertext received from server : " << C << endl;

int M = decrypt(C, PR); // decrypted text


cout << "\nDecrypted Text : " << M << endl << endl;
}

/*Server program */

# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;

int createServer(int port) // TCP connection


{
int sersock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), INADDR_ANY};
bind(sersock, (struct sockaddr *) &addr, sizeof(addr));
cout << "\nServer Online. Waiting for client...." << endl;

listen(sersock, 5);
int sock = accept(sersock, NULL, NULL);
cout << "Connection Established." << endl;

return sock;
}

int powermod(int a, int b, int n)


{
int res = 1;
for(int i=0; i<b; i++)
{
res = (res*a) % n;
}
return res;
}

// C = M^e mod n
int encrypt(int M, int PU[2]) // PU = {e, n}
{
return powermod(M, PU[0], PU[1]);
}

int main()
{
int port;
cout << "\nEnter port : "; cin >> port;
int sock = createServer(port);

int PU[2];
recv(sock, &PU, sizeof(PU), 0); // receive public key from client
cout << "\nPublic key received from client : {" << PU[0] << ", " << PU[1]
<< "}" << endl;

int M; // plaintext message (M < n)


cout << "\nEnter message(M<" << PU[1] << ") to encrypt : "; cin >> M;

int C = encrypt(M, PU);


cout << "\nEncrypted Text : " << C << endl;
send(sock, &C, sizeof(C), 0); // send ciphertext to client
cout << "\nSent ciphertext to client." << endl << endl;
}
Input & Output:
7. Implement RSA algorithm to process blocks of plaintext (refer Figure 9.7 of the text book),
where plaintext is a string of characters and let the block size be two characters. (Note: assign a
unique code to each plain text character i.e., a=00, A=26).

Source Code:

/* Client Program */

# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;

int connectToServer(const char* ip, int port)


{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), inet_addr(ip)};

if(connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0 ){


cout << "\nRun server program first." << endl; exit(0);
}else{
cout << "\nClient is connected to Server." << endl;
}
return sock;
}

int randInRange(int low, int high) // excluding high and low


{
return rand()%(high-(low+1)) + (low+1) ;
}

int gcd(int a, int b)


{
return b==0 ? a : gcd(b, a%b);
}

int powermod(int a, int b, int n)


{
int res = 1;
for(int i=0; i<b; i++)
{
res = (res*a) % n;
}
return res;
}

// M = C^d mod n
int decrypt(int C, int PR[2])
{
return powermod(C, PR[0], PR[1]);
}
// a=00, b=01, ... A=26, B=27...
char toChar(int n)
{
return (n >= 26) ? (n+'A'-26) : (n+'a');
}

int main()
{
char ip[50];
int port;
cout << "Enter Server's IP address: "; cin >> ip;
cout << "Enter port : "; cin >> port;
int sock = connectToServer(ip, port);

int p,q;
cout << "\nEnter two large prime numbers(>100) : "; cin >> p >> q;
int n = p * q ; // should be greater than 5151 (since ZZ=5151)
int phi = (p-1) * (q-1);

srand(time(NULL));
int e, d;
do{ e = randInRange(1, phi); } while(gcd(e,phi) != 1);

for(d=1; d<phi; d++)


{
if((d*e)%phi == 1) break;
}

int PU[2] = {e, n}; // public key


int PR[2] = {d, n}; // private key
cout << "\nPublic key , PU = {" << e << ", " << n << "}" << endl;
cout << "Private key, PR = {" << d << ", " << n << "}" << endl;

send(sock, &PU, sizeof(PU), 0); // send public key to server


cout << "\nSent Public key to server." << endl;

string msg = "";


while (true)
{
int C; // ciphertext
recv(sock, &C, sizeof(C), 0);
if(C == -1) break; // at the end -1 will be received
cout << "\nCiphertext received from server : " << C << endl;

int M = decrypt(C,PR);
cout << "Decrypted Text : " << M << endl;
msg += toChar(M/100); // first char in block
msg += toChar(M%100); // second char in block
}
cout << "\nDecrypted message : " << msg << endl << endl;
}
/* Server Program */

# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;

int createServer(int port) // TCP connection


{
int sersock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), INADDR_ANY};

bind(sersock, (struct sockaddr *) &addr, sizeof(addr));


cout << "\nServer Online. Waiting for client...." << endl;

listen(sersock, 5);
int sock = accept(sersock, NULL, NULL);
cout << "Connection Established." << endl;

return sock;
}

int powermod(int a, int b, int n)


{
int res = 1;
for(int i=0; i<b; i++)
{
res = (res*a) % n;
}
return res;
}

// C = M^e mod n
int encrypt(int M, int PU[2]) // PU = {e, n}
{
return powermod(M, PU[0], PU[1]);
}

// a=00, b=01, ... A=26, B=27...


int toInt(char c)
{
return (c < 'a') ? (c-'A'+26) : (c-'a');
}

int main()
{
int port;
cout << "Enter port : "; cin >> port;
int sock = createServer(port);

int PU[2];
recv(sock, &PU, sizeof(PU), 0); // receive public key from client
cout << "\nPublic key received from client : {" << PU[0] << ", " << PU[1]
<< "}" << endl;

string msg; // plaintext message


cout << "\nEnter message to encrypt : "; cin >> msg;

if(msg.length()% 2 != 0) msg+="x";

for(int i=0; i<msg.length(); i+=2) // increment by 2 for block


{
int M = toInt(msg[i])*100 + toInt(msg[i+1]); // block consist of two
msg character
cout << "\nPlaintext block : " << M << endl;

int C = encrypt(M, PU);


cout << "Encrypted text : " << C << endl;
send(sock, &C, sizeof(C), 0); // send ciphertext to client
}
int stop = -1; // at end send -1 to tell client to stop
send(sock, &stop, sizeof(stop), 0); //at end send stop to client
cout << "\nSent ciphertext to client." << endl << endl;
}

Input & Output:

You might also like