forked from uakbr/Authenticator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargon.ts
57 lines (49 loc) · 1.26 KB
/
argon.ts
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
import * as argon2 from "argon2-browser";
window.addEventListener("message", (event) => {
const message = event.data;
const source = event.source as Window;
if (!source) {
return;
}
switch (message.action) {
case "hash":
Argon.hash(message.value).then((hash) => {
source.postMessage({ response: hash }, event.origin);
});
break;
case "verify":
Argon.compareHash(message.hash, message.value).then((result) => {
source.postMessage({ response: result }, event.origin);
});
break;
default:
break;
}
return;
});
class Argon {
static async hash(value: string) {
const salt = window.crypto.getRandomValues(new Uint8Array(16));
const hash = await argon2.hash({
pass: value,
salt,
mem: 1024 * 16,
type: argon2.ArgonType.Argon2id,
});
return hash.encoded;
}
static compareHash(hash: string, value: string) {
return new Promise((resolve: (value: boolean) => void) => {
argon2
.verify({
pass: value,
encoded: hash,
})
.then(() => resolve(true))
.catch((e: { message: string; code: number }) => {
console.error("Error decoding hash", e);
resolve(false);
});
});
}
}