-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
240 lines (225 loc) · 8.78 KB
/
client.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/* ==================== PUBLIC ==================== */
/* The client and the server argree on the N, g, k and hash function */
/**
* Calculates the SHA-256 hash of a list of input arguments and returns it as a BigInt.
*
* @async
* @function
* @param {...*} args - A list of input arguments to be hashed.
* @returns {Promise<bigint>} - A Promise that resolves with the hash value as a BigInt.
*
* @example
* // Compute the hash of two strings concatenated with a colon separator.
* const result = await hash("foo", "bar");
* console.log(result); // 11957105143829254782066542462259017570009661597943739313019092793691976235973n
*/
const hash = async (...args) => {
const text = args.join(":");
const buffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
const hashString = Array.from(new Uint8Array(buffer))
.map(byte => byte.toString(16).padStart(2, '0'))
.join("");
return BigInt(`0x${hashString}`);
};
/**
* Generates a cryptographically secure salt of the specified length and returns it as a BigInt.
*
* @function
* @param {number} length - The length of the salt in bytes.
* @returns {bigint} - The salt value as a BigInt.
*
* @example
* // Generate a salt with 16 bytes of randomness.
* const salt = generateSalt(16);
* console.log(salt); // 133031290157045872024582203984
*/
const generateSalt = (length) => {
const saltBytes = new Uint8Array(length);
crypto.getRandomValues(saltBytes);
const saltString = Array.from(saltBytes)
.map(byte => byte.toString(16).padStart(2, '0'))
.join("");
return BigInt(`0x${saltString}`);
};
/**
* Computes the value of a BigInt raised to a power modulo a modulus.
* More to see https://en.wikipedia.org/wiki/Modular_exponentiation
*
* @param {BigInt} num - The base value.
* @param {BigInt} power - The exponent.
* @param {BigInt} modulus - The modulus value.
* @returns {BigInt} The value of `num` raised to the `power` modulo `modulus`.
*/
const bigIntExponentiation = (num, power, modulus) => {
let result = 1n;
num = num % modulus;
while (power > 0n) {
if (power % 2n === 1n) {
result = (result * num) % modulus;
}
power = power >> 1n;
num = (num * num) % modulus;
}
return result;
};
/* Generated by "openssl dhparam -text 2048" */
const dhparam = `\
00:aa:d9:ea:e2:b5:3d:86:fb:88:51:99:ea:cf:14:\
cd:65:f9:86:25:1e:e9:f9:42:e5:97:14:6c:49:dc:\
4c:38:e8:4c:44:24:df:f9:0f:c2:8e:cd:66:11:37:\
95:df:fe:53:a6:c5:50:1f:61:8b:fd:e8:9c:17:4d:\
84:6b:08:6d:29:76:39:79:fc:91:ea:c2:af:ad:b5:\
11:ab:de:3d:7b:d6:7f:31:8c:dc:29:2e:9a:39:6a:\
6c:cf:5f:6c:24:0c:10:21:92:8b:85:5b:67:f0:ae:\
62:93:2d:eb:75:a6:bc:f7:0c:71:8c:cd:96:0d:53:\
58:e3:7b:76:71:a9:8b:2a:93`;
/* A large safe prime */
const N = BigInt(`0x${dhparam.trim().split(":").join("")}`);
/* A generator modulo N */
const g = 2n;
/* Multiplier parameter */
const k = await hash(N, g);
console.log("==================== PUBLIC ====================");
console.log("N:", N);
console.log("g:", g);
console.log("k:", k);
console.log("================================================");
/* ==================== PARTICULAR ==================== */
const readUsernamePassword = () => ({
username: unInput ? unInput.value : "",
password: pwInput ? pwInput.value : ""
});
const unInput = document.getElementById("un-input");
const pwInput = document.getElementById("pw-input");
document.getElementById("login-btn").addEventListener("click", (e) => {
e.preventDefault();
console.log("==================== LOGIN =====================");
/* username and password */
const { username, password } = readUsernamePassword();
if (username.length === 0 || password.length === 0) {
return;
}
const I = username;
const p = password;
/* just a copy of the public ephemeral values A and B */
let _A = 0n, _B = 0n;
/* just a copy of the secret ephemeral values */
let _a = 0n;
/* just a copy of the user salt s */
let _s = "";
/* just a copy of the random scrambling parameter u */
let _u = 0n;
/* just a copy of the hash of session key K */
let _K = 0n;
const socket = new WebSocket("ws://localhost:9090/login");
socket.addEventListener("message", async (event) => {
/* serial indicates which step is doing now */
let { serial, data } = JSON.parse(event.data);
switch (serial) {
case 1:
/* Step 1: The client sends username I and public ephemeral value A to the server */
/* secret ephemeral values a */
const a = generateSalt(32) % N; _a = a;
/* public ephemeral values A */
const A = bigIntExponentiation(g, a, N); _A = A;
socket.send(JSON.stringify({
serial: serial + 1,
data: { I, A: A.toString(16) }
}));
console.log(`I(username): ${I}\na(secret ephemeral values): ${_a}\nA(public ephemeral values): ${_A}`);
break;
case 3:
/* Step 3: The client and server calculate the random scrambling parameter */
/* notify the server to calculate at the same time */
socket.send(JSON.stringify({ serial }));
const { s, B } = data; _s = BigInt(`0x${s}`); _B = BigInt(`0x${B}`);
console.log(`s(user salt): ${_s}\nB(public ephemeral values): ${_B}`);
if (_B % N === 0) {
/* The user will abort if he receives B == 0 (mod N) or u == 0. */
socket.close();
return;
}
/* random scrambling parameter */
const u = await hash(_A, _B); _u = u;
console.log(`u(random scrambling parameter): ${_u}`);
if (u === 0n) {
/* The user will abort if he receives B == 0 (mod N) or u == 0. */
socket.close();
return;
}
break;
case 4:
/* Step 4: The client computes session key */
/* private key (derived from p and s) */
const x = await hash(_s, p);
/* session key */
const S = bigIntExponentiation(_B - k * bigIntExponentiation(g, x, N), _a + _u * x, N);
/* hash of session key */
const K = await hash(S); _K = K;
console.log(`x(private key): ${x}\nS(session key): ${S}\nK(hash of session key): ${_K}`);
socket.send(JSON.stringify({ serial: serial + 1 }));
break;
case 6:
/* Step 6: The client sends proof of session key to server */
/* client M */
const C_M = await hash(
await hash(N) ^ await hash(g),
await hash(I), _s, _A, _B, _K
);
console.log(`C_M(client M): ${C_M}`);
socket.send(JSON.stringify({
serial: serial + 1,
data: { C_M: C_M.toString(16) }
}));
break;
default:
console.log("unexpected error:", data.error);
}
});
socket.addEventListener("close", (event) => {
const { status } = JSON.parse(event.reason);
if (status === 200) {
alert("login success");
}
else {
alert("login fail");
}
console.log("================================================");
});
socket.addEventListener("error", (error) => {
console.log("websocket error:", error.message);
});
});
document.getElementById("register-btn").addEventListener("click", async (e) => {
e.preventDefault();
/* username and password */
const { username, password } = readUsernamePassword();
if (username.length === 0 || password.length === 0) {
return;
}
const I = username;
const p = password;
/* random salt */
const s = generateSalt(32) % N;
/* private key */
const x = await hash(s, password);
/* password verifier */
const v = bigIntExponentiation(g, x, N);
console.log("=================== REGISTER ===================");
console.log(`I(username): ${I}\np(password): ${p}\ns(random salt): ${s}\nx(private key): ${x}\nv(password verifier): ${v}`);
console.log("================================================");
fetch("/register", {
method: "post",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify({ I, s: s.toString(16), v: v.toString(16) })
})
.then(result => result.text())
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
});