Prologue: "How Do I Send Credit Card Info Safely?"
When I first built an online shop, a terrifying thought hit me while integrating the payment system.
"When a user enters their credit card number and it travels across the internet to my server, what if a hacker intercepts it?"
HTTP communication means data flies as plain text. Anyone capturing network packets can read it directly.
POST /payment
Card Number: 4532-1234-5678-9010
Shopping on cafe wifi? Anyone on the same network can scrape packets. To prevent this, I needed encryption.
But what confused me initially: "To encrypt, I need a password (key). How do I safely send that password?"
This is the Key Distribution Problem, and Asymmetric Encryption was the revolution that solved it.
1. The Limit of Symmetric Keys: How to Deliver the Key?
First, let's look at the traditional Symmetric Key method.
Symmetric Key Method
Encryption key = Decryption key (Identical)
Plain text: "Hello"
Key: "SECRET123"
Encrypted: "xJ2k9$mP@"
...
Cipher text: "xJ2k9$mP@"
Key: "SECRET123" (Same key)
Decrypted: "Hello"
Fast and simple. But there's a fatal problem.
Problem: How to Deliver the Key?
To communicate securely with the server:
- Server and I must share the same key (SECRET123).
- I must send that key over the internet.
- If a hacker intercepts that key, game over.
Analogy:
- Me: "This letter is secret, so I locked it."
- Server: "Great. Send me the key."
- Me: "I'll... mail the key?"
- The mailman copies the key. ❌
This is the Key Distribution Problem.
My Initial Solution (Failed)
"Just hand-deliver the key when we first meet?"
But my service users are scattered worldwide. How do I meet them all? Physically impossible.
2. Genius Idea: "Make Lock and Key Different"
In 1976, two geniuses (Whitfield Diffie, Martin Hellman) had a revolutionary idea.
"What if the encryption key and decryption key are different?"
This is Asymmetric Key encryption.
Public Key and Private Key
- Public Key: Think of it as a "Padlock". Distribute it to everyone.
- Private Key: The actual "Key". Keep it secret. Never share.
Core concept:
- What's locked by Public Key can only be opened by Private Key.
- What's locked by Private Key can only be opened by Public Key.
3. Scenario 1: Sending a Secret Letter (Confidentiality)
Let's say I send a secret message to the server.
Step 1: Server Publishes Public Key
Server uploads its Public Key (Padlock) online. Anyone can download it.
Server Public Key: RSA-2048-PUBLIC-KEY-ABC123...
Step 2: I Encrypt Message with Server's Public Key
const message = "Credit Card: 1234-5678-9012";
const encrypted = encrypt(message, serverPublicKey);
// Result: "xK9jP2#mQ..."
Now I send the cipher text "xK9jP2#mQ..." to the server.
Step 3: Hacker Intercepts
A hacker captures the packet and gets the cipher text.
Cipher text: "xK9jP2#mQ..."
But can't open it. Why? This cipher text can only be decrypted by the server's Private Key. The server's Private Key is held only by the server.
Step 4: Server Decrypts with Private Key
const decrypted = decrypt("xK9jP2#mQ...", serverPrivateKey);
// Result: "Credit Card: 1234-5678-9012"
Success! The secret is safe.
Key Takeaway
- Public Key can be known by anyone (copying a padlock doesn't matter).
- As long as the Private Key never leaks, it's secure.
4. Scenario 2: Digital Signature (Authentication)
This time, we use it in reverse.
Problem Situation
I want to prove "I wrote this document." On the internet, anyone can impersonate my name.
Step 1: Sign Document with My Private Key
const document = "Transfer: $1000 → John Doe";
const signature = sign(document, myPrivateKey);
// Result: "9xP2#kQ..."
Now I send both:
Document: "Transfer: $1000 → John Doe"
Signature: "9xP2#kQ..."
Step 2: Recipient Verifies with My Public Key
The recipient (bank) fetches my Public Key (publicly available online).
const isValid = verify(document, signature, myPublicKey);
// Result: true (really signed by me)
If the document was tampered with or signed by someone else, it returns false.
Why Is It Secure?
- Only my Private Key can create this signature.
- Anyone trying to forge the document can't create a valid signature without my Private Key.
Real Example: Git Commit Signing
When I push code to GitHub, I sign commits with my GPG key.
git commit -S -m "Fix security bug"
GitHub verifies this commit using my Public Key. A "Verified" badge appears next to the commit.
5. My Hands-On Experience: JWT Token Signing
In my blog backend, I applied asymmetric encryption when using JWT (JSON Web Token).
Old Way (Symmetric Key)
const jwt = require('jsonwebtoken');
const SECRET = 'mySecretPassword'; // Symmetric key
// Token generation (Server)
const token = jwt.sign({ userId: 123 }, SECRET);
// Token verification (Server)
const payload = jwt.verify(token, SECRET);
Problem: Only the server can verify tokens.
If frontend or other services need to verify, they must share SECRET, which is risky.
Asymmetric Key Approach
const fs = require('fs');
// Server: Sign with Private Key
const privateKey = fs.readFileSync('private.key');
const token = jwt.sign({ userId: 123 }, privateKey, { algorithm: 'RS256' });
// Frontend: Verify with Public Key
const publicKey = fs.readFileSync('public.key');
const payload = jwt.verify(token, publicKey);
Now:
- Server issues tokens with Private Key.
- Client verifies with Public Key (Public Key can be distributed to anyone).
- Other microservices can verify tokens with just the Public Key.
6. HTTPS: How Did We Make Slow Asymmetric Keys Practical?
Asymmetric encryption has a fatal flaw. It's mathematically complex and SLOW. 100x slower than symmetric keys.
Encrypting/decrypting a file with RSA takes seconds. Unusable for real-time web communication.
Solution: Hybrid (HTTPS/TLS)
The internet (HTTPS) uses a clever trick.
sequenceDiagram
participant Client
participant Server
Client->>Server: 1. Request server public key
Server-->>Client: 2. Send server public key
Client->>Client: 3. Generate symmetric key (Session Key)
Client->>Server: 4. Send session key encrypted with server public key
Server->>Server: 5. Decrypt session key with server private key
Note over Client,Server: Both now have the session key
Client->>Server: 6. All further communication encrypted with session key
Server-->>Client: 7. Fast symmetric encryption
Step-by-Step Explanation
Step 1-2: Handshake
Initial connection uses Asymmetric Key. Server sends its Public Key (SSL certificate).
Step 3-5: Share Symmetric Key
Client generates a random Symmetric Key (Session Key). Encrypts this session key with server's Public Key and sends it. Server decrypts with its Private Key.
Now both sides have the same Symmetric Key. Hackers don't know this key (it was transmitted encrypted).
Step 6-7: Fast Communication
All subsequent data is encrypted with Symmetric Key. Fast.
Result
- Security: Asymmetric Key safely shares Symmetric Key.
- Speed: Symmetric Key handles actual data transmission.
7. Practical Tip: Generating RSA Keys
Commands I actually used.
Generate Private Key
openssl genrsa -out private.key 2048
Extract Public Key
openssl rsa -in private.key -pubout -out public.key
Check Files
private.key (Secret! Never share)
public.key (Safe to publish anywhere)
8. Downsides of Asymmetric Keys and Alternatives
Downside 1: Slow
RSA 2048-bit encryption is 100x slower than symmetric (AES-256).
Solution: Hybrid approach (like HTTPS).
Downside 2: Key Management
Lose the Private Key? All cipher texts are locked forever. Private Key leaks? All security collapses.
Solution:
- Use key management services like AWS KMS, HashiCorp Vault.
- Regularly rotate keys (Key Rotation).
9. Summary: When to Use What?
| Purpose | Method | Example |
|---|---|---|
| Secret Delivery | Encrypt with Public Key → Decrypt with Private Key | HTTPS, Email encryption |
| Identity Proof | Sign with Private Key → Verify with Public Key | Git Commit, JWT, SSL cert |
| Fast Encryption | Symmetric Key | AES (File encryption) |
| Real World | Hybrid | HTTPS (Asymmetric + Symmetric) |
10. The Future: Elliptic Curve Cryptography (ECC)
RSA is great, but the keys are getting too big. To be secure today, RSA needs 2048-bit or 4096-bit keys. This is heavy for mobile devices.
Enter ECC (Elliptic Curve Cryptography). It uses complex curves instead of prime factorization.
Why ECC?
- Smaller Keys: 256-bit ECC key is as strong as 3072-bit RSA key.
- Faster: Less CPU, less battery.
- Adoption: Bitcoin/Ethereum use ECC (secp256k1). Modern HTTPS uses ECC (ECDSA).
If you are setting up a server today, prefer ECDSA certificates over RSA. It makes your SSL handshake faster on mobile phones.
Final Thought: "The Internet Works Because of This Magic"
When building my first shop, I started with "How do I safely receive credit card info?" Only after studying asymmetric encryption did I realize "Oh, this is how the internet works."
- Bank websites (HTTPS)
- Login tokens (JWT)
- Git commit signing
- SSL certificates
- Cryptocurrency Wallets
All powered by Public/Private Key magic.
As I write this, my browser's address bar shows a padlock icon. Proof that my server and I are talking securely.