-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe2ee.ts
More file actions
320 lines (278 loc) · 12.4 KB
/
e2ee.ts
File metadata and controls
320 lines (278 loc) · 12.4 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
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
export type Deps = { crypto: Crypto; TransformStream: typeof TransformStream };
export type Params = {
counterLength: 64 | 128;
namedCurve: "P-256" | "P-384" | "P-521";
keyLength: 128 | 192 | 256;
};
export type Options = { deps?: Deps; params?: Params };
export type Marshalled = { params: Params; keyPair: CryptoKeyPair | null };
export type KeyGenOptions = {
extractable?: boolean;
additionalUsages?: KeyUsage[];
};
export type UnmarshalOptions = { marshalled: Marshalled; deps?: Deps };
export class E2EE {
#deps: Deps = { crypto: globalThis.crypto, TransformStream: globalThis.TransformStream };
#params: Params = {
counterLength: 64,
namedCurve: "P-256",
keyLength: 256,
};
#keyPair: CryptoKeyPair | null = null;
#sharedSecrets: Record<string | symbol, CryptoKey> = {};
#unicast = Symbol("unicast");
/**
* @param options
* @param options.deps Optionally inject your own platform dependencies.
* @param options.deps.crypto An implementation of the WebCrypto API. Defaults to `globalThis.crypto`.
* @param options.params Optionally override the default security parameters.
* @param options.params.counterLength The length of the counter used in AES-CTR. Defaults to `64`.
* @param options.params.namedCurve The named curve used in ECDH. Defaults to `P-256`.
* @param options.params.keyLength The length of the key used in AES-CTR. Defaults to `256`.
*/
constructor(options?: Options) {
Object.assign(this.#deps, options?.deps);
Object.assign(this.#params, options?.params);
}
/**
* Generates an ECDH key pair for this party.
* @param options
* @param options.extractable Whether the key should be extractable. Defaults to `false`. SECURITY: Leave it to false, unless you know what you're doing.
* @param options.additionalUsages Additional usages for the key. Defaults to `[]`.
*/
async generateKeyPair({ extractable = false, additionalUsages = [] }: KeyGenOptions = {}) {
if (this.#keyPair) throw new Error("Key pair already exists");
this.#keyPair = await this.#deps.crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: this.#params.namedCurve },
extractable,
["deriveKey", ...additionalUsages] as ReadonlyArray<KeyUsage>
);
}
/**
* @returns The public key of this party, serialised as a JWK.
*/
async exportPublicKey() {
if (!this.#keyPair) throw new Error("Key pair not generated");
return this.#marshalKey(this.#keyPair.publicKey);
}
/**
* Set the public key generated by calling `exportPublicKey()` on another party. Provide an identifier
* if you want to communicate with multiple parties from this one instance.
* @param remotePublicKey The public key that was exported from another party, serialised as a JWK.
* @param identifier Optional identifier for the other party, used for multi-cast communication. You can refer to this
* identifier in future `encrypt()` and `decrypt()` calls to specify which party you want to communicate with.
*/
async setRemotePublicKey(remotePublicKey: string, identifier: string | symbol = this.#unicast) {
if (!this.#keyPair) throw new Error("Key pair not generated");
const unmarshalled = await this.#unmarshalPublicKey(remotePublicKey);
this.#sharedSecrets[identifier] = await this.#deps.crypto.subtle.deriveKey(
{ name: "ECDH", public: unmarshalled },
this.#keyPair!.privateKey,
{ name: "AES-CTR", length: this.#params.keyLength },
false,
["encrypt", "decrypt"]
);
}
/**
* Encrypts the provided string with AES-CTR using the shared secret generated via the key exchange as the key.
* @param plaintext Any JS string.
* @param identifier Optional identifier for the other party, used for multi-cast communication.
* @returns A string representing the ciphertext.
*/
async encrypt(plaintext: string, identifier: string | symbol = this.#unicast) {
if (!this.#sharedSecrets[identifier]) throw new Error("Shared secret not set");
return this.#encryptRaw(this.#UTF8ToUint8Array(plaintext), identifier);
}
/**
* A way to encrypt streaming Uint8Array data.
* @param identifier Optional identifier for the other party, used for multi-cast communication
* @returns A TransformStream that can be fitted in any pipeline to encrypt the data flowing through it.
*/
encryptStream(identifier: string | symbol = this.#unicast) {
if (!this.#sharedSecrets[identifier]) throw new Error("Shared secret not set");
return new this.#deps.TransformStream<Uint8Array, string>({
transform: async (chunk, controller) => {
controller.enqueue(await this.#encryptRaw(chunk, identifier));
},
});
}
/**
* Decrypts the provided string with AES-CTR using the shared secret generated via the key exchange as the key.
* @param ciphertext A string representing the ciphertext.
* @param identifier Optional identifier for the other party, used for multi-cast communication.
* @returns The decrypted string.
*/
async decrypt(ciphertext: string, identifier: string | symbol = this.#unicast) {
if (!this.#sharedSecrets[identifier]) throw new Error("Shared secret not set");
const decrypted = await this.#decryptRaw(ciphertext, identifier);
return this.#Uint8ArrayToUTF8(decrypted);
}
/**
* Opposite of `encryptStream()`
* @param identifier Optional identifier for the other party, used for multi-cast communication.
* @returns A TransformStream that can be fitted in any pipeline to decrypt the data flowing through it.
*/
decryptStream(identifier: string | symbol = this.#unicast) {
if (!this.#sharedSecrets[identifier]) throw new Error("Shared secret not set");
return new this.#deps.TransformStream<string, Uint8Array>({
transform: async (chunk, controller) => {
controller.enqueue(await this.#decryptRaw(chunk, identifier));
},
});
}
/**
*
* @returns The parameters used to create this instance of E2EE.
*/
exportParams() {
return this.#params;
}
/**
* A secure way to marshal this party's security parameters and key pair.
* The key pair is returned as a `CryptoKeyPair` object, which means that the `CryptoKey` objects corresponding
* to the two keys are facades. In particular, the private key cannot be viewed from JavaScript. As such, you cannot
* serialise the key pair. Instead, store it in IndexedDB.
* @returns An object with the security parameters of this party, and the key pair if it has been generated.
*/
marshal() {
return {
keyPair: this.#keyPair,
params: this.exportParams(),
};
}
/**
* Restore a previously marshalled instance of `E2EE`.
* @param options
* @param options.marshalled The object returned by `marshal()`.
* @param options.deps Optionally inject your own platform dependencies.
* @returns A new instance of `E2EE` with the same security parameters and key pair as the marshalled instance.
*/
static unmarshal({ marshalled: { keyPair, params }, deps }) {
const e2ee = new E2EE({ params, deps });
e2ee.#restoreKeyPairObject(keyPair);
return e2ee;
}
/**
* In case you want to share the identity of this party across multiple instances of this class (maybe you want
* to support multiple devices), use this method to securely share the private key between the devices.
*
* SECURITY: Make sure you handle the private key securely. It will be visible to JavaScript.
* @returns The private key of this party, serialised as a JWK.
*/
async exportPrivateKey() {
if (!this.#keyPair) throw new Error("Key pair not generated");
if (!this.#keyPair.privateKey.extractable) throw new Error("Private key is not extractable");
return this.#marshalKey(this.#keyPair!.privateKey);
}
/**
* Used in conjunction with `exportPrivateKey()` to share the private key between multiple instances of this class.
*
* SECURITY: Make sure you handle the private key securely. It will be visible to JavaScript.
*
* You can also use this to migrate your existing identities into this library.
* @param options
* @param options.privateKey The JWK of the private key you want to import.
* @param options.publicKey The JWK of the public key you want to import.
*/
async importKeyPair({ privateKey, publicKey }: { privateKey: string; publicKey: string }) {
if (this.#keyPair) throw new Error("Key pair already exists");
const unmarshalledPrivateKey = await this.#unmarshalPrivateKey(privateKey);
const unmarshalledPublicKey = await this.#unmarshalPublicKey(publicKey);
this.#keyPair = { privateKey: unmarshalledPrivateKey, publicKey: unmarshalledPublicKey };
}
#restoreKeyPairObject(keyPair: CryptoKeyPair) {
this.#keyPair = keyPair;
}
async #encryptRaw(data: Uint8Array, identifier: string | symbol) {
const counter = this.#generateIv();
const buffer = new Uint8Array(
await this.#deps.crypto.subtle.encrypt(
{
name: "AES-CTR",
counter: counter,
length: this.#params.counterLength,
},
this.#sharedSecrets[identifier],
data
)
);
return this.#marshalCiphertext({ buffer, counter });
}
async #decryptRaw(data: string, identifier: string | symbol) {
const { buffer, counter } = this.#unmarshalCiphertext(data);
const decryptedBuffer = await this.#deps.crypto.subtle.decrypt(
{
name: "AES-CTR",
counter: counter,
length: this.#params.counterLength,
},
this.#sharedSecrets[identifier],
buffer
);
return new Uint8Array(decryptedBuffer);
}
async #marshalKey(key: CryptoKey) {
const exported = await this.#deps.crypto.subtle.exportKey("jwk", key);
const marshalled = JSON.stringify(exported);
return marshalled;
}
async #unmarshalPublicKey(marshalled: string) {
const unmarshalled = JSON.parse(marshalled);
const key = await this.#deps.crypto.subtle.importKey(
"jwk",
unmarshalled,
{ name: "ECDH", namedCurve: this.#params.namedCurve },
true,
[]
);
return key;
}
async #unmarshalPrivateKey(marshalled: string) {
const unmarshalled = JSON.parse(marshalled);
const key = await this.#deps.crypto.subtle.importKey(
"jwk",
unmarshalled,
{ name: "ECDH", namedCurve: this.#params.namedCurve },
true,
unmarshalled.key_ops
);
return key;
}
#marshalCiphertext({ buffer, counter }: { buffer: Uint8Array; counter: Uint8Array }) {
const marshalled = JSON.stringify({
buffer: this.#Uint8ArrayToAscii(buffer),
counter: this.#Uint8ArrayToAscii(counter),
});
return marshalled;
}
#unmarshalCiphertext(marshalled: string) {
const unmarshalled = JSON.parse(marshalled);
const buffer = this.#asciiToUint8Array(unmarshalled.buffer);
const counter = this.#asciiToUint8Array(unmarshalled.counter);
return { buffer, counter };
}
#Uint8ArrayToUTF8(buffer: Uint8Array) {
return new TextDecoder().decode(buffer);
}
#UTF8ToUint8Array(text: string) {
return new TextEncoder().encode(text);
}
#asciiToUint8Array(text: string) {
return new Uint8Array([...text].map(c => c.charCodeAt(0)));
}
#Uint8ArrayToAscii(buffer: Uint8Array) {
const CHUNK_SIZE = 0x2000;
if (buffer.length <= CHUNK_SIZE) {
return String.fromCharCode(...buffer);
}
let accum = "";
for (let i = 0; i < buffer.length; i += CHUNK_SIZE) {
const chunk = buffer.subarray(i, i + CHUNK_SIZE);
accum += String.fromCharCode(...chunk);
}
return accum;
}
#generateIv() {
return this.#deps.crypto.getRandomValues(new Uint8Array(16));
}
}