@waku/message-encryption 0.0.4 → 0.0.6

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.
@@ -0,0 +1,239 @@
1
+ import * as secp from "@noble/secp256k1";
2
+ import { concat, hexToBytes } from "@waku/byte-utils";
3
+
4
+ import { Symmetric } from "./constants.js";
5
+ import * as ecies from "./crypto/ecies.js";
6
+ import { keccak256, randomBytes, sign } from "./crypto/index.js";
7
+ import * as symmetric from "./crypto/symmetric.js";
8
+
9
+ import { Signature } from "./index.js";
10
+
11
+ const FlagsLength = 1;
12
+ const FlagMask = 3; // 0011
13
+ const IsSignedMask = 4; // 0100
14
+ const PaddingTarget = 256;
15
+ const SignatureLength = 65;
16
+
17
+ function getSizeOfPayloadSizeField(message: Uint8Array): number {
18
+ const messageDataView = new DataView(message.buffer);
19
+ return messageDataView.getUint8(0) & FlagMask;
20
+ }
21
+
22
+ function getPayloadSize(
23
+ message: Uint8Array,
24
+ sizeOfPayloadSizeField: number
25
+ ): number {
26
+ let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);
27
+ // int 32 == 4 bytes
28
+ if (sizeOfPayloadSizeField < 4) {
29
+ // If less than 4 bytes pad right (Little Endian).
30
+ payloadSizeBytes = concat(
31
+ [payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)],
32
+ 4
33
+ );
34
+ }
35
+ const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);
36
+ return payloadSizeDataView.getInt32(0, true);
37
+ }
38
+
39
+ function isMessageSigned(message: Uint8Array): boolean {
40
+ const messageDataView = new DataView(message.buffer);
41
+ return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;
42
+ }
43
+
44
+ /**
45
+ * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
46
+ * The data MUST be flags | payload-length | payload | [signature].
47
+ * The returned result can be set to `WakuMessage.payload`.
48
+ *
49
+ * @internal
50
+ */
51
+ export async function encryptAsymmetric(
52
+ data: Uint8Array,
53
+ publicKey: Uint8Array | string
54
+ ): Promise<Uint8Array> {
55
+ return ecies.encrypt(hexToBytes(publicKey), data);
56
+ }
57
+
58
+ /**
59
+ * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
60
+ * The returned data is expected to be `flags | payload-length | payload | [signature]`.
61
+ *
62
+ * @internal
63
+ */
64
+ export async function decryptAsymmetric(
65
+ payload: Uint8Array,
66
+ privKey: Uint8Array
67
+ ): Promise<Uint8Array> {
68
+ return ecies.decrypt(privKey, payload);
69
+ }
70
+
71
+ /**
72
+ * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
73
+ *
74
+ * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
75
+ * @param key The key to use for encryption.
76
+ * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
77
+ *
78
+ * @internal
79
+ */
80
+ export async function encryptSymmetric(
81
+ data: Uint8Array,
82
+ key: Uint8Array | string
83
+ ): Promise<Uint8Array> {
84
+ const iv = symmetric.generateIv();
85
+
86
+ // Returns `cipher | tag`
87
+ const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);
88
+ return concat([cipher, iv]);
89
+ }
90
+
91
+ /**
92
+ * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
93
+ *
94
+ * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
95
+ * @param key The key to use for decryption.
96
+ * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
97
+ *
98
+ * @internal
99
+ */
100
+ export async function decryptSymmetric(
101
+ payload: Uint8Array,
102
+ key: Uint8Array | string
103
+ ): Promise<Uint8Array> {
104
+ const ivStart = payload.length - Symmetric.ivSize;
105
+ const cipher = payload.slice(0, ivStart);
106
+ const iv = payload.slice(ivStart);
107
+
108
+ return symmetric.decrypt(iv, hexToBytes(key), cipher);
109
+ }
110
+
111
+ /**
112
+ * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
113
+ */
114
+ function addPayloadSizeField(msg: Uint8Array, payload: Uint8Array): Uint8Array {
115
+ const fieldSize = computeSizeOfPayloadSizeField(payload);
116
+ let field = new Uint8Array(4);
117
+ const fieldDataView = new DataView(field.buffer);
118
+ fieldDataView.setUint32(0, payload.length, true);
119
+ field = field.slice(0, fieldSize);
120
+ msg = concat([msg, field]);
121
+ msg[0] |= fieldSize;
122
+ return msg;
123
+ }
124
+
125
+ /**
126
+ * Returns the size of the auxiliary-field which in turns contains the payload size
127
+ */
128
+ function computeSizeOfPayloadSizeField(payload: Uint8Array): number {
129
+ let s = 1;
130
+ for (let i = payload.length; i >= 256; i /= 256) {
131
+ s++;
132
+ }
133
+ return s;
134
+ }
135
+
136
+ function validateDataIntegrity(
137
+ value: Uint8Array,
138
+ expectedSize: number
139
+ ): boolean {
140
+ if (value.length !== expectedSize) {
141
+ return false;
142
+ }
143
+
144
+ return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;
145
+ }
146
+
147
+ function getSignature(message: Uint8Array): Uint8Array {
148
+ return message.slice(message.length - SignatureLength, message.length);
149
+ }
150
+
151
+ function getHash(message: Uint8Array, isSigned: boolean): Uint8Array {
152
+ if (isSigned) {
153
+ return keccak256(message.slice(0, message.length - SignatureLength));
154
+ }
155
+ return keccak256(message);
156
+ }
157
+
158
+ function ecRecoverPubKey(
159
+ messageHash: Uint8Array,
160
+ signature: Uint8Array
161
+ ): Uint8Array | undefined {
162
+ const recoveryDataView = new DataView(signature.slice(64).buffer);
163
+ const recovery = recoveryDataView.getUint8(0);
164
+ const _signature = secp.Signature.fromCompact(signature.slice(0, 64));
165
+
166
+ return secp.recoverPublicKey(messageHash, _signature, recovery, false);
167
+ }
168
+
169
+ /**
170
+ * Prepare the payload pre-encryption.
171
+ *
172
+ * @internal
173
+ * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
174
+ * or {@link encryptSymmetric}.
175
+ */
176
+ export async function preCipher(
177
+ messagePayload: Uint8Array,
178
+ sigPrivKey?: Uint8Array
179
+ ): Promise<Uint8Array> {
180
+ let envelope = new Uint8Array([0]); // No flags
181
+ envelope = addPayloadSizeField(envelope, messagePayload);
182
+ envelope = concat([envelope, messagePayload]);
183
+
184
+ // Calculate padding:
185
+ let rawSize =
186
+ FlagsLength +
187
+ computeSizeOfPayloadSizeField(messagePayload) +
188
+ messagePayload.length;
189
+
190
+ if (sigPrivKey) {
191
+ rawSize += SignatureLength;
192
+ }
193
+
194
+ const remainder = rawSize % PaddingTarget;
195
+ const paddingSize = PaddingTarget - remainder;
196
+ const pad = randomBytes(paddingSize);
197
+
198
+ if (!validateDataIntegrity(pad, paddingSize)) {
199
+ throw new Error("failed to generate random padding of size " + paddingSize);
200
+ }
201
+
202
+ envelope = concat([envelope, pad]);
203
+ if (sigPrivKey) {
204
+ envelope[0] |= IsSignedMask;
205
+ const hash = keccak256(envelope);
206
+ const bytesSignature = await sign(hash, sigPrivKey);
207
+ envelope = concat([envelope, bytesSignature]);
208
+ }
209
+
210
+ return envelope;
211
+ }
212
+
213
+ /**
214
+ * Decode a decrypted payload.
215
+ *
216
+ * @internal
217
+ */
218
+ export function postCipher(
219
+ message: Uint8Array
220
+ ): { payload: Uint8Array; sig?: Signature } | undefined {
221
+ const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);
222
+ if (sizeOfPayloadSizeField === 0) return;
223
+
224
+ const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);
225
+ const payloadStart = 1 + sizeOfPayloadSizeField;
226
+ const payload = message.slice(payloadStart, payloadStart + payloadSize);
227
+
228
+ const isSigned = isMessageSigned(message);
229
+
230
+ let sig;
231
+ if (isSigned) {
232
+ const signature = getSignature(message);
233
+ const hash = getHash(message, isSigned);
234
+ const publicKey = ecRecoverPubKey(hash, signature);
235
+ sig = { signature, publicK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