Diffie Hellman Key Exchange
From charlesreid1
from Crypto import Random from Crypto.Util import number
def dh_generate_parameters(key_size=2048):
"""Generate DH group parameters (p, g).""" p = number.getPrime(key_size) g = 2 return p, g
def dh_generate_keypair(p, g):
"""Generate private key a and public key A = g^a mod p.""" a = int.from_bytes(Random.new().read(p.bit_length() // 8 + 8), 'big') % (p - 1) A = pow(g, a, p) return a, A
def dh_compute_shared(their_public, my_private, p):
"""Compute shared secret = (their_public)^my_private mod p.""" return pow(their_public, my_private, p)
if __name__ == '__main__':
print("=== Diffie-Hellman Key Exchange ===")
# Step 1: Agree on public parameters
p, g = dh_generate_parameters(2048)
print("Prime p (first 80 hex): %s..." % hex(p)[:80])
print("Generator g: %s" % g)
# Step 2: Alice generates keypair
alice_priv, alice_pub = dh_generate_keypair(p, g)
print("Alice public key (first 80 hex): %s..." % hex(alice_pub)[:80])
# Step 3: Bob generates keypair
bob_priv, bob_pub = dh_generate_keypair(p, g)
print("Bob public key (first 80 hex): %s..." % hex(bob_pub)[:80])
# Step 4: Each computes the shared secret s_alice = dh_compute_shared(bob_pub, alice_priv, p) s_bob = dh_compute_shared(alice_pub, bob_priv, p)
print("Shared secrets match: %s" % (s_alice == s_bob))
print("Shared secret (first 80 hex): %s..." % hex(s_alice)[:80])
https://www.pycryptodome.org/src/protocol/dh
| Crypto cryptography-related resources on the wiki
Implementing AES Cipher in Python: AES
Category:Crypto · Category:Security · Category:Encryption
|
Red Links
- RSA
- GPG
- SHA
- Diffie-Hellman Key Exchange
- Password Hashing
- TLS
- One Time Pad
- HMAC
- Base64
- Elliptic Curve Cryptography
| Python a powerful programming language
Scientific Python: Data analysis libraries: Scipy · Numpy · Pandas · Statsmodel Machine learning libraries: Sklearn Neural network libraries: Tensorflow · Keras Plotting/viz: Matplotlib · Seaborn · Jupyter Solving partial differential equations and bessel functions: Fipy · Bessel Functions
Web and Networking Python: Web programming: Flask · Webapps · Mechanize · Scrapy · Gunicorn Wifi: Wireless/Python · Scapy IPython and Jupyter: Jupyter
Drawing, Geometry, and Shapes: Shapely (for drawing shapes): Shapely Geography library: Geos
General Useful Python Utilities: Python Remote Objects: Pyro Logging (create multi-channel log messages): Logging Keyboard (control keyboard from Python): Keyboard
Black Hat Python: Network scanning: Python/Scanner
|