@waku/message-encryption 0.0.4 → 0.0.5

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,53 @@
1
+ import { Signature } from "./index.js";
2
+ /**
3
+ * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
4
+ * The data MUST be flags | payload-length | payload | [signature].
5
+ * The returned result can be set to `WakuMessage.payload`.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare function encryptAsymmetric(data: Uint8Array, publicKey: Uint8Array | string): Promise<Uint8Array>;
10
+ /**
11
+ * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
12
+ * The returned data is expected to be `flags | payload-length | payload | [signature]`.
13
+ *
14
+ * @internal
15
+ */
16
+ export declare function decryptAsymmetric(payload: Uint8Array, privKey: Uint8Array): Promise<Uint8Array>;
17
+ /**
18
+ * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
19
+ *
20
+ * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
21
+ * @param key The key to use for encryption.
22
+ * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
23
+ *
24
+ * @internal
25
+ */
26
+ export declare function encryptSymmetric(data: Uint8Array, key: Uint8Array | string): Promise<Uint8Array>;
27
+ /**
28
+ * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
29
+ *
30
+ * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
31
+ * @param key The key to use for decryption.
32
+ * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
33
+ *
34
+ * @internal
35
+ */
36
+ export declare function decryptSymmetric(payload: Uint8Array, key: Uint8Array | string): Promise<Uint8Array>;
37
+ /**
38
+ * Prepare the payload pre-encryption.
39
+ *
40
+ * @internal
41
+ * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
42
+ * or {@link encryptSymmetric}.
43
+ */
44
+ export declare function preCipher(messagePayload: Uint8Array, sigPrivKey?: Uint8Array): Promise<Uint8Array>;
45
+ /**
46
+ * Decode a decrypted payload.
47
+ *
48
+ * @internal
49
+ */
50
+ export declare function postCipher(message: Uint8Array): {
51
+ payload: Uint8Array;
52
+ sig?: Signature;
53
+ } | undefined;
@@ -0,0 +1,178 @@
1
+ import * as secp from "@noble/secp256k1";
2
+ import { concat, hexToBytes } from "@waku/byte-utils";
3
+ import { Symmetric } from "./constants.js";
4
+ import * as ecies from "./crypto/ecies.js";
5
+ import { keccak256, randomBytes, sign } from "./crypto/index.js";
6
+ import * as symmetric from "./crypto/symmetric.js";
7
+ const FlagsLength = 1;
8
+ const FlagMask = 3; // 0011
9
+ const IsSignedMask = 4; // 0100
10
+ const PaddingTarget = 256;
11
+ const SignatureLength = 65;
12
+ function getSizeOfPayloadSizeField(message) {
13
+ const messageDataView = new DataView(message.buffer);
14
+ return messageDataView.getUint8(0) & FlagMask;
15
+ }
16
+ function getPayloadSize(message, sizeOfPayloadSizeField) {
17
+ let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);
18
+ // int 32 == 4 bytes
19
+ if (sizeOfPayloadSizeField < 4) {
20
+ // If less than 4 bytes pad right (Little Endian).
21
+ payloadSizeBytes = concat([payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)], 4);
22
+ }
23
+ const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);
24
+ return payloadSizeDataView.getInt32(0, true);
25
+ }
26
+ function isMessageSigned(message) {
27
+ const messageDataView = new DataView(message.buffer);
28
+ return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;
29
+ }
30
+ /**
31
+ * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
32
+ * The data MUST be flags | payload-length | payload | [signature].
33
+ * The returned result can be set to `WakuMessage.payload`.
34
+ *
35
+ * @internal
36
+ */
37
+ export async function encryptAsymmetric(data, publicKey) {
38
+ return ecies.encrypt(hexToBytes(publicKey), data);
39
+ }
40
+ /**
41
+ * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
42
+ * The returned data is expected to be `flags | payload-length | payload | [signature]`.
43
+ *
44
+ * @internal
45
+ */
46
+ export async function decryptAsymmetric(payload, privKey) {
47
+ return ecies.decrypt(privKey, payload);
48
+ }
49
+ /**
50
+ * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
51
+ *
52
+ * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
53
+ * @param key The key to use for encryption.
54
+ * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
55
+ *
56
+ * @internal
57
+ */
58
+ export async function encryptSymmetric(data, key) {
59
+ const iv = symmetric.generateIv();
60
+ // Returns `cipher | tag`
61
+ const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);
62
+ return concat([cipher, iv]);
63
+ }
64
+ /**
65
+ * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
66
+ *
67
+ * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
68
+ * @param key The key to use for decryption.
69
+ * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
70
+ *
71
+ * @internal
72
+ */
73
+ export async function decryptSymmetric(payload, key) {
74
+ const ivStart = payload.length - Symmetric.ivSize;
75
+ const cipher = payload.slice(0, ivStart);
76
+ const iv = payload.slice(ivStart);
77
+ return symmetric.decrypt(iv, hexToBytes(key), cipher);
78
+ }
79
+ /**
80
+ * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
81
+ */
82
+ function addPayloadSizeField(msg, payload) {
83
+ const fieldSize = computeSizeOfPayloadSizeField(payload);
84
+ let field = new Uint8Array(4);
85
+ const fieldDataView = new DataView(field.buffer);
86
+ fieldDataView.setUint32(0, payload.length, true);
87
+ field = field.slice(0, fieldSize);
88
+ msg = concat([msg, field]);
89
+ msg[0] |= fieldSize;
90
+ return msg;
91
+ }
92
+ /**
93
+ * Returns the size of the auxiliary-field which in turns contains the payload size
94
+ */
95
+ function computeSizeOfPayloadSizeField(payload) {
96
+ let s = 1;
97
+ for (let i = payload.length; i >= 256; i /= 256) {
98
+ s++;
99
+ }
100
+ return s;
101
+ }
102
+ function validateDataIntegrity(value, expectedSize) {
103
+ if (value.length !== expectedSize) {
104
+ return false;
105
+ }
106
+ return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;
107
+ }
108
+ function getSignature(message) {
109
+ return message.slice(message.length - SignatureLength, message.length);
110
+ }
111
+ function getHash(message, isSigned) {
112
+ if (isSigned) {
113
+ return keccak256(message.slice(0, message.length - SignatureLength));
114
+ }
115
+ return keccak256(message);
116
+ }
117
+ function ecRecoverPubKey(messageHash, signature) {
118
+ const recoveryDataView = new DataView(signature.slice(64).buffer);
119
+ const recovery = recoveryDataView.getUint8(0);
120
+ const _signature = secp.Signature.fromCompact(signature.slice(0, 64));
121
+ return secp.recoverPublicKey(messageHash, _signature, recovery, false);
122
+ }
123
+ /**
124
+ * Prepare the payload pre-encryption.
125
+ *
126
+ * @internal
127
+ * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
128
+ * or {@link encryptSymmetric}.
129
+ */
130
+ export async function preCipher(messagePayload, sigPrivKey) {
131
+ let envelope = new Uint8Array([0]); // No flags
132
+ envelope = addPayloadSizeField(envelope, messagePayload);
133
+ envelope = concat([envelope, messagePayload]);
134
+ // Calculate padding:
135
+ let rawSize = FlagsLength +
136
+ computeSizeOfPayloadSizeField(messagePayload) +
137
+ messagePayload.length;
138
+ if (sigPrivKey) {
139
+ rawSize += SignatureLength;
140
+ }
141
+ const remainder = rawSize % PaddingTarget;
142
+ const paddingSize = PaddingTarget - remainder;
143
+ const pad = randomBytes(paddingSize);
144
+ if (!validateDataIntegrity(pad, paddingSize)) {
145
+ throw new Error("failed to generate random padding of size " + paddingSize);
146
+ }
147
+ envelope = concat([envelope, pad]);
148
+ if (sigPrivKey) {
149
+ envelope[0] |= IsSignedMask;
150
+ const hash = keccak256(envelope);
151
+ const bytesSignature = await sign(hash, sigPrivKey);
152
+ envelope = concat([envelope, bytesSignature]);
153
+ }
154
+ return envelope;
155
+ }
156
+ /**
157
+ * Decode a decrypted payload.
158
+ *
159
+ * @internal
160
+ */
161
+ export function postCipher(message) {
162
+ const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);
163
+ if (sizeOfPayloadSizeField === 0)
164
+ return;
165
+ const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);
166
+ const payloadStart = 1 + sizeOfPayloadSizeField;
167
+ const payload = message.slice(payloadStart, payloadStart + payloadSize);
168
+ const isSigned = isMessageSigned(message);
169
+ let sig;
170
+ if (isSigned) {
171
+ const signature = getSignature(message);
172
+ const hash = getHash(message, isSigned);
173
+ const publicKey = ecRecoverPubKey(hash, signature);
174
+ sig = { signature, publicKey };
175
+ }
176
+ return { payload, sig };
177
+ }
178
+ //# sourceMappingURL=waku_payload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"waku_payload.js","sourceRoot":"","sources":["../src/waku_payload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,KAAK,SAAS,MAAM,uBAAuB,CAAC;AAInD,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,QAAQ,GAAG,CAAC,CAAC,CAA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AAY,CAAC;QAC5B,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;QACjC,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACpD,QAAQ,GAAG,MAAM,CAAC,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC,CAAC;KAC/C;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACxB,OAAmB;IAEnB,MAAM,sBAAsB,GAAG,yBAAyB,CAAC,OAAO,CAAC,CAAC;IAClE,IAAI,sBAAsB,KAAK,CAAC;QAAE,OAAO;IAEzC,MAAM,WAAW,GAAG,cAAc,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACpE,MAAM,YAAY,GAAG,CAAC,GAAG,sBAAsB,CAAC;IAChD,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,YAAY,EAAE,YAAY,GAAG,WAAW,CAAC,CAAC;IAExE,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IAE1C,IAAI,GAAG,CAAC;IACR,IAAI,QAAQ,EAAE;QACZ,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;QACxC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACxC,MAAM,SAAS,GAAG,eAAe,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACnD,GAAG,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;KAChC;IAED,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;AAC1B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waku/message-encryption",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Waku Message Payload Encryption",
5
5
  "types": "./dist/index.d.ts",
6
6
  "module": "./dist/index.js",
@@ -8,6 +8,14 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "import": "./dist/index.js"
11
+ },
12
+ "./ecies": {
13
+ "types": "./dist/ecies.d.ts",
14
+ "import": "./dist/ecies.js"
15
+ },
16
+ "./symmetric": {
17
+ "types": "./dist/symmetric.d.ts",
18
+ "import": "./dist/symmetric.js"
11
19
  }
12
20
  },
13
21
  "type": "module",
@@ -70,7 +78,7 @@
70
78
  "@typescript-eslint/eslint-plugin": "^5.8.1",
71
79
  "@typescript-eslint/parser": "^5.8.1",
72
80
  "chai": "^4.3.6",
73
- "cspell": "^5.14.0",
81
+ "cspell": "^6.17.0",
74
82
  "eslint": "^8.6.0",
75
83
  "eslint-config-prettier": "^8.3.0",
76
84
  "eslint-plugin-eslint-comments": "^3.2.0",
@@ -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 "./index.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
+ }
@@ -4,7 +4,7 @@ import * as secp from "@noble/secp256k1";
4
4
  import { concat } from "@waku/byte-utils";
5
5
  import sha3 from "js-sha3";
6
6
 
7
- import { Asymmetric, Symmetric } from "./constants.js";
7
+ import { Asymmetric, Symmetric } from "../constants.js";
8
8
 
9
9
  declare const self: Record<string, any> | undefined;
10
10
  const crypto: { node?: any; web?: any } = {
@@ -0,0 +1,33 @@
1
+ import { Symmetric } from "../constants.js";
2
+
3
+ import { getSubtle, randomBytes } from "./index.js";
4
+
5
+ export async function encrypt(
6
+ iv: Uint8Array,
7
+ key: Uint8Array,
8
+ clearText: Uint8Array
9
+ ): Promise<Uint8Array> {
10
+ return getSubtle()
11
+ .importKey("raw", key, Symmetric.algorithm, false, ["encrypt"])
12
+ .then((cryptoKey) =>
13
+ getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText)
14
+ )
15
+ .then((cipher) => new Uint8Array(cipher));
16
+ }
17
+
18
+ export async function decrypt(
19
+ iv: Uint8Array,
20
+ key: Uint8Array,
21
+ cipherText: Uint8Array
22
+ ): Promise<Uint8Array> {
23
+ return getSubtle()
24
+ .importKey("raw", key, Symmetric.algorithm, false, ["decrypt"])
25
+ .then((cryptoKey) =>
26
+ getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText)
27
+ )
28
+ .then((clear) => new Uint8Array(clear));
29
+ }
30
+
31
+ export function generateIv(): Uint8Array {
32
+ return randomBytes(Symmetric.ivSize);
33
+ }