-
Notifications
You must be signed in to change notification settings - Fork 1
/
libsodium.ts
112 lines (88 loc) · 2.62 KB
/
libsodium.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
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
import sodium from "libsodium-wrappers";
import { unpack } from "msgpackr";
import type { EncryptedEntries, entry, Entries } from "$lib/types";
export async function sodiumReady() {
await sodium.ready;
return;
}
export async function generateKeyPairs(passphrase: string) {
const encoder = new TextEncoder();
const passBuf = encoder.encode(passphrase);
const seed = sodium.crypto_generichash(sodium.crypto_box_SEEDBYTES, passBuf);
const { publicKey } = sodium.crypto_box_seed_keypair(seed);
return {
publicKey: sodium.to_hex(publicKey),
};
}
export async function encryptLog(entry: Uint8Array, pubKey: string) {
const encrypted = sodium.crypto_box_seal(entry, sodium.from_hex(pubKey));
return { encrypted: encrypted };
}
export async function decrypt(
passphrase: string,
encryptedEntries: EncryptedEntries[],
) {
const { publicKey, privateKey } = await retrieveKeyPairs(passphrase);
let { decrypted } = await decryptingAllLogs(
publicKey,
privateKey,
encryptedEntries,
);
decrypted.sort((a, b) => b.timestamp - a.timestamp);
let notebooks = sortIntoNotebooks(decrypted);
return {
decryptedEntries: notebooks,
};
}
interface DecryptedLogs {
id: string;
title: string;
content: string;
timestamp: number;
notebook: string;
}
function sortIntoNotebooks(decryptedLogs: DecryptedLogs[]) {
let sortedNotebooks: Entries = {};
decryptedLogs.forEach((entry) => {
if (sortedNotebooks[entry.notebook] === undefined) {
sortedNotebooks[entry.notebook] = {};
}
sortedNotebooks[entry.notebook][entry.id] = entry;
});
return sortedNotebooks;
}
async function decryptingAllLogs(
publicKey: Uint8Array,
privateKey: Uint8Array,
logs: EncryptedEntries[],
) {
const length = logs.length;
const decrypted: DecryptedLogs[] = [];
const notebooks: string[] = [];
for (let i = 0; i < length; i++) {
const decryptedTextBuf = sodium.crypto_box_seal_open(
logs[i].entry,
publicKey,
privateKey,
);
const log: entry = unpack(decryptedTextBuf);
decrypted.push({
id: logs[i].id,
title: log[0],
content: log[1],
timestamp: log[2],
notebook: log[3],
});
if (!notebooks.includes(log[3])) {
notebooks.push(log[3]);
}
}
return { decrypted, notebooks };
}
async function retrieveKeyPairs(passphrase: string) {
const encoder = new TextEncoder();
const passBuf = encoder.encode(passphrase);
const seed = sodium.crypto_generichash(sodium.crypto_box_SEEDBYTES, passBuf);
const { publicKey, privateKey } = sodium.crypto_box_seed_keypair(seed);
return { publicKey: publicKey, privateKey: privateKey };
}