Diffie Hellman Key Exchange
From charlesreid1
<![CDATA[from Crypto.PublicKey import RSA, DSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto import Random
- --- RSA Key Generation ---
def rsa_generate_keys(key_size=2048):
key = RSA.generate(key_size) private_key = key.export_key() public_key = key.publickey().export_key() return private_key, public_key
- --- RSA Encryption / Decryption ---
def rsa_encrypt(plaintext, public_key_pem):
key = RSA.import_key(public_key_pem)
cipher = PKCS1_OAEP.new(key)
return cipher.encrypt(plaintext.encode('utf-8'))
def rsa_decrypt(ciphertext, private_key_pem):
key = RSA.import_key(private_key_pem)
cipher = PKCS1_OAEP.new(key)
return cipher.decrypt(ciphertext).decode('utf-8')
- --- RSA Signing / Verification ---
def rsa_sign(message, private_key_pem):
key = RSA.import_key(private_key_pem)
h = SHA256.new(message.encode('utf-8'))
signer = PKCS1_v1_5.new(key)
return signer.sign(h)
def rsa_verify(message, signature, public_key_pem):
key = RSA.import_key(public_key_pem)
h = SHA256.new(message.encode('utf-8'))
verifier = PKCS1_v1_5.new(key)
return verifier.verify(h, signature)
- --- Diffie-Hellman Key Exchange ---
def dh_generate_parameters(key_size=2048):
"""Generate DH group parameters (p, g).""" from Crypto.PublicKey import DSA # Use DSA to obtain safe DH parameters — p prime, g generator dsa_key = DSA.generate(key_size, randfunc=Random.new().read) params = dsa_key.p, dsa_key.g return params
def dh_generate_keypair(p, g):
"""Generate a DH 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 s = (their_public)^my_private mod p.""" return pow(their_public, my_private, p)
if __name__ == '__main__':
# --- RSA demo ---
print("=== RSA Key Generation ===")
priv, pub = rsa_generate_keys(2048)
print("Private key (first 120 chars): %s..." % priv[:120])
print("Public key (first 120 chars): %s..." % pub[:120])
message = "Hello from RSA"
ct = rsa_encrypt(message, pub)
print("\n=== RSA Encryption ===")
print("Ciphertext (hex): %s" % ct.hex()[:80])
pt = rsa_decrypt(ct, priv)
print("\n=== RSA Decryption ===")
print("Decrypted: '%s'" % pt)
sig = rsa_sign(message, priv)
print("\n=== RSA Signing ===")
print("Signature (hex): %s" % sig.hex()[:80])
ok = rsa_verify(message, sig, pub)
print("\n=== RSA Verification ===")
print("Signature valid: %s" % ok)
# --- Diffie-Hellman demo ---
print("\n=== Diffie-Hellman Key Exchange ===")
p, g = dh_generate_parameters(2048)
print("DH p (first 80 hex chars): %s..." % hex(p)[:80])
print("DH g (first 80 hex chars): %s..." % hex(g)[:80])
a_priv, a_pub = dh_generate_keypair(p, g)
b_priv, b_pub = dh_generate_keypair(p, g)
print("Alice public (first 80 hex): %s..." % hex(a_pub)[:80])
print("Bob public (first 80 hex): %s..." % hex(b_pub)[:80])
s_alice = dh_compute_shared(b_pub, a_priv, p)
s_bob = dh_compute_shared(a_pub, b_priv, p)
print("Alice shared secret matches Bob: %s" % (s_alice == s_bob))
print("Shared secret (first 80 hex): %s..." % hex(s_alice)[:80])
| 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
|
]]>