Skip to content

Instantly share code, notes, and snippets.

@morkev
Last active May 1, 2025 19:36
Show Gist options
  • Select an option

  • Save morkev/94933baa705c66ed28d94a2c76fe2d8b to your computer and use it in GitHub Desktop.

Select an option

Save morkev/94933baa705c66ed28d94a2c76fe2d8b to your computer and use it in GitHub Desktop.
Diffie-Hellman Key Exchange
from random import randint
# No documentation, and this does not document itself.
# Funck you, I guess :/
p_hex = """
FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED
EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D
C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F
83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D
670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B
E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9
DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510
15728E5A 8AACAA68 FFFFFFFF FFFFFFFF
""".replace(" ", "").replace("\n", "")
p = int(p_hex, 16)
g = 2
A_hex = """
48f4f0d3b6b4160ef4b17b719b4a03c1ae99793093c9ca3c1f2eb49625020167
3ca827a67944b6fc10897df1e9ef49a5b351d697b9420f21adbb425eff8506fc
eb5f5f711154bde0693104aaf0978b5ad067ebe68a9bbd9a6017d7c1914e0f01
ca22ae5eaf618183aa4a7b806300779d965e2c0c1b72d40f89341b54305de3b7
ec41065cdb4c7c89ad62cc34330c26ed43b37fec1ba0b1e5984ee99380e73544
c50537fdc43170f4ffdc034fab0b2f11341e43f81a03a9e76108f8adca73da19
2162a3ae9d369adb710b6c1fce74b89e8319443f870c7ba8a541d4e72bd5a765
d2377532c37c48c4ae4fdf7951acc09e77a3e33ade3f1664930df0887643193d
""".replace(" ", "").replace("\n", "")
A = int(A_hex, 16)
b = randint(2**1024 + 1, p - 1)
B = pow(g, b, p)
if B <= 2**1024:
print("B is too small, regenerating b...")
while True:
b = randint(2**1024 + 1, p - 1)
B = pow(g, b, p)
if B > 2**1024:
break
s = pow(A, b, p)
print("Private key b:", b)
print("Public key B:", hex(B))
print("Shared secret s:", hex(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment