@waku/message-encryption 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ecies.ts ADDED
@@ -0,0 +1,194 @@
1
+ import * as secp from "@noble/secp256k1";
2
+ import { concat, hexToBytes } from "@waku/byte-utils";
3
+
4
+ import { getSubtle, randomBytes, sha256 } from "./crypto.js";
5
+ /**
6
+ * HKDF as implemented in go-ethereum.
7
+ */
8
+ function kdf(secret: Uint8Array, outputLength: number): Promise<Uint8Array> {
9
+ let ctr = 1;
10
+ let written = 0;
11
+ let willBeResult = Promise.resolve(new Uint8Array());
12
+ while (written < outputLength) {
13
+ const counters = new Uint8Array([ctr >> 24, ctr >> 16, ctr >> 8, ctr]);
14
+ const countersSecret = concat(
15
+ [counters, secret],
16
+ counters.length + secret.length
17
+ );
18
+ const willBeHashResult = sha256(countersSecret);
19
+ willBeResult = willBeResult.then((result) =>
20
+ willBeHashResult.then((hashResult) => {
21
+ const _hashResult = new Uint8Array(hashResult);
22
+ return concat(
23
+ [result, _hashResult],
24
+ result.length + _hashResult.length
25
+ );
26
+ })
27
+ );
28
+ written += 32;
29
+ ctr += 1;
30
+ }
31
+ return willBeResult;
32
+ }
33
+
34
+ function aesCtrEncrypt(
35
+ counter: Uint8Array,
36
+ key: ArrayBufferLike,
37
+ data: ArrayBufferLike
38
+ ): Promise<Uint8Array> {
39
+ return getSubtle()
40
+ .importKey("raw", key, "AES-CTR", false, ["encrypt"])
41
+ .then((cryptoKey) =>
42
+ getSubtle().encrypt(
43
+ { name: "AES-CTR", counter: counter, length: 128 },
44
+ cryptoKey,
45
+ data
46
+ )
47
+ )
48
+ .then((bytes) => new Uint8Array(bytes));
49
+ }
50
+
51
+ function aesCtrDecrypt(
52
+ counter: Uint8Array,
53
+ key: ArrayBufferLike,
54
+ data: ArrayBufferLike
55
+ ): Promise<Uint8Array> {
56
+ return getSubtle()
57
+ .importKey("raw", key, "AES-CTR", false, ["decrypt"])
58
+ .then((cryptoKey) =>
59
+ getSubtle().decrypt(
60
+ { name: "AES-CTR", counter: counter, length: 128 },
61
+ cryptoKey,
62
+ data
63
+ )
64
+ )
65
+ .then((bytes) => new Uint8Array(bytes));
66
+ }
67
+
68
+ function hmacSha256Sign(
69
+ key: ArrayBufferLike,
70
+ msg: ArrayBufferLike
71
+ ): PromiseLike<Uint8Array> {
72
+ const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
73
+ return getSubtle()
74
+ .importKey("raw", key, algorithm, false, ["sign"])
75
+ .then((cryptoKey) => getSubtle().sign(algorithm, cryptoKey, msg))
76
+ .then((bytes) => new Uint8Array(bytes));
77
+ }
78
+
79
+ function hmacSha256Verify(
80
+ key: ArrayBufferLike,
81
+ msg: ArrayBufferLike,
82
+ sig: ArrayBufferLike
83
+ ): Promise<boolean> {
84
+ const algorithm = { name: "HMAC", hash: { name: "SHA-256" } };
85
+ const _key = getSubtle().importKey("raw", key, algorithm, false, ["verify"]);
86
+ return _key.then((cryptoKey) =>
87
+ getSubtle().verify(algorithm, cryptoKey, sig, msg)
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Derive shared secret for given private and public keys.
93
+ *
94
+ * @param privateKeyA Sender's private key (32 bytes)
95
+ * @param publicKeyB Recipient's public key (65 bytes)
96
+ * @returns A promise that resolves with the derived shared secret (Px, 32 bytes)
97
+ * @throws Error If arguments are invalid
98
+ */
99
+ function derive(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array {
100
+ if (privateKeyA.length !== 32) {
101
+ throw new Error(
102
+ `Bad private key, it should be 32 bytes but it's actually ${privateKeyA.length} bytes long`
103
+ );
104
+ } else if (publicKeyB.length !== 65) {
105
+ throw new Error(
106
+ `Bad public key, it should be 65 bytes but it's actually ${publicKeyB.length} bytes long`
107
+ );
108
+ } else if (publicKeyB[0] !== 4) {
109
+ throw new Error("Bad public key, a valid public key would begin with 4");
110
+ } else {
111
+ const px = secp.getSharedSecret(privateKeyA, publicKeyB, true);
112
+ // Remove the compression prefix
113
+ return new Uint8Array(hexToBytes(px).slice(1));
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Encrypt message for given recipient's public key.
119
+ *
120
+ * @param publicKeyTo Recipient's public key (65 bytes)
121
+ * @param msg The message being encrypted
122
+ * @return A promise that resolves with the ECIES structure serialized
123
+ */
124
+ export async function encrypt(
125
+ publicKeyTo: Uint8Array,
126
+ msg: Uint8Array
127
+ ): Promise<Uint8Array> {
128
+ const ephemPrivateKey = randomBytes(32);
129
+
130
+ const sharedPx = await derive(ephemPrivateKey, publicKeyTo);
131
+
132
+ const hash = await kdf(sharedPx, 32);
133
+
134
+ const iv = randomBytes(16);
135
+ const encryptionKey = hash.slice(0, 16);
136
+ const cipherText = await aesCtrEncrypt(iv, encryptionKey, msg);
137
+
138
+ const ivCipherText = concat([iv, cipherText], iv.length + cipherText.length);
139
+
140
+ const macKey = await sha256(hash.slice(16));
141
+ const hmac = await hmacSha256Sign(macKey, ivCipherText);
142
+ const ephemPublicKey = secp.getPublicKey(ephemPrivateKey, false);
143
+
144
+ return concat(
145
+ [ephemPublicKey, ivCipherText, hmac],
146
+ ephemPublicKey.length + ivCipherText.length + hmac.length
147
+ );
148
+ }
149
+
150
+ const metaLength = 1 + 64 + 16 + 32;
151
+
152
+ /**
153
+ * Decrypt message using given private key.
154
+ *
155
+ * @param privateKey A 32-byte private key of recipient of the message
156
+ * @param encrypted ECIES serialized structure (result of ECIES encryption)
157
+ * @returns The clear text
158
+ * @throws Error If decryption fails
159
+ */
160
+ export async function decrypt(
161
+ privateKey: Uint8Array,
162
+ encrypted: Uint8Array
163
+ ): Promise<Uint8Array> {
164
+ if (encrypted.length <= metaLength) {
165
+ throw new Error(
166
+ `Invalid Ciphertext. Data is too small. It should ba at least ${metaLength} bytes`
167
+ );
168
+ } else if (encrypted[0] !== 4) {
169
+ throw new Error(
170
+ `Not a valid ciphertext. It should begin with 4 but actually begin with ${encrypted[0]}`
171
+ );
172
+ } else {
173
+ // deserialize
174
+ const ephemPublicKey = encrypted.slice(0, 65);
175
+ const cipherTextLength = encrypted.length - metaLength;
176
+ const iv = encrypted.slice(65, 65 + 16);
177
+ const cipherAndIv = encrypted.slice(65, 65 + 16 + cipherTextLength);
178
+ const ciphertext = cipherAndIv.slice(16);
179
+ const msgMac = encrypted.slice(65 + 16 + cipherTextLength);
180
+
181
+ // check HMAC
182
+ const px = derive(privateKey, ephemPublicKey);
183
+ const hash = await kdf(px, 32);
184
+ const [encryptionKey, macKey] = await sha256(hash.slice(16)).then(
185
+ (macKey) => [hash.slice(0, 16), macKey]
186
+ );
187
+
188
+ if (!(await hmacSha256Verify(macKey, cipherAndIv, msgMac))) {
189
+ throw new Error("Incorrect MAC");
190
+ }
191
+
192
+ return aesCtrDecrypt(iv, encryptionKey, ciphertext);
193
+ }
194
+ }
package/src/index.ts ADDED
@@ -0,0 +1,474 @@
1
+ import * as secp from "@noble/secp256k1";
2
+ import { concat, hexToBytes } from "@waku/byte-utils";
3
+ import {
4
+ DecoderV0,
5
+ MessageV0,
6
+ proto,
7
+ } from "@waku/core/lib/waku_message/version_0";
8
+ import type {
9
+ DecodedMessage,
10
+ Decoder,
11
+ Encoder,
12
+ Message,
13
+ ProtoMessage,
14
+ } from "@waku/interfaces";
15
+ import debug from "debug";
16
+
17
+ import { Symmetric } from "./constants.js";
18
+ import {
19
+ generatePrivateKey,
20
+ generateSymmetricKey,
21
+ getPublicKey,
22
+ keccak256,
23
+ randomBytes,
24
+ sign,
25
+ } from "./crypto.js";
26
+ import * as ecies from "./ecies.js";
27
+ import * as symmetric from "./symmetric.js";
28
+
29
+ const log = debug("waku:message:version-1");
30
+
31
+ const FlagsLength = 1;
32
+ const FlagMask = 3; // 0011
33
+ const IsSignedMask = 4; // 0100
34
+ const PaddingTarget = 256;
35
+ const SignatureLength = 65;
36
+ const OneMillion = BigInt(1_000_000);
37
+
38
+ export { generatePrivateKey, generateSymmetricKey, getPublicKey };
39
+
40
+ export const Version = 1;
41
+
42
+ export type Signature = {
43
+ signature: Uint8Array;
44
+ publicKey: Uint8Array | undefined;
45
+ };
46
+
47
+ export class MessageV1 extends MessageV0 implements DecodedMessage {
48
+ private readonly _decodedPayload: Uint8Array;
49
+
50
+ constructor(
51
+ proto: proto.WakuMessage,
52
+ decodedPayload: Uint8Array,
53
+ public signature?: Uint8Array,
54
+ public signaturePublicKey?: Uint8Array
55
+ ) {
56
+ super(proto);
57
+ this._decodedPayload = decodedPayload;
58
+ }
59
+
60
+ get payload(): Uint8Array {
61
+ return this._decodedPayload;
62
+ }
63
+ }
64
+
65
+ export class AsymEncoder implements Encoder {
66
+ constructor(
67
+ public contentTopic: string,
68
+ private publicKey: Uint8Array,
69
+ private sigPrivKey?: Uint8Array
70
+ ) {}
71
+
72
+ async toWire(message: Partial<Message>): Promise<Uint8Array | undefined> {
73
+ const protoMessage = await this.toProtoObj(message);
74
+ if (!protoMessage) return;
75
+
76
+ return proto.WakuMessage.encode(protoMessage);
77
+ }
78
+
79
+ async toProtoObj(
80
+ message: Partial<Message>
81
+ ): Promise<ProtoMessage | undefined> {
82
+ const timestamp = message.timestamp ?? new Date();
83
+ if (!message.payload) {
84
+ log("No payload to encrypt, skipping: ", message);
85
+ return;
86
+ }
87
+ const preparedPayload = await preCipher(message.payload, this.sigPrivKey);
88
+
89
+ const payload = await encryptAsymmetric(preparedPayload, this.publicKey);
90
+
91
+ return {
92
+ payload,
93
+ version: Version,
94
+ contentTopic: this.contentTopic,
95
+ timestamp: BigInt(timestamp.valueOf()) * OneMillion,
96
+ rateLimitProof: message.rateLimitProof,
97
+ };
98
+ }
99
+ }
100
+
101
+ export class SymEncoder implements Encoder {
102
+ constructor(
103
+ public contentTopic: string,
104
+ private symKey: Uint8Array,
105
+ private sigPrivKey?: Uint8Array
106
+ ) {}
107
+
108
+ async toWire(message: Partial<Message>): Promise<Uint8Array | undefined> {
109
+ const protoMessage = await this.toProtoObj(message);
110
+ if (!protoMessage) return;
111
+
112
+ return proto.WakuMessage.encode(protoMessage);
113
+ }
114
+
115
+ async toProtoObj(
116
+ message: Partial<Message>
117
+ ): Promise<ProtoMessage | undefined> {
118
+ const timestamp = message.timestamp ?? new Date();
119
+ if (!message.payload) {
120
+ log("No payload to encrypt, skipping: ", message);
121
+ return;
122
+ }
123
+ const preparedPayload = await preCipher(message.payload, this.sigPrivKey);
124
+
125
+ const payload = await encryptSymmetric(preparedPayload, this.symKey);
126
+ return {
127
+ payload,
128
+ version: Version,
129
+ contentTopic: this.contentTopic,
130
+ timestamp: BigInt(timestamp.valueOf()) * OneMillion,
131
+ rateLimitProof: message.rateLimitProof,
132
+ };
133
+ }
134
+ }
135
+
136
+ export class AsymDecoder extends DecoderV0 implements Decoder<MessageV1> {
137
+ constructor(contentTopic: string, private privateKey: Uint8Array) {
138
+ super(contentTopic);
139
+ }
140
+
141
+ async fromProtoObj(
142
+ protoMessage: ProtoMessage
143
+ ): Promise<MessageV1 | undefined> {
144
+ const cipherPayload = protoMessage.payload;
145
+
146
+ if (protoMessage.version !== Version) {
147
+ log(
148
+ "Failed to decrypt due to incorrect version, expected:",
149
+ Version,
150
+ ", actual:",
151
+ protoMessage.version
152
+ );
153
+ return;
154
+ }
155
+
156
+ let payload;
157
+ if (!cipherPayload) {
158
+ log(`No payload to decrypt for contentTopic ${this.contentTopic}`);
159
+ return;
160
+ }
161
+
162
+ try {
163
+ payload = await decryptAsymmetric(cipherPayload, this.privateKey);
164
+ } catch (e) {
165
+ log(
166
+ `Failed to decrypt message using asymmetric decryption for contentTopic: ${this.contentTopic}`,
167
+ e
168
+ );
169
+ return;
170
+ }
171
+
172
+ if (!payload) {
173
+ log(`Failed to decrypt payload for contentTopic ${this.contentTopic}`);
174
+ return;
175
+ }
176
+
177
+ const res = await postCipher(payload);
178
+
179
+ if (!res) {
180
+ log(`Failed to decode payload for contentTopic ${this.contentTopic}`);
181
+ return;
182
+ }
183
+
184
+ log("Message decrypted", protoMessage);
185
+ return new MessageV1(
186
+ protoMessage,
187
+ res.payload,
188
+ res.sig?.signature,
189
+ res.sig?.publicKey
190
+ );
191
+ }
192
+ }
193
+
194
+ export class SymDecoder extends DecoderV0 implements Decoder<MessageV1> {
195
+ constructor(contentTopic: string, private symKey: Uint8Array) {
196
+ super(contentTopic);
197
+ }
198
+
199
+ async fromProtoObj(
200
+ protoMessage: ProtoMessage
201
+ ): Promise<MessageV1 | undefined> {
202
+ const cipherPayload = protoMessage.payload;
203
+
204
+ if (protoMessage.version !== Version) {
205
+ log(
206
+ "Failed to decrypt due to incorrect version, expected:",
207
+ Version,
208
+ ", actual:",
209
+ protoMessage.version
210
+ );
211
+ return;
212
+ }
213
+
214
+ let payload;
215
+ if (!cipherPayload) {
216
+ log(`No payload to decrypt for contentTopic ${this.contentTopic}`);
217
+ return;
218
+ }
219
+
220
+ try {
221
+ payload = await decryptSymmetric(cipherPayload, this.symKey);
222
+ } catch (e) {
223
+ log(
224
+ `Failed to decrypt message using asymmetric decryption for contentTopic: ${this.contentTopic}`,
225
+ e
226
+ );
227
+ return;
228
+ }
229
+
230
+ if (!payload) {
231
+ log(`Failed to decrypt payload for contentTopic ${this.contentTopic}`);
232
+ return;
233
+ }
234
+
235
+ const res = await postCipher(payload);
236
+
237
+ if (!res) {
238
+ log(`Failed to decode payload for contentTopic ${this.contentTopic}`);
239
+ return;
240
+ }
241
+
242
+ log("Message decrypted", protoMessage);
243
+ return new MessageV1(
244
+ protoMessage,
245
+ res.payload,
246
+ res.sig?.signature,
247
+ res.sig?.publicKey
248
+ );
249
+ }
250
+ }
251
+
252
+ function getSizeOfPayloadSizeField(message: Uint8Array): number {
253
+ const messageDataView = new DataView(message.buffer);
254
+ return messageDataView.getUint8(0) & FlagMask;
255
+ }
256
+
257
+ function getPayloadSize(
258
+ message: Uint8Array,
259
+ sizeOfPayloadSizeField: number
260
+ ): number {
261
+ let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);
262
+ // int 32 == 4 bytes
263
+ if (sizeOfPayloadSizeField < 4) {
264
+ // If less than 4 bytes pad right (Little Endian).
265
+ payloadSizeBytes = concat(
266
+ [payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)],
267
+ 4
268
+ );
269
+ }
270
+ const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);
271
+ return payloadSizeDataView.getInt32(0, true);
272
+ }
273
+
274
+ function isMessageSigned(message: Uint8Array): boolean {
275
+ const messageDataView = new DataView(message.buffer);
276
+ return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;
277
+ }
278
+
279
+ /**
280
+ * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
281
+ * The data MUST be flags | payload-length | payload | [signature].
282
+ * The returned result can be set to `WakuMessage.payload`.
283
+ *
284
+ * @internal
285
+ */
286
+ export async function encryptAsymmetric(
287
+ data: Uint8Array,
288
+ publicKey: Uint8Array | string
289
+ ): Promise<Uint8Array> {
290
+ return ecies.encrypt(hexToBytes(publicKey), data);
291
+ }
292
+
293
+ /**
294
+ * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
295
+ * The returned data is expected to be `flags | payload-length | payload | [signature]`.
296
+ *
297
+ * @internal
298
+ */
299
+ export async function decryptAsymmetric(
300
+ payload: Uint8Array,
301
+ privKey: Uint8Array
302
+ ): Promise<Uint8Array> {
303
+ return ecies.decrypt(privKey, payload);
304
+ }
305
+
306
+ /**
307
+ * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
308
+ *
309
+ * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
310
+ * @param key The key to use for encryption.
311
+ * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
312
+ *
313
+ * @internal
314
+ */
315
+ export async function encryptSymmetric(
316
+ data: Uint8Array,
317
+ key: Uint8Array | string
318
+ ): Promise<Uint8Array> {
319
+ const iv = symmetric.generateIv();
320
+
321
+ // Returns `cipher | tag`
322
+ const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);
323
+ return concat([cipher, iv]);
324
+ }
325
+
326
+ /**
327
+ * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
328
+ *
329
+ * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
330
+ * @param key The key to use for decryption.
331
+ * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
332
+ *
333
+ * @internal
334
+ */
335
+ export async function decryptSymmetric(
336
+ payload: Uint8Array,
337
+ key: Uint8Array | string
338
+ ): Promise<Uint8Array> {
339
+ const ivStart = payload.length - Symmetric.ivSize;
340
+ const cipher = payload.slice(0, ivStart);
341
+ const iv = payload.slice(ivStart);
342
+
343
+ return symmetric.decrypt(iv, hexToBytes(key), cipher);
344
+ }
345
+
346
+ /**
347
+ * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
348
+ */
349
+ function addPayloadSizeField(msg: Uint8Array, payload: Uint8Array): Uint8Array {
350
+ const fieldSize = computeSizeOfPayloadSizeField(payload);
351
+ let field = new Uint8Array(4);
352
+ const fieldDataView = new DataView(field.buffer);
353
+ fieldDataView.setUint32(0, payload.length, true);
354
+ field = field.slice(0, fieldSize);
355
+ msg = concat([msg, field]);
356
+ msg[0] |= fieldSize;
357
+ return msg;
358
+ }
359
+
360
+ /**
361
+ * Returns the size of the auxiliary-field which in turns contains the payload size
362
+ */
363
+ function computeSizeOfPayloadSizeField(payload: Uint8Array): number {
364
+ let s = 1;
365
+ for (let i = payload.length; i >= 256; i /= 256) {
366
+ s++;
367
+ }
368
+ return s;
369
+ }
370
+
371
+ function validateDataIntegrity(
372
+ value: Uint8Array,
373
+ expectedSize: number
374
+ ): boolean {
375
+ if (value.length !== expectedSize) {
376
+ return false;
377
+ }
378
+
379
+ return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;
380
+ }
381
+
382
+ function getSignature(message: Uint8Array): Uint8Array {
383
+ return message.slice(message.length - SignatureLength, message.length);
384
+ }
385
+
386
+ function getHash(message: Uint8Array, isSigned: boolean): Uint8Array {
387
+ if (isSigned) {
388
+ return keccak256(message.slice(0, message.length - SignatureLength));
389
+ }
390
+ return keccak256(message);
391
+ }
392
+
393
+ function ecRecoverPubKey(
394
+ messageHash: Uint8Array,
395
+ signature: Uint8Array
396
+ ): Uint8Array | undefined {
397
+ const recoveryDataView = new DataView(signature.slice(64).buffer);
398
+ const recovery = recoveryDataView.getUint8(0);
399
+ const _signature = secp.Signature.fromCompact(signature.slice(0, 64));
400
+
401
+ return secp.recoverPublicKey(messageHash, _signature, recovery, false);
402
+ }
403
+
404
+ /**
405
+ * Prepare the payload pre-encryption.
406
+ *
407
+ * @internal
408
+ * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
409
+ * or {@link encryptSymmetric}.
410
+ */
411
+ export async function preCipher(
412
+ messagePayload: Uint8Array,
413
+ sigPrivKey?: Uint8Array
414
+ ): Promise<Uint8Array> {
415
+ let envelope = new Uint8Array([0]); // No flags
416
+ envelope = addPayloadSizeField(envelope, messagePayload);
417
+ envelope = concat([envelope, messagePayload]);
418
+
419
+ // Calculate padding:
420
+ let rawSize =
421
+ FlagsLength +
422
+ computeSizeOfPayloadSizeField(messagePayload) +
423
+ messagePayload.length;
424
+
425
+ if (sigPrivKey) {
426
+ rawSize += SignatureLength;
427
+ }
428
+
429
+ const remainder = rawSize % PaddingTarget;
430
+ const paddingSize = PaddingTarget - remainder;
431
+ const pad = randomBytes(paddingSize);
432
+
433
+ if (!validateDataIntegrity(pad, paddingSize)) {
434
+ throw new Error("failed to generate random padding of size " + paddingSize);
435
+ }
436
+
437
+ envelope = concat([envelope, pad]);
438
+ if (sigPrivKey) {
439
+ envelope[0] |= IsSignedMask;
440
+ const hash = keccak256(envelope);
441
+ const bytesSignature = await sign(hash, sigPrivKey);
442
+ envelope = concat([envelope, bytesSignature]);
443
+ }
444
+
445
+ return envelope;
446
+ }
447
+
448
+ /**
449
+ * Decode a decrypted payload.
450
+ *
451
+ * @internal
452
+ */
453
+ export function postCipher(
454
+ message: Uint8Array
455
+ ): { payload: Uint8Array; sig?: Signature } | undefined {
456
+ const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);
457
+ if (sizeOfPayloadSizeField === 0) return;
458
+
459
+ const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);
460
+ const payloadStart = 1 + sizeOfPayloadSizeField;
461
+ const payload = message.slice(payloadStart, payloadStart + payloadSize);
462
+
463
+ const isSigned = isMessageSigned(message);
464
+
465
+ let sig;
466
+ if (isSigned) {
467
+ const signature = getSignature(message);
468
+ const hash = getHash(message, isSigned);
469
+ const publicKey = ecRecoverPubKey(hash, signature);
470
+ sig = { signature, publicKey };
471
+ }
472
+
473
+ return { payload, sig };
474
+ }
@@ -0,0 +1,32 @@
1
+ import { Symmetric } from "./constants";
2
+ import { getSubtle, randomBytes } from "./crypto.js";
3
+
4
+ export async function encrypt(
5
+ iv: Uint8Array,
6
+ key: Uint8Array,
7
+ clearText: Uint8Array
8
+ ): Promise<Uint8Array> {
9
+ return getSubtle()
10
+ .importKey("raw", key, Symmetric.algorithm, false, ["encrypt"])
11
+ .then((cryptoKey) =>
12
+ getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)
13
+ )
14
+ .then((cipher) => new Uint8Array(cipher));
15
+ }
16
+
17
+ export async function decrypt(
18
+ iv: Uint8Array,
19
+ key: Uint8Array,
20
+ cipherText: Uint8Array
21
+ ): Promise<Uint8Array> {
22
+ return getSubtle()
23
+ .importKey("raw", key, Symmetric.algorithm, false, ["decrypt"])
24
+ .then((cryptoKey) =>
25
+ getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)
26
+ )
27
+ .then((clear) => new Uint8Array(clear));
28
+ }
29
+
30
+ export function generateIv(): Uint8Array {
31
+ return randomBytes(Symmetric.ivSize);
32
+ }