Path: blob/master/Diffie-Hellman-Key-Exchange/example.py
1402 views
#!/usr/bin/env python2.712from Crypto.Util.number import bytes_to_long, inverse, long_to_bytes3from Crypto.Random.random import randint45class PublicKey:6def __init__(self, h, p, g, q):7self.h = h8self.p = p9self.g = g10self.q = q1112class PrivateKey:13def __init__(self, x, p, g, q):14self.x = x15self.p = p16self.g = g17self.q = q1819def _generate_key():20"""21Generate private-public key pair.22For security reasons, either p should be a safe prime or g should have a23prime subgroup order. Otherwise it is vulnerable to Short Subgroup Attack.2425:Parameters: _None_2627:Variables:28g : int/long29Base point for modular exponentiation.30p : int/long31Modulus for modular exponentiation. Should be a safe prime.32x : int/long33Receiver's private key, should be kept secret.34h : int/long35Receiver's public key36q : int/long37Order of group generated by p and equals p-13839:Return: A tuple containing a Public Key object (class `PublicKey`) and40a Private Key object (class `PrivateKey`)41"""42# Assigning the largest 1024-bit safe prime as p43p = (1 << 1024) - 109333744x = randint(2, p-2)45g = 746q = p - 147h = pow(g, x, p)48pubkey = PublicKey(h, p, g, q)49privkey = PrivateKey(x, p, g, q)50return (pubkey, privkey)515253def _derive_key(pubkey, x):54"""55Derive shared secret from the public key of the sender and private key of the56user.5758:parameters:59pubkey : object of class `PublicKey`60x : secret key of the user6162Returns the derived shared key63"""64p = pubkey.p65g = pubkey.g66h = pubkey.h67q = pubkey.q68# h = g^x_alice % p69# _key = h^x_bob % p = g^(x_alice*x_bob) % p70_key = pow(h, x, p)71return _key7273if __name__ == "__main__":74try:75for i in range(100):76pubkey, privkey = _generate_key()77p = pubkey.p78g = pubkey.g79x = privkey.x80y = randint(2, p-2)81assert pow(g, x*y, p) == _derive_key(pubkey, y)82except:83print "[-] Something's wrong in your code! Check the implementation"848586