Diffie-Hellman-Merkle
Alice and Bob agree two numbers:
Alice and Bob each choose a secret random integer:
Create two integers A and B that they send to each other.
- Alice sends A = ga mod p = {{ A }} to Bob.
- Bob sends B = gb mod p = {{ B }} to Alice.
Alice and Bob now compute the same shared secret, s.
- sa = Ba mod p = (gb mod p)a mod p = gba mod p = {{ sa }}
- sb = Ab mod p = (ga mod p)b mod p = gab mod p = {{ sb }}
- ∴ sa = sb = s
Alice and Bob now share the same secret s={{ sa }} and use this to encrypt and decrypt messages.
Diffie-Hellman key exchange
is a means to agree a secret number to encrypt and decrypt messages.
Number theory may seems very abstract but this is a very practical application.
It is used by TLS,
which is the protocol used to secure requests the URLs with the https:// prexix.
An intuitive way to understand this is that Alice chooses a secret color she mixes with red and Bob chooses a secret color he mixes with blue.
They send the mixes to each other. Alice adds her secret color to Bob's mix and Bob adds his to Alices, each ends up with the same colour.
Thus secrets colors remain secret if eavesdroppers are unable to separate mixes.
The random integers are kept secret, never sent over a network and the bigger the numbers the more secure but the slower the calculation.
Any eavesdropper would see the numbers A and B but not a and b.
To calculate these would require too much computing power to be practical.
Note that the secret number is always less than the chosen prime (s<p) because operations are mod p.
Since the Math.pow
function produces numbers far larger than can fit into the IEEE 754 double precision numbers provided by Javascript.
This algorithm needs arbitrary precision arithmetic,
gratefully provided bignumber.js for this implementation.
One can implement the algorithm in Python trivially since it has arbitrary precision arithmetic built into the language.
In practice one would use Modular exponentiation.
About
Arbitrary precision arithmetic
$ p=23;g=5;a=18;b=17;
$ A=g**a % p; B=g**b % p;
$ sa=B**a % p; sb=A**b %p)
$ sa,sb
(12, 12)