JAVA   34

DiffieHellmanExchange

Guest on 14th August 2022 06:43:20 AM

  1. import java.security.*;
  2. import java.math.*;
  3. import java.io.*;
  4.  
  5. class DiffieHellmanExchange {
  6.    int keysize;
  7.    DHKey key;
  8.    BigInteger x, x_pub, s_secret;
  9.  
  10.    // Get the numbers p,g from file (in "key" object)
  11.    // Generate a secure random number and create a public key from p,g
  12.    public DiffieHellmanExchange (String filename) throws Exception {  
  13.       keysize = 512;  
  14.       FileInputStream fis = new FileInputStream(filename);
  15.       ObjectInputStream oin = new ObjectInputStream(fis);
  16.       key = (DHKey)oin.readObject();
  17.       oin.close();
  18.       SecureRandom sr = new SecureRandom();  // Get a secure random number
  19.       x = new BigInteger(keysize, sr);  // Generate the secure secret key
  20.       x_pub = key.g.modPow(x, key.p);   // Compute the public key from p,g
  21.    }
  22.  
  23.    public BigInteger getPublicKey (String filename) { return x_pub; }
  24.  
  25.    // Send the client's public key to the server,
  26.    // Get the server's public key
  27.    // Compute the secret
  28.    public BigInteger computeSecret (BufferedReader in, PrintWriter out)
  29.       throws IOException {  
  30.       out.println(x_pub.toString());
  31.       BigInteger pkey = new BigInteger(in.readLine());
  32.       s_secret = pkey.modPow(x, key.p);
  33.       return s_secret;
  34.    }
  35. }

Raw Paste


Login or Register to edit or fork this paste. It's free.