Password Hasher with Salt - Problem

Implement a secure password hashing system that protects user credentials from rainbow table attacks and brute force attempts. Your implementation must generate random salts, perform key stretching, and provide verification functionality.

Requirements:

  • Generate a cryptographically secure random salt for each password
  • Implement key stretching using multiple hash iterations to slow down brute force attacks
  • Combine salt and password before hashing to prevent rainbow table attacks
  • Provide a verification function to check if a password matches the stored hash

Function Signatures:

hashPassword(password: string, iterations: number) -> {salt: string, hash: string}
verifyPassword(password: string, salt: string, hash: string, iterations: number) -> boolean

Note: Use SHA-256 for hashing and ensure salt is at least 32 characters of random alphanumeric characters.

Input & Output

Example 1 — Hash Password
$ Input: password = "mySecret123", iterations = 1000, action = "hash"
Output: {"salt":"aB3kL9mX4pR7sT2wQ8vN5yE1jH6uI0oP","hash":"7f3e9a2b8c4d1f6e5a7b3c2d8f4e1a9b"}
💡 Note: Generate 32-character random salt, combine with password, apply SHA-256 1000 times. Salt and final hash are returned for secure storage.
Example 2 — Verify Password
$ Input: password = "mySecret123", iterations = 1000, action = "verify"
Output: {"verified":true}
💡 Note: Use stored salt to recreate hash process, compare with stored hash. Returns true if password matches original.
Example 3 — High Security
$ Input: password = "admin2024!", iterations = 5000, action = "hash"
Output: {"salt":"X9mK2pR5sT8wQ1vN4yE7jH0uI3oP6lB","hash":"2c8f1e6a9b4d7f3e5a2b8c1d4f7e0a3b"}
💡 Note: Higher iteration count (5000) provides stronger protection against brute force attacks, taking more computational time per attempt.

Constraints

  • 1 ≤ password.length ≤ 1000
  • 100 ≤ iterations ≤ 10000
  • action ∈ {"hash", "verify"}
  • Salt must be exactly 32 alphanumeric characters

Visualization

Tap to expand
INPUTALGORITHMRESULTmySecret123Password to Hash1000IterationshashAction1Generate Random Salt32 alphanumeric characters2Combine Salt + PasswordaB3kL9mX...mySecret1233Apply SHA-256 HashIteratively 1000 times4Return Salt & HashFor secure storageSaltaB3kL9mX4pR7sT2w...Unique per passwordHash7f3e9a2b8c4d1f6e...After key stretching✓ SECURERainbow table resistantBrute force protectedKey Insight:Random salts make each password unique while key stretching makes brute force attacks computationally expensive, providing comprehensive protection against modern attack methods.TutorialsPoint - Password Hasher with Salt | Secure Implementation
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen