Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 77 ยท CS Fundamentals Interview Questions

Security and Cryptography Questions

Answer security interview questions with confidence: hashing vs encryption, password storage, JWT, XSS, CSRF and SQL injection, with runnable Node examples.

Security questions show up in almost every backend and full-stack interview, even for roles that are not "security" jobs. Interviewers do not expect you to be a cryptographer. They want to hear that you know the difference between the basic tools (hashing, encryption, signing), that you never invent your own crypto, and that you can name the classic web attacks and the one-line fix for each.

The examples run on the site's Node 24 runner using only the built-in node:crypto module. Real servers, browsers and databases cannot run here, so attacks are shown with stand-ins: small functions that behave like the vulnerable and the fixed version. The real-world code in plain blocks is read-only.

Three tools, three jobs

Hashing One-way fingerprint of data.
Encryption Two-way, needs a key.
Signing Proves who made it and that it is unchanged.

Mixing these up is the most common wrong answer.

1 / 2

What is the difference between hashing and encryption?

Short answer: Hashing is one-way: you turn any input into a fixed-size digest and you cannot get the input back. Encryption is two-way: with the right key you can decrypt what you encrypted. Use hashing to check that data matches (passwords, file integrity); use encryption when you must read the data again later (a stored API token, a message).

Good hash functions are deterministic (same input, same digest), fast to compute (for the general-purpose ones), and tiny changes in the input change the whole digest. Be ready to add that encoding is neither: Base64 is just a reversible format with no secret at all.

Node.js Hash, encrypt, encode: three different things

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Symmetric vs asymmetric, and what signing is

Symmetric encryption (AES) uses one shared key and is fast. Asymmetric encryption (RSA, elliptic curves) uses a key pair: what the public key locks, only the private key opens. It is slow, so real systems (TLS) use asymmetric crypto to agree on a key and symmetric crypto for the bulk data.

A digital signature goes the other way: the private key signs, the public key verifies. A MAC (such as HMAC) gives you the same "unchanged and from someone with the secret" guarantee using one shared secret. Signing does not hide the data.

How should you store passwords?

Short answer: Never store the password and never encrypt it. Store the output of a deliberately slow, salted password hash: Argon2id first choice, or scrypt or bcrypt. On login, hash the attempt with the stored salt and compare in constant time.

Why each piece matters:

  • Plain SHA-256 is wrong for passwords: it is built to be fast, so an attacker with a leaked table can try billions of guesses per second.
  • A salt is a random value per user, stored next to the hash. It makes identical passwords produce different hashes and defeats precomputed "rainbow tables".
  • A work factor (cost) makes every guess expensive; raise it as hardware improves.
  • A pepper is an optional extra secret kept outside the database.
  • Constant-time comparison avoids leaking how many leading bytes matched.
Node.js Salted scrypt password storage

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real PHP, Python or Java equivalents (password_hash, bcrypt, Spring's PasswordEncoder) do the salt and format handling for you. In an interview, say "I would use the framework's built-in password hasher" rather than hand-rolling the code above.

What is a JWT and what are its pitfalls?

A JSON Web Token is three Base64URL parts joined by dots: header.payload.signature. The header names the algorithm, the payload holds claims (sub, exp, roles), and the signature is a MAC or digital signature over the first two parts. The server can verify a token without a database lookup, which is why JWTs are popular for stateless APIs.

The points that earn credit:

  • A JWT is signed, not encrypted. Anyone can decode the payload, so never put secrets in it.
  • Always verify the signature and check exp, and pin the expected algorithm. Historic bugs accepted alg: none or let an attacker switch RS256 to HS256.
  • Revocation is hard. A stolen token works until it expires, so use short lifetimes plus refresh tokens, or keep a deny list.
  • Where to store it: localStorage is readable by any XSS; an HttpOnly, Secure, SameSite cookie is not readable by scripts.
  • Sessions with an opaque ID in a cookie are often simpler and easier to revoke. JWT is a trade-off, not an upgrade.
Node.js Build and verify an HS256 token by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What are the OWASP Top 10 issues you should know?

The OWASP Top 10 is a community-maintained list of the most common web application risks. The exact ranking changes between editions, so do not memorize numbers; know the themes: broken access control (users reaching data that is not theirs), cryptographic failures (weak or missing encryption, bad password storage), injection (SQL, command, template), insecure design, security misconfiguration (default passwords, debug mode on), vulnerable and outdated components, authentication failures, integrity failures (unsigned updates, untrusted deserialization), insufficient logging and monitoring, and server-side request forgery (SSRF).

A strong answer picks one and goes deep. Broken access control is a good choice: it is number one for a reason. The classic bug is an endpoint like GET /invoices/123 that checks you are logged in but not that invoice 123 is yours (an IDOR, insecure direct object reference). The fix is to authorize on the server for every object, on every request.

What is SQL injection and how do you prevent it?

Short answer: SQL injection happens when user input is glued into a query string, so the input can change the query's structure. The fix is parameterized queries (prepared statements): the SQL text and the values travel separately, so a value can never become code.

PHP
// Read-only: the vulnerable pattern and the fix (PHP PDO)
$bad  = $pdo->query("SELECT * FROM users WHERE name = '$name'");   // never

$stmt = $pdo->prepare('SELECT * FROM users WHERE name = ?');         // yes
$stmt->execute([$name]);

Escaping by hand is fragile; an ORM helps only if you do not drop into raw string-built SQL. Add least privilege (the app's database user cannot drop tables) as defense in depth. Table and column names cannot be parameters, so allow-list them.

The real database cannot run here, so this stand-in builds the query text both ways and shows what the database would receive:

Node.js String-built query vs parameterized query (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What is XSS and how do you stop it?

Cross-site scripting lets an attacker get their JavaScript to run on your page, with your page's privileges: reading the DOM, calling your API as the user, stealing tokens from localStorage. There are three flavors: stored (the script is saved, say in a comment), reflected (it is echoed from the URL) and DOM-based (client code writes untrusted data into the page with innerHTML).

The defenses, in order of importance:

  1. Escape output for its context (HTML text, attribute, URL, JavaScript). Template engines such as Blade {{ }}, React JSX and Jinja do this by default; the danger is the opt-out ({!! !!}, dangerouslySetInnerHTML, |safe).
  2. Prefer textContent over innerHTML. If you must render user HTML, sanitize it with a maintained library.
  3. Content-Security-Policy header as a second wall, blocking inline scripts and unknown origins.
  4. HttpOnly cookies so a script cannot read the session cookie.
Node.js Escaping output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What is CSRF and how do you stop it?

Cross-site request forgery tricks a logged-in user's browser into sending a request to your site, such as a hidden form on evil.example that posts to /transfer. The browser attaches your session cookie automatically, so the server cannot tell the request was not intended. The attacker cannot read the response; the harm is the state change.

Defenses: a CSRF token (a secret per session that must be in the form or a header, which the attacker cannot guess), SameSite=Lax or Strict cookies (the browser does not send the cookie on most cross-site requests), checking the Origin header, and never changing state on GET. APIs that use a bearer token in an Authorization header are not affected, because the browser does not attach that header by itself.

Node.js A CSRF token check (stand-in server)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Quick answers for the follow-ups

  • HTTPS protects data in transit (confidentiality, integrity, server identity); it does not fix XSS or injection. See browser, HTTP and networking questions.
  • CORS relaxes the browser's same-origin policy for reading responses; it is not an authentication or CSRF defense.
  • Rate limiting and lockouts slow down credential stuffing; add multi-factor authentication for important accounts.
  • Secrets belong in environment variables or a secrets manager, never in the repository.
  • Least privilege everywhere: database users, API keys, cloud roles.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A teammate wants to store user passwords encrypted with AES so support can recover them. What is the best response?

    Passwords should never be recoverable. A salted, deliberately slow hash lets you verify logins while making leaked data expensive to crack. Plain SHA-256 is too fast, and Base64 is not protection at all.
  2. 2. What does the signature in a JWT guarantee?

    A signature provides integrity and origin, not secrecy: the payload is only Base64URL-encoded and readable by anyone. Revocation needs extra machinery.
  3. 3. Which change fixes SQL injection at its root?

    Parameterized queries keep data and code apart. Blacklisting characters is fragile, and hiding errors only hides symptoms.
  4. 4. Why does a CSRF attack work against cookie-based sessions?

    The attacker never sees the cookie; the browser sends it for them. CSRF tokens and SameSite cookies stop the forged request from being accepted.
  5. 5. Which is the most direct defense against stored XSS in a comment section?

    XSS is about untrusted data being interpreted as markup or script. Output escaping (plus CSP as backup) neutralizes it; CSRF tokens address a different attack.

Summary

  • Hashing is one-way, encryption is two-way with a key, signing proves integrity and origin, and Base64 is only an encoding.
  • Store passwords with a salted, slow hash (Argon2id, scrypt, bcrypt) and compare in constant time.
  • A JWT is signed, not secret: verify signature, algorithm and expiry, and keep lifetimes short.
  • Stop SQL injection with parameterized queries, XSS with context-aware output escaping and CSP, CSRF with tokens and SameSite cookies.
  • Broken access control (IDOR) is the most common real-world flaw: authorize every object on the server.

Next: Git and Linux Interview Questions.