Ilovepdf Merged
Ilovepdf Merged
Ilovepdf Merged
TASK:
1. Write a socket program to demonstrate Caesar Cipher.
AIM:
Develop a socket program in C to showcase the implementation of Caesar Cipher, demonstrating
encryption and decryption functionalities between a client and server.
ALGORITHM:
1. Server Side:
a. Create a socket using socket().
b. Set socket options using setsockopt().
c. Bind the socket to a specific address and port using bind().
d. Listen for incoming connections using listen().
e. Accept the connection from the client using accept().
f. Receive the plain text and key from the client using recv().
g. Encrypt the plain text using the Caesar Cipher algorithm.
h. Send the encrypted text back to the client using send().
i. Close the connected socket and the listening socket.
2. Client Side:
a. Create a socket using socket().
b. Define the server address and port.
c. Connect to the server using connect().
d. Input the plain text and key from the user.
e. Send the plain text and key to the server using send().
f. Receive the encrypted text from the server using recv().
g. Display the encrypted text.
h. Close the connected socket.
CODE:
Server code:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <ctype.h>
#define PORT 8080
int main(int argc, char const* argv[])
{
int server_fd, new_socket;
ssize_t valread;
struct sockaddr_in address;
int opt = 1;
socklen_t addrlen = sizeof(address);
char buffer[1024] = { 0 };
cipherText[strlen(plainText)] = '\0';
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#define PORT 8080
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
Client side:
2. Write a socket program to demonstrate Rail Fence Cipher.
AIM:
Create a C socket program to illustrate Rail Fence Cipher, showcasing encryption and decryption
processes through communication between a client and server.
ALGORITHM:
Server Side:
a. Create a socket using socket().
b. Set socket options using setsockopt().
c. Bind the socket to a specific address and port using bind().
d. Listen for incoming connections using listen().
e. Accept the connection from the client using accept().
f. Receive the plain text from the client using recv().
g. Remove spaces from the received plain text using removeSpaces().
h. Encrypt the plain text using the Rail Fence Cipher algorithm.
i. Send the encrypted text back to the client using send().
j. Close the connected socket and the listening socket.
Client Side:
a. Create a socket using socket().
b. Define the server address and port.
c. Connect to the server using connect().
d. Input the plain text from the user.
e. Send the plain text to the server using send().
f. Receive the encrypted text from the server using recv().
g. Display the encrypted text in uppercase.
h. Close the connected socket.
CODE:
Server code:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <ctype.h>
removeSpaces(plainText);
char buffer[1024] = { 0 };
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Receiving text
char plainText[MAX_BUFFER_SIZE];
printf("Enter the Plain text: ");
fgets(plainText, sizeof(plainText), stdin);
plainText[strcspn(plainText, "\n")] = '\0';
//Sending plain texT to server side
if (send(client_fd, &plainText, sizeof(plainText), 0) < 0) {
perror("Failed to send plain text\n");
exit(EXIT_FAILURE);
}
char cipherText[sizeof(plainText)];
if (recv(client_fd, &cipherText, sizeof(cipherText), 0) < 0) {
perror("Failed to receive cipher text\n");
exit(EXIT_FAILURE);
}
OUTPUT:
Server side:
Client side:
3. Write a socket program to demonstrate Playfair Cipher.
AIM:
Construct a C socket program to exhibit Playfair Cipher, highlighting encryption and decryption
functionalities during communication between a client and server.
ALGORITHM:
Server Side:
a. Create a socket using socket().
b. Set socket options using setsockopt().
c. Bind the socket to a specific address and port using bind().
d. Listen for incoming connections using listen().
e. Accept the connection from the client using accept().
f. Receive the cipher text from the client using recv().
g. Print the received cipher text.
h. Close the connected socket and the listening socket.
Client Side:
a. Create a socket using socket().
b. Define the server address and port.
c. Connect to the server using connect().
d. Input the plain text and key from the user.
e. Create the Playfair matrix using the key.
f. Encrypt the plain text using the Playfair cipher algorithm.
g. Send the cipher text to the server using send().
h. Print a success message.
i. Close the connected socket.
CODE:
Server code:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <ctype.h>
#define SIZE 5
#define MAX_BUFFER_SIZE 1024
char keyMatrix[SIZE][SIZE];
char cipherText[MAX_BUFFER_SIZE];
int x = 0;
if (!found) {
keyMatrix[k / SIZE][k % SIZE] = currentChar;
k++;
}
}
if (!found) {
keyMatrix[k / SIZE][k % SIZE] = currentChar;
k++;
}
}
}
void findPosition(char letter, int *row, int *col) {
if (letter == 'I') {
letter = 'J';
}
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (keyMatrix[i][j] == letter) {
*row = i;
*col = j;
return;
}
}
}
}
if (row1 == row2) {
col1 = (col1 + 1) % SIZE;
col2 = (col2 + 1) % SIZE;
}
else if (col1 == col2) {
row1 = (row1 + 1) % SIZE;
row2 = (row2 + 1) % SIZE;
}
else {
int temp = col1;
col1 = col2;
col2 = temp;
}
cipherText[x++] = keyMatrix[row1][col1];
cipherText[x++] = keyMatrix[row2][col2];
cipherText[x++] = ' ';
// printf("%c%c ", keyMatrix[row1][col1], keyMatrix[row2][col2]);
}
void removeSpaces(char* text) {
// Remove spaces
int l = strlen(text);
int j = 0;
for (int i = 0;i<l;i++) {
if (text[i] != ' ') {
text[j++] = text[i];
}
}
text[j] = '\0';
}
removeSpaces(plaintext);
printf("\n");
}
char buffer[1024] = { 0 };
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
char key[25];
char plaintext[MAX_BUFFER_SIZE];
char ciphertext[100];
createMatrix(key);
int j = 0;
for (int i=0;i<MAX_BUFFER_SIZE;i++) {
if (plaintext[i] == ' ' && plaintext[i++] == ' ') {
break;
}
j++;
}
char text[j];
for (int i=0;i<j;i++) {
text[i] = plaintext[i];
}
printf("Encrypting...\n");
playfairEncrypt(plaintext);
printf("The Play Fair Cipher Text has been successfully sent to the server\n");
Client side:
Client Side:
a. Create a socket using socket().
b. Define the server address and port.
c. Connect to the server using connect().
d. Input the plain text and key from the user.
e. Remove spaces from the plain text.
f. Encrypt the plain text using the Row Transposition Cipher algorithm.
g. Send the size of the cipher text and the cipher text to the server using send().
h. Print a success message.
i. Close the connected socket.
CODE:
Server code:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <ctype.h>
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
char cipherText[size];
if (recv(new_socket, &cipherText, sizeof(cipherText), 0) < 0) {
perror("Failed to receive plain text\n");
exit(EXIT_FAILURE);
}
return 0;
}
Client code:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
return index;
}
char* RowTranspositionCipher(int key, char text[], int size) {
int c = 0;
int n = key;
while (n != 0){
n /= 10;
c++;
}
int numberArray[c];
n = key;
int i = c;
/* extract each digit */
while (n != 0) {
i--;
numberArray[i] = n % 10;
n /= 10;
}
int r = size % c;
char textMatrix[r][c];
int k = 0, z;
if (size != r*c) {
z = (r * c) - size;
}
return cipherText;
char buffer[1024] = { 0 };
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
int size = 0, b = 0;
for (int i=0;i<SIZE;i++) {
if (plaintext[i] == '\0') {
break;
}
if (plaintext[i] == ' ') {
b++;
}
size++;
}
printf("Encrypting...\n");
char cipher[SIZE];
for (int i=0;i<SIZE;i++){
cipher[i] = cipherText[i];
}
//Sending cipher text and size of cipher text to server side
if (send(client_fd, &SIZE, sizeof(SIZE), 0) < 0) {
perror("Failed to send size\n");
exit(EXIT_FAILURE);
}
if (send(client_fd, &cipher, sizeof(cipher), 0) < 0) {
perror("Failed to send cipher text\n");
exit(EXIT_FAILURE);
}
printf("\nThe Row Transposition Cipher Text has been successfully sent to the server\n");
OUTPUT:
Server Side:
Client side:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 2: Cryptography & Network Security 08-01-2024
TASK:
CODE:
#include <stdio.h>
// Euclidean Algorithm
int euclidean_GCD(int a, int b)
{
if (a == 0)
return b;
return euclidean_GCD(b % a, a);
}
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("The GCD of %d and %d is: %d\n", a, b, euclidean_GCD(a, b));
return 0;
}
OUTPUT:
*x = y1 - (b / a) * x1;
*y = x1;
return gcd;
}
int main() {
int a, b, x, y;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
return 0;
}
OUTPUT:
3) Demonstrate Euler’s Theorem.
AIM: To elucidate Euler's Theorem by demonstrating its application in modular arithmetic,
emphasizing the relationship between modular exponentiation and the totient function.
ALGORITHM:
1. Input: Obtain values for a and n from the user.
2. Compute GCD: Calculate the greatest common divisor (gcd) of a and n.
3. Check Coprimality: If gcd(a, n) is not 1, print an error message and exit.
4. Calculate Totient (ϕ): Determine Euler's totient function (ϕ(n)) by counting coprime integers
less than n.
5. Compute Modular Exponentiation: Utilize modular exponentiation to find a^ϕ(n) mod n.
6. Output: Print the result of a^ϕ(n) mod n.
7. Main Algorithm: Execute the above steps in order, checking coprimality, calculating ϕ(n),
performing modular exponentiation, and printing the result.
CODE:
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int phi(int n) {
int result = 1;
for (int i = 2; i < n; ++i) {
if (gcd(i, n) == 1) {
++result;
}
}
return result;
}
int power(int x, unsigned int y, int m) {
int result = 1;
x = x % m;
while (y > 0) {
if (y & 1) {
result = (result * x) % m;
}
y = y >> 1;
x = (x * x) % m;
}
return result;
}
int main() {
int a, n;
eulerTheorem(a, n);
return 0;
}
OUTPUT:
ALGORITHM:
1. Find integers k, q, k > 0, q odd, so that (n–1)=(2^k).q
2. Select a random integer a, 1<a<n–1
3. if a^q mod n = 1 then return (“inconclusive");
4. for j = 0 to k – 1 do
5. if ((a^((2^j).q)) mod n = n-1), then return(“inconclusive")
6. return (“composite")
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
long long modular_pow(long long base, long long exponent, long long modulus) {
long long result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exponent /= 2;
}
return result;
}
long long k = 0;
long long q = n - 1;
while (q % 2 == 0) {
k++;
q /= 2;
}
int inconclusive = 0;
for (long long j = 0; j < k - 1; j++) {
x = modular_pow(x, 2, n);
if (x == n - 1) {
inconclusive = 1;
break;
}
}
if (!inconclusive) {
return 0;
}
}
return 1;
}
int main() {
long long num;
int iterations;
return 0;
}
OUTPUT:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 3: Implementation of DES 22-01-2024
TASK:
3. Key Initialization:
a. Replace the keyString with your own 64-bit key (8 bytes).
b. Convert the keyString to bytes using UTF-8 encoding.
4. Initialize Input and Output Streams:
a. Create DataInputStream and DataOutputStream to communicate with the client.
6. Decrypt Ciphertext:
a. Call the decrypt method with the received ciphertext and key to obtain decrypted bytes.
8. Close Connection:
a. Close the client socket and the server socket.
2. Key Initialization:
a. Replace the keyString with your own 64-bit key (8 bytes).
b. Convert the keyString to bytes using UTF-8 encoding.
5. Encrypt Plaintext:
a. Convert the plaintext to bytes using UTF-8 encoding.
b. Call the encrypt method with the plaintext bytes and key to obtain encrypted bytes.
6. Display Ciphertext:
a. Print the Base64-encoded ciphertext before sending it to the server.
8. Close Connection:
a. Close the socket.
CODE:
Server Code:
// server code
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
System.out.println("Ciphertext: " +
Base64.getEncoder().encodeToString(encryptedBytes));
outputStream.writeUTF(Base64.getEncoder().encodeToString(encryptedBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
OUTPUT:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 4: Implementation of AES 29-01-2024
TASK:
Client Algorithm:
• Initialize Socket:
• Create a socket to connect to the server at the specified address and port (e.g.,
localhost:12345).
• nitialize Input and Output Streams:
• Create DataInputStream and DataOutputStream to communicate with the server.
• Generate AES Key:
• Call the generateAESKey method to generate a fixed AES key (for demonstration
purposes).
• Display Key for Encryption:
• Print the Base64-encoded AES key used for encryption.
• Encrypt Plaintext:
• Use the encryptAES method to encrypt the plaintext using the generated AES key.
• Print the Base64-encoded ciphertext.
• Send Key and Ciphertext to Server:
• Send the Base64-encoded AES key to the server using outputStream.writeUTF().
• Send the Base64-encoded ciphertext to the server using outputStream.writeUTF().
• Close Connection:
• Close the socket.
CODE:
Server Code:
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
try {
String receivedKeyBase64 = inputStream.readUTF();
byte[] receivedKeyBytes = Base64.getDecoder().decode(receivedKeyBase64);
SecretKey secretKey = new SecretKeySpec(receivedKeyBytes, "AES");
} catch (Exception e) {
e.printStackTrace();
}
}
Client Code:
//client
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Scanner;
outputStream.writeUTF(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
outputStream.writeUTF(Base64.getEncoder().encodeToString(encryptedBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
Client Side:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 5: Implementation of RSA Cryptosystem 05-02-2024
TASK:
1) Develop a cipher scheme using the RSA algorithm.
AIM: To illustrate the process of creating a secure communication channel through the
development of a cipher scheme using the RSA algorithm.
ALGORITHM:
Server Algorithm:
• Create a server socket using socket().
• Bind the server socket to a specific port using bind().
• Listen for incoming connections using listen().
• Accept the connection from the client using accept().
• Generate two random prime numbers (prime1 and prime2) using the prime filler function
(primefiller()).
• Calculate n as the product of prime1 and prime2.
• Calculate Euler's totient function (fi) as (prime1 - 1) * (prime2 - 1).
• Choose a public key (e) such that it is coprime with fi.
• Calculate a corresponding private key (d) using the extended Euclidean algorithm.
• Send the public key (e) to the client.
• Receive the encrypted message from the client.
• Decrypt the message using the private key (d) and n.
• Display the decrypted message.
• Close the client socket and the server socket.
Client Algorithm:
• Create a client socket using socket().
• Connect to the server using the server's IP address and port using connect().
• Input the message to be sent from the user.
• Encode the message into a vector of integers using the encoder() function.
• Send the encoded message to the server.
• Close the client socket.
CODE:
Server Code:
//Server code:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <bits/stdc++.h>
set<int> prime;
int public_key;
int private_key;
int n;
void primefiller() {
vector<bool> sieve(250, true);
sieve[0] = false;
sieve[1] = false;
void setkeys() {
int prime1 = pickrandomprime();
int prime2 = pickrandomprime();
n = prime1 * prime2;
int fi = (prime1 - 1) * (prime2 - 1);
int e = 2;
while (1) {
if (__gcd(e, fi) == 1)
break;
e++;
}
public_key = e;
int d = 2;
while (1) {
if ((d * e) % fi == 1)
break;
d++;
}
private_key = d;
}
while (e--) {
encrypted_text *= message;
encrypted_text %= n;
}
return encrypted_text;
}
long long int decrypt(int encrypted_text) {
int d = private_key;
long long int decrypted = 1;
while (d--) {
decrypted *= encrypted_text;
decrypted %= n;
}
return decrypted;
}
return form;
}
return s;
}
int main() {
primefiller();
setkeys();
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "Error creating socket" << endl;
exit(EXIT_FAILURE);
}
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8080);
server_address.sin_addr.s_addr = INADDR_ANY;
if (listen(server_socket, 3) < 0) {
cerr << "Listening failed" << endl;
exit(EXIT_FAILURE);
}
int client_socket;
struct sockaddr_in client_address;
socklen_t client_addr_size = sizeof(client_address);
if (client_socket < 0) {
cerr << "Acceptance failed" << endl;
exit(EXIT_FAILURE);
}
string message(buffer);
istringstream iss(message);
vector<int> encoded_text;
int num;
close(server_socket);
return 0;
}
Client Code:
// Client side:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <bits/stdc++.h>
set<int> prime;
int public_key;
int private_key;
int n;
void primefiller() {
vector<bool> sieve(250, true);
sieve[0] = false;
sieve[1] = false;
int pickrandomprime() {
int k = rand() % prime.size();
auto it = prime.begin();
while (k--)
it++;
int ret = *it;
prime.erase(it);
return ret;
}
void setkeys() {
int prime1 = pickrandomprime();
int prime2 = pickrandomprime();
n = prime1 * prime2;
int fi = (prime1 - 1) * (prime2 - 1);
int e = 2;
while (1) {
if (__gcd(e, fi) == 1)
break;
e++;
}
public_key = e;
int d = 2;
while (1) {
if ((d * e) % fi == 1)
break;
d++;
}
private_key = d;
}
while (e--) {
encrypted_text *= message;
encrypted_text %= n;
}
return encrypted_text;
}
while (d--) {
decrypted *= encrypted_text;
decrypted %= n;
}
return decrypted;
}
return form;
}
return s;
}
int main() {
primefiller();
setkeys();
int server_socket;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "Error creating socket" << endl;
exit(EXIT_FAILURE);
}
int client_socket;
struct sockaddr_in client_address;
socklen_t client_addr_size = sizeof(client_address);
if (client_socket < 0) {
cerr << "Acceptance failed" << endl;
exit(EXIT_FAILURE);
}
string message(buffer);
istringstream iss(message);
vector<int> encoded_text;
int num;
close(server_socket);
return 0;
}
OUTPUT:
Server Side:
Client side:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
CODE:
Server Code:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
public Elgamal_Server() {
SecureRandom random = new SecureRandom();
prime = BigInteger.probablePrime(512, random);
base = new BigInteger("3");
privateKey = new BigInteger(512, random);
publicKey = base.modPow(privateKey, prime);
}
socket.close();
serverSocket.close();
}
}
Client Code:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.util.Random;
import java.util.Scanner;
socket.close();
}
}
OUTPUT:
Server Side:
Client side:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 7: Implementation of Elliptic Curve Cryptosystem 26-02-2024
TASK:
1) Develop a cipher scheme using the Elliptic Curve Cryptosystem algorithm
AIM: To enhance data security by designing a cipher scheme utilizing the Elliptic Curve
Cryptosystem algorithm.
ALGORITHM:
Server Algorithm:
1. Create a server socket using `ServerSocket`.
2. Bind the server socket to a specific port.
3. Listen for incoming connections.
4. Accept the connection from the client.
5. Receive the encrypted points `C1` and `C2` and the private key `privateKey` from the client.
6. Perform decryption:
a. Calculate `decryptedPoint` as `C2` + `C1` * (-`privateKey`).
7. Display the decrypted point `decryptedPoint`.
8. Close the client socket and the server socket.
Client Algorithm:
1. Create a socket to connect to the server using `Socket`.
2. Connect to the server using the server's IP address and port.
3. Input the parameters: prime modulus (`p`), parameters `a`, `b`, coordinates of base point `G`,
private key (`nB`), coordinates of the point to be encrypted (`Pm`), and a random integer (`k`).
4. Calculate the public key `PB` as `G` * `nB`.
5. Encrypt the point `Pm` using Elliptic Curve Cryptography:
a. Calculate `kG` as `G` * `k`.
b. Calculate `kPB` as `PB` * `k`.
c. Calculate `C1` as `kG`.
d. Calculate `C2` as `Pm` + `kPB`.
6. Send the encrypted points `C1` and `C2`, and the private key `nB` to the server.
7. Close the socket connection.
CODE:
Server Code:
import java.io.*;
import java.net.*;
// Perform decryption
ECC_Client.Point decryptedPoint = C2.add1(C1.multiply1(-privateKey));
out.writeObject(encryptedPoints[0]);
out.writeObject(encryptedPoints[1]);
out.writeInt(privateKey);
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static Point[] encrypt(Point P, Point PB, Point G, int k) {
// Calculate kG
Point kG = G.multiply1(k);
// Calculate kPB
Point kPB = PB.multiply1(k);
// Calculate C1 = kG
Point C1 = kG;
// Calculate C2 = P + kPB
Point C2 = P.add1(kPB);
// Point addition
public Point add1(Point other) {
if (other == null) return this;
int lambda;
int xr, yr;
if (this.equals(other)) {
int numerator = (3 * x * x + a) % p;
int denominator = (2 * y) % p;
int inverseDenominator = modInverse(denominator, p);
lambda = (numerator * inverseDenominator) % p;
} else {
int l = (other.x - x + p);
int inverseL = modInverse(l, p);
int l1 = modInverse(-l, p);
if (l < 0) {
lambda = (((other.y - y) * -1) % p * l1) % p;
} else {
lambda = ((other.y - y) % p * inverseL) % p;
}
}
lambda = (lambda + p) % p;
System.out.println("Lambda: " + lambda);
xr = ((lambda * lambda) % p - x - other.x + 2 * p) % p;
if (xr < 0) {
xr += p;
}
yr = ((lambda * (x - xr)) % p - y + p) % p;
if (yr < 0) {
yr += p;
}
return new Point(xr, yr, a, p);
}
// Point multiplication
public Point multiply1(int n) {
Point result = null;
for (int i = 0; i < n; i++) {
result = result != null ? result.add1(result) : this;
}
return result;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
}
OUTPUT:
Server Side:
Client side:
BCSE309P – Cryptography and Network Security Laboratory
Name: Mohamed Rasheed Ahamed
Register No: 21BCE5570
Course Code: BCSE309P
Ex. No. 8: Implementation of Diffie-Hellman Key Exchange Protocol 4-03-2024
TASK:
1) Design a Diffie Hellman multiparty key exchange protocol and perform a
Man-in-the-Middle Attack.
AIM: To Develop a multiparty key exchange protocol using Diffie-Hellman, ensuring secure
communication. This includes generating public/private keys for encryption. Additionally,
simulate a Man-in-the-Middle Attack to showcase vulnerabilities in the protocol's security.
ALGORITHM:
Server Algorithm:
1. Create a server socket using `ServerSocket`.
2. Bind the server socket to a specific port.
3. Listen for incoming connections.
4. Accept the connection from the client.
5. Generate a large prime number (`prime`), a base (`generator`), a private key
(`server_private_key`), and a public key (`server_public_key`) using the Diffie-Hellman key
exchange algorithm.
6. Send the `prime`, `generator`, and `server_public_key` to the client using `ObjectOutputStream`.
7. Receive the encrypted message (`encryptedMessage`) from the client using `ObjectInputStream`.
8. Calculate the shared secret key (`shared_secret_key`) using the received public key from the
client and the server's private key.
9. Decrypt the `encryptedMessage` using the shared secret key.
10. Display the decrypted message.
11. Close the client socket and the server socket.
Client Algorithm:
1. Create a socket to connect to the server using `Socket`.
2. Connect to the server using the server's IP address and port.
3. Input the message to be encrypted from the user.
4. Receive the prime number (`prime`), base (`generator`), and public key (`server_public_key`)
from the server.
5. Generate a private key (`client_private_key`).
6. Calculate the shared secret key (`shared_secret_key`) using the received public key from the
server and the client's private key.
7. Encrypt the message using the shared secret key.
8. Send the encrypted message (`encryptedMessage`) to the server using `ObjectOutputStream`.
9. Close the socket connection.
CODE:
Server Code:
import java.io.*;
import java.net.*;
import java.math.BigInteger;
serverSocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Client Code:
import java.io.*;
import java.net.*;
import java.math.BigInteger;
import java.util.Scanner;
scanner.close();
socket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
Client side: