Cryptography interview questions and answers

Cryptography interview questions for engineers are about using primitives correctly, not inventing them: knowing hashing from encryption, picking an authenticated cipher mode, never reusing a nonce, storing passwords with a slow hash and managing keys. Fundamentals cover symmetric and asymmetric keys, hashes, MACs and signatures. Senior questions turn into design reviews, where you spot the misuse in someone's scheme and propose a safer one built from standard libraries.

By Published 8 min read

What cryptography interviews actually test

Outside research roles, nobody asks you to design a cipher. Backend, security, platform, payments and identity teams ask whether you can tell when cryptography is being misused, because most real failures come from wrong modes, reused nonces, fast password hashes, hard-coded keys and skipped verification. Expect short definition questions, a snippet to review, and a design question such as storing sensitive fields or signing webhooks.

  1. DefinitionsRapid questions on what each primitive guarantees. Precise words matter: confidentiality, integrity, authenticity, non-repudiation.
  2. Misuse reviewA snippet or a scheme with a flaw: ECB mode, a static IV, MD5 for passwords, == on a MAC. You name it and fix it.
  3. Protocol walk-throughExplain a TLS handshake, a JWT check or a key exchange step by step, and say what an attacker could do if one step were skipped.
  4. Design and operationsWhere keys live, who can use them, how they rotate and what happens when one leaks.

Cryptography fundamentals questions

Fundamentals for freshers and general backend rounds
QuestionWhat it testsWhat a strong answer shows
Encoding, hashing and encryption: what is the difference?VocabularyEncoding such as Base64 changes representation and anyone can reverse it. Hashing is one-way and fixed-length. Encryption is reversible only with a key. Calling Base64 "encryption" is a red flag.
Symmetric versus asymmetric encryption?Key modelsSymmetric uses one shared secret and is fast, as with AES. Asymmetric uses a public and private key pair, is slower, and solves key distribution and signatures.
Why do real systems combine both?HybridPublic-key cryptography agrees on or wraps a fresh symmetric key, and the symmetric cipher encrypts the bulk data. TLS and most file encryption tools work this way.
What three properties should a cryptographic hash have?Hash securityPreimage resistance (cannot find an input for a given hash), second preimage resistance (cannot find another input with the same hash as a given one) and collision resistance (cannot find any two inputs that collide).
Why are MD5 and SHA-1 avoided?Broken primitivesPractical collisions exist for both, so they fail where collision resistance matters, such as signatures and certificates. Use SHA-256 or newer for general hashing.
MAC versus digital signature?AuthenticityA MAC uses a shared secret, so either party could have produced it. A signature uses a private key that only the signer holds, so anyone with the public key can verify it and the signer cannot plausibly deny it.
What is a salt, and what is a pepper?PasswordsA salt is a unique random value per password, stored next to the hash, which defeats precomputed tables and hides identical passwords. A pepper is a secret kept outside the database, adding protection if only the database leaks.
Why not use Math.random() or rand() for tokens?RandomnessThose generators are predictable. Session IDs, reset tokens and keys need a cryptographically secure generator, such as crypto.randomBytes in Node or secrets in Python.
What is Kerckhoffs's principle?DesignA system should stay secure even if everything except the key is public. Security through a secret algorithm fails once the algorithm leaks.
Block cipher versus stream cipher?PrimitivesA block cipher transforms fixed-size blocks and needs a mode of operation to handle longer data. A stream cipher produces a keystream that is XORed with the data, as ChaCha20 does.
What does a certificate prove?PKIThat a certificate authority vouched for the binding between a public key and a name, for a period of time. Clients check the chain, the name, the dates and revocation where supported.
Fundamentals for freshers and general backend rounds. Scroll sideways on a small screen.

Intermediate: modes, nonces and integrity

Mid-level questions are mostly about how correct primitives get used incorrectly. Two failures come up constantly, and both are easy to show in a few lines.

import { createCipheriv, randomBytes } from "node:crypto";

// ECB encrypts equal blocks to equal ciphertext, so patterns leak
const key = randomBytes(16);
const block = Buffer.from("ATTACK AT DAWN!!");               // exactly 16 bytes
const ecb = createCipheriv("aes-128-ecb", key, null).setAutoPadding(false);
const out = Buffer.concat([ecb.update(Buffer.concat([block, block])), ecb.final()]);
console.log(out.subarray(0, 16).equals(out.subarray(16)));   // true: the repeat is visible

// CTR mode with a reused nonce: XOR of two ciphertexts equals XOR of the plaintexts
const iv = randomBytes(16);
const enc = (m) => createCipheriv("aes-128-ctr", key, iv).update(m);
const p1 = Buffer.from("PAY ALICE 100"), p2 = Buffer.from("PAY BOB   900");
const c1 = enc(p1), c2 = enc(p2);
const x = (a, b) => Buffer.from(a.map((v, i) => v ^ b[i]));
console.log(x(c1, c2).equals(x(p1, p2)));                    // true: keystream cancels out
Why ECB leaks patterns and why a reused CTR nonce leaks plaintext. Node with node:crypto; outputs are in the comments.
Intermediate questions on using primitives safely
QuestionWhat it testsWhat a strong answer shows
What is wrong with ECB mode?ModesIdentical plaintext blocks give identical ciphertext blocks, so structure shows through. It also offers no integrity. It should not be used for data.
CBC with a constant IV: what breaks?IVsTwo messages that start the same produce the same first ciphertext blocks, revealing shared prefixes. CBC needs an unpredictable IV per message, and it still needs a MAC.
What is a padding oracle?Unauthenticated decryptionIf a server reveals whether CBC padding was valid, through an error or timing, an attacker can decrypt ciphertext byte by byte. Authenticated encryption, checked before decrypting, removes the oracle.
What does AEAD mean, and what is associated data for?AEADAuthenticated encryption with associated data protects confidentiality and integrity together, as AES-GCM and ChaCha20-Poly1305 do. Associated data, such as a user ID or header, is authenticated but not encrypted, binding the ciphertext to its context.
Why is nonce reuse in GCM so serious?Nonce disciplineIt leaks the XOR of the plaintexts, as with CTR, and can let an attacker recover the authentication key and forge messages. Use a counter or random 96-bit nonces and rotate keys well before random nonces risk repeating.
Encrypt-then-MAC or MAC-then-encrypt?CompositionEncrypt-then-MAC: verify the tag over the ciphertext before decrypting anything. Better still, use an AEAD mode that does this for you.
What is a length extension attack?Hash misuseWith Merkle-Damgard hashes such as SHA-256, knowing hash(secret + message) lets an attacker compute the hash of that message with extra data appended, without the secret. HMAC is built to prevent it.
Why compare MACs in constant time?Side channelsA normal comparison returns at the first differing byte, and the timing difference can reveal how many bytes matched. Use a constant-time function such as timingSafeEqual or hmac.compare_digest.
PBKDF2, bcrypt, scrypt or Argon2?Password hashingAll are deliberately slow. Argon2id and scrypt are also memory-hard, which raises the cost of GPU attacks. Many guides favor Argon2id for new systems, with bcrypt or PBKDF2 acceptable where they are the supported option.
HKDF versus a password hash?KDFsHKDF derives several keys from one key that is already strong and random, and it is fast. Password hashes stretch weak, human-chosen secrets and are slow on purpose. Do not swap them.
Intermediate questions on using primitives safely. Scroll sideways on a small screen.
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";

// Hashing is not encryption, and Base64 is neither
console.log(Buffer.from("secret").toString("base64"));                 // c2VjcmV0 (anyone can decode it)
console.log(createHash("sha256").update("abc").digest("hex").slice(0, 16));   // ba7816bf8f01cfea

// Authenticated encryption with AES-256-GCM: fresh 12-byte nonce per message
const key = randomBytes(32);
function seal(plaintext, aad) {
  const iv = randomBytes(12);
  const c = createCipheriv("aes-256-gcm", key, iv);
  c.setAAD(aad);
  const ct = Buffer.concat([c.update(plaintext, "utf8"), c.final()]);
  return { iv, ct, tag: c.getAuthTag() };
}
function open({ iv, ct, tag }, aad) {
  const d = createDecipheriv("aes-256-gcm", key, iv);
  d.setAAD(aad);
  d.setAuthTag(tag);
  return Buffer.concat([d.update(ct), d.final()]).toString("utf8");   // throws if anything changed
}
const box = seal("transfer 100 to account 42", Buffer.from("user:7"));
console.log(open(box, Buffer.from("user:7")));    // transfer 100 to account 42
box.ct[0] ^= 1;                                    // flip one bit of the ciphertext
try { open(box, Buffer.from("user:7")); } catch { console.log("rejected: tag mismatch"); }

// Message authentication: HMAC, compared in constant time
const macKey = randomBytes(32);
const mac = (msg) => createHmac("sha256", macKey).update(msg).digest();
const sent = mac("order=991&amount=25");
console.log(timingSafeEqual(sent, mac("order=991&amount=25")));   // true
console.log(timingSafeEqual(sent, mac("order=991&amount=2500"))); // false

// Password storage: a slow, salted KDF (scrypt here), never a bare fast hash
function hashPassword(pw) {
  const salt = randomBytes(16);
  return { salt, hash: scryptSync(pw, salt, 32, { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }) };
}
function verify(pw, { salt, hash }) {
  return timingSafeEqual(hash, scryptSync(pw, salt, 32, { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }));
}
const stored = hashPassword("correct horse battery staple");
console.log(verify("correct horse battery staple", stored), verify("Tr0ub4dor&3", stored));   // true false
The correct versions: AES-256-GCM with associated data, an HMAC check in constant time, and salted scrypt for passwords. Node with node:crypto; outputs are in the comments.

Public keys, signatures and TLS

  • How does Diffie-Hellman let two parties agree on a key over an open channel? Each side combines its private value with the other's public value and both reach the same shared secret, which an eavesdropper cannot compute from the public values alone. On its own it does not authenticate either side, so signatures or certificates must be added to stop a man in the middle.
  • What is forward secrecy? Each session uses fresh, ephemeral key exchange values that are thrown away afterwards, so stealing the server's long-term private key later does not decrypt recorded sessions. Full TLS 1.3 handshakes always use ephemeral key exchange; only a pre-shared-key resumption mode can skip it.
  • Walk through a TLS 1.3 handshake at a high level. The client sends supported cipher suites and a key share. The server picks one, sends its key share, certificate and a signature over the handshake, and both derive session keys. That fits in one round trip, and the certificate itself is sent encrypted.
  • Why sign with RSA-PSS, ECDSA or Ed25519 rather than "encrypt with the private key"? Signatures are their own scheme with padding and hashing designed for the job. Describing them as encryption with a private key leads to unsafe homemade constructions.
  • What goes wrong if ECDSA reuses a nonce? Two signatures with the same per-signature nonce let anyone solve for the private key. Deterministic nonce generation or Ed25519, which derives the nonce from the key and message, avoids it.
  • What does certificate pinning protect against, and what does it cost? It rejects certificates that chain to a trusted CA but are not the expected key, which helps against a misissued certificate. It also makes key rotation risky, since a wrong pin locks clients out.
  • Name two classic JWT verification mistakes. Accepting alg: none, and letting the token's header pick the algorithm so an RSA public key gets used as an HMAC secret. Fix the expected algorithm and key on the server.

Senior and scenario questions

Key management, design reviews and long-term planning
QuestionWhat it testsWhat a strong answer shows
Design encryption for a column of national ID numbers.Field encryptionAEAD with a key from a key management service, the row ID as associated data, a key version stored with each value, and a separate keyed hash (HMAC) if the column must be searchable for exact matches.
What is envelope encryption?Key hierarchyData is encrypted with a data key, and the data key is encrypted with a master key that never leaves the KMS or HSM. Rotation re-wraps data keys instead of re-encrypting every record.
A developer committed an API signing key to a public repo. Steps?IncidentRevoke and replace the key first, then find what it signed or accessed since exposure, purge it from history, and add secret scanning so it is caught before push next time.
How do you rotate keys without downtime?OperationsStore a key ID with every ciphertext or signature, accept old and new keys for verification during a window, write only with the new key, re-encrypt lazily or in batches, then retire the old one.
Tokenization or encryption for card numbers?Trade-offTokenization replaces the value with a random reference stored in a separate vault, keeping the real data out of most systems. Encryption keeps data in place but means every system with the key is in scope.
What is the plan for quantum computers?Post-quantumLarge quantum computers would break RSA and elliptic-curve key exchange and signatures. NIST has standardized post-quantum algorithms such as ML-KEM, and hybrid key exchange is being deployed. Inventory where public-key crypto is used, prioritize data that must stay secret for years, and keep algorithms swappable.
Someone proposes their own encryption scheme. How do you respond?JudgmentAsk what problem a standard construction does not solve, point to reviewed libraries such as libsodium or the platform's crypto module, and ask for an external review if a custom protocol is truly needed.
Key management, design reviews and long-term planning. Scroll sideways on a small screen.

Fictional example

Design review answer: "We store passwords as SHA-256 hashes"
Interviewer
The login service stores sha256(password) for each user. Is that acceptable?
Candidate
No. SHA-256 is designed to be fast, so a leaked table can be attacked with billions of guesses on GPUs, and without a salt every user with the same password shares a hash. I would move to Argon2id or scrypt with a unique salt per user and parameters tuned so one check takes a noticeable fraction of a second on our servers, and compare results in constant time.
Interviewer
We cannot force every user to reset. How do you migrate?
Candidate
Two options. Wrap the existing hashes now: store argon2id(sha256(password)) with a version flag, so every record is protected today. Then, on each successful login, recompute a plain Argon2id hash from the password the user just typed and drop the wrapper. I would also check that passwords never reach logs, and add rate limiting on the login endpoint, since better hashing does not stop online guessing.

A ten-day cryptography study plan

  • Days 1 and 2: definitions. Write one precise sentence each for hash, MAC, signature, symmetric and asymmetric encryption, KDF and nonce.
  • Day 3: cipher modes. Reproduce the ECB and nonce-reuse demos, then explain why AEAD fixes both concerns.
  • Day 4: passwords. Compare PBKDF2, bcrypt, scrypt and Argon2id, and practice the migration answer above.
  • Day 5: MACs and side channels: HMAC, length extension and constant-time comparison.
  • Day 6: key exchange, forward secrecy and signatures, including the ECDSA nonce failure.
  • Day 7: TLS 1.3 and certificates. Draw the handshake and list what the client checks.
  • Day 8: key management: KMS, envelope encryption, rotation with key IDs and the leaked-key incident.
  • Days 9 and 10: mock design reviews: field encryption, webhook signing, JWT validation and a post-quantum inventory.

Cryptography rarely stands alone in a loop. Web risks around it are on OWASP interview questions, the transport it protects is on TCP/IP interview questions, and the full role is covered by security engineer interview questions.

Precise wording is what separates a strong crypto answer from a vague one, and you only notice the vague parts when you read them back. Natively is an AI interview assistant for Mac and Windows that can transcribe a mock design review on your computer and keep the transcript and notes, so you can see where you said "encrypted" when you meant "hashed". In practice it can read a snippet or a handshake diagram from a screenshot and suggest what is misused. With Pro or the free trial it can draw on your résumé and the job description you add.

Questions people ask

What cryptography questions are asked in software interviews?

The difference between encoding, hashing and encryption, symmetric versus asymmetric keys, MACs versus signatures, cipher modes such as ECB and GCM, nonce reuse, password hashing with Argon2id or bcrypt, forward secrecy, TLS and key rotation.

What is the difference between hashing and encryption?

Hashing is one-way and produces a fixed-length digest that cannot be turned back into the input. Encryption is reversible by anyone holding the right key.

How should passwords be stored, according to interviewers?

With a slow, salted password hashing function such as Argon2id, scrypt or bcrypt, compared in constant time, never with a fast hash such as SHA-256 or with reversible encryption.

Do I need to know the math for a cryptography interview?

For most engineering roles, no. You need to know what each primitive guarantees, how it is commonly misused and which standard library construction to choose. Research roles are the exception.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP