Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Lab 7

IMPLEMENTATION OF MAN IN MIDDLE ATTACK


Abhimanyu Mittal
21BCE1323
Code:
import java.util.Scanner;
import java.util.Random;
import java.math.BigInteger;

class Person {
private Random random = new Random();
private BigInteger p, g, n;

public Person(BigInteger p, BigInteger g) {


this.p = p;
this.g = g;
this.n = new
BigInteger(Integer.toString(random.nextInt(p.intValue() -
1) + 1));
}

public BigInteger publish() {


return g.modPow(n, p);
}

public BigInteger computeSecret(BigInteger


otherPublicKey) {
return otherPublicKey.modPow(n, p);
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a prime number (p): ");
BigInteger p = new BigInteger(scanner.nextLine());

System.out.print("Enter a base value (g): ");


BigInteger g = new BigInteger(scanner.nextLine());

Person alice = new Person(p, g);


Person bob = new Person(p, g);
Person eve = new Person(p, g);

System.out.println("Alice private number (a): " +


alice);
System.out.println("Bob private number (b): " +
bob);
System.out.println("Eve private number for Alice (c):
" + eve);
BigInteger ga = alice.publish();
BigInteger gb = bob.publish();
BigInteger gea = eve.publish();

System.out.println("Alice published (ga): " + ga);


System.out.println("Bob published (gb): " + gb);
System.out.println("Eve published for Alice (gc): " +
gea);

BigInteger sa = alice.computeSecret(gea);
BigInteger sb = bob.computeSecret(gea);

System.out.println("Alice computed secret key: " +


sa);
System.out.println("Bob computed secret key: " +
sb);

scanner.close();
}
}
Output:

You might also like