Home >Backend Development >PHP Tutorial >Diffie–Hellman key exchange (Diffie–Hellman) algorithm principle and PHP implementation version_PHP tutorial
This article mainly introduces the Diffie-Hellman key exchange (Diffie–Hellman) algorithm principle and PHP implementation version, friends in need can refer to it
Diffie-Hellman is an algorithm that allows both parties to establish a secret key on an insecure public channel. Both parties can later use this secret key to encrypt content (such as RC4).
The principle of Diffie–Hellman algorithm is very simple:
Based on the above principle, it is easy to prove through mathematical principles that (g^b%p)^a%p = (g^a%p)^b%p, so they get the same key.
Except for a, b and the final public key, which are secret, the others can be transmitted on the public channel. In practical applications, p is very large (more than 300 bits), and g usually takes 2 or 5. Then it is almost impossible to calculate a from p, g and g^a%p (discrete math problem).
Many languages have implemented this algorithm. Take Crypt_DiffieHellman in the PHP package as an example:
?
10 11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<🎜>include 'DiffieHellman.php';<🎜> <🎜> <🎜> <🎜>/*<🎜> <🎜>* Alice: prime = 563<🎜> <🎜>* generator = 5<🎜> <🎜>* private key = 9<🎜> <🎜>* Bob: prime = 563<🎜> <🎜>* generator = 5<🎜> <🎜>* private key = 14<🎜> <🎜>*/<🎜> <🎜> <🎜> <🎜>$p = 563;<🎜> <🎜>$g = 5;<🎜> <🎜>$alice = new Crypt_DiffieHellman($p, $g, 9);<🎜> <🎜>$alice_pubKey = $alice->generateKeys()->getPublicKey(); $bob = new Crypt_DiffieHellman($p, $g, 14); $bob_pubKey = $bob->generateKeys()->getPublicKey(); $alice_computeKey = $alice->computeSecretKey($bob_pubKey)->getSharedSecretKey(); $bob_computeKey = $bob->computeSecretKey($alice_pubKey)->getSharedSecretKey(); echo "{$alice_pubKey}-{$bob_pubKey}-{$alice_computeKey}-{$bob_computeKey}"; //78-534-117-117 |