Lab Note (After DSP)
Lab Note (After DSP)
No Problem Name
01 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
Figure:
6. Write a matlab program for sampling.
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);
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;
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)')
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
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;
fin.open("plaintext.txt");
fin >> ptext;
fin.close();
return ptext;
}
int main()
{
srand(time(NULL)) ;
Source Code:
#include <bits/stdc++.h>
using namespace std;
typedef struct{
int row;
int col;
}position;
if(flag[key[i]-'a'] == 0)
{
mat[x][y++] = key[i];
flag[key[i]-'a'] = 1;
}
if(y==5) x++, y=0;
}
if(flag[ch - 'a'] == 0)
{
mat[x][y++] = ch;
flag[ch - 'a'] = 1 ;
}
if(y==5) x++, y=0;
}
}
int main()
{
string plaintext;
cout << "Enter message : "; cin >> plaintext;
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;
Source Code:
#include<bits/stdc++.h>
using namespace std ;
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);
}
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]) ;
}
}
}
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];
}
}
}
// 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
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 ;
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 ;
Source Code:
#include<bits/stdc++.h>
using namespace std ;
int main()
{
string plaintext , key , ciphertext , decryptext;
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 };
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
key = firstPermute(key) ;
cout << "PC-1 key (k+) \t: " << key << endl;
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;
// 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);
int C; // ciphertext
recv(sock, &C, sizeof(C), 0); // receive ciphertext from server
cout << "\nCiphertext received from server : " << C << endl;
/*Server program */
# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;
listen(sersock, 5);
int sock = accept(sersock, NULL, NULL);
cout << "Connection Established." << endl;
return sock;
}
// 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;
Source Code:
/* Client Program */
# include <bits/stdc++.h>
# include <arpa/inet.h>
using namespace std;
// 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);
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;
listen(sersock, 5);
int sock = accept(sersock, NULL, NULL);
cout << "Connection Established." << endl;
return sock;
}
// 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 << "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;
if(msg.length()% 2 != 0) msg+="x";