Skip to content

Commit bb987c4

Browse files
committed
Refactor doctest; change initializer arguments
group: int -> prime: int, generator: int
1 parent a65b346 commit bb987c4

File tree

1 file changed

+26
-20
lines changed

1 file changed

+26
-20
lines changed

ciphers/diffie_hellman.py

+26-20
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1-
import random
1+
"""
2+
https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
3+
"""
24

3-
# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
4-
# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
5+
import random
56

6-
PRIMES = {
7+
"""
8+
RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for
9+
Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526
10+
"""
11+
GROUPS = {
712
# 1536-bit
813
5: {
914
"prime": int(
@@ -179,28 +184,29 @@
179184

180185
class DiffieHellman:
181186
"""
182-
Class to represent the Diffie-Hellman key exchange protocol
187+
Class to represent one party in the Diffie-Hellman key exchange protocol
183188
189+
Current minimum recommendation is 2048 bit
190+
>>> group = GROUPS[14]
191+
>>> prime, generator = group['prime'], group['generator']
192+
>>> alice = DiffieHellman(prime, generator)
184193
185-
>>> alice = DiffieHellman()
186-
>>> bob = DiffieHellman()
194+
Both parties should agree on the same public parameters
195+
>>> bob = DiffieHellman(alice.prime, alice.generator)
187196
188-
>>> alice_public = alice.public_key
189-
>>> bob_public = bob.public_key
197+
Alice sends Bob its public key,
198+
>>> bob_shared = bob.generate_shared_key(alice.public_key)
190199
191-
Generating shared key using the DH object
192-
>>> alice_shared = alice.generate_shared_key(bob_public)
193-
>>> bob_shared = bob.generate_shared_key(alice_public)
194-
>>> assert alice_shared == bob_shared
195-
"""
200+
and the same vice versa:
201+
>>> alice_shared = alice.generate_shared_key(bob.public_key)
196202
197-
# Current minimum recommendation is 2048 bit (group 14)
198-
def __init__(self, group: int = 14) -> None:
199-
if group not in PRIMES:
200-
raise ValueError("Unsupported Group")
201-
self.prime = PRIMES[group]["prime"]
202-
self.generator = PRIMES[group]["generator"]
203+
>>> alice_shared == bob_shared
204+
True
205+
"""
203206

207+
def __init__(self, prime: int, generator: int) -> None:
208+
self.prime = prime
209+
self.generator = generator
204210
self.__private_key = random.getrandbits(256)
205211

206212
@property

0 commit comments

Comments
 (0)