At login, the server takes the user's stored salt, hashes it with the typed password and compares with the stored hash.
What to build
Check login attempts against a table of salted hashes.
Requirements
- FNV-1a 32-bit: start at 2166136261; for each character, XOR the hash with the character code, then multiply by 16777619 keeping 32 bits (
Math.imul(hash, 16777619) >>> 0). Print it as 8 lower-case hex digits. - Line 1 is N. The next N lines are
name salt hash. - Each remaining line is an attempt
name password. - Print
welcome nameif the user exists and fnv1a(salt + password) matches, otherwisewrong name or password(the same message whether the name or the password was wrong).
Input
As described.
Output
One line per attempt.
Constraints
Up to 50 users and 50 attempts. Names, salts and passwords have no spaces.
Example
Input:
2
rahim q7Lp f77e9c1c
anika Z2xe d4d27d19
rahim dhaka2024
rahim dhaka2025
Output:
welcome rahim
wrong name or password
Why it works
Hashing the typed password with the same salt reproduces the stored value exactly when the password is right, and one message for both kinds of failure tells an attacker nothing about which names exist.
Examples
Example 1 · Input
2 rahim q7Lp f77e9c1c anika Z2xe d4d27d19 rahim dhaka2024 rahim dhaka2025
Expected output
welcome rahim wrong name or password
Example 2 · Input
1 babul s1 7f1277fc nobody pass babul pass
Expected output
wrong name or password welcome babul
Hints
Hint 1
Keep the users in an object keyed by name.
Hint 2
Check that the user exists before using their salt.
Solution
Show one correct solution (try it yourself first)
function fnv1a(text) {
let hash = 2166136261;
for (let k = 0; k < text.length; k++) {
hash = hash ^ text.charCodeAt(k);
hash = Math.imul(hash, 16777619) >>> 0;
}
return hash.toString(16).padStart(8, "0");
}
const n = Number(prompt());
const users = {};
for (let k = 0; k < n; k++) {
const [name, salt, hash] = prompt().trim().split(/\s+/);
users[name] = { salt, hash };
}
let line = prompt();
while (line !== null) {
const [name, password] = line.trim().split(/\s+/);
const u = Object.prototype.hasOwnProperty.call(users, name) ? users[name] : null;
console.log(u && fnv1a(u.salt + password) === u.hash ? `welcome ${name}` : "wrong name or password");
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step