-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashing_algo.js
95 lines (81 loc) · 2.7 KB
/
hashing_algo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Array to store user credentials
let users = [];
// Function to generate a random salt
function generate_Salt (length = 16) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
let salt = '';
for (let i = 0; i < length; i++) {
salt += chars.charAt(Math.floor(Math.random() * chars.length));
}
return salt;
}
// Function to generate a hash with salt
function generate_Hash (password, salt) {
const combinedString = password + salt;
let hash = 0;
for (let i = 0; i < combinedString.length; i++) {
const char = combinedString.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash;
}
// Function to handle sign up
function signUp(username, password) {
// Check if username already exists
if (users.some(user => user.username === username)) {
return "Username already exists!";
}
// Generate salt and hash password
const salt = generate_Salt();
const hashedPassword = generate_Hash(password, salt);
// Store username, hashed password, and salt
users.push({
username: username,
password: hashedPassword,
salt: salt
});
return "Sign up successful!";
}
// Function to handle login
function login(username, password) {
// Find user in array
const user = users.find(user => user.username === username);
if (!user) {
return "User not found!";
}
// Compare hashed passwords using the stored salt
const hashedPassword = generate_Hash(password, user.salt);
if (user.password === hashedPassword) {
return "Login successful!";
} else {
return "Incorrect password!";
}
}
// Main function to handle user interaction
function main() {
while (true) {
const choice = prompt("Enter 1 for Sign Up, 2 for Login, or 3 to Exit:");
if (choice === '3') {
console.log("Goodbye!");
break;
}
const username = prompt("Enter username:");
const password = prompt("Enter password:");
if (choice === '1') {
const result = signUp(username, password);
console.log(result);
// Display users array without showing actual passwords
console.log("Current users:", users.map(user => ({
username: user.username,
salt: user.salt
})));
} else if (choice === '2') {
const result = login(username, password);
console.log(result);
} else {
console.log("Invalid choice!");
}
}
}
main();