Last active
September 24, 2023 16:58
-
-
Save savaged/ec90d1bfa50868421f60b23218f2f580 to your computer and use it in GitHub Desktop.
High-level Diffie-Hellman key exchange
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// public (primitive root) base¹, known to Alice, Bob, and Eve | |
const long G = 5; | |
// public (prime) modulus², known to Alice, Bob, and Eve | |
const long P = 23; | |
var aliceCalc = new Calc(6, G, P); | |
var bobCalc = new Calc(5, G, P); | |
// Alice's public key, known to Alice, Bob, and Eve. A = g^a mod p | |
long A = aliceCalc.GetPublicKey(bobCalc.OutgoingSharedKey); | |
// Bob's public key, known to Alice, Bob, and Eve. B = g^b mod p | |
long B = bobCalc.GetPublicKey(aliceCalc.OutgoingSharedKey); | |
System.Console.WriteLine($"Alice's secret key: {A}\nBob's secret key: {B}\nEve can only guess."); | |
class Calc | |
{ | |
private long _privateKey; | |
public Calc(long privateKey, long primeBase, long primeModulus) | |
{ | |
_privateKey = privateKey; | |
PrimeBase = primeBase; | |
PrimeModulus = primeModulus; | |
} | |
public long PrimeBase { get; } | |
public long PrimeModulus { get; } | |
public long OutgoingSharedKey => PrimeBase.PowMod(_privateKey, PrimeModulus); | |
public long GetPublicKey(long incomingSharedKey) => incomingSharedKey.PowMod(_privateKey, PrimeModulus); | |
} | |
static class LongEx | |
{ | |
public static long PowMod(this long self, long i, long m) => | |
i == 1 ? self : ((long)System.Math.Pow(self, i)) % m; | |
} | |
// Footnotes (see https://brilliant.org/wiki/diffie-hellman-protocol) | |
// 1. The base G should be chosen so that G has large order | |
// 2. The prime P should be chosen so that the largest prime factor of P-1 is large, | |
// in order to negate the Pohlig-Hellman algorithm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment