现在,让我们用Python实现ECDH算法(Elliptic Curve Diffie–Hellman Key Exchange)。
我们将使用Python中用于ECC的tinyec库:
pip install tinyec
现在,让我们生成两个公钥-私钥对,交换公钥并计算共享密钥:
from tinyec import registry
import secrets
def compress(pubKey):
return hex(pubKey.x) + hex(pubKey.y % 2)[2:]
curve = registry.get_curve('brainpoolP256r1')
alicePrivKey = secrets.randbelow(curve.field.n)
alicePubKey = alicePrivKey * curve.g
print("Alice public key:", compress(alicePubKey))
bobPrivKey = secrets.randbelow(curve.field.n)
bobPubKey = bobPrivKey * curve.g
print("Bob public key:", compress(bobPubKey))
print("Now exchange the public keys (e.g. through Internet)")
aliceSharedKey = alicePrivKey * bobPubKey
print("Alice shared key:", compress(aliceSharedKey))
bobSharedKey = bobPrivKey * alicePubKey
print("Bob shared key:", compress(bobSharedKey))
print("Equal shared keys:", aliceSharedKey == bobSharedKey)
运行上面的代码示例: ECDH Key Exchange in Python - Python Repl - Replit
用于ECDH计算的椭圆曲线为256位,命名为curve brainpoolP256r1。私钥为256位(64位十六进制数字),随机生成。由于密钥压缩,公钥将为257位(65个十六进制数字)。
上述代码的输出如下所示:
Alice public key: 0x66c808e6b5be6d6620934bc6ffa2b8b47f9786c002bfb06d53a0c27535641a5d1
Bob public key: 0x7d15195432d1ac7f38aeb054d07d9b2e1faa913b78ad04d5efdd4a1ee8d9a3191
Now exchange the public keys (e.g. through Internet)
Alice shared key: 0x90f5a1cf2ed1dbb0322178df6bb0dd72c541884618b2989a3e5e663198667a621
Bob shared key: 0x90f5a1cf2ed1dbb0322178df6bb0dd72c541884618b2989a3e5e663198667a621
Equal shared keys: True
由于随机性,如果运行上述代码,密钥将不同,但最后计算的Alice和Bob的共享密钥将始终相同。生成的共享密钥是257位整数(256位曲线的压缩EC点,编码为65个十六进制数字)。