-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
argon2.js
366 lines (350 loc) · 11.7 KB
/
argon2.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.argon2 = factory();
}
})(typeof self !== 'undefined' ? self : this, function () {
const global = typeof self !== 'undefined' ? self : this;
/**
* @enum
*/
const ArgonType = {
Argon2d: 0,
Argon2i: 1,
Argon2id: 2,
};
function loadModule(mem) {
if (loadModule._promise) {
return loadModule._promise;
}
if (loadModule._module) {
return Promise.resolve(loadModule._module);
}
let promise;
if (
global.process &&
global.process.versions &&
global.process.versions.node
) {
promise = loadWasmModule().then(
(Module) =>
new Promise((resolve) => {
Module.postRun = () => resolve(Module);
})
);
} else {
promise = loadWasmBinary().then((wasmBinary) => {
const wasmMemory = mem ? createWasmMemory(mem) : undefined;
return initWasm(wasmBinary, wasmMemory);
});
}
loadModule._promise = promise;
return promise.then((Module) => {
loadModule._module = Module;
delete loadModule._promise;
return Module;
});
}
function initWasm(wasmBinary, wasmMemory) {
return new Promise((resolve) => {
global.Module = {
wasmBinary,
wasmMemory,
postRun() {
resolve(Module);
},
};
return loadWasmModule();
});
}
function loadWasmModule() {
if (global.loadArgon2WasmModule) {
return global.loadArgon2WasmModule();
}
if (typeof require === 'function') {
return Promise.resolve(require('../dist/argon2.js'));
}
return import('../dist/argon2.js');
}
function loadWasmBinary() {
if (global.loadArgon2WasmBinary) {
return global.loadArgon2WasmBinary();
}
if (typeof require === 'function') {
return Promise.resolve(require('../dist/argon2.wasm')).then(
(wasmModule) => {
return decodeWasmBinary(wasmModule);
}
);
}
const wasmPath =
global.argon2WasmPath ||
'node_modules/argon2-browser/dist/argon2.wasm';
return fetch(wasmPath)
.then((response) => response.arrayBuffer())
.then((ab) => new Uint8Array(ab));
}
function decodeWasmBinary(base64) {
if (typeof Buffer === 'function') {
return new Uint8Array(Buffer.from(base64, 'base64'));
}
const text = atob(base64);
const binary = new Uint8Array(new ArrayBuffer(text.length));
for (let i = 0; i < text.length; i++) {
binary[i] = text.charCodeAt(i);
}
return binary;
}
function createWasmMemory(mem) {
const KB = 1024;
const MB = 1024 * KB;
const GB = 1024 * MB;
const WASM_PAGE_SIZE = 64 * KB;
const totalMemory = (2 * GB - 64 * KB) / WASM_PAGE_SIZE;
const initialMemory = Math.min(
Math.max(Math.ceil((mem * KB) / WASM_PAGE_SIZE), 256) + 256,
totalMemory
);
return new WebAssembly.Memory({
initial: initialMemory,
maximum: totalMemory,
});
}
function allocateArray(Module, arr) {
return Module.allocate(arr, 'i8', Module.ALLOC_NORMAL);
}
function allocateArrayStr(Module, arr) {
const nullTerminatedArray = new Uint8Array([...arr, 0]);
return allocateArray(Module, nullTerminatedArray);
}
function encodeUtf8(str) {
if (typeof str !== 'string') {
return str;
}
if (typeof TextEncoder === 'function') {
return new TextEncoder().encode(str);
} else if (typeof Buffer === 'function') {
return Buffer.from(str);
} else {
throw new Error("Don't know how to encode UTF8");
}
}
/**
* Argon2 hash
* @param {string|Uint8Array} params.pass - password string
* @param {string|Uint8Array} params.salt - salt string
* @param {number} [params.time=1] - the number of iterations
* @param {number} [params.mem=1024] - used memory, in KiB
* @param {number} [params.hashLen=24] - desired hash length
* @param {number} [params.parallelism=1] - desired parallelism
* @param {number} [params.type=argon2.ArgonType.Argon2d] - hash type:
* argon2.ArgonType.Argon2d
* argon2.ArgonType.Argon2i
* argon2.ArgonType.Argon2id
*
* @return Promise
*
* @example
* argon2.hash({ pass: 'password', salt: 'somesalt' })
* .then(h => console.log(h.hash, h.hashHex, h.encoded))
* .catch(e => console.error(e.message, e.code))
*/
function argon2Hash(params) {
const mCost = params.mem || 1024;
return loadModule(mCost).then((Module) => {
const tCost = params.time || 1;
const parallelism = params.parallelism || 1;
const pwdEncoded = encodeUtf8(params.pass);
const pwd = allocateArrayStr(Module, pwdEncoded);
const pwdlen = pwdEncoded.length;
const saltEncoded = encodeUtf8(params.salt);
const salt = allocateArrayStr(Module, saltEncoded);
const saltlen = saltEncoded.length;
const argon2Type = params.type || ArgonType.Argon2d;
const hash = Module.allocate(
new Array(params.hashLen || 24),
'i8',
Module.ALLOC_NORMAL
);
const secret = params.secret
? allocateArray(Module, params.secret)
: 0;
const secretlen = params.secret ? params.secret.byteLength : 0;
const ad = params.ad ? allocateArray(Module, params.ad) : 0;
const adlen = params.ad ? params.ad.byteLength : 0;
const hashlen = params.hashLen || 24;
const encodedlen = Module._argon2_encodedlen(
tCost,
mCost,
parallelism,
saltlen,
hashlen,
argon2Type
);
const encoded = Module.allocate(
new Array(encodedlen + 1),
'i8',
Module.ALLOC_NORMAL
);
const version = 0x13;
let err;
let res;
try {
res = Module._argon2_hash_ext(
tCost,
mCost,
parallelism,
pwd,
pwdlen,
salt,
saltlen,
hash,
hashlen,
encoded,
encodedlen,
argon2Type,
secret,
secretlen,
ad,
adlen,
version
);
} catch (e) {
err = e;
}
let result;
if (res === 0 && !err) {
let hashStr = '';
const hashArr = new Uint8Array(hashlen);
for (let i = 0; i < hashlen; i++) {
const byte = Module.HEAP8[hash + i];
hashArr[i] = byte;
hashStr += ('0' + (0xff & byte).toString(16)).slice(-2);
}
const encodedStr = Module.UTF8ToString(encoded);
result = {
hash: hashArr,
hashHex: hashStr,
encoded: encodedStr,
};
} else {
try {
if (!err) {
err = Module.UTF8ToString(
Module._argon2_error_message(res)
);
}
} catch (e) {}
result = { message: err, code: res };
}
try {
Module._free(pwd);
Module._free(salt);
Module._free(hash);
Module._free(encoded);
if (ad) {
Module._free(ad);
}
if (secret) {
Module._free(secret);
}
} catch (e) {}
if (err) {
throw result;
} else {
return result;
}
});
}
/**
* Argon2 verify function
* @param {string} params.pass - password string
* @param {string|Uint8Array} params.encoded - encoded hash
* @param {number} [params.type=argon2.ArgonType.Argon2d] - hash type:
* argon2.ArgonType.Argon2d
* argon2.ArgonType.Argon2i
* argon2.ArgonType.Argon2id
*
* @returns Promise
*
* @example
* argon2.verify({ pass: 'password', encoded: 'encoded-hash' })
* .then(() => console.log('OK'))
* .catch(e => console.error(e.message, e.code))
*/
function argon2Verify(params) {
return loadModule().then((Module) => {
const pwdEncoded = encodeUtf8(params.pass);
const pwd = allocateArrayStr(Module, pwdEncoded);
const pwdlen = pwdEncoded.length;
const secret = params.secret
? allocateArray(Module, params.secret)
: 0;
const secretlen = params.secret ? params.secret.byteLength : 0;
const ad = params.ad ? allocateArray(Module, params.ad) : 0;
const adlen = params.ad ? params.ad.byteLength : 0;
const encEncoded = encodeUtf8(params.encoded);
const enc = allocateArrayStr(Module, encEncoded);
let argon2Type = params.type;
if (argon2Type === undefined) {
let typeStr = params.encoded.split('$')[1];
if (typeStr) {
typeStr = typeStr.replace('a', 'A');
argon2Type = ArgonType[typeStr] || ArgonType.Argon2d;
}
}
let err;
let res;
try {
res = Module._argon2_verify_ext(
enc,
pwd,
pwdlen,
secret,
secretlen,
ad,
adlen,
argon2Type
);
} catch (e) {
err = e;
}
let result;
if (res || err) {
try {
if (!err) {
err = Module.UTF8ToString(
Module._argon2_error_message(res)
);
}
} catch (e) {}
result = { message: err, code: res };
}
try {
Module._free(pwd);
Module._free(enc);
} catch (e) {}
if (err) {
throw result;
} else {
return result;
}
});
}
function unloadRuntime() {
if (loadModule._module) {
loadModule._module.unloadRuntime();
delete loadModule._promise;
delete loadModule._module;
}
}
return {
ArgonType,
hash: argon2Hash,
verify: argon2Verify,
unloadRuntime,
};
});