๐Ÿ”‘ PKI
HOME

๐Ÿง  Asymmetric Crypto Fundamentals

๐ŸŽฏ What is Public/Private Key Cryptography?

Public key cryptography (asymmetric cryptography) uses a pair of keys: a public key that can be shared with anyone, and a private key that must be kept secret. It enables encryption, digital signatures, and key exchange without sharing a secret key beforehand. Invented by Diffie and Hellman in 1976, it's the foundation of modern secure communication (TLS, SSH, blockchain, email).

Why Asymmetric Crypto Matters

No shared secret: Key exchange. Encryption: Confidentiality. Signatures: Authentication. Non-repudiation: Proof. TLS: Web security. Blockchain: Ownership.

๐Ÿ“Œ Public key๐Ÿ“Œ Private key๐Ÿ“Œ Encryption๐Ÿ“Œ Signatures
# Public/Private Key Cryptography โ€” the big picture # Asymmetric encryption and digital signatures. print(""" === Public/Private Key Cryptography === What it is: - Key pair - Public key: share - Private key: secret - Asymmetric Why it matters: - No shared secret - Encryption - Digital signatures - Non-repudiation - TLS/SSL - SSH - Blockchain - Email (PGP) Key concepts: - Key pair - Encryption - Decryption - Signing - Verification - Key exchange - Certificates - PKI Algorithms: - RSA - ECC - ECDSA - Ed25519 - Diffie-Hellman - ElGamal - DSA Applications: - TLS/SSL - SSH - PGP/GPG - Bitcoin - Ethereum - Code signing - Document signing - Email security """) print("=== Historical Context ===") print(""" 1976: Diffie-Hellman key exchange 1977: RSA (Rivest, Shamir, Adleman) 1985: Elliptic Curve Cryptography (Koblitz, Miller) 1991: PGP (Zimmermann) 1994: SSL 1.0 1999: TLS 1.0 2000: ECDSA 2011: Ed25519 2018: TLS 1.3 2020: Post-quantum crypto 2025: Post-quantum standards """) print("=== Why It's Hard ===") print(""" 1. MATHEMATICAL HARDNESS - Factoring (RSA) - Discrete log (DH, DSA) - Elliptic curve discrete log (ECC) 2. KEY MANAGEMENT - Key generation - Distribution - Revocation - Storage 3. QUANTUM - Shor's algorithm - Breaks RSA, ECC - Post-quantum needed 4. PERFORMANCE - Slower than symmetric - Key size - Hybrid 5. IMPLEMENTATION - Side channels - Randomness - Padding """)

๐ŸŽฏ Why Asymmetric Crypto Matters

๐ŸŽฏ The Value of Public Key Cryptography

Public key cryptography solved the key distribution problem and enabled secure communication over insecure channels, digital signatures, and modern PKI.

Key Benefits

Key exchange: No shared secret. Encryption: Confidentiality. Signatures: Authentication. Non-repudiation: Proof. Scalability: Public keys. Trust: PKI.

๐ŸŽฏ Key exchange๐ŸŽฏ Encryption๐ŸŽฏ Signatures๐ŸŽฏ Non-repudiation
# Why Asymmetric Crypto Matters print("=== 1. Key Exchange ===") print(""" Key exchange: - Two parties - Insecure channel - Shared secret Example: Alice + Bob โ†’ Diffie-Hellman โ†’ Shared secret """) print("\n=== 2. Encryption ===") print(""" Encryption: - Public key encrypt - Private key decrypt - Confidentiality Example: Alice โ†’ Bob's public key โ†’ Encrypt โ†’ Bob's private key โ†’ Decrypt """) print("\n=== 3. Digital Signatures ===") print(""" Signatures: - Private key sign - Public key verify - Authentication Example: Alice โ†’ sign โ†’ Bob verify โ†’ Authentic """) print("\n=== 4. Non-Repudiation ===") print(""" Non-repudiation: - Cannot deny - Signature - Legal Example: Contract โ†’ Signature โ†’ Non-repudiation """) print("\n=== 5. Scalability ===") print(""" Scalability: - Public keys - No shared secret - N keys Example: N parties โ†’ N key pairs โ†’ Not Nยฒ """) print("\n=== 6. Trust ===") print(""" Trust: - PKI - Certificates - CA Example: Website โ†’ Certificate โ†’ Trust """) print("\n=== 7. Web Security ===") print(""" Web: - HTTPS - TLS - Certificates Example: https:// โ†’ TLS โ†’ Secure """) print("\n=== 8. SSH ===") print(""" SSH: - Secure shell - Key pair - Authentication Example: ssh-keygen โ†’ Key pair โ†’ Login """) print("\n=== 9. Blockchain ===") print(""" Blockchain: - Key pair - Address - Signatures Example: Bitcoin โ†’ Private key โ†’ Sign """) print("\n=== 10. Email ===") print(""" Email: - PGP/GPG - Encryption - Signatures Example: PGP โ†’ Encrypt โ†’ Sign """)

๐Ÿ”‘ Key Pairs

๐ŸŽฏ Public and Private Keys

A key pair consists of a public key and a private key. The public key is shared openly, while the private key must be kept secret.

Key Pairs

Public: Share. Private: Secret. Mathematical: Related. Asymmetric: Different. Generation: Random. Storage: Secure.

๐Ÿ”‘ Public๐Ÿ”‘ Private๐Ÿ”‘ Related๐Ÿ”‘ Secure
# Key Pairs print("=== 1. What is a Key Pair? ===") print(""" Key pair: - Public key - Private key - Mathematically related - Asymmetric Example: Private key โ†’ Public key (not reverse) """) print("\n=== 2. Public Key ===") print(""" Public key: - Share openly - Encrypt - Verify - No secret Example: Alice's public key โ†’ Anyone """) print("\n=== 3. Private Key ===") print(""" Private key: - Keep secret - Decrypt - Sign - Critical Example: Alice's private key โ†’ Only Alice """) print("\n=== 4. Generation ===") print(""" Generation: - Random - Secure - Entropy - Algorithm Example: openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -pubout -out public.pem """) print("\n=== 5. Key Size ===") print(""" Key size: - RSA: 2048-4096 - ECC: 256-521 - Ed25519: 256 Example: RSA 2048 ECC 256 โ†’ Equivalent """) print("\n=== 6. Storage ===") print(""" Storage: - PEM - DER - PKCS#12 - Hardware Example: -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- """) print("\n=== 7. Key Formats ===") print(""" Formats: - PEM (base64) - DER (binary) - OpenSSH - PKCS#8 Example: PEM: -----BEGIN RSA PRIVATE KEY----- OpenSSH: -----BEGIN OPENSSH PRIVATE KEY----- """) print("\n=== 8. Python Key Pair ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization # Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) """) print("\n=== 9. Key Security ===") print(""" Security: - Random - Strong - Secure storage - Backup - Revocation Example: Hardware security module โ†’ Secure """) print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - SSH - PGP - Blockchain - Code signing - Document signing """)

๐Ÿ”’ Encryption

๐ŸŽฏ Asymmetric Encryption

Asymmetric encryption uses the recipient's public key to encrypt a message and the recipient's private key to decrypt it. Only the holder of the private key can decrypt.

Encryption

Public: Encrypt. Private: Decrypt. Confidentiality: Yes. Slow: Symmetric faster. Hybrid: TLS. Padding: OAEP.

๐Ÿ”’ Public encrypt๐Ÿ”’ Private decrypt๐Ÿ”’ OAEP๐Ÿ”’ Hybrid
# Encryption print("=== 1. How It Works ===") print(""" Encryption: 1. Alice gets Bob's public key 2. Alice encrypts message 3. Bob decrypts with private key Example: Alice โ†’ Bob's public key โ†’ Encrypt โ†’ Bob's private key โ†’ Decrypt """) print("\n=== 2. Confidentiality ===") print(""" Confidentiality: - Only private key - Decrypt - Secure Example: Public key โ†’ Encrypt โ†’ Private key โ†’ Decrypt """) print("\n=== 3. RSA Encryption ===") print(""" RSA: - Public key - Private key - OAEP padding Example: from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes ciphertext = public_key.encrypt( plaintext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) """) print("\n=== 4. ECC Encryption ===") print(""" ECC: - ECIES - Hybrid - Public key Example: from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.kdf.hkdf import HKDF # ECIES shared = private_key.exchange(ec.ECDH(), peer_public_key) """) print("\n=== 5. Hybrid Encryption ===") print(""" Hybrid: - Asymmetric: key exchange - Symmetric: data - Fast + secure Example: TLS: RSA/ECC โ†’ key exchange AES โ†’ data """) print("\n=== 6. Padding ===") print(""" Padding: - OAEP - PKCS#1 v1.5 - Secure Example: OAEP โ†’ Secure """) print("\n=== 7. Python RSA Encryption ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes # Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Encrypt message = b"Hello, Bob!" ciphertext = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # Decrypt plaintext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(plaintext) """) print("\n=== 8. Python ECIES ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.ciphers.aead import AESGCM import os # Generate private_key = ec.generate_private_key(ec.SECP256R1()) public_key = private_key.public_key() # ECIES peer_private = ec.generate_private_key(ec.SECP256R1()) peer_public = peer_private.public_key() # Shared secret shared = private_key.exchange(ec.ECDH(), peer_public) # Derive key derived = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'ecies' ).derive(shared) # Encrypt aesgcm = AESGCM(derived) nonce = os.urandom(12) ciphertext = aesgcm.encrypt(nonce, b"message", None) """) print("\n=== 9. Comparison ===") print(f"{'Algorithm':<15} {'Key Size':<15} {'Speed':<15} {'Security':<15}") print("-" * 60) print(f"{'RSA-2048':<15} {'2048':<15} {'Slow':<15} {'Secure':<15}") print(f"{'RSA-4096':<15} {'4096':<15} {'Slower':<15} {'Secure':<15}") print(f"{'ECC-256':<15} {'256':<15} {'Fast':<15} {'Secure':<15}") print(f"{'Ed25519':<15} {'256':<15} {'Fast':<15} {'Secure':<15}") print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - Email (PGP) - Messaging - File encryption - Hybrid """)

โœ๏ธ Digital Signatures

๐ŸŽฏ Digital Signatures

Digital signatures use a private key to sign a message (or its hash), and a public key to verify it. They provide authenticity, integrity, and non-repudiation.

Signatures

Sign: Private key. Verify: Public key. Authentication: Yes. Integrity: Yes. Non-repudiation: Yes. ECDSA: Bitcoin.

โœ๏ธ Signโœ๏ธ Verifyโœ๏ธ Authenticationโœ๏ธ Non-repudiation
# Digital Signatures print("=== 1. What is a Digital Signature? ===") print(""" Signature: - Sign with private key - Verify with public key - Authentication - Integrity - Non-repudiation Example: Alice โ†’ sign โ†’ Bob verify โ†’ Authentic """) print("\n=== 2. Signing Process ===") print(""" Sign: 1. Hash message: h = H(m) 2. Sign hash: s = Sign(h, private_key) 3. Send (m, s) Verify: 1. Hash message: h = H(m) 2. Verify: Verify(s, h, public_key) """) print("\n=== 3. Properties ===") print(""" Properties: - Authenticity - Integrity - Non-repudiation - Unforgeable """) print("\n=== 4. RSA Signatures ===") print(""" RSA: - PKCS#1 v1.5 - PSS - Sign/verify Example: from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) public_key.verify( signature, message, padding.PSS(...), hashes.SHA256() ) """) print("\n=== 5. ECDSA ===") print(""" ECDSA: - Elliptic Curve - Bitcoin - Ethereum - secp256k1 Example: from cryptography.hazmat.primitives.asymmetric import ec signature = private_key.sign( message, ec.ECDSA(hashes.SHA256()) ) public_key.verify( signature, message, ec.ECDSA(hashes.SHA256()) ) """) print("\n=== 6. EdDSA ===") print(""" EdDSA: - Ed25519 - Modern - Fast - Secure Example: from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey private_key = Ed25519PrivateKey.generate() signature = private_key.sign(message) public_key.verify(signature, message) """) print("\n=== 7. Python RSA Signature ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes # Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Sign message = b"Hello, Bob!" signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) # Verify public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) """) print("\n=== 8. Python ECDSA ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes # Generate private_key = ec.generate_private_key(ec.SECP256R1()) public_key = private_key.public_key() # Sign signature = private_key.sign( message, ec.ECDSA(hashes.SHA256()) ) # Verify public_key.verify( signature, message, ec.ECDSA(hashes.SHA256()) ) """) print("\n=== 9. Python Ed25519 ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # Generate private_key = Ed25519PrivateKey.generate() public_key = private_key.public_key() # Sign signature = private_key.sign(message) # Verify public_key.verify(signature, message) """) print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - Code signing - Document signing - Email (S/MIME) - Blockchain - SSH """)

๐Ÿค Key Exchange

๐ŸŽฏ Diffie-Hellman Key Exchange

Diffie-Hellman is a method for two parties to securely exchange cryptographic keys over an insecure channel without prior shared secrets.

Key Exchange

DH: Classic. ECDH: Elliptic. Shared secret: Derived. No prior: No shared. TLS: Uses. Forward secrecy: Yes.

๐Ÿค DH๐Ÿค ECDH๐Ÿค Shared secret๐Ÿค Forward secrecy
# Key Exchange print("=== 1. Diffie-Hellman ===") print(""" DH: - Two parties - Insecure channel - Shared secret - 1976 Example: Alice + Bob โ†’ DH โ†’ Shared secret """) print("\n=== 2. Algorithm ===") print(""" Steps: 1. Public: p (prime), g (generator) 2. Alice: a (private), A = g^a mod p 3. Bob: b (private), B = g^b mod p 4. Exchange A, B 5. Alice: s = B^a mod p 6. Bob: s = A^b mod p 7. s = g^(ab) mod p Example: p = 23, g = 5 a = 6, A = 5^6 mod 23 = 8 b = 15, B = 5^15 mod 23 = 19 s = 19^6 mod 23 = 2 s = 8^15 mod 23 = 2 """) print("\n=== 3. ECDH ===") print(""" ECDH: - Elliptic Curve - Faster - Smaller keys - Modern Example: Alice: private a, public A = a*G Bob: private b, public B = b*G Shared: a*B = b*A = ab*G """) print("\n=== 4. Forward Secrecy ===") print(""" Forward secrecy: - Ephemeral keys - Per session - Compromise - Past secure Example: DHE โ†’ Ephemeral โ†’ Forward secrecy """) print("\n=== 5. Python DH ===") print(""" from cryptography.hazmat.primitives.asymmetric import dh from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF # Parameters parameters = dh.generate_parameters(generator=2, key_size=2048) # Alice alice_private = parameters.generate_private_key() alice_public = alice_private.public_key() # Bob bob_private = parameters.generate_private_key() bob_public = bob_private.public_key() # Shared shared = alice_private.exchange(bob_public) derived = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake' ).derive(shared) """) print("\n=== 6. Python ECDH ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes # Generate alice_private = ec.generate_private_key(ec.SECP256R1()) alice_public = alice_private.public_key() bob_private = ec.generate_private_key(ec.SECP256R1()) bob_public = bob_private.public_key() # Shared shared = alice_private.exchange(ec.ECDH(), bob_public) derived = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake' ).derive(shared) """) print("\n=== 7. X25519 ===") print(""" X25519: - Curve25519 - Fast - Modern - TLS 1.3 Example: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey private = X25519PrivateKey.generate() public = private.public_key() shared = private.exchange(peer_public) """) print("\n=== 8. TLS Handshake ===") print(""" TLS: - Client hello - Server hello - Key exchange (ECDHE) - Finished Example: Client + Server โ†’ ECDHE โ†’ Shared secret โ†’ AES """) print("\n=== 9. Comparison ===") print(f"{'Method':<15} {'Type':<15} {'Key Size':<15} {'Speed':<15}") print("-" * 60) print(f"{'DH':<15} {'Classic':<15} {'2048+':<15} {'Slow':<15}") print(f"{'ECDH':<15} {'Elliptic':<15} {'256':<15} {'Fast':<15}") print(f"{'X25519':<15} {'Modern':<15} {'256':<15} {'Very fast':<15}") print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - SSH - VPN - Messaging - Signal """)

๐Ÿ”ข RSA

๐ŸŽฏ RSA Algorithm

RSA (Rivest-Shamir-Adleman) is one of the first public-key cryptosystems, based on the difficulty of factoring large integers.

RSA

Factoring: Hard. Key size: 2048-4096. Encryption: Yes. Signatures: Yes. Slow: Symmetric faster. OAEP: Padding.

๐Ÿ”ข Factoring๐Ÿ”ข 2048-4096๐Ÿ”ข OAEP๐Ÿ”ข PSS
# RSA print("=== 1. What is RSA? ===") print(""" RSA: - Rivest, Shamir, Adleman - 1977 - Factoring - Public key Example: p, q primes n = p*q โ†’ Hard to factor """) print("\n=== 2. Key Generation ===") print(""" Generation: 1. Choose p, q primes 2. n = p*q 3. ฯ†(n) = (p-1)(q-1) 4. e coprime with ฯ†(n) 5. d = e^-1 mod ฯ†(n) 6. Public: (e, n) 7. Private: (d, n) Example: p = 61, q = 53 n = 3233 ฯ† = 3120 e = 17 d = 2753 """) print("\n=== 3. Encryption ===") print(""" Encrypt: c = m^e mod n Decrypt: m = c^d mod n Example: m = 65 c = 65^17 mod 3233 = 2790 m = 2790^2753 mod 3233 = 65 """) print("\n=== 4. Signatures ===") print(""" Sign: s = H(m)^d mod n Verify: H(m) = s^e mod n Example: s = H(m)^d โ†’ Verify """) print("\n=== 5. Padding ===") print(""" Padding: - OAEP (encryption) - PSS (signatures) - PKCS#1 v1.5 Example: OAEP โ†’ Secure """) print("\n=== 6. Key Size ===") print(""" Key size: - 1024: weak - 2048: standard - 3072: strong - 4096: very strong Example: 2048-bit โ†’ Standard """) print("\n=== 7. Python RSA ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes, serialization # Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) """) print("\n=== 8. Python Encrypt/Decrypt ===") print(""" # Encrypt message = b"Hello!" ciphertext = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # Decrypt plaintext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(plaintext) """) print("\n=== 9. Comparison ===") print(f"{'Key Size':<15} {'Security':<15} {'Speed':<15}") print("-" * 45) print(f"{'1024':<15} {'Weak':<15} {'Fast':<15}") print(f"{'2048':<15} {'Standard':<15} {'Medium':<15}") print(f"{'3072':<15} {'Strong':<15} {'Slow':<15}") print(f"{'4096':<15} {'Very strong':<15} {'Slower':<15}") print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - SSH - PGP - Code signing - Document signing """)

๐Ÿ“ ECC

๐ŸŽฏ Elliptic Curve Cryptography

ECC is based on the discrete logarithm problem on elliptic curves. It provides equivalent security to RSA with much smaller keys.

ECC

Small keys: 256-bit. Fast: Yes. Secure: Yes. ECDSA: Signatures. ECDH: Key exchange. Curves: secp256k1, P-256.

๐Ÿ“ Small keys๐Ÿ“ Fast๐Ÿ“ ECDSA๐Ÿ“ ECDH
# ECC print("=== 1. What is ECC? ===") print(""" ECC: - Elliptic Curve - 1985 - Koblitz, Miller - Discrete log Example: yยฒ = xยณ + ax + b โ†’ Curve """) print("\n=== 2. Why ECC? ===") print(""" Advantages: - Small keys - Fast - Efficient - Mobile Example: ECC 256 = RSA 3072 """) print("\n=== 3. Curves ===") print(""" Curves: - secp256k1 (Bitcoin) - P-256 (NIST) - P-384 - P-521 - Curve25519 - Ed25519 Example: secp256k1 โ†’ Bitcoin """) print("\n=== 4. ECDSA ===") print(""" ECDSA: - Signatures - Bitcoin - Ethereum Example: from cryptography.hazmat.primitives.asymmetric import ec signature = private_key.sign( message, ec.ECDSA(hashes.SHA256()) ) """) print("\n=== 5. ECDH ===") print(""" ECDH: - Key exchange - Shared secret - TLS Example: shared = private_key.exchange( ec.ECDH(), peer_public_key ) """) print("\n=== 6. Python ECC ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes # Generate private_key = ec.generate_private_key(ec.SECP256R1()) public_key = private_key.public_key() # Sign signature = private_key.sign( b"message", ec.ECDSA(hashes.SHA256()) ) # Verify public_key.verify( signature, b"message", ec.ECDSA(hashes.SHA256()) ) """) print("\n=== 7. Python ECDH ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes # Alice alice_private = ec.generate_private_key(ec.SECP256R1()) alice_public = alice_private.public_key() # Bob bob_private = ec.generate_private_key(ec.SECP256R1()) bob_public = bob_private.public_key() # Shared shared = alice_private.exchange(ec.ECDH(), bob_public) derived = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake' ).derive(shared) """) print("\n=== 8. Comparison ===") print(f"{'ECC':<15} {'RSA':<15} {'Security':<15}") print("-" * 45) print(f"{'256':<15} {'3072':<15} {'128-bit':<15}") print(f"{'384':<15} {'7680':<15} {'192-bit':<15}") print(f"{'521':<15} {'15360':<15} {'256-bit':<15}") print("\n=== 9. Python Example ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes, serialization # Generate private_key = ec.generate_private_key(ec.SECP256R1()) public_key = private_key.public_key() # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) # Sign signature = private_key.sign( b"message", ec.ECDSA(hashes.SHA256()) ) print(f"Signature: {signature.hex()[:32]}...") # Verify public_key.verify( signature, b"message", ec.ECDSA(hashes.SHA256()) ) print("Verified!") """) print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS - SSH - Bitcoin - Ethereum - Mobile - IoT """)

โšก EdDSA & Ed25519

๐ŸŽฏ Modern Signatures

EdDSA (Edwards-curve Digital Signature Algorithm) is a modern signature scheme. Ed25519 is its most popular instantiation, known for speed, security, and simplicity.

EdDSA

Ed25519: Fast. Secure: Yes. Deterministic: Yes. Simple: Yes. Modern: TLS 1.3. SSH: Uses.

โšก Ed25519โšก Fastโšก Deterministicโšก Modern
# EdDSA & Ed25519 print("=== 1. What is EdDSA? ===") print(""" EdDSA: - Edwards-curve - Digital Signature - 2011 - Bernstein Example: Ed25519 โ†’ Signatures """) print("\n=== 2. Ed25519 ===") print(""" Ed25519: - Curve25519 - 256-bit - Fast - Secure - Deterministic Example: Ed25519 โ†’ Sign """) print("\n=== 3. Advantages ===") print(""" Advantages: - Fast - Secure - Simple - Deterministic - No randomness - Side-channel resistant Example: Ed25519 โ†’ Fast + secure """) print("\n=== 4. Python Ed25519 ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives import serialization # Generate private_key = Ed25519PrivateKey.generate() public_key = private_key.public_key() # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) """) print("\n=== 5. Python Sign/Verify ===") print(""" # Sign message = b"Hello, Bob!" signature = private_key.sign(message) print(f"Signature: {signature.hex()}") # Verify public_key.verify(signature, message) print("Verified!") # Invalid try: public_key.verify(signature, b"Tampered") except Exception as e: print(f"Invalid: {e}") """) print("\n=== 6. X25519 ===") print(""" X25519: - Key exchange - Curve25519 - Fast - TLS 1.3 Example: from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey private = X25519PrivateKey.generate() public = private.public_key() shared = private.exchange(peer_public) """) print("\n=== 7. Comparison ===") print(f"{'Algorithm':<15} {'Key Size':<15} {'Speed':<15} {'Security':<15}") print("-" * 60) print(f"{'ECDSA P-256':<15} {'256':<15} {'Fast':<15} {'Secure':<15}") print(f"{'Ed25519':<15} {'256':<15} {'Very fast':<15} {'Secure':<15}") print(f"{'RSA-2048':<15} {'2048':<15} {'Slow':<15} {'Secure':<15}") print("\n=== 8. Use Cases ===") print(""" Use cases: - SSH - TLS 1.3 - Signal - WireGuard - Blockchain - Modern crypto """) print("\n=== 9. Python Complete ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives import serialization # Generate private_key = Ed25519PrivateKey.generate() public_key = private_key.public_key() # Sign message = b"Hello, World!" signature = private_key.sign(message) print(f"Message: {message}") print(f"Signature: {signature.hex()}") # Verify public_key.verify(signature, message) print("Verified!") # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) """) print("\n=== 10. Best Practices ===") print(""" Best practices: - Use Ed25519 - Use X25519 - Avoid custom - Use libraries - Test """)

๐Ÿ“œ Certificates & PKI

๐ŸŽฏ Public Key Infrastructure

PKI is a system for managing digital certificates and public-key encryption. It includes Certificate Authorities (CAs) that issue and sign certificates.

PKI

CA: Certificate Authority. Certificate: Public key + identity. Sign: CA signs. Trust: Chain. Revocation: CRL, OCSP. TLS: Uses.

๐Ÿ“œ CA๐Ÿ“œ Certificate๐Ÿ“œ Chain๐Ÿ“œ Revocation
# Certificates & PKI print("=== 1. What is a Certificate? ===") print(""" Certificate: - Public key - Identity - CA signature - X.509 Example: Website โ†’ Certificate โ†’ Trust """) print("\n=== 2. X.509 ===") print(""" X.509: - Standard - Certificate format - Fields Fields: - Version - Serial number - Signature algorithm - Issuer - Validity - Subject - Public key - Extensions - Signature """) print("\n=== 3. CA ===") print(""" CA: - Certificate Authority - Issues - Signs - Trusted Examples: - Let's Encrypt - DigiCert - GlobalSign """) print("\n=== 4. Chain of Trust ===") print(""" Chain: - Root CA - Intermediate CA - Leaf - Verify Example: Root โ†’ Intermediate โ†’ Leaf โ†’ Trust """) print("\n=== 5. Revocation ===") print(""" Revocation: - CRL - OCSP - Compromised Example: CRL โ†’ Revoked """) print("\n=== 6. Python Certificate ===") print(""" from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID import datetime # Generate key private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) # Subject subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Example"), x509.NameAttribute(NameOID.COMMON_NAME, "example.com"), ]) # Certificate cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).sign(private_key, hashes.SHA256()) # Serialize pem = cert.public_bytes(serialization.Encoding.PEM) print(pem.decode()) """) print("\n=== 7. Python Verify ===") print(""" from cryptography import x509 from cryptography.hazmat.primitives import hashes # Load cert = x509.load_pem_x509_certificate(pem) # Verify public_key = cert.public_key() public_key.verify( cert.signature, cert.tbs_certificate_bytes, padding.PKCS1v15(), cert.signature_hash_algorithm ) print("Verified!") """) print("\n=== 8. Let's Encrypt ===") print(""" Let's Encrypt: - Free - Automated - ACME - Popular Example: certbot โ†’ Certificate """) print("\n=== 9. Python ACME ===") print(""" # pip install certbot # certbot certonly --standalone -d example.com """) print("\n=== 10. Use Cases ===") print(""" Use cases: - TLS/SSL - Code signing - Email (S/MIME) - VPN - Client certificates """)

๐ŸŒ TLS/SSL

๐ŸŽฏ Transport Layer Security

TLS (Transport Layer Security) is the protocol that secures HTTPS, using public key cryptography for key exchange and authentication.

TLS

Handshake: Key exchange. Certificates: Authentication. ECDHE: Key exchange. AES: Data. TLS 1.3: Modern. Forward secrecy: Yes.

๐ŸŒ Handshake๐ŸŒ Certificates๐ŸŒ ECDHE๐ŸŒ TLS 1.3
# TLS/SSL print("=== 1. What is TLS? ===") print(""" TLS: - Transport Layer Security - HTTPS - Secure - 1999 Versions: - SSL 1.0 (1994) - SSL 2.0 (1995) - SSL 3.0 (1996) - TLS 1.0 (1999) - TLS 1.1 (2006) - TLS 1.2 (2008) - TLS 1.3 (2018) """) print("\n=== 2. Handshake ===") print(""" Handshake: 1. Client hello 2. Server hello 3. Certificate 4. Key exchange 5. Finished 6. Data Example: Client + Server โ†’ Handshake โ†’ Secure """) print("\n=== 3. Key Exchange ===") print(""" Key exchange: - ECDHE - Forward secrecy - Shared secret Example: ECDHE โ†’ Shared secret โ†’ AES """) print("\n=== 4. Certificates ===") print(""" Certificates: - Server - CA - Trust - Verify Example: Certificate โ†’ Verify โ†’ Trust """) print("\n=== 5. TLS 1.3 ===") print(""" TLS 1.3: - 2018 - Faster - Secure - Forward secrecy - 1-RTT Example: TLS 1.3 โ†’ Fast """) print("\n=== 6. Python TLS Client ===") print(""" import ssl import socket # Context context = ssl.create_default_context() # Connect with socket.create_connection(("example.com", 443)) as sock: with context.wrap_socket(sock, server_hostname="example.com") as ssock: print(ssock.version()) print(ssock.getpeercert()) """) print("\n=== 7. Python TLS Server ===") print(""" import ssl import socket # Context context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain("cert.pem", "key.pem") # Server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(("0.0.0.0", 443)) sock.listen(5) with context.wrap_socket(sock, server_side=True) as ssock: conn, addr = ssock.accept() print(f"Connected: {addr}") """) print("\n=== 8. Python Requests ===") print(""" import requests # HTTPS response = requests.get("https://example.com") print(response.status_code) # Verify response = requests.get("https://example.com", verify=True) print(response.status_code) # Disable (not recommended) response = requests.get("https://example.com", verify=False) print(response.status_code) """) print("\n=== 9. Comparison ===") print(f"{'Version':<15} {'Year':<10} {'Security':<15} {'Speed':<15}") print("-" * 55) print(f"{'SSL 3.0':<15} {'1996':<10} {'Broken':<15} {'Slow':<15}") print(f"{'TLS 1.0':<15} {'1999':<10} {'Weak':<15} {'Slow':<15}") print(f"{'TLS 1.1':<15} {'2006':<10} {'Weak':<15} {'Slow':<15}") print(f"{'TLS 1.2':<15} {'2008':<10} {'Secure':<15} {'Medium':<15}") print(f"{'TLS 1.3':<15} {'2018':<10} {'Secure':<15} {'Fast':<15}") print("\n=== 10. Use Cases ===") print(""" Use cases: - HTTPS - Email - VPN - Messaging - IoT """)

๐Ÿ’ป SSH

๐ŸŽฏ Secure Shell

SSH (Secure Shell) uses public key cryptography for secure remote login and file transfer.

SSH

Key pair: Public/private. Authentication: Key-based. Encryption: Symmetric. Key exchange: DH. Ed25519: Modern. SSH keys: ~/.ssh/.

๐Ÿ’ป Key pair๐Ÿ’ป Authentication๐Ÿ’ป Ed25519๐Ÿ’ป ~/.ssh/
# SSH print("=== 1. What is SSH? ===") print(""" SSH: - Secure Shell - Remote login - File transfer - Tunneling - 1995 Example: ssh user@host """) print("\n=== 2. Key Generation ===") print(""" ssh-keygen: - Generate key pair - RSA, ECDSA, Ed25519 - ~/.ssh/ Example: ssh-keygen -t ed25519 -C "email@example.com" """) print("\n=== 3. Key Files ===") print(""" Files: - ~/.ssh/id_ed25519 (private) - ~/.ssh/id_ed25519.pub (public) - ~/.ssh/authorized_keys - ~/.ssh/known_hosts Example: id_ed25519 id_ed25519.pub """) print("\n=== 4. Authentication ===") print(""" Authentication: 1. Client sends public key 2. Server checks authorized_keys 3. Server sends challenge 4. Client signs with private key 5. Server verifies Example: Key-based โ†’ Secure """) print("\n=== 5. Copy Public Key ===") print(""" ssh-copy-id: - Copy public key - Authorized_keys - Passwordless Example: ssh-copy-id user@host """) print("\n=== 6. SSH Config ===") print(""" ~/.ssh/config: - Host alias - User - IdentityFile - Port Example: Host myserver HostName example.com User admin IdentityFile ~/.ssh/id_ed25519 """) print("\n=== 7. Python Paramiko ===") print(""" # pip install paramiko import paramiko # Connect client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect( "example.com", username="user", key_filename="~/.ssh/id_ed25519" ) # Execute stdin, stdout, stderr = client.exec_command("ls -la") print(stdout.read().decode()) client.close() """) print("\n=== 8. SSH Tunneling ===") print(""" Tunneling: - Local forward - Remote forward - Dynamic Example: ssh -L 8080:localhost:80 user@host """) print("\n=== 9. Python Key Generation ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives import serialization # Generate private_key = Ed25519PrivateKey.generate() public_key = private_key.public_key() # Serialize (OpenSSH) private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.OpenSSH, encryption_algorithm=serialization.NoEncryption() ) print(private_pem.decode()) public_ssh = public_key.public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH ) print(public_ssh.decode()) """) print("\n=== 10. Use Cases ===") print(""" Use cases: - Remote login - File transfer (SCP, SFTP) - Tunneling - Git - Automation """)

โ›“๏ธ Blockchain

๐ŸŽฏ Keys in Blockchain

Blockchain uses public key cryptography for ownership, transactions, and signatures. Your private key controls your cryptocurrency.

Blockchain

Private key: Control. Public key: Address. Signatures: Transactions. ECDSA: Bitcoin. Ed25519: Modern. Not your keys: Not your coins.

โ›“๏ธ Private keyโ›“๏ธ Public keyโ›“๏ธ Signaturesโ›“๏ธ Address
# Blockchain print("=== 1. Key Pair ===") print(""" Key pair: - Private key - Public key - Address Example: Private โ†’ Public โ†’ Address """) print("\n=== 2. Bitcoin ===") print(""" Bitcoin: - ECDSA - secp256k1 - Address Example: Private key โ†’ Public key โ†’ SHA256 + RIPEMD160 โ†’ Address """) print("\n=== 3. Ethereum ===") print(""" Ethereum: - ECDSA - secp256k1 - Keccak-256 Example: Private key โ†’ Public key โ†’ Keccak-256 โ†’ Address """) print("\n=== 4. Transactions ===") print(""" Transaction: - Sign with private key - Verify with public key - Broadcast Example: Tx โ†’ Sign โ†’ Broadcast """) print("\n=== 5. Address ===") print(""" Address: - Derived - Public key - Hash Example: Bitcoin: 1A1zP1... Ethereum: 0x742d35... """) print("\n=== 6. Python Bitcoin ===") print(""" from ecdsa import SigningKey, SECP256k1 import hashlib # Generate private_key = SigningKey.generate(curve=SECP256k1) public_key = private_key.get_verifying_key() # Public key bytes public_bytes = b'\\x04' + public_key.to_string() # SHA-256 sha = hashlib.sha256(public_bytes).digest() # RIPEMD-160 ripemd = hashlib.new('ripemd160', sha).digest() # Address (simplified) print(f"Address: {ripemd.hex()}") """) print("\n=== 7. Python Ethereum ===") print(""" from eth_account import Account from eth_keys import keys import sha3 # Generate private_key = keys.PrivateKey(b'\\x01' * 32) public_key = private_key.public_key # Address keccak = sha3.keccak_256() keccak.update(public_key.to_bytes()) address = keccak.hexdigest()[-40:] print(f"Address: 0x{address}") """) print("\n=== 8. Python Sign Transaction ===") print(""" from eth_account import Account from web3 import Web3 # Account acct = Account.from_key('0x...') # Transaction tx = { 'to': '0x...', 'value': Web3.toWei(0.01, 'ether'), 'gas': 21000, 'gasPrice': Web3.toWei(50, 'gwei'), 'nonce': 0, 'chainId': 1 } # Sign signed = acct.sign_transaction(tx) print(signed.rawTransaction.hex()) """) print("\n=== 9. HD Wallets ===") print(""" HD: - Hierarchical Deterministic - BIP32 - BIP39 (mnemonic) - BIP44 Example: Mnemonic โ†’ Seed โ†’ Private keys """) print("\n=== 10. Use Cases ===") print(""" Use cases: - Bitcoin - Ethereum - DeFi - NFTs - DAOs - Web3 """)

๐Ÿ Python Implementation

๐ŸŽฏ Asymmetric Crypto in Python

Python provides excellent libraries for public key cryptography: cryptography, PyCryptodome, ecdsa, and eth-account.

Python

cryptography: Modern. PyCryptodome: Classic. ecdsa: ECDSA. eth-account: Ethereum. paramiko: SSH. Complete: Examples.

๐Ÿ cryptography๐Ÿ PyCryptodome๐Ÿ ecdsa๐Ÿ eth-account
# Python Implementation print("=== 1. RSA Key Generation ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization # Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Serialize pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) print(pem.decode()) """) print("\n=== 2. RSA Encryption ===") print(""" from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes # Encrypt message = b"Hello, Bob!" ciphertext = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # Decrypt plaintext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(plaintext) """) print("\n=== 3. RSA Signatures ===") print(""" # Sign signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) # Verify public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) """) print("\n=== 4. ECC ===") print(""" from cryptography.hazmat.primitives.asymmetric import ec # Generate private_key = ec.generate_private_key(ec.SECP256R1()) public_key = private_key.public_key() # Sign signature = private_key.sign( message, ec.ECDSA(hashes.SHA256()) ) # Verify public_key.verify( signature, message, ec.ECDSA(hashes.SHA256()) ) """) print("\n=== 5. Ed25519 ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # Generate private_key = Ed25519PrivateKey.generate() public_key = private_key.public_key() # Sign signature = private_key.sign(message) # Verify public_key.verify(signature, message) """) print("\n=== 6. X25519 ===") print(""" from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # Generate private_key = X25519PrivateKey.generate() public_key = private_key.public_key() # Exchange shared = private_key.exchange(peer_public) """) print("\n=== 7. Certificates ===") print(""" from cryptography import x509 from cryptography.x509.oid import NameOID import datetime # Subject subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, "example.com"), ]) # Certificate cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( public_key ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).sign(private_key, hashes.SHA256()) """) print("\n=== 8. SSH Keys ===") print(""" from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives import serialization # Generate private_key = Ed25519PrivateKey.generate() # OpenSSH format private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.OpenSSH, encryption_algorithm=serialization.NoEncryption() ) print(private_pem.decode()) public_ssh = private_key.public_key().public_bytes( encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH ) print(public_ssh.decode()) """) print("\n=== 9. Complete Example ===") print(""" from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import hashes, serialization # 1. Generate private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # 2. Encrypt message = b"Secret message" ciphertext = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # 3. Decrypt plaintext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) print(f"Decrypted: {plaintext}") # 4. Sign signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) # 5. Verify public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) print("Verified!") """) print("\n=== 10. Libraries ===") print(""" Libraries: - cryptography - PyCryptodome - ecdsa - eth-account - paramiko - pyOpenSSL - bcrypt - passlib """)

โš–๏ธ Comparison

๐ŸŽฏ Which Algorithm?

Choosing the right asymmetric algorithm depends on your use case, security requirements, and performance needs.

Comparison

RSA: Classic. ECC: Modern. Ed25519: Fastest. ECDSA: Bitcoin. X25519: Key exchange. DH: Classic.

โš–๏ธ RSAโš–๏ธ ECCโš–๏ธ Ed25519โš–๏ธ ECDSA
Algorithm Type Key Size Speed Best For
RSA-2048Encryption/Sign2048SlowLegacy, TLS
RSA-4096Encryption/Sign4096SlowerHigh security
ECC P-256Encryption/Sign256FastTLS, general
secp256k1Signatures256FastBitcoin, Ethereum
Ed25519Signatures256Very fastModern, SSH
X25519Key exchange256Very fastTLS 1.3, Signal
ECDH P-256Key exchange256FastTLS
Diffie-HellmanKey exchange2048+SlowLegacy
DSASignatures2048+SlowLegacy
ElGamalEncryption2048+SlowLegacy
# Decision Guide print("=== Choose Algorithm by Use Case ===") print(""" General encryption: โ†’ RSA-2048/4096 โ†’ ECC P-256 Signatures: โ†’ Ed25519 (best) โ†’ ECDSA (Bitcoin) โ†’ RSA-PSS Key exchange: โ†’ X25519 (best) โ†’ ECDH โ†’ DH Blockchain: โ†’ secp256k1 (Bitcoin) โ†’ Ed25519 (Solana) SSH: โ†’ Ed25519 (best) โ†’ ECDSA โ†’ RSA TLS: โ†’ X25519 โ†’ ECDHE โ†’ RSA Email (PGP): โ†’ RSA โ†’ Ed25519 Code signing: โ†’ Ed25519 โ†’ ECDSA โ†’ RSA """) print("\n=== Security Comparison ===") print(f"{'Algorithm':<20} {'Security':<15} {'Key Size':<15} {'Speed':<15}") print("-" * 65) print(f"{'RSA-1024':<20} {'Weak':<15} {'1024':<15} {'Fast':<15}") print(f"{'RSA-2048':<20} {'Standard':<15} {'2048':<15} {'Medium':<15}") print(f"{'RSA-4096':<20} {'Strong':<15} {'4096':<15} {'Slow':<15}") print(f"{'ECC-256':<20} {'Standard':<15} {'256':<15} {'Fast':<15}") print(f"{'Ed25519':<20} {'Strong':<15} {'256':<15} {'Very fast':<15}") print(f"{'X25519':<20} {'Strong':<15} {'256':<15} {'Very fast':<15}") print("\n=== Speed Comparison ===") print(f"{'Algorithm':<20} {'Sign/Verify':<20} {'Key Gen':<15}") print("-" * 55) print(f"{'RSA-2048':<20} {'Slow':<20} {'Slow':<15}") print(f"{'RSA-4096':<20} {'Slower':<20} {'Slower':<15}") print(f"{'ECC-256':<20} {'Fast':<20} {'Fast':<15}") print(f"{'Ed25519':<20} {'Very fast':<20} {'Very fast':<15}") print(f"{'X25519':<20} {'Very fast':<20} {'Very fast':<15}") print("\n=== When to Use Which ===") print(""" USE RSA: โœ“ Legacy compatibility โœ“ Encryption โœ“ Signatures USE ECC: โœ“ Modern โœ“ Mobile โœ“ IoT โœ“ TLS USE Ed25519: โœ“ Best signatures โœ“ SSH โœ“ Modern USE X25519: โœ“ Best key exchange โœ“ TLS 1.3 โœ“ Signal USE secp256k1: โœ“ Bitcoin โœ“ Ethereum USE ECDSA: โœ“ Bitcoin โœ“ General """)

โ“ FAQ

๐ŸŽฏ Frequently Asked Questions

Answers to common questions about public key cryptography.

What is public key cryptography?

Public key cryptography (asymmetric cryptography) uses a pair of keys: a public key that can be shared with anyone, and a private key that must be kept secret. It enables encryption, digital signatures, and key exchange without sharing a secret key beforehand.

What is the difference between RSA and ECC?

RSA is based on the difficulty of factoring large integers, while ECC (Elliptic Curve Cryptography) is based on the discrete logarithm problem on elliptic curves. ECC provides equivalent security with much smaller keys (e.g., 256-bit ECC โ‰ˆ 3072-bit RSA), making it faster and more efficient.

What is a digital signature?

A digital signature is a cryptographic mechanism that uses a private key to sign a message (or its hash), and a public key to verify it. It provides authenticity, integrity, and non-repudiation, ensuring the message came from the claimed sender and was not altered.

What is Diffie-Hellman key exchange?

Diffie-Hellman is a method for two parties to securely exchange cryptographic keys over an insecure channel. Each party generates a private key and computes a public key; by combining their private key with the other's public key, they derive the same shared secret. It is used in TLS, SSH, and VPNs.

What is PKI?

PKI (Public Key Infrastructure) is a system for managing digital certificates and public-key encryption. It includes Certificate Authorities (CAs) that issue and sign certificates, Registration Authorities (RAs), and certificate repositories. PKI underpins TLS/SSL, code signing, and email security.

What is the best algorithm for signatures?

Ed25519 is widely considered the best modern signature algorithm due to its speed, security, and simplicity. ECDSA is also good and is used in Bitcoin and Ethereum. RSA-PSS is still acceptable for compatibility.

What is the best key exchange algorithm?

X25519 is the modern standard for key exchange, used in TLS 1.3, Signal, and WireGuard. ECDH with P-256 is also widely used. Classic Diffie-Hellman is still used but with larger keys.

What is forward secrecy?

Forward secrecy (perfect forward secrecy) means that compromising long-term keys does not compromise past session keys. It is achieved by using ephemeral key exchange (e.g., ECDHE) for each session, so past sessions remain secure.

What is a certificate?

A certificate (X.509) is a digital document that binds a public key to an identity (e.g., a website). It is signed by a Certificate Authority (CA), which vouches for the identity. Certificates enable trust in TLS/SSL.

What is the difference between encryption and signatures?

Encryption uses the recipient's public key to encrypt and their private key to decrypt (confidentiality). Signatures use the sender's private key to sign and their public key to verify (authenticity, integrity, non-repudiation). They serve different purposes.

# Quick Reference print("=== Quick Answers ===") print(""" Q: What is public key crypto? A: Asymmetric crypto with key pair. Q: Public key? A: Share openly. Q: Private key? A: Keep secret. Q: Best signatures? A: Ed25519. Q: Best key exchange? A: X25519. Q: Bitcoin? A: ECDSA secp256k1. Q: Ethereum? A: ECDSA secp256k1. Q: SSH? A: Ed25519. Q: TLS? A: X25519 + ECDHE. Q: What is PKI? A: Public Key Infrastructure. Q: What is a certificate? A: Public key + identity + CA signature. Q: Free? A: Yes โ€” all algorithms are open. """)

๐Ÿš€ Future

๐ŸŽฏ Where Asymmetric Crypto Is Going

The future is post-quantum, hybrid, privacy-preserving, threshold, and hardware-accelerated.

Future Directions

Post-quantum: Quantum-resistant. Hybrid: Classic + PQ. Privacy: ZK. Threshold: MPC. Hardware: HSM. Standards: NIST PQC.

๐Ÿš€ Post-quantum๐Ÿš€ Hybrid๐Ÿš€ Privacy๐Ÿš€ Threshold
# Future of Asymmetric Crypto print("=== 1. Post-Quantum ===") print(""" Trend: Post-quantum Current: - RSA - ECC - Broken by quantum Future: - Quantum-resistant - Lattice-based - Hash-based - Code-based Examples: - CRYSTALS-Kyber (KEM) - CRYSTALS-Dilithium (signatures) - Falcon (signatures) - SPHINCS+ (signatures) Future: - Quantum-safe - NIST standards - Migration """) print("\n=== 2. Hybrid ===") print(""" Trend: Hybrid Current: - Classic only Future: - Classic + PQ - Transition - Security Examples: - X25519 + Kyber - ECDSA + Dilithium - TLS hybrid Future: - Transition - Both - Secure """) print("\n=== 3. Privacy-Preserving ===") print(""" Trend: Privacy Current: - Basic crypto Future: - Zero-knowledge - Homomorphic - Secure MPC Examples: - ZK-SNARKs - ZK-STARKs - FHE Future: - Privacy - Computation - Trust """) print("\n=== 4. Threshold ===") print(""" Trend: Threshold Current: - Single key Future: - Threshold - MPC - Shared Examples: - Threshold ECDSA - Threshold RSA - FROST Future: - Distributed - Secure - No single point """) print("\n=== 5. Hardware ===") print(""" Trend: Hardware Current: - Software Future: - HSM - TPM - Secure enclave Examples: - Hardware wallets - HSM - TPM Future: - Secure - Fast - Integrated """) print("\n=== 6. Standards ===") print(""" Trend: Standards Current: - NIST - RSA - ECC Future: - NIST PQC - Hybrid - International Examples: - NIST PQC - ISO - IETF Future: - Updated - Quantum-safe - Global """) # TIMELINE print("\n=== Timeline ===") print(""" Past: 1976: Diffie-Hellman 1977: RSA 1985: ECC 1991: PGP 1999: TLS 1.0 2000: ECDSA 2011: Ed25519 2018: TLS 1.3 Present: 2025: Post-quantum 2026: Hybrid Future: 2030: PQ migration 2035: Quantum-safe 2040: ? """) print("\n=== Final Thoughts ===") print(""" Public key crypto is: - Fundamental - Everywhere - Evolving - Critical The future is: - Post-quantum - Hybrid - Privacy-preserving - Threshold - Hardware-accelerated - Standards "The key to trust in the digital world." Keep exploring. Keep building. """)