@push.rocks/smartcrypto 2.1.0 → 2.3.0

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.
Files changed (34) hide show
  1. package/.smartconfig.json +6 -5
  2. package/dist_ts/00_commitinfo_data.js +1 -1
  3. package/dist_ts/index.d.ts +4 -0
  4. package/dist_ts/index.js +4 -1
  5. package/dist_ts/smartcrypto.classes.keypair.d.ts +6 -1
  6. package/dist_ts/smartcrypto.classes.keypair.js +11 -5
  7. package/dist_ts/smartcrypto.classes.privatekey.d.ts +13 -0
  8. package/dist_ts/smartcrypto.classes.privatekey.js +26 -1
  9. package/dist_ts/smartcrypto.classes.smartcrypto.d.ts +2 -2
  10. package/dist_ts/smartcrypto.classes.smartcrypto.js +3 -3
  11. package/dist_ts/smartcrypto.errors.d.ts +17 -0
  12. package/dist_ts/smartcrypto.errors.js +27 -0
  13. package/dist_ts/smartcrypto.internal.d.ts +12 -0
  14. package/dist_ts/smartcrypto.internal.js +133 -0
  15. package/dist_ts/smartcrypto.pkcs8.d.ts +14 -0
  16. package/dist_ts/smartcrypto.pkcs8.js +252 -0
  17. package/dist_ts/smartcrypto.webcrypto.d.ts +49 -0
  18. package/dist_ts/smartcrypto.webcrypto.js +179 -0
  19. package/dist_ts/smartcrypto.x25519.d.ts +46 -0
  20. package/dist_ts/smartcrypto.x25519.js +339 -0
  21. package/{license → license.md} +2 -1
  22. package/package.json +14 -9
  23. package/readme.md +138 -55
  24. package/ts/00_commitinfo_data.ts +1 -1
  25. package/ts/index.ts +7 -0
  26. package/ts/smartcrypto.classes.keypair.ts +18 -4
  27. package/ts/smartcrypto.classes.privatekey.ts +34 -0
  28. package/ts/smartcrypto.classes.smartcrypto.ts +3 -3
  29. package/ts/smartcrypto.errors.ts +54 -0
  30. package/ts/smartcrypto.internal.ts +162 -0
  31. package/ts/smartcrypto.pkcs8.ts +311 -0
  32. package/ts/smartcrypto.webcrypto.ts +266 -0
  33. package/ts/smartcrypto.x25519.ts +493 -0
  34. package/readme.hints.md +0 -1
@@ -0,0 +1,311 @@
1
+ import * as plugins from './smartcrypto.plugins.js';
2
+ import { createSmartCryptoError } from './smartcrypto.errors.js';
3
+ import { getWebCrypto, toArrayBuffer } from './smartcrypto.internal.js';
4
+
5
+ type TAsn1 = plugins.nodeForge.asn1.Asn1;
6
+
7
+ const encryptedPemType = 'ENCRYPTED PRIVATE KEY';
8
+ const saltBytes = 16;
9
+ const aesCbcIvBytes = 16;
10
+ /** PBKDF2 iteration count written by `encryptPrivateKeyInfo()`. */
11
+ const pbkdf2Iterations = 600_000;
12
+ /** Upper bound accepted on import, so a crafted PEM cannot stall decryption. */
13
+ const maxPbkdf2Iterations = 10_000_000;
14
+
15
+ const pbes2Oid = '1.2.840.113549.1.5.13';
16
+ const pbkdf2Oid = '1.2.840.113549.1.5.12';
17
+ const hmacWithSha256Oid = '1.2.840.113549.2.9';
18
+ const aes256CbcOid = '2.16.840.1.101.3.4.1.42';
19
+
20
+ /** PBKDF2 PRFs accepted on import; absent PRF parameters mean HMAC-SHA1. */
21
+ const prfHashByOid = new Map<string, string>([
22
+ ['1.2.840.113549.2.7', 'SHA-1'],
23
+ [hmacWithSha256Oid, 'SHA-256'],
24
+ ['1.2.840.113549.2.10', 'SHA-384'],
25
+ ['1.2.840.113549.2.11', 'SHA-512'],
26
+ ]);
27
+
28
+ /** AES-CBC key sizes accepted on import. */
29
+ const aesCbcKeyBitsByOid = new Map<string, number>([
30
+ ['2.16.840.1.101.3.4.1.2', 128],
31
+ ['2.16.840.1.101.3.4.1.22', 192],
32
+ [aes256CbcOid, 256],
33
+ ]);
34
+
35
+ const asn1 = plugins.nodeForge.asn1;
36
+ const rawBytes = plugins.nodeForge.util.binary.raw;
37
+
38
+ const invalidKey = () => createSmartCryptoError('INVALID_KEY');
39
+ const unsupportedProfile = () => createSmartCryptoError('UNSUPPORTED_PROFILE');
40
+
41
+ // ========================================
42
+ // ASN.1 encoding
43
+ // ========================================
44
+ const createSequence = (childrenArg: TAsn1[]): TAsn1 =>
45
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, childrenArg);
46
+
47
+ const createOid = (oidArg: string): TAsn1 =>
48
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(oidArg).getBytes());
49
+
50
+ const createOctetString = (bytesArg: Uint8Array): TAsn1 =>
51
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, rawBytes.encode(bytesArg));
52
+
53
+ const createInteger = (valueArg: number): TAsn1 =>
54
+ asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(valueArg).getBytes());
55
+
56
+ const createNull = (): TAsn1 => asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');
57
+
58
+ // ========================================
59
+ // ASN.1 decoding
60
+ // ========================================
61
+ const readSequence = (nodeArg: TAsn1 | undefined, minLengthArg: number, maxLengthArg: number): TAsn1[] => {
62
+ if (
63
+ !nodeArg
64
+ || nodeArg.tagClass !== asn1.Class.UNIVERSAL
65
+ || nodeArg.type !== asn1.Type.SEQUENCE
66
+ || !Array.isArray(nodeArg.value)
67
+ || nodeArg.value.length < minLengthArg
68
+ || nodeArg.value.length > maxLengthArg
69
+ ) {
70
+ throw invalidKey();
71
+ }
72
+ return nodeArg.value;
73
+ };
74
+
75
+ const readPrimitive = (nodeArg: TAsn1 | undefined, typeArg: plugins.nodeForge.asn1.Type): string => {
76
+ if (
77
+ !nodeArg
78
+ || nodeArg.tagClass !== asn1.Class.UNIVERSAL
79
+ || nodeArg.type !== typeArg
80
+ || typeof nodeArg.value !== 'string'
81
+ ) {
82
+ throw invalidKey();
83
+ }
84
+ return nodeArg.value;
85
+ };
86
+
87
+ const readOid = (nodeArg: TAsn1 | undefined): string => asn1.derToOid(readPrimitive(nodeArg, asn1.Type.OID));
88
+
89
+ const readOctetString = (nodeArg: TAsn1 | undefined): Uint8Array =>
90
+ rawBytes.decode(readPrimitive(nodeArg, asn1.Type.OCTETSTRING));
91
+
92
+ /** Reads a non-negative INTEGER that fits into 31 bits. */
93
+ const readSmallInteger = (nodeArg: TAsn1 | undefined): number => {
94
+ const integerBytes = readPrimitive(nodeArg, asn1.Type.INTEGER);
95
+ if (integerBytes.length < 1 || integerBytes.length > 4 || integerBytes.charCodeAt(0) >= 0x80) {
96
+ throw invalidKey();
97
+ }
98
+ return asn1.derToInteger(integerBytes);
99
+ };
100
+
101
+ // ========================================
102
+ // PBES2
103
+ // ========================================
104
+ /**
105
+ * Validates a passphrase. Export requires a non-empty passphrase; import also
106
+ * accepts an empty one, because `@push.rocks/smartkey` stored keys encrypted
107
+ * under an empty passphrase by default.
108
+ */
109
+ const assertPassphrase = (passphraseArg: string, optionsArg: { allowEmpty: boolean }): void => {
110
+ if (typeof passphraseArg !== 'string' || (!optionsArg.allowEmpty && passphraseArg.length < 1)) {
111
+ throw createSmartCryptoError('INVALID_ARGUMENT');
112
+ }
113
+ };
114
+
115
+ const deriveAesCbcKey = async (optionsArg: {
116
+ passphrase: string;
117
+ salt: Uint8Array;
118
+ iterations: number;
119
+ hash: string;
120
+ keyBits: number;
121
+ usage: KeyUsage;
122
+ }): Promise<CryptoKey> => {
123
+ const subtle = getWebCrypto().subtle;
124
+ const passphraseBuffer = toArrayBuffer(new TextEncoder().encode(optionsArg.passphrase));
125
+ try {
126
+ const passphraseKey = await subtle.importKey('raw', passphraseBuffer, 'PBKDF2', false, [
127
+ 'deriveKey',
128
+ ]);
129
+ return await subtle.deriveKey(
130
+ {
131
+ name: 'PBKDF2',
132
+ salt: toArrayBuffer(optionsArg.salt),
133
+ iterations: optionsArg.iterations,
134
+ hash: optionsArg.hash,
135
+ },
136
+ passphraseKey,
137
+ { name: 'AES-CBC', length: optionsArg.keyBits },
138
+ false,
139
+ [optionsArg.usage],
140
+ );
141
+ } catch {
142
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
143
+ } finally {
144
+ new Uint8Array(passphraseBuffer).fill(0);
145
+ }
146
+ };
147
+
148
+ /**
149
+ * Encrypts a PKCS#8 PrivateKeyInfo into an `ENCRYPTED PRIVATE KEY` PEM using
150
+ * PBES2 with PBKDF2-HMAC-SHA256 (600,000 iterations, 16-byte salt) and AES-256-CBC.
151
+ */
152
+ export const encryptPrivateKeyInfo = async (
153
+ privateKeyInfoArg: TAsn1,
154
+ passphraseArg: string,
155
+ ): Promise<string> => {
156
+ assertPassphrase(passphraseArg, { allowEmpty: false });
157
+ const webCrypto = getWebCrypto();
158
+ const salt = webCrypto.getRandomValues(new Uint8Array(saltBytes));
159
+ const iv = webCrypto.getRandomValues(new Uint8Array(aesCbcIvBytes));
160
+ const key = await deriveAesCbcKey({
161
+ passphrase: passphraseArg,
162
+ salt,
163
+ iterations: pbkdf2Iterations,
164
+ hash: 'SHA-256',
165
+ keyBits: 256,
166
+ usage: 'encrypt',
167
+ });
168
+
169
+ const privateKeyInfoBuffer = toArrayBuffer(
170
+ rawBytes.decode(asn1.toDer(privateKeyInfoArg).getBytes()),
171
+ );
172
+ let encryptedData: Uint8Array;
173
+ try {
174
+ encryptedData = new Uint8Array(
175
+ await webCrypto.subtle.encrypt({ name: 'AES-CBC', iv: toArrayBuffer(iv) }, key, privateKeyInfoBuffer),
176
+ );
177
+ } catch {
178
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
179
+ } finally {
180
+ new Uint8Array(privateKeyInfoBuffer).fill(0);
181
+ }
182
+
183
+ const encryptedPrivateKeyInfo = createSequence([
184
+ createSequence([
185
+ createOid(pbes2Oid),
186
+ createSequence([
187
+ createSequence([
188
+ createOid(pbkdf2Oid),
189
+ createSequence([
190
+ createOctetString(salt),
191
+ createInteger(pbkdf2Iterations),
192
+ createSequence([createOid(hmacWithSha256Oid), createNull()]),
193
+ ]),
194
+ ]),
195
+ createSequence([createOid(aes256CbcOid), createOctetString(iv)]),
196
+ ]),
197
+ ]),
198
+ createOctetString(encryptedData),
199
+ ]);
200
+ return plugins.nodeForge.pem.encode({
201
+ type: encryptedPemType,
202
+ body: asn1.toDer(encryptedPrivateKeyInfo).getBytes(),
203
+ });
204
+ };
205
+
206
+ /**
207
+ * Decrypts an `ENCRYPTED PRIVATE KEY` PEM (PKCS#8 PBES2 with PBKDF2 and
208
+ * AES-CBC, as written by OpenSSL, Node.js and `encryptPrivateKeyInfo()`) and
209
+ * returns the PrivateKeyInfo. An empty passphrase is accepted here only.
210
+ */
211
+ export const decryptPrivateKeyInfo = async (
212
+ pemArg: string,
213
+ passphraseArg: string,
214
+ ): Promise<TAsn1> => {
215
+ assertPassphrase(passphraseArg, { allowEmpty: true });
216
+ if (typeof pemArg !== 'string') {
217
+ throw invalidKey();
218
+ }
219
+ let encryptedPrivateKeyInfo: TAsn1;
220
+ try {
221
+ const pemMessages = plugins.nodeForge.pem.decode(pemArg);
222
+ if (
223
+ pemMessages.length !== 1
224
+ || pemMessages[0].type !== encryptedPemType
225
+ || pemMessages[0].procType
226
+ ) {
227
+ throw invalidKey();
228
+ }
229
+ encryptedPrivateKeyInfo = asn1.fromDer(pemMessages[0].body, true);
230
+ } catch {
231
+ throw invalidKey();
232
+ }
233
+
234
+ const [encryptionAlgorithm, encryptedDataNode] = readSequence(encryptedPrivateKeyInfo, 2, 2);
235
+ const [schemeOidNode, pbes2Params] = readSequence(encryptionAlgorithm, 2, 2);
236
+ if (readOid(schemeOidNode) !== pbes2Oid) {
237
+ throw unsupportedProfile();
238
+ }
239
+ const [keyDerivationFunc, encryptionScheme] = readSequence(pbes2Params, 2, 2);
240
+ const [kdfOidNode, kdfParamsNode] = readSequence(keyDerivationFunc, 2, 2);
241
+ if (readOid(kdfOidNode) !== pbkdf2Oid) {
242
+ throw unsupportedProfile();
243
+ }
244
+
245
+ // PBKDF2-params ::= SEQUENCE { salt, iterationCount, keyLength OPTIONAL, prf DEFAULT hmacWithSHA1 }
246
+ const pbkdf2Params = readSequence(kdfParamsNode, 2, 4);
247
+ const salt = readOctetString(pbkdf2Params[0]);
248
+ const iterations = readSmallInteger(pbkdf2Params[1]);
249
+ let paramIndex = 2;
250
+ let keyLengthBytes: number | undefined;
251
+ if (pbkdf2Params[paramIndex]?.type === asn1.Type.INTEGER) {
252
+ keyLengthBytes = readSmallInteger(pbkdf2Params[paramIndex]);
253
+ paramIndex++;
254
+ }
255
+ let prfHash = 'SHA-1';
256
+ if (pbkdf2Params[paramIndex]) {
257
+ const [prfOidNode] = readSequence(pbkdf2Params[paramIndex], 1, 2);
258
+ const configuredPrfHash = prfHashByOid.get(readOid(prfOidNode));
259
+ if (!configuredPrfHash) {
260
+ throw unsupportedProfile();
261
+ }
262
+ prfHash = configuredPrfHash;
263
+ paramIndex++;
264
+ }
265
+ if (paramIndex !== pbkdf2Params.length) {
266
+ throw invalidKey();
267
+ }
268
+ if (iterations < 1 || iterations > maxPbkdf2Iterations) {
269
+ throw unsupportedProfile();
270
+ }
271
+
272
+ const [cipherOidNode, ivNode] = readSequence(encryptionScheme, 2, 2);
273
+ const keyBits = aesCbcKeyBitsByOid.get(readOid(cipherOidNode));
274
+ if (!keyBits) {
275
+ throw unsupportedProfile();
276
+ }
277
+ const iv = readOctetString(ivNode);
278
+ if (iv.byteLength !== aesCbcIvBytes || (keyLengthBytes !== undefined && keyLengthBytes * 8 !== keyBits)) {
279
+ throw invalidKey();
280
+ }
281
+ const encryptedData = readOctetString(encryptedDataNode);
282
+
283
+ const key = await deriveAesCbcKey({
284
+ passphrase: passphraseArg,
285
+ salt,
286
+ iterations,
287
+ hash: prfHash,
288
+ keyBits,
289
+ usage: 'decrypt',
290
+ });
291
+ let privateKeyInfoBytes: Uint8Array;
292
+ try {
293
+ privateKeyInfoBytes = new Uint8Array(
294
+ await getWebCrypto().subtle.decrypt(
295
+ { name: 'AES-CBC', iv: toArrayBuffer(iv) },
296
+ key,
297
+ toArrayBuffer(encryptedData),
298
+ ),
299
+ );
300
+ } catch {
301
+ throw createSmartCryptoError('AUTHENTICATION_FAILED');
302
+ }
303
+ try {
304
+ return asn1.fromDer(rawBytes.encode(privateKeyInfoBytes), true);
305
+ } catch {
306
+ // A wrong passphrase can yield valid CBC padding over undecodable plaintext.
307
+ throw createSmartCryptoError('AUTHENTICATION_FAILED');
308
+ } finally {
309
+ privateKeyInfoBytes.fill(0);
310
+ }
311
+ };
@@ -0,0 +1,266 @@
1
+ import { SmartCryptoError, createSmartCryptoError } from './smartcrypto.errors.js';
2
+ import {
3
+ concatBytes,
4
+ getWebCrypto,
5
+ requireLength,
6
+ requireUint8Array,
7
+ toArrayBuffer,
8
+ } from './smartcrypto.internal.js';
9
+
10
+ export const SMARTCRYPTO_AES_256_KEY_BYTES = 32;
11
+ export const SMARTCRYPTO_AES_GCM_NONCE_BYTES = 12;
12
+ export const SMARTCRYPTO_AES_GCM_TAG_BYTES = 16;
13
+
14
+ export interface IAesGcmCiphertext {
15
+ nonce: Uint8Array;
16
+ ciphertext: Uint8Array;
17
+ tag: Uint8Array;
18
+ }
19
+
20
+ export interface IAesGcmEncryptOptions {
21
+ key: Uint8Array;
22
+ plaintext: Uint8Array;
23
+ aad: Uint8Array;
24
+ }
25
+
26
+ export interface IAesGcmDecryptOptions {
27
+ key: Uint8Array;
28
+ encryptedData: IAesGcmCiphertext;
29
+ aad: Uint8Array;
30
+ }
31
+
32
+ export interface IWrapDekOptions {
33
+ dek: Uint8Array;
34
+ kek: Uint8Array;
35
+ wrapAad: Uint8Array;
36
+ }
37
+
38
+ export interface IUnwrapDekOptions {
39
+ wrappedDek: IAesGcmCiphertext;
40
+ kek: Uint8Array;
41
+ wrapAad: Uint8Array;
42
+ }
43
+
44
+ export interface IRewrapDekOptions {
45
+ wrappedDek: IAesGcmCiphertext;
46
+ currentKek: Uint8Array;
47
+ currentWrapAad: Uint8Array;
48
+ newKek: Uint8Array;
49
+ newWrapAad: Uint8Array;
50
+ }
51
+
52
+ const importAesKey = async (
53
+ rawKeyArg: Uint8Array,
54
+ usagesArg: KeyUsage[],
55
+ ): Promise<CryptoKey> => {
56
+ const rawKey = requireLength(
57
+ requireUint8Array(rawKeyArg, 'INVALID_KEY'),
58
+ SMARTCRYPTO_AES_256_KEY_BYTES,
59
+ 'INVALID_KEY',
60
+ );
61
+ const rawKeyBuffer = toArrayBuffer(rawKey);
62
+ try {
63
+ return await getWebCrypto().subtle.importKey(
64
+ 'raw',
65
+ rawKeyBuffer,
66
+ { name: 'AES-GCM' },
67
+ false,
68
+ usagesArg,
69
+ );
70
+ } catch {
71
+ throw createSmartCryptoError('INVALID_KEY');
72
+ } finally {
73
+ rawKey.fill(0);
74
+ new Uint8Array(rawKeyBuffer).fill(0);
75
+ }
76
+ };
77
+
78
+ const copyEncryptedData = (valueArg: IAesGcmCiphertext): IAesGcmCiphertext => {
79
+ if (valueArg === null || typeof valueArg !== 'object') {
80
+ throw createSmartCryptoError('INVALID_ARGUMENT');
81
+ }
82
+ return {
83
+ nonce: requireLength(
84
+ requireUint8Array(valueArg.nonce),
85
+ SMARTCRYPTO_AES_GCM_NONCE_BYTES,
86
+ 'INVALID_ARGUMENT',
87
+ ),
88
+ ciphertext: requireUint8Array(valueArg.ciphertext),
89
+ tag: requireLength(
90
+ requireUint8Array(valueArg.tag),
91
+ SMARTCRYPTO_AES_GCM_TAG_BYTES,
92
+ 'INVALID_ARGUMENT',
93
+ ),
94
+ };
95
+ };
96
+
97
+ /** Generates a raw 32-byte data-encryption key. */
98
+ export const generateAes256GcmKey = (): Uint8Array =>
99
+ getWebCrypto().getRandomValues(new Uint8Array(SMARTCRYPTO_AES_256_KEY_BYTES));
100
+
101
+ /** Generates a raw 32-byte data-encryption key. */
102
+ export const generateDek = generateAes256GcmKey;
103
+
104
+ /** Encrypts bytes with AES-256-GCM and a fresh 96-bit nonce. AAD is mandatory. */
105
+ export const aesGcmEncrypt = async (
106
+ optionsArg: IAesGcmEncryptOptions,
107
+ ): Promise<IAesGcmCiphertext> => {
108
+ if (optionsArg === null || typeof optionsArg !== 'object') {
109
+ throw createSmartCryptoError('INVALID_ARGUMENT');
110
+ }
111
+ const plaintextInput = optionsArg.plaintext;
112
+ const aadInput = optionsArg.aad;
113
+ const keyInput = optionsArg.key;
114
+ if (
115
+ !(plaintextInput instanceof Uint8Array)
116
+ || !(aadInput instanceof Uint8Array)
117
+ ) {
118
+ throw createSmartCryptoError('INVALID_ARGUMENT');
119
+ }
120
+ let plaintext: Uint8Array | undefined;
121
+ let aad: Uint8Array | undefined;
122
+ let plaintextBuffer: ArrayBuffer | undefined;
123
+ let aadBuffer: ArrayBuffer | undefined;
124
+ let combined: Uint8Array | undefined;
125
+ try {
126
+ plaintext = new Uint8Array(plaintextInput);
127
+ aad = new Uint8Array(aadInput);
128
+ const crypto = getWebCrypto();
129
+ const nonce = crypto.getRandomValues(new Uint8Array(SMARTCRYPTO_AES_GCM_NONCE_BYTES));
130
+ const key = await importAesKey(keyInput, ['encrypt']);
131
+ plaintextBuffer = toArrayBuffer(plaintext);
132
+ aadBuffer = toArrayBuffer(aad);
133
+ combined = new Uint8Array(await crypto.subtle.encrypt(
134
+ {
135
+ name: 'AES-GCM',
136
+ iv: toArrayBuffer(nonce),
137
+ additionalData: aadBuffer,
138
+ tagLength: SMARTCRYPTO_AES_GCM_TAG_BYTES * 8,
139
+ },
140
+ key,
141
+ plaintextBuffer,
142
+ ));
143
+ if (combined.byteLength < SMARTCRYPTO_AES_GCM_TAG_BYTES) {
144
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
145
+ }
146
+ const tagOffset = combined.byteLength - SMARTCRYPTO_AES_GCM_TAG_BYTES;
147
+ return {
148
+ nonce: new Uint8Array(nonce),
149
+ ciphertext: combined.slice(0, tagOffset),
150
+ tag: combined.slice(tagOffset),
151
+ };
152
+ } catch (error) {
153
+ if (error instanceof SmartCryptoError) {
154
+ throw error;
155
+ }
156
+ throw createSmartCryptoError('CRYPTO_OPERATION_FAILED');
157
+ } finally {
158
+ plaintext?.fill(0);
159
+ aad?.fill(0);
160
+ if (plaintextBuffer) {
161
+ new Uint8Array(plaintextBuffer).fill(0);
162
+ }
163
+ if (aadBuffer) {
164
+ new Uint8Array(aadBuffer).fill(0);
165
+ }
166
+ combined?.fill(0);
167
+ }
168
+ };
169
+
170
+ /** Decrypts a split AES-256-GCM ciphertext and authenticates mandatory AAD. */
171
+ export const aesGcmDecrypt = async (
172
+ optionsArg: IAesGcmDecryptOptions,
173
+ ): Promise<Uint8Array> => {
174
+ if (optionsArg === null || typeof optionsArg !== 'object') {
175
+ throw createSmartCryptoError('INVALID_ARGUMENT');
176
+ }
177
+ const encryptedData = copyEncryptedData(optionsArg.encryptedData);
178
+ const aad = requireUint8Array(optionsArg.aad);
179
+ let aadBuffer: ArrayBuffer | undefined;
180
+ let combined: Uint8Array | undefined;
181
+ let combinedBuffer: ArrayBuffer | undefined;
182
+ try {
183
+ const key = await importAesKey(optionsArg.key, ['decrypt']);
184
+ aadBuffer = toArrayBuffer(aad);
185
+ combined = concatBytes(encryptedData.ciphertext, encryptedData.tag);
186
+ combinedBuffer = toArrayBuffer(combined);
187
+ return new Uint8Array(await getWebCrypto().subtle.decrypt(
188
+ {
189
+ name: 'AES-GCM',
190
+ iv: toArrayBuffer(encryptedData.nonce),
191
+ additionalData: aadBuffer,
192
+ tagLength: SMARTCRYPTO_AES_GCM_TAG_BYTES * 8,
193
+ },
194
+ key,
195
+ combinedBuffer,
196
+ ));
197
+ } catch {
198
+ throw createSmartCryptoError('AUTHENTICATION_FAILED');
199
+ } finally {
200
+ aad.fill(0);
201
+ if (aadBuffer) {
202
+ new Uint8Array(aadBuffer).fill(0);
203
+ }
204
+ combined?.fill(0);
205
+ if (combinedBuffer) {
206
+ new Uint8Array(combinedBuffer).fill(0);
207
+ }
208
+ }
209
+ };
210
+
211
+ /** Wraps one exact 32-byte DEK using an exact 32-byte KEK and independent AAD. */
212
+ export const wrapDek = async (optionsArg: IWrapDekOptions): Promise<IAesGcmCiphertext> => {
213
+ if (optionsArg === null || typeof optionsArg !== 'object') {
214
+ throw createSmartCryptoError('INVALID_ARGUMENT');
215
+ }
216
+ const dek = requireLength(
217
+ requireUint8Array(optionsArg.dek, 'INVALID_KEY'),
218
+ SMARTCRYPTO_AES_256_KEY_BYTES,
219
+ 'INVALID_KEY',
220
+ );
221
+ try {
222
+ return await aesGcmEncrypt({
223
+ key: optionsArg.kek,
224
+ plaintext: dek,
225
+ aad: optionsArg.wrapAad,
226
+ });
227
+ } finally {
228
+ dek.fill(0);
229
+ }
230
+ };
231
+
232
+ /** Unwraps and validates one exact 32-byte DEK. */
233
+ export const unwrapDek = async (optionsArg: IUnwrapDekOptions): Promise<Uint8Array> => {
234
+ if (optionsArg === null || typeof optionsArg !== 'object') {
235
+ throw createSmartCryptoError('INVALID_ARGUMENT');
236
+ }
237
+ const dek = await aesGcmDecrypt({
238
+ key: optionsArg.kek,
239
+ encryptedData: optionsArg.wrappedDek,
240
+ aad: optionsArg.wrapAad,
241
+ });
242
+ return requireLength(dek, SMARTCRYPTO_AES_256_KEY_BYTES, 'INVALID_KEY');
243
+ };
244
+
245
+ /** Rewraps a DEK without receiving or modifying its payload ciphertext. */
246
+ export const rewrapDek = async (
247
+ optionsArg: IRewrapDekOptions,
248
+ ): Promise<IAesGcmCiphertext> => {
249
+ if (optionsArg === null || typeof optionsArg !== 'object') {
250
+ throw createSmartCryptoError('INVALID_ARGUMENT');
251
+ }
252
+ const dek = await unwrapDek({
253
+ wrappedDek: optionsArg.wrappedDek,
254
+ kek: optionsArg.currentKek,
255
+ wrapAad: optionsArg.currentWrapAad,
256
+ });
257
+ try {
258
+ return await wrapDek({
259
+ dek,
260
+ kek: optionsArg.newKek,
261
+ wrapAad: optionsArg.newWrapAad,
262
+ });
263
+ } finally {
264
+ dek.fill(0);
265
+ }
266
+ };