This paper reference source https://segmentfault.com/a/1190000010917737 and https://zh.wikipedia.org/wiki/%E6%A8%A1%E9%99%A4 and https://www.cnblogs.com /DarkValkyrie/p/10962231.html (basic formula of this article chiefs of great help)
- Modulo operation with the four basic arithmetic somewhat similar, but the division exceptions. Its rules are as follows:
- (a + b) % p = (a % p + b % p) % p (1)
- (a - b) % p = (a % p - b % p) % p (2)
- (a * b) % p = (a % p * b % p) % p (3)
- a ^ b % p = ((a % p)^b) % p (4)
- Associative law:
- ((a+b) % p + c) % p = (a + (b+c) % p) % p (5)
- ((a*b) % p * c)% p = (a * (b*c) % p) % p (6)
- Commutative:
- (a + b) % p = (b+a) % p (7)
- (a * b) % p = (b * a) % p (8)
- Distributive law:
- (a+b) % p = ( a % p + b % p ) % p (9)
- ((a +b)% p * c) % p = ((a * c) % p + (b * c) % p) % p (10)
-
Client: a natural number selected Xa, Ya = a ^ Xa mod p, Ya and transmits to the server;
-
Server: selecting a natural number Xb, Yb = a ^ Xb mod p, and sends to the client Yb;
-
Client: calculated Ka = Yb ^ Xa mod p
- Server: computing Kb = Ya ^ Xb mod p
The derivation process
Ka = Yb ^ Send mod p
= (a^Xb mod p)^Xa mod p
==> (A ^ Xb MOD P) ^ Xa MOD P of the equation can be split into four (a ^ Xb) ^ Xa mod p
= a^(Xb * Xa) mod p
= (a^Xa mod p)^Xb mod p
= Ya ^ Xb mod p
Code Example Nodejs
As mentioned previously in conjunction with the following summary of the code view, which is one of the points client, server use the same prime number a, p.
the require Crypto = var ( 'Crypto'); var primeLength = 1024; // length prime p var generator = 5; // A prime // create client DH instance var = crypto.createDiffieHellman Client (primeLength, Generator); / / generated public key pair, MOD Xa Ya = a ^ PVAr clientKey client.generateKeys = (); // Create instance DH server, using the client with the same prime number a, P var = crypto.createDiffieHellman Server (client. getPrime (), client.getGenerator ()); // generate public-private key pair, Xb Yb = A ^ P MOD var server.generateKeys ServerKey = (); // calculate ^ Xa Yb = MOD Ka of P var = Client clientSecret .computeSecret (server.getPublicKey ()); // calculate Ya ^ Xb = MOD Kb P var serverSecret = server.computeSecret (client.getPublicKey ()); // Since the prime number p is generated dynamically, so that each print is not same // but clientSecret === serverSecret console.log(clientSecret.toString('hex')); console.log(serverSecret.toString('hex'));