Professional Documents
Culture Documents
Rec (Info Sec) - 2
Rec (Info Sec) - 2
Rec (Info Sec) - 2
CAESAR CIPHER
AIM:
To implement Caesar cipher using C++
ALGORITHM:
STEP1 Start the program
STEP2 Initialize variables to get the key value and the message to process as input from user
STEP3 Use ‘for’ loop to give the condition for the encryption process
STEP4 Display the encrypted message
STEP5 Condition for the decryption process is given using ‘for’ loop , after getting the
encrypted message as input
STEP6 The decrypted message is displayed
STEP7 End the program
PROGRAM:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int i;
string s,t,m;
int key;
cout<<"Enter the key:";
cin>>key;
cout<<"\n Enter the message to encrypt: ";
cin>>s;
for(i=0;i<s.size();i++)
{
t+=(s[i]-'A'+key)%26+'A';
}
cout<<"\n\n\n The encrypted message is "<<t<<'\n';
cout<<"\n\n Enter the message to decrypt: "<<t<<'\n';
for(i=0;i<t.size();i++)
{
m+=(t[i]-'A'-key+26)%26+'A';
}
OUTPUT:
cout<<"\n\n\n The decrypted message is "<<m<<'\n';
return 0;
}
RESULT:
The above program to implement caesar cipher using C++ is executed successfully and the
desired output is obtained.
Exp No: 02 Date: 23-01-24
TRANSPOSITION CIPHER
AIM:
To implement transposition cipher using C++
ALGORITHM:
STEP1 Start the program
STEP2 Create a function encrypt and use ‘if’ statement and ‘for’ loop to give the condition for
encryption process
STEP3 Similarly, Create a function encrypt and use ‘if’ statement and ‘for’ loop to give the
condition for decryption process
STEP4 The message to execute is given in the main function
STEP5 In the main function the encrypt and decrypt function is called with the given message
STEP6 The output is displayed
STEP7 End the program
PROGRAM:
#include<bits/stdc++.h>
using namespace std;
string const key = "HACK";
map<int,int> keyMap;
void setPermutationOrder()
{
for(int i=0; i < key.length(); i++)
{
keyMap[key[i]] = i;
}
}
string encryptMessage(string msg)
{
int row,col,j;
string cipher = "";
col = key.length();
row = msg.length()/col;
if (msg.length() % col)
row += 1;
OUTPUT:
char matrix[row][col];
for (int i=0,k=0; i < row; i++)
{
for (int j=0; j<col; )
{
if(msg[k] == '\0')
{
matrix[i][j] = '_';
j++;
}
if( isalpha(msg[k]) || msg[k]==' ')
{
matrix[i][j] = msg[k];
j++;
}
k++;
}
}
for (map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii)
{
j=ii->second;
for (int i=0; i<row; i++)
{
if( isalpha(matrix[i][j]) || matrix[i][j]==' ' || matrix[i][j]=='_')
cipher += matrix[i][j];
}
}
return cipher;
}
string decryptMessage(string cipher)
{
int col = key.length();
int row = cipher.length()/col;
char cipherMat[row][col];
for (int j=0,k=0; j<col; j++)
for (int i=0; i<row; i++)
cipherMat[i][j] = cipher[k++];
int index = 0;
for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii)
ii->second = index++;
char decCipher[row][col];
map<int,int>::iterator ii=keyMap.begin();
int k = 0;
for (int l=0,j; key[l]!='\0'; k++)
{
j = keyMap[key[l++]];
for (int i=0; i<row; i++)
{
decCipher[i][k]=cipherMat[i][j];
}
}
string msg = "";
for (int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
if(decCipher[i][j] != '_')
msg += decCipher[i][j];
}
}
return msg;
}
int main(void)
{
string msg = "HELLO WORLD";
setPermutationOrder();
string cipher = encryptMessage(msg);
cout << "Encrypted Message: " << cipher << endl;
cout << "Decrypted Message: " << decryptMessage(cipher) << endl;
return 0;
}
RESULT:
The above program to implement transposition cipher using C++ is executed successfully and the
desired output is obtained.
Exp No: 03 Date: 30-01-24
PLAYFAIR CIPHER
AIM:
To implement playfair cipher using C++
ALGORITHM:
STEP1 Start the program
STEP2 Create a class with a grid of alphabets except J
STEP3 The input is converted into uppercase
STEP4 The plain text is broken and a bogus letter is added if the numbers of letters are odd
STEP5 With the help of the grid created, replace the plain text with the suitable letters of the
grid
STEP6 The output is displayed
STEP7 End the program
PROGRAM:
#include<iostream>
#include<string>
using namespace std;
class playfair
{ public:
void doIt(string k,string t,bool ij,bool e)
{createGrid(k,ij);
get TextReady(t,ij,e);
if(e) doIt(1); else doIt (-1);
display();
}
private:
void doIt(int dir)
{ int a,b,c,d;
string ntxt;
for (string:: const_iterator ti=_txt.begin(); ti!=_txt.end();ti++)
{ if(getCharPos(*ti++,a,b))
if(getCharpes(*ti,c,d))
{ if(a==c)
{ntxt+=getChar(a,b+dir);next+=gotChar(c,d+dir);}
else if (b==d)
{ntxt+=getChar(a+dir,b);ntxt+=getChar(c+dir,b);}
OUTPUT:
else
{ntxt+=getChar(c, b);ntxt+=getChar(a,d);}
}
}
-txt=ntxt;
}
void display()
{
cout<<"\n\n OUTPUT: \n ====="<<endl;
string::iterator si=_txt.begin();
int cnt=0;
while(si!=_txt.end())
{
cout<<*si,si++; cout<<*si<<"";si++
if(++cnt>=26)cout<<endl,cnt=0;
}
cout<<endl<<endl;
}
char getChar(int a, int b)
{ return_m[(b+5)%5][(a+5)%5];}
bool getCharPos(char l, int &a, int &b)
{
for(int y=0;y<5;y++)
for(int x=0;x<5;x++)
if(_m[y][x]==l) { a=x;b=y; return true;}
return false;
}
void getTextReady(string t,bool ij,bool e)
{ for(string::iterator si=t.begin(); si!=t.end(); si++)
{ *st=toupper(*si);if(*si<65||*si>90) count thue
if(*si=='J'&&ij)*si='I';
else if(*si=='Q' &&!ij) continue;
-txt+=*si;
}
if(e)
{
string ntxt="";size_t len=_txt.length();
for(size_t x=0;x<len;x+=2)
{
ntxt+=_txt[x];
if (x+1<len)
{if(_txt[x]==_txt[x+1]) ntxt+='x';ntxt+=_txt[x+1];}
}
_txt=ntxt,
}
if(_txt.length()&1)_txt+='x'
}
void createGrid(string k,bool ij)
{ if (k.length()<1) k="KEYWORD";
k+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk="";
for (string::iterator si=k.begin();si!=k.end(); si++)
{ *si=toupper(*si);if(*si<65||*si>90) continue;
if(*si=='J'&&ij )||(*si=='Q'&&!ij))continue;
if(nk.find(*si)==-1)nk+=*si;
}
copy( nk.begin() , nk.end() , &_m[0][0] );
}
string_txt;char_m[5][5];
};
int main(int argc,char*argv[])
{ string key,i,txt;
bool ij,e;
cout<<"(E)ncode or (D)ecode!?!"
getline(cin,i);e=(i[0]=='e'||i[0]=='E');
cout<<"Enter the key:"getline(cin,key);
cout<<"Enter the text:"getline(cin,txt);
playfair pf; pf.doIt(key,txt,ij,e);
return system("Pause");
RESULT:
The above program to implement playfair cipher using C++ is executed successfully and the
desired output is obtained
Exp No: 04 Date: 30-01-24
AIM:
To implement rail fence cipher using C++
ALGORITHM:
STEP1 Start the program
STEP2 The numbers of rows are determined from the input in the encryption function
STEP3 Grids is created with the length of text and number of rails as columns and rows, and
fill it diagonally
STEP4 The encrypted message is displayed after reading the letters row by row from the grid
STEP5 In the decrypt function, the size of the grid is determined by the encrypted message
STEP6 Create a grid to fill the letters diagonally
STEP7 For decryption, read the letters from the top left diagonally and display the output
STEP8 End the program
PROGRAM:
#include <bits/stdc++.h>
using namespace std;
string encryptRailFence(string text, int key)
{
char rail[key][(text.length())];
for (int i=0; i < key; i++)
for (int j = 0; j < text.length(); j++)
rail[i][j] = '\n';
bool dir_down = false;
int row = 0, col = 0;
for (int i=0; i < text.length(); i++)
{
if (row == 0 || row == key-1)
dir_down = !dir_down;
rail[row][col++] = text[i];
dir_down?row++ : row--;
}
string result;
for (int i=0; i < key; i++)
for (int j=0; j < text.length(); j++)
OUTPUT:
if (rail[i][j]!='\n')
result.push_back(rail[i][j]);
return result;
}
string decryptRailFence(string cipher, int key)
{
char rail[key][cipher.length()];
for (int i=0; i < key; i++)
for (int j=0; j < cipher.length(); j++)
rail[i][j] = '\n';
bool dir_down;
int row = 0, col = 0;
for (int i=0; i < cipher.length(); i++)
{
if (row == 0)
dir_down = true;
if (row == key-1)
dir_down = false;
rail[row][col++] = '*';
dir_down?row++ : row--;
}
int index = 0;
for (int i=0; i<key; i++)
for (int j=0; j<cipher.length(); j++)
if (rail[i][j] == '*' && index<cipher.length())
rail[i][j] = cipher[index++];
string result;
row = 0, col = 0;
for (int i=0; i< cipher.length(); i++)
{
if (row == 0)
dir_down = true;
if (row == key-1)
dir_down = false;
if (rail[row][col] != '*')
result.push_back(rail[row][col++]);
dir_down?row++: row--;
}
return result;
}
int main()
{
string text; int key;
cout<<"Enter the text to encrypt: ";
cin>>text;
cout<<"Enter the key: ";
cin>>key;
cout<<encryptRailFence(text,key)<<endl;
cout<<"Enter the text to decrypt: ";
cin>>text;
cout<<"Enter the key: ";
cin>>key;
cout<<decryptRailFence(text,key)<<endl;
return 0;
}
RESULT:
The above program to implement rail fence cipher using C++ is executed successfully and the
desired output is obtained.
Exp No: 05 Date: 06-02-24
AIM:
To implement data encryption standard using C++ program
ALGORITHM:
STEP1 Start the program
STEP2 Generate a 64-bit key, but only 56 bits are used for encryption, while the other 8 bits
are used for parity
STEP3 The 56-bit key is then split into two 28-bit halves, and 16 subkeys are generated by
rotating each half separately, one or two bits to the left, depending on the round number
STEP4 Permute the 64-bit plaintext according to a fixed permutation table
STEP5 Permute the 64-bit block resulting from the last round according to a fixed permutation
table, which is the inverse of the initial permutation
STEP6 The decryption process is essentially the same as encryption, except the round keys are
used in reverse order
STEP7The key schedule generates 16 round keys, one for each round of encryption/decryption
STEP8 Create a main function and enter the plain text
STEP8 The output is displayed
STEP10 End the program
PROGRAM:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
string round_keys[16];
string pt;
string convertDecimalToBinary(int decimal) { string binary;
while(decimal != 0) {
binary = (decimal % 2 == 0 ? "0" : "1") + binary; decimal = decimal/2;}
while(binary.length() < 4){ binary = "0" + binary;}
return binary;}
int convertBinaryToDecimal(string binary) { int decimal = 0;
int counter = 0;
int size = binary.length(); for(int i = size-1; i >= 0; i--) {
OUTPUT:
if(binary[i] == '1'){
decimal += pow(2, counter);
}
counter++;
}
return decimal;
}
string shift_left_once(string key_chunk){ string shifted="";
for(int i = 1; i < 28; i++){ shifted += key_chunk[i];
}
shifted += key_chunk[0]; return shifted;
}
string shift_left_twice(string key_chunk){ string shifted="";
for(int i = 0; i < 2; i++){ for(int j = 1; j < 28; j++){
shifted += key_chunk[j];}
shifted += key_chunk[0]; key_chunk= shifted; shifted ="";}
return key_chunk;}
string Xor(string a, string b){ string result = "";
int size = b.size();
for(int i = 0; i < size; i++){ if(a[i] != b[i]){
result += "1";}
else{
result += "0";}
}
return result;
void generate_keys(string key){ int pc1[56] = { 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 pc2[48] = { 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};
string perm_key =""; for(int i = 0; i < 56; i++){
perm_key+= key[pc1[i]-1];
}
string left= perm_key.substr(0, 28);
string right= perm_key.substr(28, 28);
for(int i=0; i<16; i++){
if(i == 0 || i == 1 || i==8 || i==15 ){ left= shift_left_once(left); right= shift_left_once(right);}
else{
left= shift_left_twice(left); right= shift_left_twice(right);}
string combined_key = left + right; string round_key = "";
for(int i = 0; i < 48; i++){
round_key += combined_key[pc2[i]-1];}
round_keys[i] = round_key;}
string DES(){
int initial_permutation[64] = { 58,50,42,34,26,18,10,2,
60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,
64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,
59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,
63,55,47,39,31,23,15,7
};
int expansion_table[48] = { 32,1,2,3,4,5,4,5,
6,7,8,9,8,9,10,11,
12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,
22,23,24,25,24,25,26,27,
28,29,28,29,30,31,32,1};
int substition_boxes[8][4][16]= {{ 14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,
0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,
4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,
15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13},
{15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,
3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,
0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,
13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9},
{10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,
13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,
13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,
1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12},
{7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,
13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,
10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,
3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14},
{ 2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,
14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,
4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,
11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3},
{ 12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,
10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,
9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,
4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13},
{4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,
13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,
1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,
6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12},
{13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,
1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,
7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,
2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11}};
int permutation_tab[32] = { 16,7,20,21,29,12,28,17,
1,15,23,26,5,18,31,10,
2,8,24,14,32,27,3,9,
19,13,30,6,22,11,4,25};
int inverse_permutation[64]= { 40,8,48,16,56,24,64,32,
39,7,47,15,55,23,63,31,
38,6,46,14,54,22,62,30,
37,5,45,13,53,21,61,29,
36,4,44,12,52,20,60,28,
35,3,43,11,51,19,59,27,
34,2,42,10,50,18,58,26,
33,1,41,9,49,17,57,25};
string perm = "";
for(int i = 0; i < 64; i++){
perm += pt[initial_permutation[i]-1];
}
string left = perm.substr(0, 32); string right = perm.substr(32, 32); for(int i=0; i<16; i++) {
string right_expanded = "";
for(int i = 0; i < 48; i++) {
right_expanded += right[expansion_table[i]-1];
};
string xored = Xor(round_keys[i], right_expanded); string res = "";
for(int i=0;i<8; i++){
string row1= xored.substr(i*6,1) + xored.substr(i*6 + 5,1); int row =
convertBinaryToDecimal(row1);
string col1 = xored.substr(i*6 + 1,1) + xored.substr(i*6 + 2,1) + xored.substr(i*6 + 3,1) +
xored.substr(i*6 + 4,1);;
int col = convertBinaryToDecimal(col1); int val = substition_boxes[i][row][col]; res +=
convertDecimalToBinary(val);
}
string perm2 ="";
for(int i = 0; i < 32; i++){
perm2 += res[permutation_tab[i]-1];
}
xored = Xor(perm2, left); left = xored;
if(i < 15){
string temp = right; right = xored;
left = temp;
}
}
string combined_text = left + right; string ciphertext ="";
for(int i = 0; i < 64; i++){
ciphertext+= combined_text[inverse_permutation[i]-1];
}
return ciphertext;
}
int main(){
string key= "1010101010111011000010010001100000100111001101101100110011011101";
pt= "1010101111001101111001101010101111001101000100110010010100110110";
generate_keys(key); cout<<"Plain text: "<<pt<<endl; string ct= DES(); cout<<"Ciphertext:
"<<ct<<endl;
}
OUTPUT:
The above program to implement data encryption standard using C++ has been executed
successfully and the desired output is obtained
Exp No: 06 Date: 27-02-24
AIM:
To implement simplified data encryption standard using C++ program
ALGORITHM:
STEP1 Start the program
STEP2 Generate a 10-bit key, which will be used for both encryption and decryption
STEP3 Permute the 8-bit plaintext block according to a fixed permutation table
STEP4 Split the permuted block into two 4-bit halves, denoted as L0 and R0
STEP5 Generate two 8-bit subkeys, K1 and K2, using the 10-bit key
STEP6 Perform a series of operations, including expansion, XOR with K1, substitution using
the S-boxes, and a permutation
STEP7 Swap the positions of the left and right halves
STEP8 Repeat the operations from Round 1, but use K2 instead of K1
STEP9 Permute the resulting block from Round 2 using a fixed permutation table
STEP10 The output is displayed
STEP11 End the program
PROGRAM:
#include<iostream>
using namespace std;
static int round1_key[8],round2_key[8];
void p10(int key[]){
int out[10]={3,5,2,7,4,10,1,9,8,6};
int temp[10];
for(int i=0;i<10;i++) temp[i]=key[i]; for(int i=0;i<10;i++){key[i]=temp[out[i]-1];}
}
void p8(int key[]){
int out[8]={6,3,7,4,8,5,10,9};
int temp[10];
for(int i=0;i<10;i++) temp[i]=key[i]; for(int i=0;i<8;i++){key[i]=temp[out[i]-1];
}}
void p4(int s0s1[]){
int out[4]={2,4,3,1}; int temp[4];
for(int i=0;i<4;i++) temp[i]=s0s1[i];
for(int i=0;i<4;i++){ s0s1[i]=temp[out[i]-1];
OUTPUT:
}}
void left_shift(int left_half[], int right_half[], int shift_count){ int temp1=left_half[0];
int temp2=right_half[0]; for(int i=0;i<4;i++){
left_half[i]=left_half[i+1]; right_half[i]=right_half[i+1];
}
left_half[4]=temp1; right_half[4]=temp2; if(shift_count==2) left_shift(left_half,right_half,1);
}
int* generate_key(int key[],int round){ int left_half[5],right_half[5];
static int key1[10],key2[8]; p10(key);
for(int i=0;i<10;i++){ if(i<5){
left_half[i]=key[i];
}
else{
right_half[i-5]=key[i];
}}
left_shift(left_half,right_half,1); for(int i=0;i<5;i++) {
key1[i]=left_half[i]; key1[i+5]=right_half[i];
}
if(round==1){ p8(key1); return key1;
}
else{
left_shift(left_half,right_half,2);
for(int i=0;i<5;i++){ key2[i]=left_half[i]; key2[i+5]=right_half[i];
}
p8(key2); return key2;
}}
void initial_permutation(int pt[]){ int out[8]={2,6,3,1,4,8,5,7};
int temp[8];
for(int i=0;i<8;i++) temp[i]=pt[i]; for(int i=0;i<8;i++){
pt[i]=temp[out[i]-1];
}}
void inverse_initial_permutation(int pt[]){ int out[8]={2,6,3,1,4,8,5,7};
int temp[8];
for(int i=0;i<8;i++) temp[i]=pt[i]; for(int i=0;i<8;i++){
pt[out[i]-1]=temp[i];
}}
int* expand_and_permute(int right_half[]){ int out[8]={4,1,2,3,2,3,4,1};
int temp[4];
static int expanded_right[8]; for(int i=0;i<4;i++)
temp[i]=right_half[i]; for(int i=0;i<8;i++){
expanded_right[i]=temp[out[i]-1];}
return expanded_right;
}
int get_S0(int row,int column){ int s0[4][4]={
{01,00,11,10},
{11,10,01,00},
{00,10,01,11},
{11,01,11,10}
};
return s0[row][column];
}
int get_S1(int row,int column){ int s1[4][4]={
{00,01,10,11},
{10,00,01,11},
{11,00,01,00},
{10,01,00,11}
};
return s1[row][column];
}
int* rounds(int pt[],int key[],int round_no,int flag){
int left[4],right[4],*expanded_right,s0[4],s1[4],temp_key[10]; cout<<"\
nROUND-"<<round_no;
for(int i=0;i<10;i++){ temp_key[i]=key[i];
}
if(round_no==1) initial_permutation(pt);
for(int i=0;i<4;i++){ left[i]=pt[i]; right[i]=pt[i+4];
}
expanded_right= expand_and_permute(right); static int* key1;
if(flag==0) { key1=generate_key(key,round_no); if(round_no==1){
for(int i=0;i<8;i++) round1_key[i]=key1[i];
}
else{for(int i=0;i<8;i++) round2_key[i]=key1[i];}
cout<<"\n\nEncode Key of Round "<<round_no<<endl; for(int i=0;i<8;i++){cout<<key1[i];}
}
else {
if(round_no==1){ for(int i=0;i<8;i++){key1[i]=round2_key[i];}
}
else {
for(int i=0;i<8;i++){ key1[i]=round1_key[i];}
}
cout<<"\n\nDecode Key of Round "<<round_no<<endl; for(int i=0;i<8;i++){
cout<<key1[i];}}
for(int i=0;i<8;i++){ expanded_right[i]=expanded_right[i] ^ key1[i]; if(i<4)
s0[i]=expanded_right[i]; else
s1[i-4]=expanded_right[i];
}
int row=s0[3]+(s0[0]*2);
int column=s0[2]+(s0[1]*2); static int s0s1[4];
int ss0=get_S0(row,column); row=s1[3]+(s1[0]*2);
column=s1[2]+(s1[1]*2);
int ss1=get_S1(row,column); s0s1[1]=ss0%10;
s0s1[0]=ss0/10; s0s1[3]=ss1%10;
s0s1[2]=ss1/10; p4(s0s1);
static int new_plain_text[8]; for(int i=0;i<4;i++){
s0s1[i]=s0s1[i] ^ left[i]; if(round_no!=2){new_plain_text[i]=right[i];
new_plain_text[i+4]=s0s1[i];}
else{ new_plain_text[i+4]=right[i];
new_plain_text[i]=s0s1[i];
}}
cout<<"\n\nRound "<<round_no<<" Output:\n"; for(int i=0;i<8;i++)
cout<<new_plain_text[i]<<"\t";
cout<<endl; if(round_no==1){
if(flag==0) rounds(new_plain_text,temp_key,2,0);
else
rounds(new_plain_text,temp_key,2,1);
}
else{return new_plain_text;} }
int* encode(int pt[],int* round_text,int key[]){ round_text=rounds(pt,key,1,0);
inverse_initial_permutation(round_text);
cout<<"\n\n-------------FINAL CIPHER TEXT \n";
for(int i=0;i<8;i++) cout<<round_text[i];
return round_text;
}
void decode(int pt[], int* cipher_text,int key[]){ int *new_ct=rounds(cipher_text,key,1,1);
inverse_initial_permutation(new_ct);
cout<<"\n\n-------------DECODED TEXT \n";
for(int i=0;i<8;i++) cout<<new_ct[i];
}
int main(){
int *round_text, *cipher_text, pt[8],key[10]; cout<<"\nEnter the plain text (8-bits) :"; for(int
i=0;i<8;i++)
cin>>pt[i];
cout<<"\nEnter the key (10-bits) :"; for(int i=0;i<10;i++)
cin>>key[i];
cout<<"\n-------------ENCRYPTION \n";
cipher_text=encode(pt,round_text,key);
cout<<"\n\n\n-------------DECRYPTION \n";
decode(pt,cipher_text,key); return 0;
}
RESULT:
The above program to implement simplified data encryption standard using C++ has been executed
successfully and the desired output is obtained
Exp No: 07 Date: 19-03-24
RSA ALGORITHM
AIM:
To implement RSA algorithm using C++
ALGORITHM:
STEP1 Start the program
STEP2 Define the gcd function and initialize the temp variable.
STEP3 While temp is not equal to 0, set temp as the remainder of a divided by h.
STEP4 Update a as h and h as temp.
STEP5 Define prime numbers p and q and calculate n as the product of p and q.
STEP6 Find a suitable value for d, the decryption key, such the (d*e)%phi = 1.
STEP7 Encrypt the message - c = (msg^e)%n
STEP8 Decrypt the message – m = (c^d)%n
STEP9 Output the original message, encrypted message and decrypted message.
STEP10 End the program
PROGRAM:
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int h)
{
int temp;
while (1) {temp = a % h;
if (temp == 0)
return h;
a = h;
h = temp;}
}
int main()
{
double p = 3;
double q = 7;
double n = p * q;
double e = 2;
double phi = (p - 1) * (q - 1);
while (e < phi) {
OUTPUT:
if (gcd(e, phi) == 1)
break;
else
e++;
}
int k = 2; // A constant value
double d = (1 + (k * phi)) / e;
double msg = 12;
printf("Message data = %lf", msg);
double c = pow(msg, e);
c = fmod(c, n);
printf("\nEncrypted data = %lf", c);
double m = pow(c, d);
m = fmod(m, n);
printf("\nOriginal Message Sent = %lf", m);
return 0;
}
RESULT:
The above program to implement RSA algorithm using C++ has been executed successfully and
the desired output is obtained
Exp No: 08 Date: 26-03-24
AIM:
To implement Diffie Hellman algorithm using C++
ALGORITHM:
Step 1 Start the program
Step 2 Define the prime number and the base value
Step 3 Generate private keys a and b for the two parties
Step 4 Calculate the public keys for each party using modular
exponentiation
Step 5 The parties exchange the public keys
Step 6 Both parties calculate the shared secret using other party’s public key and their own
private key
Step 7 Output is displayed
Step 8 End the program
PROGRAM:
#include <cmath>
#include <iostream>
using namespace std;
long long int power(long long int a, long long int b,long long int P)
{
if (b == 1)
return a;
else
}
return (((long long int)pow(a, b)) % P);
int main()
{
long long int P, G, x, a, y, b, ka, kb; P = 23;
cout << "The value of P : " << P << endl; G = 9;
cout << "The value of G : " << G << endl; a = 4;
cout << "The private key a for Alice : " << a << endl; x = power(G, a, P);
b = 3;
cout << "The private key b for Bob : " << b << endl;
y = power(G, b, P);
ka = power(y, a, P);
OUTPUT:
cout << "Secret key for the Alice is : " << ka << endl;
cout << "Secret key for the Bob is : " << kb << endl;
return 0;
}
RESULT:
The above program to implement Diffie Hellman algorithm using C++ has been executed
successfully and the desired output is obtained
OUTPUT:
AIM:
To implement MD5 algorithm using C++
ALGORITHM:
Step 1 Start the program
Step 2 Initialize variables with predefined constants
Step 3 Append padding bits such that the length of the message is congruent to 448 mod 512
Step 4 Break the padded message into 512-bit block
Step 5 Process each block in the message sequentially
Step 6 Perform 64 operations on the message block using a nonlinear function
Step 7 Output is displayed
Step 8 End the program
PROGRAM:
#include <iostream>
#include <openssl/md5.h>
#include <cstring>
std::string md5(const std::string& input) {
unsigned char digest[MD5_DIGEST_LENGTH];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, input.c_str(), input.length()); MD5_Final(digest, &context);
char mdString[33];
for(int i = 0; i < 16; i++)
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
return std::string(mdString);
}
int main() {
std::string input = "Hello World";
std::string result = md5(input);
std::cout << "MD5 hash of '" << input << "' is: " << result << std::endl;
return 0;
}
RESULT:
The above program to implement MD5 algorithm using C++ has been executed successfully and
the desired output is obtained
OUTPUT:
AIM:
To implement SHA algorithm using C++
ALGORITHM:
Step 1 Start the program
Step 2 Initialize variables with predefined constants
Step 3 Append padding bits such that the length of the message is congruent to 448 mod 512
Step 4 Append the length of the original message as a 64-bit representation
Step 5 Process each block in the message sequentially
Step 6 Perform 64 rounds of mixing operations on the message block
Step 7 Output is displayed
Step 8 End the program
PROGRAM:
#include <iostream>
#include
<openssl/sha.h>
#include <cstring>
std::string sha256(const std::string& input)
{
unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256_CTX context;
SHA256_Init(&context);
SHA256_Update(&context, input.c_str(), input.length());
SHA256_Final(digest, &context);
char shaString[SHA256_DIGEST_LENGTH * 2 + 1];
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
sprintf(&shaString[i*2], "%02x", (unsigned int)digest[i]); return std::string(shaString);
}
int main()
{
std::string input = "Hello
World"; std::string result =
sha256(input);
std::cout << "SHA-256 hash of '" << input << "' is: " << result <<
std::endl; return 0;
}
RESULT:
The above program to implement SHA algorithm using C++ has been executed successfully and
the desired output is obtained
Exp No: 11 Date: 23-04-24
DIGITAL SIGNATURE STANDARD
AIM:
To implement digital signature standard using C++
ALGORITHM:
Step 1 Start the program
Step 2 Generate a key pair: a private key and a corresponding public key
Step 3 Hash the message using a secure hash function to create a digest
Step 4 Encrypt the digest with your private key to create the digital signature
Step 5 Receive the signed message along with the digital signature
Step 6 Decrypt the digital signature using the sender's public key to obtain the digest
Step 7 Compare the two digests. If they match, the message is authentic and output is
displayed
Step 8 End the program
PROGRAM:
#include <iostream>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <cstring>
RSA* generateRSAKey()
{
RSA *rsa = RSA_new();
BIGNUM *e = BN_new();
BN_set_word(e, RSA_F4);
if (!RSA_generate_key_ex(rsa, 2048, e, NULL))
{std::cerr << "Failed to generate RSA key pair." << std::endl; return nullptr;}
BN_free(e); return rsa;
}
std::string signData(const std::string& data, RSA* privateKey)
{ unsigned char signature[4096];
unsigned int signatureLength;
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!EVP_SignInit(ctx, EVP_sha256()))
{std::cerr << "Sign initialization failed." << std::endl; return "";}
if (!EVP_SignUpdate(ctx, data.c_str(), data.size()))
OUTPUT:
RESULT:
The above program to implement Digital Signature Standard has been executed successfully and
the desired output is obtained
AIM:
Install JCRYPT tool (or any other equivalent). Demonstrate Symmetric and Asymmetric cryptographic
algorithm, hash and digital signatures
ALGORITHM:
1. Generate a secret key.
2. Encrypt plaintext using the secret key.
3. Decrypt ciphertext using the secret key.
4. Generate public and private keys.
5. Encrypt plaintext using the public key.
6. Decrypt ciphertext using the private key.
7. Generate a public-private key pair.
8. Sign a message using the private key.
9. Verify the signature using the public key.
PROGRAM:
#Symmetric Cryptographic Algorithm (AES)
def symmetric_crypto_demo():
decryptor = cipher.decryptor()
print("Symmetric Encryption-Decryption:")
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)
symmetric_crypto_demo()
def asymmetric_crypto_demo():
public_key = private_key.public_key()
ciphertext = public_key.encrypt(plaintext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(),
label=None))
decrypted_text = private_key.decrypt(ciphertext,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(),
label=None))
print("\nAsymmetric Encryption-Decryption:")
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)
asymmetric_crypto_demo()
def hash_function_demo():
digest.update(plaintext)
hashed_text = digest.finalize()
print("Plaintext:", plaintext)
hash_function_demo()
# Digital Signatures
def digital_signature_demo():
public_key = private_key.public_key()
try:
verified = True
except:
verified = False
print("\nDigital Signature:")
print("Message:", message)
print("Signature:", signature)
print("Verified:", verified)
digital_signature_demo()
OUTPUT:
Asymmetric Encryption-Decryption:
Digital Signatures
RESULT:
The above codes has been executed successfully for Install JCRYPT tool (or any other equivalent).
Demonstrate Symmetric and Asymmetric cryptographic algorithm, hash and digital signatures convert into a single
line topic main
EXP NO: 13 DATE:
Demonstrate Intrusion Detection System (IDS) using any tool using SNORT (or any other equivalent)
AIM:
To Demonstrate Intrusion Detection System (IDS) using any tool using SNORT (or any other equivalent)
Algorithm:
Program:
# Example SNORT configuration file: snort.conf
alert tcp any any -> $HOME_NET 22 (msg:"Potential SSH Brute Force Attack"; \
sid:100001;)
alert icmp any any -> $HOME_NET any (msg:"ICMP Echo Request Detected"; \
sid:100002;z
# Configure logging
Data storage, secure data transmission and create Digital Signatures GnuPG
Aim:
To Demonstrate secure data storage, secure data transmission and create Digital Signatures GnuPG
(or any other equivalent)
Algorithm:
1. Secure Data Storage:
Encrypt sensitive data using GnuPG with a symmetric encryption algorithm (e.g., AES).
Store the encrypted data securely on the system or in a database.
2. Secure Data Transmission:
Encrypt data before transmission using GnuPG with a recipient's public key.
Transmit the encrypted data over a secure channel (e.g., HTTPS).
3. Digital Signatures:
Generate a digital signature for a file or message using GnuPG with your private key.
Verify the digital signature using GnuPG with your public key.
Program:
import subprocess
def secure_data_storage():
def secure_data_transmission():
def digital_signatures():
if result.returncode == 0:
else:
# Main function
def main():
secure_data_storage()
secure_data_transmission()
digital_signatures()
if __name__ == "__main__":
main()
Output:
Result:
The above program for Demonstrate secure data storage, secure data transmission and create Digital
Signatures GnuPG (or any other equivalent)
EXP NO:15 DATE:
Aim:
Configure SSH (Secure Shell) and send/receive a file on this. connection to verify the correctness of
this system using the configured parameters.
Algorithm:
1. Configure SSH Server:
Install and configure an SSH server (e.g., OpenSSH) on the destination system.
Configure SSH to allow remote access and file transfer.
2. Configure SSH Client:
Install SSH client software (e.g., OpenSSH) on the local system.
Generate SSH key pair (public and private keys) for authentication.
3. Establish SSH Connection:
Use SSH client to connect to the SSH server using its IP address or hostname.
Authenticate using SSH key pair or password, depending on server configuration.
4. Send/Receive File:
Once connected, use SCP (Secure Copy Protocol) or SFTP (SSH File Transfer Protocol) to
send or receive files securely over the SSH connection.
5. Verify Correctness:
Check that the file transfer completes successfully without errors.
Ensure that the transferred file is identical to the original file in terms of content and integrity.
Program:
import paramiko
def ssh_file_transfer():
host = 'remote_server_ip'
port = 22
username = 'username'
password = 'password'
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
except Exception as e:
print("Error:", e)
finally:
ssh_client.close()
# Main function
def main():
ssh_file_transfer()
if __name__ == "__main__":
main()
Output:
Result:
The above for the SSH (Secure Shell) and send/receive a file on this. connection to verify the
correctness of this system using the configured parameters.
Exp no:16 date:
Aim:
To implement rootkit and explore all the options available in the rootkits.
Algorithm:
Step1:install chkrootkit using sudo apt-get install chkrootkit.
Chkrootkit-q
Chkrootkit-p
Chkrootkit-x
Chkrootkit-r
Program:
sudo chkrootkit –x
sudo chkrootkit –r
Aim:
Algorithm:
1. Set the Password: Define the password that you want to hash. For example,
password="MySecurePassword123".
2. Print Header: Output a header message to indicate that password hashes are being generated.
3. Generate MD5 Hash:
Use the openssl passwd -1 command to generate an MD5 hash of the password.
Store the generated MD5 hash in a variable (md5_hash).
4. Print MD5 Hash: Output the generated MD5 hash to the console.
5. Generate SHA-1 Hash:
Use the openssl passwd -1 -salt command to generate a SHA-1 hash of the password with a
specific salt (e.g., abc123).
Store the generated SHA-1 hash in a variable (sha1_hash).
6. Print SHA-1 Hash: Output the generated SHA-1 hash to the console.
7. Generate SHA-256 and SHA-512 Hashes:
Use the openssl passwd -6 command to generate SHA-256 and SHA-512 hashes of the
password.
Optionally, provide a salt value using the -salt option for increased security.
Store the generated SHA-256 hash in a variable (sha256_hash) and the SHA-512 hash in
another variable (sha512_hash).
8. Print SHA-256 and SHA-512 Hashes: Output the generated SHA-256 and SHA-512 hashes to the
console.
9. End of Script: End the script execution.
Program:
#!/bin/bash
password="MySecurePassword123"
echo ""
The above code to generate password hashes with OpenSSL has been done successfully.
EXP NO: 18 DATE:
Aim:
To implement sample Configuring S/MIME for e-mail communication
Algorithm:
1. Generate a Digital Certificate: Obtain a digital certificate from a trusted Certificate Authority (CA)
specifically for S/MIME usage.
2. Install the Certificate: Import the certificate into your email client's certificate store.
3. Configure Email Client Settings:
Outlook: Navigate to File > Options > Trust Center > Trust Center Settings > Email
Security. Choose to encrypt outgoing messages and digitally sign them. Select your S/MIME
certificate.
Thunderbird: Go to Tools > Account Settings > Security. Import your S/MIME certificate
under "Security Devices" and configure S/MIME settings under "Security."
Apple Mail: Access Mail > Preferences > Accounts > [Your Account] > Security. Configure
encryption and signing options, and select your certificate.
4. Exchange Public Keys: Exchange public keys with recipients to encrypt emails. Send a digitally
signed email to the recipient; their email client will extract your public key from the signature.
5. Test Encryption and Signing: Send test emails to yourself or trusted recipients to verify encryption
and signature verification.
6. Communicate Encryption Preferences: Inform recipients that you support S/MIME encryption and
encourage them to configure their email clients accordingly.
7. Regularly Update Certificates: Renew your S/MIME certificate before it expires to avoid
interruptions in email encryption and signing.
Program:
#!/bin/bash
Output:
Result:
The above code to implement the sample Configuring S/MIME for e-mail communication.
EXP NO: 19 DATE:
Aim:
To implement the program for filtering rules settings using IPTABLES on Linux.
Algorithm:
1. Open Terminal: Launch a terminal session on your Linux machine.
2. Check Current Rules: Use the following command to view the current IPTABLES rules:
sudo iptables -L
3. Set Default Policies: Define default policies for INPUT, FORWARD, and OUTPUT chains to
determine how traffic that does not match any rule will be handled:
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT
4. Create New Chains (Optional): You can create custom chains for organizing rules efficiently:
sudo iptables -N MY_CUSTOM_CHAIN
5. Define Rules: Add rules to the appropriate chains to allow or deny traffic based on criteria such as
source/destination IP, port, protocol, etc. For example:
# Allow incoming SSH traffic
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Program:
#!/bin/bash
sudo iptables -L
# Set default policies
# Define rules
# Save rules
Result:
The above code by using IPTABLES on Linux and setting the filtering rules.
EXP NO:20
DATE:
AIM:
To implement and Understanding Buffer Overflow and Format String Attacks.
Algorithm:
1. The vulnerableFunction takes a user input input and copies it into a fixed-size buffer buffer using
strcpy.
2. If the length of input exceeds the size of buffer, a buffer overflow occurs, potentially overwriting
adjacent memory locations.
3. An attacker can exploit this vulnerability by providing input larger than the buffer size, injecting
malicious code or altering program behavior.
4. The vulnerableFunction takes a user input input and directly passes it to printf for formatting and
printing.
5. If the input string contains format specifiers (%s, %n, etc.) without corresponding arguments, it can
lead to a format string vulnerability.
6. An attacker can exploit this vulnerability to leak sensitive information from memory, modify
memory contents, or even execute arbitrary code.
Program:
#include <stdio.h>
#include <string.h>
char buffer[10];
strcpy(buffer, input);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
return 1;
vulnerableFunction(argv[1]);
return 0;
printf(input);
if (argc != 2) {
return 1;
vulnerableFunction(argv[1]);
return 0;
}
Output:
Setup a Honey pot and monitor the honey pot on network using KF Sensor (or any
other equivalent)
AIM:
To Setup a Honey pot and monitor the honey pot on network using KF Sensor (or any other
equivalent).
Algorithm:
1. Choose Honeypot Software: Select a honeypot software like Cowrie, Dionaea, or Honeyd based on
your requirements and preferences.
2. Install Honeypot Software: Follow the installation instructions provided by the chosen honeypot
software's documentation. This typically involves downloading the software package and
configuring it according to your environment.
3. Configure Honeypot: Configure the honeypot to mimic vulnerable services or systems to attract
potential attackers. Set up fake credentials, open ports, and simulate vulnerabilities to entice attackers
to interact with the honeypot.
4. Deploy Honeypot: Deploy the honeypot in your network environment. Ensure it is isolated from
production systems to prevent any accidental impact on legitimate services.
5. Monitor Network Traffic: Use a network monitoring tool like KF Sensor (or equivalent) to monitor
the network traffic directed towards the honeypot. Configure the monitoring tool to capture and
analyze traffic specific to the honeypot's IP address and ports.
6. Analyze Logs: Regularly analyze the logs generated by the honeypot software and the network
monitoring tool. Look for patterns of malicious activity, such as unauthorized access attempts, brute
force attacks, or exploits targeting known vulnerabilities.
7. Alerts and Notifications: Configure the monitoring tool to generate alerts or notifications when
suspicious activity is detected. This can include sending emails, SMS alerts, or triggering automated
response actions.
8. Investigate Incidents: When suspicious activity is detected, investigate the incidents further to
understand the nature of the attack, identify potential threats, and gather evidence for forensic
analysis.
9. Take Countermeasures: Based on the analysis of detected threats, take appropriate countermeasures
to mitigate the risks. This may involve blocking IP addresses, updating firewall rules, or
implementing additional security controls.
Program:
#!/bin/bash
# Define variables
# Start honeypot
HONEYPOT_PID=$!
# Start KF Sensor
KF_SENSOR_PID=$!
tail -f $LOG_FILE
# Cleanup on exit
function cleanup {
rm $LOG_FILE
Output:
Result:
The above code to Setting Up a Honeypot and Monitoring with KF Sensor
Exp no:22 Date:
Aim:
To configure the firewall to block all ip addresses on lan, all icmp requests and all tcp syn packets
Algorithm:
Program:
The above program has been executed successfully and output has been verified.