Exp.
no: Implementation of Diffie - Hellman Key Exchange
Date:
Aim:
To implement Diffie-Hellman Key Exchange for secure key generation between two parties over
an insecure communication channel.
Algorithm:
Step 1: Two parties (Alice and Bob) publicly agree on two numbers:
A large prime number p.
A primitive root g modulo p (this is also known as the base or generator).
Step 2: Alice chooses a private key a (a random number less than p) and computes the public key
A = g^a mod p
Step 3: Bob chooses a private key b (a random number less than p) and computes the public key
B = g^b mod p.
Step 4: Exchange of Public Keys:
Alice sends her public key A to Bob.
Bob sends his public key B to Alice.
Step 5: Shared Secret Calculation:
Alice computes the shared secret using Bob's public key:
SA = B^a mod p.
Bob computes the shared secret using Alice's public key:
SB = A^b mod p.
Step 6: Since SA = SB = g^(a*b) mod p, both Alice and Bob now share the same secret key, which can be
used for further encryption.
Step 7: The shared secret can now be used as a symmetric key for encrypting further communication
between Alice and Bob using secure encryption algorithms (e.g., AES).
Program:
#include <stdio.h>
#include <math.h>
long long int modExp(long long int base, long long int exp, long long int mod) {
long long int result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1)
result = (result * base) % mod;
exp = exp >> 1;
base = (base * base) % mod; }
return result; }
int main() {
long long int p, g, a, b, A, B, shared_secret_A, shared_secret_B;
printf("Enter the prime number (p): ");
scanf("%lld", &p);
printf("Enter the primitive root modulo p (g): ");
scanf("%lld", &g);
printf("Alice, enter your private key (a): ");
scanf("%lld", &a);
A = modExp(g, a, p);
printf("Alice's public key (A): %lld\n", A);
printf("Bob, enter your private key (b): ");
scanf("%lld", &b);
B = modExp(g, b, p);
printf("Bob's public key (B): %lld\n", B);
shared_secret_A = modExp(B, a, p);
shared_secret_B = modExp(A, b, p);
printf("Shared secret computed by Alice: %lld\n", shared_secret_A);
printf("Shared secret computed by Bob: %lld\n", shared_secret_B);
if (shared_secret_A == shared_secret_B) {
printf("The shared secret is: %lld\n", shared_secret_A);
} else {
printf("Error: Shared secrets do not match!\n");
}
printf("220171601093\n");
return 0; }
Output :
sReview Questions :
Result:
Hence the program for Implementing Diffie-Hellman Key Exchange has been successfully
implemented and output is verified.