This article mainly introduces the principle of the Diffie-Hellman algorithm and the PHP implementation version. For more information, see Diffie-Hellman) it is an algorithm that allows both parties to establish a key on an insecure public channel. later, both parties can use this key to encrypt (such as RC4) content.
The principle of the Diffie-Hellman algorithm is simple:
The above principle makes it easy to prove (g ^ B % p) ^ a % p = (g ^ a % p) ^ B % p, therefore, they get the same key.
Except for a, B and the final public key, the above are private keys, and others can be transmitted on the public channel. In actual use, p is very large (more than 300 bits), and g is usually 2 or 5. It is almost impossible to calculate a from p, g, and g ^ a % p (discrete mathematical problem ).
This algorithm is implemented in many languages. the following uses Crypt_DiffieHellman in the PHP package as an example:
<?phpinclude '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