How to use this file
Answer each question aloud in 30–90 seconds. For scenario questions, state the threat, the control, why it works, the trade-off, and how you would monitor or recover from failure. For deeper explanation, see 2. Security Fundamentals - System Design, Theory and Java..
1. Core security vocabulary
Q: Explain confidentiality, integrity, authenticity, authorization, and availability.
Answer
- Confidentiality: only authorized parties can read the data.
- Integrity: unauthorized changes are prevented or detected.
- Authenticity: verify the identity/source of a message or peer.
- Authorization: decide whether an authenticated identity may perform a specific action on a resource.
- Availability: legitimate users can access the service when needed.
Interview framing
TLS helps confidentiality/integrity in transit; authentication identifies the caller; authorization protects each action/resource; resilience controls availability.
Q: What is threat modeling? How would you start?
Answer
Identify assets, actors, entry points, trust boundaries, data flows, and likely abuse cases. Use STRIDE as a checklist: spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege. Prioritize risks by likelihood and impact, then assign preventive, detective, and recovery controls.
2. Hashing, MD5, SHA, and HMAC
Q: What is a cryptographic hash, and what properties should it have?
Answer
A deterministic one-way function maps arbitrary-length input to a fixed-size digest. Important properties are preimage resistance, second-preimage resistance, and collision resistance. Hashing is not encryption and has no decryption key. [!TIP]- Example SHA-256 can fingerprint a file. To establish authenticity, the expected digest must come from a trusted source, or use a MAC/signature.
Q: Why is MD5 considered insecure? Is SHA-256 a direct replacement in every case?
Answer
MD5 produces a 128-bit digest and practical collision attacks make it unsuitable for security-sensitive integrity, signatures, or certificates. SHA-256 is a modern general-purpose digest, but replacement must respect the protocol and compatibility needs. For keyed integrity use HMAC; for password storage use an adaptive password-hashing function. [!WARNING]- Pitfall “MD5 is broken” does not mean every legacy checksum is exploitable in the same way. Understand whether an attacker controls both the content and checksum.
Q: Compare MD5, SHA-1, SHA-256, and SHA-3.
Answer
MD5 is 128-bit and collision-broken for adversarial uses. SHA-1 is 160-bit and no longer appropriate for new collision-resistant security uses. SHA-256 is part of SHA-2 and widely used. SHA-3 is a separate Keccak-based construction standardized as an alternative design. Use current policy rather than choosing by output size alone.
Q: If SHA-256 is strong, why not store
SHA256(password)?Answer
SHA-256 is intentionally fast, so stolen password hashes can be attacked with huge numbers of offline guesses. Use Argon2id, scrypt, bcrypt, or PBKDF2 with unique salts and tuned work factors. Password hashes should be slow/adaptive; ordinary content hashes should generally be fast. [!TIP]- Related Security Fundamentals — System Design, Theory and Java > 5. Passwords: password encoder, salt, pepper, and work factor
Q: What is a salt? Is it secret?
Answer
A salt is a unique random value stored with each password hash. It prevents precomputed rainbow-table reuse and ensures equal passwords normally produce different stored outputs. It is not secret; the password and any optional pepper must remain protected.
Q: What is a pepper, and what are its trade-offs?
Answer
A pepper is an additional secret kept separately from the password database, ideally in a secrets manager or HSM-backed system. It can add defense in depth if only the database leaks, but creates key access, rotation, availability, and recovery requirements. It does not replace salt or an adaptive password hash.
Q: What is HMAC? How does it differ from SHA-256?
Answer
SHA-256 is an unkeyed digest; anyone can compute it. HMAC-SHA-256 combines a secret key with the hash construction, allowing parties that share the secret to verify message integrity and authenticity. HMAC is not encryption and does not provide non-repudiation because both parties share the key. [!WARNING]- Pitfall Request signing needs canonicalization and replay prevention, not just
HMAC(secret, body).
3. Password encoders and login security
Q: How should an application store passwords?
Answer
Never plaintext and normally not reversible encryption. Use a vetted adaptive password hashing implementation such as Argon2id; alternatives include scrypt, bcrypt, or PBKDF2 when appropriate. Generate a unique salt, tune cost parameters, store the encoded parameters with the result, and upgrade the hash after successful login when policy changes. Add rate limits and MFA/passkeys as appropriate.
Q: What does a password encoder do during registration and login?
Answer
At registration/reset,
encode(rawPassword)generates a salted adaptive hash and stores its encoded representation. At login,matches(candidate, storedHash)parses the stored parameters and checks the candidate without decrypting the stored value. Use framework-supported code such as Spring Security’sPasswordEncoder; don’t write your own.
Q: Why do we need rate limiting if passwords are hashed correctly?
Answer
Hashing makes offline guessing more expensive after database theft. Rate limiting, throttling, anomaly detection, MFA, and account protections limit online guessing and credential stuffing. Phishing and session theft need additional controls.
4. Symmetric encryption, AES, and key management
Q: Compare hashing and encryption.
Answer
Hashing is one-way and useful for fingerprints and as a component in other protocols. Encryption is reversible with a key and primarily protects confidentiality. AEAD encryption, such as AES-GCM, also protects ciphertext integrity/authenticity.
Q: What is AES? Why does mode of operation matter?
Answer
AES is a symmetric block cipher with a 128-bit block and 128/192/256-bit keys. A safe scheme requires a mode and correct parameters. Prefer authenticated encryption such as AES-GCM or ChaCha20-Poly1305. Avoid ECB and don’t invent an unauthenticated encryption construction.
Q: What is a nonce, and why is AES-GCM nonce reuse dangerous?
Answer
A nonce is a value used once under the relevant key according to the algorithm’s requirements. AES-GCM requires nonce uniqueness for each encryption under the same key; reuse can undermine confidentiality and authentication severely. Design nonce generation and key rotation for scale, not just a single unit test.
Q: Explain envelope encryption.
Answer
A data encryption key (DEK) encrypts the payload. A key-encryption key or managed KMS key wraps the DEK. Store ciphertext, wrapped DEK, and key metadata. Authorized readers ask KMS to unwrap the DEK and then decrypt the data. This separates data encryption from key governance and supports centralized access control/audit.
Q: What does encryption at rest not protect against?
Answer
It does not necessarily protect data from an application or identity authorized to decrypt it, nor from data leaked in logs or API responses. Add least privilege, tenant-level authorization, key access controls, monitoring, retention controls, and secure backups.
5. RSA, signatures, and public-key cryptography
Q: Explain RSA and its common use cases.
Answer
RSA uses a public/private key pair based on the practical difficulty of factoring a large composite number. Depending on the scheme, it can support encryption/key transport or digital signatures. Use standardized padding: RSA-OAEP for RSA encryption where needed and RSA-PSS for new RSA signatures where supported. Follow current key-size policy.
Q: Is signing the same as encrypting with a private key?
Answer
No. A digital signature is a defined scheme that signs a message or its digest with a private key; the public key verifies it. It provides integrity and evidence that the signer controlled the private key, assuming the key is bound to a trusted identity. It does not make the message confidential.
Q: Why not encrypt a large file directly with RSA?
Answer
RSA is slower and can only process inputs limited by key size and padding overhead. Use hybrid encryption: encrypt the file with a random symmetric AEAD key, then wrap that key using a recipient public key or KMS. Store nonce, ciphertext/tag, wrapped key, and key ID.
Q: What is the difference between symmetric and asymmetric cryptography?
Answer
Symmetric crypto uses a shared secret key and is efficient for bulk data. Asymmetric crypto uses related public/private keys and helps with signatures, identity, and key establishment. Modern protocols combine them rather than choosing only one.
6. PKI, certificates, and TLS
Q: What is PKI, and what does a TLS certificate prove?
Answer
PKI uses certificate authorities and trust anchors to bind identities to public keys. A TLS client validates the certificate chain, validity, hostname/SAN, and usage under its trust policy. A certificate is not the private key; it carries identity and public-key information.
Q: Explain the TLS handshake at a high level.
Answer
The client and server negotiate protocol parameters and key agreement, the server proves possession of the private key associated with its certificate, the client validates the certificate/hostname, and both derive traffic keys and verify the handshake. Application data is then protected by symmetric authenticated encryption. TLS 1.3 differs in details from TLS 1.2.
Q: What is the difference between SSL, TLS, and HTTPS?
Answer
SSL is the obsolete predecessor to TLS. Modern systems should use policy-approved TLS versions, commonly TLS 1.2 or 1.3. HTTPS is HTTP carried over TLS. Don’t enable obsolete SSL protocols to support old clients without a deliberate risk decision.
Q: What is mutual TLS (mTLS)?
Answer
In ordinary server-authenticated TLS, the client validates the server. In mTLS, the client also presents a certificate and the server validates it, enabling certificate-based client/workload identity. mTLS does not automatically decide which business actions that workload may perform; authorization is still required.
Q: A certificate expires in production. What do you do?
Answer
Renew/replace it through the managed certificate lifecycle, validate the chain and hostname, verify deployment across every instance/load balancer, and monitor expiry ahead of time. Do not disable certificate validation. Investigate why alerting/automated rotation failed and test rollback safely.
Q: What is a truststore versus a keystore in Java?
Answer
A keystore can hold private keys and associated certificates; a truststore holds certificates/anchors trusted when validating peers. Exact contents depend on deployment. Java JSSE uses key/trust manager configuration via
SSLContext. Protect private keys and never bypass normal certificate/hostname validation.
7. Authentication, JWT, OAuth 2.0, and OIDC
Q: Authentication versus authorization?
Answer
Authentication establishes who the caller is. Authorization checks whether that identity can perform a specific action on a specific resource. A valid login or token is not permission to access every record.
Q: Is a JWT encrypted?
Answer
Not necessarily. A common signed JWT (JWS) is Base64URL-encoded and readable; its signature protects integrity, not secrecy. Encrypted JWTs (JWE) are a different format. Don’t place secrets in a normal signed token.
Q: What must an API validate in a JWT?
Answer
Verify the signature using a trusted key and explicit algorithm allowlist; validate issuer, audience, expiration, and not-before if used; enforce scopes/roles and resource-level policy. Plan key rotation, token lifetime, revocation strategy, and safe token storage. Do not trust arbitrary token-provided algorithms or key URLs.
Q: OAuth 2.0 versus OpenID Connect?
Answer
OAuth 2.0 is primarily an authorization/delegation framework. OpenID Connect adds an identity layer, including ID tokens and standardized user identity claims. Use Authorization Code with PKCE for suitable user-facing clients; select flows based on client type and current security guidance.
Q: JWT or server-side session?
Answer
Neither is universally better. Server-side sessions simplify centralized revocation but need shared/session storage and scaling decisions. Self-contained tokens can help distributed validation but complicate revocation and claim freshness. Decide based on clients, trust boundaries, lifecycle, and operational needs; use secure cookies or token storage appropriate to the client.
Q: What is CSRF, and how is it different from XSS?
Answer
CSRF tricks a browser into sending an authenticated request, often because cookies are automatically attached. Use appropriate SameSite cookies, anti-CSRF tokens or origin checks, and safe methods. XSS injects executable script into a trusted origin; use output encoding, safe templating, CSP as defense in depth, and avoid unsafe DOM operations. XSS can undermine some client-side CSRF defenses.
8. REST and API security
Q: How would you secure a REST API?
Answer
Use TLS, suitable authentication, per-action/resource authorization, input validation, parameterized database access, rate limits/timeouts/body limits, safe CORS, secure session/CSRF controls for browser cookies, dependency and secret scanning, and safe audit logging. Address BOLA/IDOR, injection, SSRF, mass assignment, and sensitive data exposure.
Q: What is BOLA/IDOR? How do you prevent it?
Answer
Broken Object Level Authorization occurs when a caller can access or modify an object by changing its identifier. Authenticate the caller, then enforce ownership/tenant/policy checks for the requested object on every relevant operation. UUIDs are not authorization.
Q: Is CORS a security boundary for an API?
Answer
No. CORS is primarily a browser-enforced cross-origin policy. Non-browser clients can call an API directly. The server still needs authentication, authorization, validation, and rate limiting.
Q: How do you secure file uploads?
Answer
Enforce size/type limits, don’t trust filenames or client MIME types, use safe generated storage names, prevent path traversal, store outside executable/public paths, scan or sandbox content as appropriate, quarantine before processing, restrict parser privileges, and audit access. Encrypt storage and use short-lived authorized download links where suitable.
9. Java security implementation
Q: Which Java APIs map to common cryptographic tasks?
Answer
MessageDigestfor hashes,Macfor HMAC,Cipherfor encryption,Signaturefor signatures,KeyGeneratorandKeyPairGeneratorfor keys,SecureRandomfor cryptographic randomness,KeyStorefor keys/certificates, and JSSE (SSLContext, key/trust managers) for TLS. Prefer vetted libraries for password hashing.
Q: Why should we not implement our own cryptography?
Answer
Secure crypto depends on subtle algorithms, encodings, nonce/key lifecycle, constant-time behavior, protocol composition, and error handling. Use standardized primitives through vetted libraries, follow current recommendations, and focus engineering effort on correct configuration, access control, and key management.
Q: What are common Java security mistakes?
Answer
Hardcoded secrets; weak crypto or modes; trusting all TLS certificates; unsafe deserialization; SQL concatenation; path traversal; logging credentials; verbose client errors; missing object-level authorization; outdated dependencies; and catching crypto failures then continuing with insecure defaults.
10. Kafka and event-driven system security
Q: How do you secure Kafka?
Answer
Encrypt client and inter-broker traffic with TLS; authenticate clients with an appropriate mechanism such as mTLS, SASL/SCRAM, or OAuth-based authentication; authorize principals using ACLs or the configured authorizer; restrict topic, group, and admin operations; apply quotas; protect credentials; and monitor access. Encrypt disks/backups separately and minimize sensitive event payloads.
Q: What is the difference between TLS, SASL, and ACLs in Kafka?
Answer
TLS protects transport and validates peers. SASL is a framework for client authentication mechanisms. ACLs/authorizer enforce what an authenticated principal can do. They solve different problems and are usually configured together.
Q: Does Kafka encryption at rest mean messages are safe?
Answer
It protects broker storage media/snapshots under the relevant threat model, but authorized consumers can still read message payloads. Use ACLs, least privilege, retention controls, payload minimization, secure backups, and application-level field encryption where warranted.
Q: How would you rotate a Kafka credential without downtime?
Answer
Use a staged rotation supported by the chosen mechanism: provision the new credential/certificate, allow it in broker/client policy, roll clients gradually, verify authentication and consumer-group operation, then revoke the old credential. Automate expiry monitoring and test rollback. Exact steps depend on SASL mechanism or certificate infrastructure.
11. Architect-level scenarios
Q: Design security for an e-commerce system with browser, API, database, and Kafka.
Answer
Start with assets and trust boundaries. Use HTTPS/TLS at the edge, OIDC/session authentication, strict object-level authorization, input validation, rate limiting, and safe error handling at the API. Use least-privilege workload identities and secrets management. Encrypt database, object storage, backups, and Kafka transport; configure Kafka authentication and topic/group ACLs. Centralize audit logs and alerts while redacting secrets. Include key/certificate rotation, incident response, and recovery testing. [!TIP]- Structure your answer Threat → control → why it works → trade-off → monitoring/recovery.
Q: A database snapshot is stolen. What protects the data?
Answer
Encryption at rest with keys stored separately can make the snapshot unreadable without key access. Also restrict snapshot creation/export and KMS permissions, audit key use, encrypt backups, and minimize stored sensitive data. If the attacker also obtained usable KMS permissions or plaintext exports, the risk changes; encryption is not a complete access-control strategy.
Q: A service's JWT signature validates, but a user can see another tenant's invoice. What failed?
Answer
Authentication/token integrity may be working, but authorization is broken. Enforce tenant and object ownership checks for every read/write, derive tenant identity from trusted claims/context, and avoid trusting client-supplied tenant IDs. Add negative tests for cross-tenant access.
Q: A team says internal traffic doesn't need TLS because it is inside a VPC. How do you respond?
Answer
A private network is a useful layer, not a complete trust boundary. Misconfiguration, compromised workloads, lateral movement, shared infrastructure, and accidental exposure remain possible. Use TLS/mTLS where the threat model, compliance, or platform architecture requires it, alongside identity and authorization. Balance the control against latency, certificate lifecycle, and operational complexity.
Q: How would you respond to a suspected leaked signing key?
Answer
Treat it as an incident: contain access, identify affected systems and time window, rotate/revoke the key, reject tokens/signatures from the compromised key where possible, assess forged artifacts, preserve audit evidence, notify stakeholders per policy, and verify all dependent services have the new trusted key set. Rotation alone does not invalidate artifacts unless verifiers stop trusting the old key.
Q: What is the difference between encryption in transit, at rest, and in use?
Answer
In transit protects data crossing a network; at rest protects stored media and backups; in use concerns data being processed in memory. TLS handles transport, storage encryption/KMS handles stored data, and isolation/least privilege/memory protections help during processing. Traditional encryption generally requires plaintext for normal computation.
Q: What security controls would you add to a file-processing pipeline?
Answer
Authenticate uploader, authorize destination/tenant, limit size and file types, generate safe filenames, quarantine and scan uploads, parse in a restricted worker, validate schema, protect temporary files, encrypt storage and transfer, use least-privilege S3/object-store roles, avoid logging contents or credentials, and audit lifecycle actions. Add retries, idempotency, malware-response handling, and retention/deletion policy.
12. Quick decision table
| Requirement | Prefer | Do not confuse it with |
|---|---|---|
| Fingerprint bytes | SHA-256 / SHA-3 | Authentication |
| Integrity with shared secret | HMAC-SHA-256 | Encryption |
| Store user passwords | Argon2id / scrypt / bcrypt / PBKDF2 | Fast SHA-256 |
| Encrypt application data | AES-GCM / ChaCha20-Poly1305 | RSA for bulk data |
| Sign a message | RSA-PSS / ECDSA / EdDSA according to policy | “Encrypt with private key” |
| Protect network traffic | TLS | API authorization |
| Bind DNS identity to public key | X.509 certificate + PKI trust | Certificate alone without validation |
| Delegate authorization | OAuth 2.0 | OIDC identity by itself |
| Standard user identity layer | OpenID Connect | Raw JWT alone |
| Protect Kafka transport | TLS | Topic authorization |
| Authenticate Kafka client | SASL/mTLS/OAuth mechanism | ACLs |
| Limit Kafka operations | ACLs/authorizer | Authentication |
| Protect data keys | KMS/HSM + envelope encryption | Disk encryption alone |
13. Rapid-fire revision
Q: Can a hash be decrypted?
No. A hash is designed as a one-way digest. An attacker may guess candidate inputs and compare hashes, which is why password storage needs adaptive hashing.
Q: Does a salt need to be secret?
No. It should be unique and random for each password. A pepper, if used, is secret and stored separately.
Q: Does TLS prove that a user is authorized?
No. TLS protects the connection and may authenticate a peer; application authorization must still check permissions.
Q: Does a valid JWT signature mean its claims are safe to use?
Only after verifying with a trusted key and validating issuer, audience, time claims, allowed algorithms, and application-specific authorization policy.
Q: Is AES-256 always safer than AES-128 in practice?
Not automatically. Both are widely considered strong when correctly implemented. Mode, nonce discipline, key protection, configuration, and threat model often matter more than choosing 256 instead of 128 bits.
Q: Can you use RSA to sign and encrypt with the same key?
RSA supports distinct signature and encryption schemes, but key separation and policy matter. Do not reuse keys across purposes unless a well-defined standard and policy explicitly permit it.
Q: What is the biggest crypto implementation risk?
Often not breaking the algorithm, but misusing it: poor key management, nonce reuse, weak parameters, unsafe validation, custom protocols, or leaking plaintext/secrets elsewhere.