This article mainly introduces the principle of the Diffie-Hellman algorithm and the PHP implementation version. For more information, see
This article mainly introduces the principle of the Diffie-Hellman algorithm and the PHP implementation version. For more information, see
Diffie-Hellman is an algorithm that allows both parties to establish a key on an insecure public channel. Both parties can use this key to encrypt it later (such as RC4) content.
The principle of the Diffie-Hellman algorithm is simple:
Based on the above principle, it is easy to prove through mathematical principles (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