Secure Communication Protocols
SSH, JWT signing, TOTP, and secure API authentication
Skills taught: crypto.protocols
SSH: Secure Shell
SSH uses public-key cryptography for authentication. Your private key proves your identity without ever sending a password over the network. The server stores your public key in ~/.ssh/authorized_keys and verifies that you can produce a signature matching it.
# --- Generate Ed25519 key pair (recommended) ---
ssh-keygen -t ed25519 -C "your@email.com" -f ~/.ssh/id_ed25519
# -C: comment for identification -f: output file
# --- Generate RSA key pair (if Ed25519 not supported) ---
ssh-keygen -t rsa -b 4096 -C "your@email.com"
# --- Copy public key to server ---
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server.com
# or manually: cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys (on server)
# --- Verify key fingerprint (confirm server identity on first connect) ---
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
# --- Secure SSH server config (/etc/ssh/sshd_config) ---
# PasswordAuthentication no <- disable password login
# PermitRootLogin no <- never allow root SSH
# AllowUsers youruser <- whitelist users
# PubkeyAuthentication yes
# AuthorizedKeysFile .ssh/authorized_keys
# Protocol 2 <- SSHv1 is broken
# KexAlgorithms curve25519-sha256@libssh.org <- prefer modern key exchange
sudo systemctl restart sshd # apply changes
JWT: JSON Web Tokens
JWTs are signed JSON tokens for stateless API authentication. Format: base64url(header).base64url(payload).signature. The server signs the token; any service that knows the key (HS256) or has the public key (RS256/ES256) can verify it without a database lookup.
import jwt
import datetime
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
# --- HS256: symmetric (single service) ---
SECRET = "super-secret-key-at-least-256-bits-long"
payload = {
"sub": "user:1234",
"role": "admin",
"iat": datetime.datetime.utcnow(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1),
"jti": __import__('secrets').token_hex(16) # unique ID prevents replay
}
token = jwt.encode(payload, SECRET, algorithm="HS256")
print("Token:", token)
# Verify (always specify allowed algorithms — prevents alg:none attack)
decoded = jwt.decode(token, SECRET, algorithms=["HS256"])
print("User:", decoded["sub"])
# --- RS256: asymmetric (multiple services) ---
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key_pem = private_key.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
)
# Auth service signs with private key
token_rs256 = jwt.encode(payload, private_key, algorithm="RS256")
# Any service verifies with public key (never needs the private key)
decoded_rs256 = jwt.decode(token_rs256, public_key_pem, algorithms=["RS256"])
print("Verified by any service:", decoded_rs256["sub"])
Warning: Always whitelist algorithms when decoding JWTs: algorithms=["RS256"]. Never use algorithms=["RS256", "HS256"] together — this enables the RS256→HS256 confusion attack where an attacker uses your public key as an HS256 secret to forge tokens.
TOTP: Time-Based One-Time Passwords
TOTP (RFC 6238) generates 6-digit codes that change every 30 seconds from a shared secret. It is the basis of Google Authenticator, Authy, and hardware tokens. The server and client independently compute HMAC-SHA1(secret + current_time_step) and compare results.
import pyotp # pip install pyotp
import qrcode # pip install qrcode[pil]
# --- Setup: generate secret for a new user ---
secret = pyotp.random_base32() # 32-char base32 secret
print("Store in DB (encrypted):", secret)
# --- Generate QR code for authenticator app ---
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(name="user@example.com", issuer_name="MyApp")
qr = qrcode.make(uri)
qr.save("qr.png")
# --- Verify a 6-digit code ---
def verify_totp(user_secret: str, code: str) -> bool:
t = pyotp.TOTP(user_secret)
# valid_window=1 allows ±30 seconds for clock drift
return t.verify(code, valid_window=1)
# Example: user submits "123456"
if verify_totp(secret, "123456"):
print("2FA valid")
else:
print("2FA invalid or expired")
# --- HOTP (counter-based OTP, e.g. hardware tokens) ---
hotp = pyotp.HOTP(secret)
print("Code for counter 0:", hotp.at(0))
print("Code for counter 1:", hotp.at(1))
HS256 vs RS256 for JWTs
- HS256 (HMAC-SHA256): Symmetric — same secret for signing and verifying
- RS256 / ES256 (Asymmetric): Asymmetric — private key signs, public key verifies
Tip: JWTs are not encrypted by default — the payload is just base64-encoded and readable by anyone. Never put sensitive data (SSNs, credit card numbers, passwords) in a JWT payload. Use JWE if you need an encrypted token.
Frequently Asked Questions
What algorithm should I use to sign JWTs in production?
RS256 (RSA-SHA256) or ES256 (ECDSA-P256) for services where multiple parties verify tokens. HS256 for a single service that both signs and verifies. Never use RS256 and HS256 in the same library configuration — it enables key confusion attacks.
Are JWTs safe to store in localStorage?
They are vulnerable to XSS attacks — any JavaScript on the page can read localStorage. Use HttpOnly cookies instead: they cannot be accessed by JavaScript. If you must use localStorage, ensure you have strong XSS prevention.
Can TOTP be phished?
Yes, in a real-time phishing attack. A phishing page can collect both the password and TOTP code from the user and immediately use them on the real site within the 30-second window. FIDO2/WebAuthn (passkeys) is phishing-resistant. TOTP is still much better than no 2FA.