ECDH Key Exchange - Examples
Now let's implement the ECDH algorithm (Elliptic Curve Diffie–Hellman Key Exchange) in Python.
We shall use the tinyec library for ECC in Python:
1
pip install tinyec
Copied!
Now, let's generate two public-private key pairs, exchange the public keys and calculate the shared secret:
1
from tinyec import registry
2
import secrets
3
4
def compress(pubKey):
5
return hex(pubKey.x) + hex(pubKey.y % 2)[2:]
6
7
curve = registry.get_curve('brainpoolP256r1')
8
9
alicePrivKey = secrets.randbelow(curve.field.n)
10
alicePubKey = alicePrivKey * curve.g
11
print("Alice public key:", compress(alicePubKey))
12
13
bobPrivKey = secrets.randbelow(curve.field.n)
14
bobPubKey = bobPrivKey * curve.g
15
print("Bob public key:", compress(bobPubKey))
16
17
print("Now exchange the public keys (e.g. through Internet)")
18
19
aliceSharedKey = alicePrivKey * bobPubKey
20
print("Alice shared key:", compress(aliceSharedKey))
21
22
bobSharedKey = bobPrivKey * alicePubKey
23
print("Bob shared key:", compress(bobSharedKey))
24
25
print("Equal shared keys:", aliceSharedKey == bobSharedKey)
Copied!
The elliptic curve used for the ECDH calculations is 256-bit named curve brainpoolP256r1. The private keys are 256-bit (64 hex digits) and are generated randomly. The public keys will be 257 bits (65 hex digits), due to key compression.
The output of the above code looks like this:
1
Alice public key: 0x66c808e6b5be6d6620934bc6ffa2b8b47f9786c002bfb06d53a0c27535641a5d1
2