Skip to content

Instantly share code, notes, and snippets.

Last active August 23, 2022 10:33
Show Gist options
  • Save jiacheo/3dd14d4be509fb7f945b926cf237a921 to your computer and use it in GitHub Desktop.
Save jiacheo/3dd14d4be509fb7f945b926cf237a921 to your computer and use it in GitHub Desktop.
a DHKE simple implementation demo
package org.jiacheo.awesome.blockchain.encrypt.communication;
import java.math.BigInteger;
import java.util.concurrent.ThreadLocalRandom;
* a DHKE simple implementation demo.
* Created on 2022/8/23. <br/> contact: <a style="color:yellow;text-decoration:none;"
* href="" target="_blank">jiacheo[at]</a> <br/>
* @author jiacheo
public class SimpleDHKE {
public static void main(String[] args) {
//some common primes which a/b have known them.
BigInteger p = new BigInteger("ff327579dd3b51e57c979b88825093a91e1d382bb9a5811c79c66f99511ce039", 16);
BigInteger g = new BigInteger("b46460395370c5a13327cb7b75cd8ac27fb9b8c10fb64baae070262629928719", 16);
System.out.println("p=0x" + p.toString(16));
System.out.println("g=0x" + g.toString(16));
//just the random numbers held by Alice and Bob, and don't share them to anyone else (including each other).
//they dont need to be a prime.
BigInteger a = BigInteger.probablePrime(256, ThreadLocalRandom.current()).subtract(BigInteger.ONE);
BigInteger b = BigInteger.probablePrime(256, ThreadLocalRandom.current()).subtract(BigInteger.ONE);
//they calculate data1/data2 themselves in local machines.
BigInteger data1 = g.modPow(a, p);
BigInteger data2 = g.modPow(b, p);
//they exchange each other's calculated data and calculate the modPow
BigInteger sofa = data2.modPow(a, p);
BigInteger sofb = data1.modPow(b, p);
int compare = sofa.compareTo(sofb);
//sofa and sofb must be same
System.out.println("compareResult=" + compare);
System.out.println("secret=0x" + sofa.toString(16));
System.out.println("secret`=0x" + sofb.toString(16));
//now Alice and Bob can use sofa and sofb as the secret key to communicate to each other. :)
//alice.send(bob, encrypt(data, sofa));
//let data = bob.receiveFrom(bob).decrypt(sofb);
Copy link

jiacheo commented Aug 23, 2022

a sample output case:


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment