π 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
- VPN Deep Dive: Tunneling, Encapsulation & Packet Lifecycle
- Symmetric vs Asymmetric Encryption & Hybrid Cryptography
- Encoding vs Encryption vs Hashing vs Tokenization (Comparison Matrix)
- What is Tokenization? (Payment Gateway & RBI Mandate Focus)
- JWT (JSON Web Tokens): Anatomy, Verification & Flaws
- 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:
- Confidentiality & Integrity: All traffic passing through untrusted ISPs or public Wi-Fi is encrypted.
- IP Masking & Geo-Relocation: Public internet destinations see the VPN Gateway's egress IP instead of the client's actual ISP-assigned IP.
- 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 GamingTUN(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
| Protocol | Layer / Ports | Cryptographic Suite | Performance / Latency | Kernel Integration |
|---|---|---|---|---|
| WireGuard | Layer 3 (UDP port 51820) | Noise Protocol, ChaCha20-Poly1305, Curve25519, BLAKE2s | Fastest (~95% bare-metal line speed, ~4,000 lines of code) | Native Linux Kernel Module (drivers/net/wireguard) |
| OpenVPN | Layer 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 groups | High (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
| Dimension | Symmetric Encryption | Asymmetric Encryption |
|---|---|---|
| Algorithms | AES (AES-128, AES-256 in GCM mode), ChaCha20-Poly1305, DES/3DES (deprecated) | RSA (2048/4096-bit), ECC (ECDSA, Ed25519, Curve25519), Diffie-Hellman |
| Key Count | 1 Shared Secret Key | 2 Keys: 1 Public Key + 1 Private Key |
| Speed / Throughput | Extremely 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 Usage | Minimal CPU and memory | High mathematical compute overhead |
| Primary Use Case | Bulk payload encryption (Databases, Disk encryption, HTTPS data transfer, VPN tunnels) | Key exchange, digital signatures, identity verification, TLS handshakes |
| Key Distribution | The 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:
| Dimension | Encoding | Hashing | Encryption | Tokenization |
|---|---|---|---|---|
| Primary Purpose | Ensure 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 Size | Proportional 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 / Formats | Base64, 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 Value | Zero 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:
- 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.
- Device-Bound (Optional): For Apple Pay / Google Pay / Samsung Pay, tokens are locked to the physical secure enclave chip of a specific smartphone.
- Cryptogram Verification: Every transaction requires a dynamic, single-use cryptographic signature (TAVV / Cryptogram) generated by the network, preventing replay attacks.
- 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 Signature1. 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>:
- The backend splits the string by the
.character intoH,P, andS. - The server independently calculates: $$\text{Expected Signature} = \text{HMAC-SHA256}(H + "." + P, \text{Server Secret})$$
- It performs a Constant-Time Comparison (
crypto.timingSafeEqual) betweenExpected SignatureandS:- If they match: The payload has not been tampered with. The server reads
user_idand grants access. - If they do not match: The token was altered in transit; request is rejected with
401 Unauthorized.
- If they match: The payload has not been tampered with. The server reads
Critical JWT Pitfalls & Interview Attack Vectors
- 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']).
- Attack: An attacker modifies the header to
- 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.ioand read the claims in cleartext! Never store passwords, credit card PANs, or PII in JWT payloads.
- The Revocation / Logout Problem:
- Because JWTs are stateless, once issued, a token remains valid until its
exptimestamp 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.
- Because JWTs are stateless, once issued, a token remains valid until its
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?
- 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). - Tooling & Dependency Management: npm manages the
package.jsonmanifest, resolves nested dependency trees, enforces semantic versioning (^,~), and locks exact builds viapackage-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)- Module System Mismatch:
- Historically, Node.js packages in
node_modulesused the CommonJS format (const x = require('x')andmodule.exports). - Web browsers do not have a built-in
require()function or filesystem access to traversenode_modules/react/index.js.
- Historically, Node.js packages in
- 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.
- 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:
- CDN Script Tags:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> - 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_modulescontaining 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."