09-vpn-tunneling-cryptography-and-encoding.md

🌐 CN 09: VPN Internals, Cryptography, Tokenization, JWT & Frontend Tooling

Targeted for: Juspay Elimination Round, Systems & Backend Architecture Interviews
Key Focus: VPN tunneling & TUN/TAP virtual devices, Symmetric vs Asymmetric encryption, Hybrid TLS cryptosystems, The 4-way distinction (Encoding vs Encryption vs Hashing vs Tokenization), RBI Payment Card Tokenization (PCI-DSS), JWT mechanics & security flaws, and "Can we use npm for frontend?".


πŸ“‘ Quick Navigation

  1. VPN Deep Dive: Tunneling, Encapsulation & Packet Lifecycle
  2. Symmetric vs Asymmetric Encryption & Hybrid Cryptography
  3. Encoding vs Encryption vs Hashing vs Tokenization (Comparison Matrix)
  4. What is Tokenization? (Payment Gateway & RBI Mandate Focus)
  5. JWT (JSON Web Tokens): Anatomy, Verification & Flaws
  6. Can We Use npm for Frontend? (Ecosystem & Bundler Architecture)

1. VPN Deep Dive: Tunneling, Encapsulation & Packet Lifecycle

What is a Virtual Private Network (VPN)?

A VPN extends a private network across a public network (the Internet) by creating a secure, encrypted logical point-to-point tunnel. It makes the client device appear as if it is directly connected to the remote private network, granting:

  1. Confidentiality & Integrity: All traffic passing through untrusted ISPs or public Wi-Fi is encrypted.
  2. IP Masking & Geo-Relocation: Public internet destinations see the VPN Gateway's egress IP instead of the client's actual ISP-assigned IP.
  3. Internal Resource Access: Enables remote developers to securely access private microservices, databases, and internal payment APIs behind VPC firewalls.

Virtual Network Interfaces: TUN vs TAP

Operating systems (Linux, macOS, Windows) use software-defined virtual network device drivers to implement VPNs:

+-------------------------------------------------------------+ | OS NETWORK STACK COMPARISON | +-------------------------------------------------------------+ Layer 3: Network Layer (IP) Layer 2: Data Link Layer (Ethernet) ============================ =================================== [ TUN Device ] [ TAP Device ] Transfers raw IP Packets Transfers raw Ethernet Frames (No Ethernet MAC headers) (Includes MAC header, ARP, Broadcasts) Used by: WireGuard, OpenVPN, IPsec Used by: Virtual Machines (QEMU/KVM), Bridge Networks, LAN Gaming
  • TUN (Network Tunnel): Simulates a network-layer device. It receives and transmits raw Layer 3 IP packets directly to/from a user-space application without Ethernet headers.
  • TAP (Network Tap): Simulates a link-layer device. It captures Layer 2 Ethernet frames (including source/destination MAC addresses and ARP requests).

Step-by-Step Packet Lifecycle: Sending a Request via VPN

[ BROWSER ] β”‚ (1. HTTP Request to 93.184.216.34:443) β–Ό [ OS ROUTING TABLE ] β”‚ (2. Default route 0.0.0.0/0 points to tun0 interface) β–Ό [ VIRTUAL INTERFACE: tun0 ] β”‚ (3. Kernel routes raw IP packet to tun0 character device /dev/net/tun) β–Ό [ VPN CLIENT PROCESS (User Space) ] β”‚ (4. Reads raw IP packet from /dev/net/tun) β”‚ (5. Encrypts entire packet: Payload + Original IP Header) β”‚ (6. Wraps inside an OUTER UDP packet: Src = 192.168.1.50, Dst = VPN_Server_IP:51820) β–Ό [ PHYSICAL NIC: eth0 / Wi-Fi ] β”‚ (7. Sends outer encrypted UDP packet across the public Internet) β–Ό ========================== PUBLIC INTERNET (ISP / ROUTERS) ========================== β”‚ (Routers inspect only OUTER UDP header; inner traffic is completely opaque) β–Ό [ VPN SERVER GATEWAY ] β”‚ (8. Receives UDP packet on port 51820) β”‚ (9. Decrypts payload using client's session key -> Recovers original inner IP packet) β”‚ (10. Applies NAT / Masquerade: Rewrites Src IP to VPN Server Public IP) β–Ό [ DESTINATION WEB SERVER (e.g., example.com) ] (Receives clean IP packet; sees source as VPN Server IP, completely unaware of client!)

VPN Protocol Comparison

ProtocolLayer / PortsCryptographic SuitePerformance / LatencyKernel Integration
WireGuardLayer 3 (UDP port 51820)Noise Protocol, ChaCha20-Poly1305, Curve25519, BLAKE2sFastest (~95% bare-metal line speed, ~4,000 lines of code)Native Linux Kernel Module (drivers/net/wireguard)
OpenVPNLayer 3 (TUN) or Layer 2 (TAP) (UDP/TCP 1194)OpenSSL (AES-256-GCM, RSA/ECDSA, SHA-256)Moderate (Heavy user-space context switches between /dev/net/tun and network sockets)User-space daemon
IPsec (IKEv2)Layer 3 (UDP 500, UDP 4500 NAT-T, ESP protocol 50)AES-CBC / AES-GCM, DH groupsHigh (In-kernel hardware acceleration)Native OS Kernel

2. Symmetric vs Asymmetric Encryption & Hybrid Cryptography

Core Definitions

  • Symmetric Encryption (Secret-Key Cryptography): Uses the exact same secret key to both encrypt and decrypt data. Both parties must securely share this single key beforehand.
  • Asymmetric Encryption (Public-Key Cryptography): Uses a mathematically linked key pair:
    • Public Key: Shared openly with the world; used by anyone to encrypt data or verify digital signatures.
    • Private Key: Kept strictly confidential by the owner; used to decrypt data or generate digital signatures.
+-----------------------------------------------------------------------------------------+ | SYMMETRIC ENCRYPTION | +-----------------------------------------------------------------------------------------+ Plaintext ────► [ AES-256-GCM Encrypt with Key K ] ────► Ciphertext β”‚ Plaintext ◄──── [ AES-256-GCM Decrypt with Key K ] β—„β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (Key K must be shared in advance. Fast, but key distribution is difficult) +-----------------------------------------------------------------------------------------+ | ASYMMETRIC ENCRYPTION | +-----------------------------------------------------------------------------------------+ Plaintext ────► [ Encrypt with Bob's PUBLIC Key ] ────► Ciphertext β”‚ Plaintext ◄──── [ Decrypt with Bob's PRIVATE Key ] β—„β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (No prior shared secret needed. Extremely secure, but mathematically slow)

Mathematical Foundation: The One-Way Trapdoor Function

  • RSA: Relies on the Integer Factorization Problem. Multiplying two 2048-bit prime numbers $p \times q = n$ takes microseconds; factoring $n$ back into $p$ and $q$ would take billions of compute years on supercomputers.
  • ECC (Elliptic Curve Cryptography): Relies on the Elliptic Curve Discrete Logarithm Problem (ECDLP) over equations like $y^2 = x^3 + ax + b$.
    • Advantage: A 256-bit ECC key (Curve25519) provides identical security to a 3072-bit RSA key with significantly lower CPU overhead and smaller packet sizes.

Detailed Comparison Matrix

DimensionSymmetric EncryptionAsymmetric Encryption
AlgorithmsAES (AES-128, AES-256 in GCM mode), ChaCha20-Poly1305, DES/3DES (deprecated)RSA (2048/4096-bit), ECC (ECDSA, Ed25519, Curve25519), Diffie-Hellman
Key Count1 Shared Secret Key2 Keys: 1 Public Key + 1 Private Key
Speed / ThroughputExtremely Fast ($> 2\text{ to } 4\text{ GB/sec}$ via hardware AES-NI CPU instructions)Slow ($1000\times$ slower than AES due to modular exponentiation)
Resource UsageMinimal CPU and memoryHigh mathematical compute overhead
Primary Use CaseBulk payload encryption (Databases, Disk encryption, HTTPS data transfer, VPN tunnels)Key exchange, digital signatures, identity verification, TLS handshakes
Key DistributionThe Hard Problem: How to transmit the secret key safely over an insecure channel?Trivial: Public keys can be broadcast on billboards or DNS records

The Real-World Solution: Hybrid Cryptosystem (How HTTPS/TLS Works)

Neither symmetric nor asymmetric encryption is sufficient on its own:

  • Symmetric is fast, but cannot safely exchange keys across the Internet.
  • Asymmetric solves key exchange, but is far too slow to stream videos or payment payloads.

The Hybrid Approach:

[ CLIENT ] [ SERVER ] β”‚ β”‚ β”‚ ─── 1. Asymmetric Handshake (ECDHE: Elliptic Curve Diffie-Hellman) ─── β”‚ β”‚ Exchanges public parameters; computes SHARED SESSION KEY (K)β”‚ β”‚ β”‚ β”‚ ═══ 2. Bulk Symmetric Transmission (AES-256-GCM using Key K) ════ β”‚ β”‚ Streams gigabytes of application data at full line-speed! β”‚

3. Encoding vs Encryption vs Hashing vs Tokenization (Comparison Matrix)

A favorite Juspay interview question designed to test precision in cryptographic vocabulary:

DimensionEncodingHashingEncryptionTokenization
Primary PurposeEnsure data usability and safe transmission across systems with character set limits.Ensure data integrity and verify authenticity without storing plaintext.Ensure data confidentiality and privacy against unauthorized eavesdroppers.Protect high-value sensitive data (Credit Card PAN) by replacing it with a surrogate token.
Reversible?Yes, easily reversible by anyone without a secret.No, mathematically one-way and irreversible.Yes, reversible only with the correct decryption key.Yes, but only via lookup inside an isolated, highly secure Token Vault.
Key / Secret Required?None (public standard algorithm).None (or secret salt/HMAC key).Required (Symmetric secret key or Asymmetric private key).None mathematically; security relies on access control to the central Token Vault.
Output SizeProportional to input (e.g., Base64 expands by $\approx 33%$).Fixed length (SHA-256 is always 256 bits / 32 bytes regardless of input size).Proportional to input (often padded to 16-byte block boundary in CBC mode).Format-Preserving: Matches the exact length and shape of the original data (e.g., 16 digits).
Common Algorithms / FormatsBase64, Hexadecimal, URL Encoding, ASCII, UTF-8, UTF-16.SHA-256, SHA-3, bcrypt, Argon2id, PBKDF2.AES-256-GCM, ChaCha20, RSA-4096, ECC.Random UUIDv4 generation, Format-Preserving Tokenization (FPE - FF1/FF3-1).
Security ValueZero Security (Obfuscation only; anyone can decode).High (Protects passwords; verifies file checksums).High (Mathematical security based on computational hardness).Highest for Compliance: Removes underlying data from system storage entirely.

4. What is Tokenization? (Payment Gateway & RBI Mandate Focus)

Why Juspay Cares Deeply About Tokenization

In India, the Reserve Bank of India (RBI) issued the Card-on-File (CoF) Tokenization Mandate:

"No entity in the card transaction/payment chain, other than card networks and card issuers, shall store actual card data (16-digit PAN, CVV, expiry date) after September 30, 2022."

Before this mandate, e-commerce merchants (Amazon, Flipkart, Swiggy) and payment gateways stored raw card numbers in databases. If a merchant's database was breached, millions of credit card numbers were exposed.


How Card Tokenization Works (Card-on-File Flow)

[ CUSTOMER ] [ MERCHANT / JUSPAY ] [ CARD NETWORK (Visa/Mastercard) ] [ ISSUER BANK (HDFC/ICICI) ] β”‚ β”‚ β”‚ β”‚ β”‚ 1. Enters 16-digit PAN β”‚ β”‚ β”‚ β”‚ ──────────────────────► β”‚ β”‚ β”‚ β”‚ β”‚ 2. Request Token (PAN + Merchant ID) β”‚ β”‚ β”‚ β”‚ ────────────────────────────────────► β”‚ β”‚ β”‚ β”‚ β”‚ 3. Validates with Issuer & triggers OTP β”‚ β”‚ β”‚ ────────────────────────────────► β”‚ β”‚ 4. Enters OTP to consentβ”‚ β”‚ β”‚ β”‚ ──────────────────────────────────────────────────────────────► β”‚ β”‚ β”‚ β”‚ β”‚ 5. Generates Unique Token β”‚ β”‚ β”‚ 6. Returns Token: 4111-XXXX-XXXX-1234 β”‚ (e.g., 4111-8923-4567-1234) β”‚ β”‚ β”‚ ◄──────────────────────────────────── β”‚ + Cryptogram Key β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ 7. Merchant stores ONLY Token in DB! β”‚ β”‚ β”‚ β”‚ (Raw PAN is discarded from memory) β”‚ β”‚

Key Properties of Payment Tokens:

  1. Domain-Bound: A token generated for Flipkart cannot be used on Swiggy. Even if a hacker steals the merchant's database, the tokens are useless anywhere else.
  2. Device-Bound (Optional): For Apple Pay / Google Pay / Samsung Pay, tokens are locked to the physical secure enclave chip of a specific smartphone.
  3. Cryptogram Verification: Every transaction requires a dynamic, single-use cryptographic signature (TAVV / Cryptogram) generated by the network, preventing replay attacks.
  4. PCI-DSS De-scoping: Storing tokens instead of raw PANs drastically reduces the PCI-DSS compliance burden and audit scope for merchant systems.

5. JWT (JSON Web Tokens): Anatomy, Verification & Flaws

Structure of a JWT

A JSON Web Token consists of three distinct parts separated by dots (.): $$\mathbf{Header} ,., \mathbf{Payload} ,., \mathbf{Signature}$$

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsIm5hbWUiOiJPbWt1bWFyIiwiZXhwIjoxNzczNjQ4MDAwfQ.7f2a1b9c4... β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Header Payload Signature
1. HEADER (Base64Url Encoded JSON) { "alg": "HS256", // Algorithm used for signing (HS256, RS256, ES256) "typ": "JWT" // Type of token } 2. PAYLOAD / CLAIMS (Base64Url Encoded JSON) { "sub": "user_987654", // Subject (User ID) "name": "Omkumar", "role": "admin", "iat": 1694822400, // Issued At timestamp "exp": 1694826000 // Expiration timestamp } 3. SIGNATURE (Cryptographic Verification Hash) HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret_key )

How Signature Verification Works

When a client sends a request with Authorization: Bearer <token>:

  1. The backend splits the string by the . character into H, P, and S.
  2. The server independently calculates: $$\text{Expected Signature} = \text{HMAC-SHA256}(H + "." + P, \text{Server Secret})$$
  3. It performs a Constant-Time Comparison (crypto.timingSafeEqual) between Expected Signature and S:
    • If they match: The payload has not been tampered with. The server reads user_id and grants access.
    • If they do not match: The token was altered in transit; request is rejected with 401 Unauthorized.

Critical JWT Pitfalls & Interview Attack Vectors

  1. The alg: "none" Vulnerability:
    • Attack: An attacker modifies the header to {"alg": "none"}, strips the signature, and modifies the payload to {"role": "admin"}.
    • Vulnerable libraries accepted unsigned tokens if they didn't enforce valid algorithms.
    • Fix: Explicitly whitelist algorithms on the verification server (e.g., algorithms: ['HS256']).
  2. Payload is NOT Encrypted!:
    • Common misconception: Beginners assume JWT encrypts data.
    • Truth: Base64Url is an encoding, not encryption. Anyone can paste a JWT into jwt.io and read the claims in cleartext! Never store passwords, credit card PANs, or PII in JWT payloads.
  3. The Revocation / Logout Problem:
    • Because JWTs are stateless, once issued, a token remains valid until its exp timestamp passes. If a user logs out, changes passwords, or gets banned, the token cannot be revoked without maintaining server state.
    • Production Solution: Use Short-Lived Access Tokens (5–15 mins) + Refresh Tokens (7 days) stored in Redis with Token Rotation.

6. Can We Use npm for Frontend? (Ecosystem & Bundler Architecture)

Interview Question: "Can we use npm for frontend? Isn't npm only for Node.js backend?"

The Definitive Answer: YES, Absolutely.

While npm stands for Node Package Manager and was originally created to manage server-side modules for Node.js, today it is the undisputed standard package manager for frontend web development as well.


Why Can We Use npm for Frontend?

  1. The Registry is Universal: The npm public registry (registry.npmjs.org) hosts JavaScript libraries regardless of where they runβ€”frontend UI libraries (react, vue, svelte), CSS frameworks (tailwindcss, bootstrap), utility libraries (lodash, date-fns), and backend frameworks (express).
  2. Tooling & Dependency Management: npm manages the package.json manifest, resolves nested dependency trees, enforces semantic versioning (^, ~), and locks exact builds via package-lock.json.

The Fundamental Architectural Catch: Why Browsers Cannot Run node_modules Directly

THE BUILD-TIME BRIDGE ===================== [ npm install react lodash ] ──► Stores files in ./node_modules/ β”‚ β–Ό (Browser cannot read CommonJS 'require' or resolve 10,000 individual files!) β”‚ [ MODULE BUNDLER / BUILD TOOL ] β—„β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (Vite / esbuild / Webpack / Rollup) 1. Resolves dependency graph 2. Transpiles modern JSX/TS to standard JS (Babel / SWC) 3. Tree-shaking (strips unused exports) 4. Minifies & bundles into single static bundle β”‚ β–Ό [ DIST / BUILD ARTIFACTS ] ──► [ NGINX / CDN ] ──► [ WEB BROWSER ] (index.html, bundle.js, style.css) (Executes standard Vanilla JS)
  1. Module System Mismatch:
    • Historically, Node.js packages in node_modules used the CommonJS format (const x = require('x') and module.exports).
    • Web browsers do not have a built-in require() function or filesystem access to traverse node_modules/react/index.js.
  2. Network Waterfall Problem:
    • A typical React application includes hundreds of packages comprising tens of thousands of individual JS files.
    • If a browser had to make separate HTTP requests to load every single file individually over the network, page load times would exceed 30 seconds.
  3. The Role of Bundlers (Webpack, Vite, Rollup, Parcel):
    • Frontend developers use npm to install libraries and build tools.
    • Tools like Vite (powered by esbuild & Rollup) parse imports at build time, eliminate dead code (tree-shaking), transpile JSX/TypeScript into standard ES5/ES6, and package everything into compact static assets.

Can We Run Frontend Code WITHOUT npm?

Yes! There are two modern alternatives:

  1. CDN Script Tags:
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  2. Modern Native Browser ES Modules & Import Maps: All modern browsers natively support ES Modules (import / export) without build tools:
    <script type="importmap"> { "imports": { "lodash": "https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.js" } } </script> <script type="module"> import { chunk } from 'lodash'; console.log(chunk([1, 2, 3, 4], 2)); </script>

🎯 Summary Matrix: Explaining npm for Frontend in an Interview

  • "npm is used during development and build time to install dependencies, manage versioning, and run scripts."
  • "Because browsers cannot natively consume unbundled node_modules containing CommonJS syntax and thousands of individual files, modern build tools (like Vite or Webpack) compile and bundle these npm packages into optimized static assets (.js, .css) that the browser executes."