Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Diffie-Hellman-Key-Exchange/example.py
1402 views
1
#!/usr/bin/env python2.7
2
3
from Crypto.Util.number import bytes_to_long, inverse, long_to_bytes
4
from Crypto.Random.random import randint
5
6
class PublicKey:
7
def __init__(self, h, p, g, q):
8
self.h = h
9
self.p = p
10
self.g = g
11
self.q = q
12
13
class PrivateKey:
14
def __init__(self, x, p, g, q):
15
self.x = x
16
self.p = p
17
self.g = g
18
self.q = q
19
20
def _generate_key():
21
"""
22
Generate private-public key pair.
23
For security reasons, either p should be a safe prime or g should have a
24
prime subgroup order. Otherwise it is vulnerable to Short Subgroup Attack.
25
26
:Parameters: _None_
27
28
:Variables:
29
g : int/long
30
Base point for modular exponentiation.
31
p : int/long
32
Modulus for modular exponentiation. Should be a safe prime.
33
x : int/long
34
Receiver's private key, should be kept secret.
35
h : int/long
36
Receiver's public key
37
q : int/long
38
Order of group generated by p and equals p-1
39
40
:Return: A tuple containing a Public Key object (class `PublicKey`) and
41
a Private Key object (class `PrivateKey`)
42
"""
43
# Assigning the largest 1024-bit safe prime as p
44
p = (1 << 1024) - 1093337
45
x = randint(2, p-2)
46
g = 7
47
q = p - 1
48
h = pow(g, x, p)
49
pubkey = PublicKey(h, p, g, q)
50
privkey = PrivateKey(x, p, g, q)
51
return (pubkey, privkey)
52
53
54
def _derive_key(pubkey, x):
55
"""
56
Derive shared secret from the public key of the sender and private key of the
57
user.
58
59
:parameters:
60
pubkey : object of class `PublicKey`
61
x : secret key of the user
62
63
Returns the derived shared key
64
"""
65
p = pubkey.p
66
g = pubkey.g
67
h = pubkey.h
68
q = pubkey.q
69
# h = g^x_alice % p
70
# _key = h^x_bob % p = g^(x_alice*x_bob) % p
71
_key = pow(h, x, p)
72
return _key
73
74
if __name__ == "__main__":
75
try:
76
for i in range(100):
77
pubkey, privkey = _generate_key()
78
p = pubkey.p
79
g = pubkey.g
80
x = privkey.x
81
y = randint(2, p-2)
82
assert pow(g, x*y, p) == _derive_key(pubkey, y)
83
except:
84
print "[-] Something's wrong in your code! Check the implementation"
85
86