-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargon2.js
More file actions
65 lines (55 loc) · 2.71 KB
/
argon2.js
File metadata and controls
65 lines (55 loc) · 2.71 KB
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
import { hashRaw, Config, Variant, Version } from '@hicaru/argon2-pure.js';
import { encode as unicodeEncode } from './unicode.js';
import { random as getRandom } from './csprng.js';
import * as wasmcheck from 'wasm-check';
function hexToBytes(hex) {
if (hex.length % 2 !== 0) throw new Error("Invalid hex string");
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return bytes;
}
export function generateSalt() {
return getRandom(16, Uint8Array);
}
export async function hash(password, salt = null, length = 32, iterations = 3, memory = 4096, raw = true) {
if (window.speedups_loaded instanceof Promise) {
await window.speedups_loaded;
}
if (wasmcheck.support() && window?.argon2 !== undefined) {
return (await window.argon2.hash({
pass: password,
salt: salt ? salt : generateSalt(),
time: iterations,
mem: memory,
hashLen: length,
parallelism: 4,
type: window.argon2.ArgonType.Argon2id
})).hash;
} else if (typeof Worker !== undefined && window?.Argon2id !== undefined) {
console.warn("WARNING: WASM unavailable, will use slower workers JS Argon2id implementation!");
password = String(password);
salt = salt ? String(salt) : String(generateSalt());
const hash = await window.Argon2id.hash(password, salt, iterations, memory, 4, length);
return hexToBytes(hash);
} else {
// note: for some reason, it looks like this single-threaded implementation is faster than the multi-threaded one
// with workers but without webassembly. in the future, we should look into making a multi-threaded workers-based
// version of this algorithm due to how more efficient it is
// the only reason we prefer using the slower, worker based version is because it doesn't block execution
// while this one does, so we are keeping it that way for now
console.warn("WARNING: WASM and workers unavailable, will use painfully slow plain JS Argon2id implementation!");
const config = new Config(
new Uint8Array(),
length, 4, memory,
new Uint8Array(),
iterations,
Variant.Argon2id,
Version.Version13 // note: the revision 1.3 must be used by all 3 algorithms here (for now, this is the case)
); // as well as the other params which should be the same between the 3 algorithms
password = unicodeEncode(password);
salt = salt ? salt : generateSalt();
return hashRaw(password, salt, config);
}
};