@fgv/ts-web-extras 5.1.0-17 → 5.1.0-19
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/.rush/temp/{edc66e6a37414a0b69e52d768684c18c9d5825e3.tar.log → 42a7a953924ae898114e7b6231a2408228d92433.tar.log} +8 -2
- package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +19 -17
- package/.rush/temp/operation/build/all.log +19 -17
- package/.rush/temp/operation/build/log-chunks.jsonl +19 -17
- package/.rush/temp/operation/build/state.json +1 -1
- package/dist/packlets/crypto-utils/browserCryptoProvider.js +176 -18
- package/dist/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js +221 -0
- package/dist/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
- package/dist/ts-web-extras.d.ts +46 -6
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.exportPublicKeyJwk.md +24 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.generateKeyPair.md +25 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.importPublicKeyJwk.md +25 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.md +67 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
- package/docs/CryptoUtils/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
- package/docs/classes/BrowserCryptoProvider.exportPublicKeyJwk.md +24 -0
- package/docs/classes/BrowserCryptoProvider.generateKeyPair.md +25 -0
- package/docs/classes/BrowserCryptoProvider.importPublicKeyJwk.md +25 -0
- package/docs/classes/BrowserCryptoProvider.md +67 -0
- package/docs/classes/BrowserCryptoProvider.unwrapBytes.md +27 -0
- package/docs/classes/BrowserCryptoProvider.wrapBytes.md +28 -0
- package/etc/ts-web-extras.api.md +10 -5
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts +46 -5
- package/lib/packlets/crypto-utils/browserCryptoProvider.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/browserCryptoProvider.js +175 -17
- package/lib/packlets/crypto-utils/browserCryptoProvider.js.map +1 -1
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts +2 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.d.ts.map +1 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js +223 -0
- package/lib/test/unit/browserCryptoProvider.wrapBytes.test.js.map +1 -0
- package/package.json +14 -14
- package/rush-logs/ts-web-extras.build.cache.log +1 -1
- package/rush-logs/ts-web-extras.build.log +19 -17
- package/src/packlets/crypto-utils/browserCryptoProvider.ts +244 -23
- package/src/test/unit/browserCryptoProvider.wrapBytes.test.ts +325 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +692 -29
- package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/index.html +9 -9
- package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/httpTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/index.html +1 -1
- package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/helpers/index.html +1 -1
- package/temp/coverage/index.html +10 -10
- package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +692 -29
- package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/index.html +9 -9
- package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/index.html +1 -1
- package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/index.html +1 -1
- package/temp/coverage/lcov-report/index.html +10 -10
- package/temp/coverage/lcov-report/url-utils/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
- package/temp/coverage/lcov.info +294 -23
- package/temp/coverage/url-utils/index.html +1 -1
- package/temp/coverage/url-utils/urlParams.ts.html +1 -1
- package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
- package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -1
- package/temp/ts-web-extras.api.json +465 -4
- package/temp/ts-web-extras.api.md +10 -5
|
@@ -18,14 +18,10 @@
|
|
|
18
18
|
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
19
|
// SOFTWARE.
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
import { captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';
|
|
21
|
+
import { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';
|
|
23
22
|
import { CryptoUtils } from '@fgv/ts-extras';
|
|
24
23
|
|
|
25
|
-
|
|
26
|
-
type IEncryptionResult = CryptoUtils.IEncryptionResult;
|
|
27
|
-
const CryptoConstants = CryptoUtils.Constants;
|
|
28
|
-
|
|
24
|
+
/* c8 ignore start - Used only by browser-only methods that cannot be tested in Node.js environment */
|
|
29
25
|
/**
|
|
30
26
|
* Extracts an `ArrayBuffer` from a Uint8Array, handling the potential SharedArrayBuffer case.
|
|
31
27
|
* @param arr - The Uint8Array to extract from
|
|
@@ -37,6 +33,25 @@ function toArrayBuffer(arr: Uint8Array): ArrayBuffer {
|
|
|
37
33
|
new Uint8Array(buffer).set(arr);
|
|
38
34
|
return buffer;
|
|
39
35
|
}
|
|
36
|
+
/* c8 ignore stop */
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns a fresh Uint8Array view over a non-shared ArrayBuffer copy of `arr`.
|
|
40
|
+
* Used by {@link BrowserCryptoProvider.wrapBytes | wrapBytes} and
|
|
41
|
+
* {@link BrowserCryptoProvider.unwrapBytes | unwrapBytes}: Node 20's
|
|
42
|
+
* webcrypto.subtle rejects raw `ArrayBuffer` for several `BufferSource`
|
|
43
|
+
* parameters with "is not instance of ArrayBuffer, Buffer, TypedArray, or
|
|
44
|
+
* DataView" even though `ArrayBuffer` should be valid per the spec; a
|
|
45
|
+
* TypedArray view is accepted on Node 20+ and on browsers, and the explicit
|
|
46
|
+
* `Uint8Array<ArrayBuffer>` return type also satisfies TypeScript's `BufferSource`
|
|
47
|
+
* (which excludes the `SharedArrayBuffer` branch of `Uint8Array`'s buffer type).
|
|
48
|
+
*/
|
|
49
|
+
function toBufferView(arr: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
50
|
+
const buffer = new ArrayBuffer(arr.byteLength);
|
|
51
|
+
const view = new Uint8Array(buffer);
|
|
52
|
+
view.set(arr);
|
|
53
|
+
return view;
|
|
54
|
+
}
|
|
40
55
|
|
|
41
56
|
/**
|
|
42
57
|
* Browser implementation of `ICryptoProvider` using the Web Crypto API.
|
|
@@ -47,9 +62,10 @@ function toArrayBuffer(arr: Uint8Array): ArrayBuffer {
|
|
|
47
62
|
*
|
|
48
63
|
* @public
|
|
49
64
|
*/
|
|
50
|
-
export class BrowserCryptoProvider implements ICryptoProvider {
|
|
65
|
+
export class BrowserCryptoProvider implements CryptoUtils.ICryptoProvider {
|
|
51
66
|
private readonly _crypto: Crypto;
|
|
52
67
|
|
|
68
|
+
/* c8 ignore start - Existing browser-only methods cannot be tested in Node.js environment */
|
|
53
69
|
/**
|
|
54
70
|
* Creates a new {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider}.
|
|
55
71
|
* @param cryptoApi - Optional Crypto instance (defaults to globalThis.crypto)
|
|
@@ -72,14 +88,14 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
72
88
|
* @param key - 32-byte encryption key
|
|
73
89
|
* @returns `Success` with encryption result, or `Failure` with an error.
|
|
74
90
|
*/
|
|
75
|
-
public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {
|
|
76
|
-
if (key.length !==
|
|
77
|
-
return Failure.with(`Key must be ${
|
|
91
|
+
public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<CryptoUtils.IEncryptionResult>> {
|
|
92
|
+
if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {
|
|
93
|
+
return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
78
94
|
}
|
|
79
95
|
|
|
80
96
|
try {
|
|
81
97
|
// Generate random IV
|
|
82
|
-
const iv = this._crypto.getRandomValues(new Uint8Array(
|
|
98
|
+
const iv = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));
|
|
83
99
|
|
|
84
100
|
// Import the key
|
|
85
101
|
const cryptoKey = await this._crypto.subtle.importKey(
|
|
@@ -99,7 +115,7 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
99
115
|
{
|
|
100
116
|
name: 'AES-GCM',
|
|
101
117
|
iv: iv,
|
|
102
|
-
tagLength:
|
|
118
|
+
tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
|
|
103
119
|
},
|
|
104
120
|
cryptoKey,
|
|
105
121
|
plaintextBytes
|
|
@@ -109,9 +125,9 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
109
125
|
const encryptedArray = new Uint8Array(encryptedWithTag);
|
|
110
126
|
const encryptedData = encryptedArray.slice(
|
|
111
127
|
0,
|
|
112
|
-
encryptedArray.length -
|
|
128
|
+
encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE
|
|
113
129
|
);
|
|
114
|
-
const authTag = encryptedArray.slice(encryptedArray.length -
|
|
130
|
+
const authTag = encryptedArray.slice(encryptedArray.length - CryptoUtils.Constants.GCM_AUTH_TAG_SIZE);
|
|
115
131
|
return Success.with({
|
|
116
132
|
iv,
|
|
117
133
|
authTag,
|
|
@@ -137,15 +153,15 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
137
153
|
iv: Uint8Array,
|
|
138
154
|
authTag: Uint8Array
|
|
139
155
|
): Promise<Result<string>> {
|
|
140
|
-
if (key.length !==
|
|
141
|
-
return Failure.with(`Key must be ${
|
|
156
|
+
if (key.length !== CryptoUtils.Constants.AES_256_KEY_SIZE) {
|
|
157
|
+
return Failure.with(`Key must be ${CryptoUtils.Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);
|
|
142
158
|
}
|
|
143
|
-
if (iv.length !==
|
|
144
|
-
return Failure.with(`IV must be ${
|
|
159
|
+
if (iv.length !== CryptoUtils.Constants.GCM_IV_SIZE) {
|
|
160
|
+
return Failure.with(`IV must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);
|
|
145
161
|
}
|
|
146
|
-
if (authTag.length !==
|
|
162
|
+
if (authTag.length !== CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
|
|
147
163
|
return Failure.with(
|
|
148
|
-
`Auth tag must be ${
|
|
164
|
+
`Auth tag must be ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`
|
|
149
165
|
);
|
|
150
166
|
}
|
|
151
167
|
|
|
@@ -169,7 +185,7 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
169
185
|
{
|
|
170
186
|
name: 'AES-GCM',
|
|
171
187
|
iv: toArrayBuffer(iv),
|
|
172
|
-
tagLength:
|
|
188
|
+
tagLength: CryptoUtils.Constants.GCM_AUTH_TAG_SIZE * 8 // bits
|
|
173
189
|
},
|
|
174
190
|
cryptoKey,
|
|
175
191
|
encryptedWithTag
|
|
@@ -190,7 +206,9 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
190
206
|
*/
|
|
191
207
|
public async generateKey(): Promise<Result<Uint8Array>> {
|
|
192
208
|
try {
|
|
193
|
-
return Success.with(
|
|
209
|
+
return Success.with(
|
|
210
|
+
this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.AES_256_KEY_SIZE))
|
|
211
|
+
);
|
|
194
212
|
} catch (e) {
|
|
195
213
|
const message = e instanceof Error ? e.message : String(e);
|
|
196
214
|
return Failure.with(`Key generation failed: ${message}`);
|
|
@@ -235,7 +253,7 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
235
253
|
hash: 'SHA-256'
|
|
236
254
|
},
|
|
237
255
|
keyMaterial,
|
|
238
|
-
|
|
256
|
+
CryptoUtils.Constants.AES_256_KEY_SIZE * 8 // bits
|
|
239
257
|
);
|
|
240
258
|
|
|
241
259
|
return Success.with(new Uint8Array(derivedBits));
|
|
@@ -318,8 +336,211 @@ export class BrowserCryptoProvider implements ICryptoProvider {
|
|
|
318
336
|
return Failure.with('Invalid base64 string');
|
|
319
337
|
}
|
|
320
338
|
}
|
|
339
|
+
|
|
340
|
+
// ============================================================================
|
|
341
|
+
// Asymmetric Key Operations
|
|
342
|
+
// ============================================================================
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Generates a new asymmetric keypair via Web Crypto.
|
|
346
|
+
* @param algorithm - The algorithm to use.
|
|
347
|
+
* @param extractable - Whether the resulting keys may be exported.
|
|
348
|
+
* @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
|
|
349
|
+
*/
|
|
350
|
+
public async generateKeyPair(
|
|
351
|
+
algorithm: CryptoUtils.KeyPairAlgorithm,
|
|
352
|
+
extractable: boolean
|
|
353
|
+
): Promise<Result<CryptoKeyPair>> {
|
|
354
|
+
const params = CryptoUtils.keyPairAlgorithmParams[algorithm];
|
|
355
|
+
const result = await captureAsyncResult(() =>
|
|
356
|
+
this._crypto.subtle.generateKey(params.generateKey, extractable, params.keyPairUsages)
|
|
357
|
+
);
|
|
358
|
+
return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Exports a public `CryptoKey` as a JSON Web Key.
|
|
363
|
+
* @remarks
|
|
364
|
+
* Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
|
|
365
|
+
* does not enforce public-vs-private; without this guard a caller that
|
|
366
|
+
* passed an extractable private key would receive its private fields
|
|
367
|
+
* (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
|
|
368
|
+
* @param publicKey - Extractable public key to export.
|
|
369
|
+
* @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
|
|
370
|
+
*/
|
|
371
|
+
public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {
|
|
372
|
+
if (publicKey.type !== 'public') {
|
|
373
|
+
return Failure.with(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);
|
|
374
|
+
}
|
|
375
|
+
const result = await captureAsyncResult(() => this._crypto.subtle.exportKey('jwk', publicKey));
|
|
376
|
+
return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
|
|
381
|
+
* @param jwk - The JSON Web Key produced by a prior export.
|
|
382
|
+
* @param algorithm - The algorithm the key was generated for.
|
|
383
|
+
* @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
|
|
384
|
+
*/
|
|
385
|
+
public async importPublicKeyJwk(
|
|
386
|
+
jwk: JsonWebKey,
|
|
387
|
+
algorithm: CryptoUtils.KeyPairAlgorithm
|
|
388
|
+
): Promise<Result<CryptoKey>> {
|
|
389
|
+
const params = CryptoUtils.keyPairAlgorithmParams[algorithm];
|
|
390
|
+
const result = await captureAsyncResult(() =>
|
|
391
|
+
this._crypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)
|
|
392
|
+
);
|
|
393
|
+
return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
|
|
394
|
+
}
|
|
395
|
+
/* c8 ignore stop */
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Wraps `plaintext` for the holder of `recipientPublicKey` using
|
|
399
|
+
* ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
|
|
400
|
+
* {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
|
|
401
|
+
* @param plaintext - The bytes to wrap.
|
|
402
|
+
* @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
|
|
403
|
+
* @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
|
|
404
|
+
* @returns `Success` with the wrapped payload, or `Failure` with an error.
|
|
405
|
+
*/
|
|
406
|
+
public async wrapBytes(
|
|
407
|
+
plaintext: Uint8Array,
|
|
408
|
+
recipientPublicKey: CryptoKey,
|
|
409
|
+
options: CryptoUtils.IWrapBytesOptions
|
|
410
|
+
): Promise<Result<CryptoUtils.IWrappedBytes>> {
|
|
411
|
+
const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
|
|
412
|
+
if (recipientCheck.isFailure()) {
|
|
413
|
+
return Failure.with(`wrapBytes failed: ${recipientCheck.message}`);
|
|
414
|
+
}
|
|
415
|
+
const subtle = this._crypto.subtle;
|
|
416
|
+
const result = await captureAsyncResult(async () => {
|
|
417
|
+
const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
|
|
418
|
+
'deriveKey'
|
|
419
|
+
])) as CryptoKeyPair;
|
|
420
|
+
const hkdfBase = await subtle.deriveKey(
|
|
421
|
+
{ name: 'ECDH', public: recipientPublicKey },
|
|
422
|
+
ephemeral.privateKey,
|
|
423
|
+
{ name: 'HKDF' },
|
|
424
|
+
false,
|
|
425
|
+
['deriveKey']
|
|
426
|
+
);
|
|
427
|
+
const wrapKey = await subtle.deriveKey(
|
|
428
|
+
{ name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },
|
|
429
|
+
hkdfBase,
|
|
430
|
+
{ name: 'AES-GCM', length: 256 },
|
|
431
|
+
false,
|
|
432
|
+
['encrypt']
|
|
433
|
+
);
|
|
434
|
+
const nonce = this._crypto.getRandomValues(new Uint8Array(CryptoUtils.Constants.GCM_IV_SIZE));
|
|
435
|
+
const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, toBufferView(plaintext));
|
|
436
|
+
const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
|
|
437
|
+
return {
|
|
438
|
+
ephemeralPublicKey,
|
|
439
|
+
nonce: this.toBase64(nonce),
|
|
440
|
+
ciphertext: this.toBase64(new Uint8Array(ctBuf))
|
|
441
|
+
};
|
|
442
|
+
});
|
|
443
|
+
return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Unwraps a payload produced by `wrapBytes` using the recipient's private
|
|
448
|
+
* key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
|
|
449
|
+
* @param wrapped - The wrapped payload.
|
|
450
|
+
* @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
|
|
451
|
+
* @param options - HKDF salt and info matching the wrap call.
|
|
452
|
+
* @returns `Success` with the original `plaintext`, or `Failure` with an error.
|
|
453
|
+
*/
|
|
454
|
+
public async unwrapBytes(
|
|
455
|
+
wrapped: CryptoUtils.IWrappedBytes,
|
|
456
|
+
recipientPrivateKey: CryptoKey,
|
|
457
|
+
options: CryptoUtils.IWrapBytesOptions
|
|
458
|
+
): Promise<Result<Uint8Array>> {
|
|
459
|
+
const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
|
|
460
|
+
if (recipientCheck.isFailure()) {
|
|
461
|
+
return Failure.with(`unwrapBytes failed: ${recipientCheck.message}`);
|
|
462
|
+
}
|
|
463
|
+
const nonceResult = this.fromBase64(wrapped.nonce);
|
|
464
|
+
if (nonceResult.isFailure()) {
|
|
465
|
+
return Failure.with(`unwrapBytes failed: nonce: ${nonceResult.message}`);
|
|
466
|
+
}
|
|
467
|
+
if (nonceResult.value.length !== CryptoUtils.Constants.GCM_IV_SIZE) {
|
|
468
|
+
return Failure.with(
|
|
469
|
+
`unwrapBytes failed: nonce must be ${CryptoUtils.Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
const ciphertextResult = this.fromBase64(wrapped.ciphertext);
|
|
473
|
+
if (ciphertextResult.isFailure()) {
|
|
474
|
+
return Failure.with(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
|
|
475
|
+
}
|
|
476
|
+
if (ciphertextResult.value.length < CryptoUtils.Constants.GCM_AUTH_TAG_SIZE) {
|
|
477
|
+
return Failure.with(
|
|
478
|
+
`unwrapBytes failed: ciphertext must be at least ${CryptoUtils.Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
const subtle = this._crypto.subtle;
|
|
482
|
+
const result = await captureAsyncResult(async () => {
|
|
483
|
+
const ephemeralPub = await subtle.importKey(
|
|
484
|
+
'jwk',
|
|
485
|
+
wrapped.ephemeralPublicKey,
|
|
486
|
+
{ name: 'ECDH', namedCurve: 'P-256' },
|
|
487
|
+
false,
|
|
488
|
+
[]
|
|
489
|
+
);
|
|
490
|
+
const hkdfBase = await subtle.deriveKey(
|
|
491
|
+
{ name: 'ECDH', public: ephemeralPub },
|
|
492
|
+
recipientPrivateKey,
|
|
493
|
+
{ name: 'HKDF' },
|
|
494
|
+
false,
|
|
495
|
+
['deriveKey']
|
|
496
|
+
);
|
|
497
|
+
const wrapKey = await subtle.deriveKey(
|
|
498
|
+
{ name: 'HKDF', salt: toBufferView(options.salt), info: toBufferView(options.info), hash: 'SHA-256' },
|
|
499
|
+
hkdfBase,
|
|
500
|
+
{ name: 'AES-GCM', length: 256 },
|
|
501
|
+
false,
|
|
502
|
+
['decrypt']
|
|
503
|
+
);
|
|
504
|
+
const ptBuf = await subtle.decrypt(
|
|
505
|
+
{ name: 'AES-GCM', iv: toBufferView(nonceResult.value) },
|
|
506
|
+
wrapKey,
|
|
507
|
+
toBufferView(ciphertextResult.value)
|
|
508
|
+
);
|
|
509
|
+
return new Uint8Array(ptBuf);
|
|
510
|
+
});
|
|
511
|
+
return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
|
|
517
|
+
* (public or private). Used by the wrap/unwrap methods to surface a clean
|
|
518
|
+
* `Failure` instead of letting the WebCrypto deriveKey call throw a less
|
|
519
|
+
* informative error later in the pipeline. Key usages are intentionally not
|
|
520
|
+
* checked here: WebCrypto already produces a specific error if `deriveKey` is
|
|
521
|
+
* not in `usages`, and `deriveBits` is an equally valid alternative usage that
|
|
522
|
+
* an explicit check would have to track.
|
|
523
|
+
* @param key - The CryptoKey to validate.
|
|
524
|
+
* @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
|
|
525
|
+
* @param label - Human-readable role label included in the failure message.
|
|
526
|
+
* @returns `Success` with the key (unchanged) when the algorithm, curve, and
|
|
527
|
+
* type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
|
|
528
|
+
*/
|
|
529
|
+
function checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {
|
|
530
|
+
if (key.algorithm.name !== 'ECDH') {
|
|
531
|
+
return Failure.with(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
|
|
532
|
+
}
|
|
533
|
+
const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;
|
|
534
|
+
if (namedCurve !== 'P-256') {
|
|
535
|
+
return Failure.with(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
|
|
536
|
+
}
|
|
537
|
+
if (key.type !== keyType) {
|
|
538
|
+
return Failure.with(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
|
|
539
|
+
}
|
|
540
|
+
return succeed(key);
|
|
321
541
|
}
|
|
322
542
|
|
|
543
|
+
/* c8 ignore start - Constructs a provider; only meaningful in a real browser environment */
|
|
323
544
|
/**
|
|
324
545
|
* Creates a {@link CryptoUtils.BrowserCryptoProvider | BrowserCryptoProvider} if Web
|
|
325
546
|
* Crypto API is available.
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Erik Fortune
|
|
3
|
+
*
|
|
4
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
* in the Software without restriction, including without limitation the rights
|
|
7
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
* furnished to do so, subject to the following conditions:
|
|
10
|
+
*
|
|
11
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
* copies or substantial portions of the Software.
|
|
13
|
+
*
|
|
14
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
|
+
* SOFTWARE.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import '@fgv/ts-utils-jest';
|
|
24
|
+
|
|
25
|
+
import { CryptoUtils } from '@fgv/ts-extras';
|
|
26
|
+
import { BrowserCryptoProvider } from '../../packlets/crypto-utils';
|
|
27
|
+
|
|
28
|
+
const provider = new BrowserCryptoProvider();
|
|
29
|
+
const subtle = globalThis.crypto.subtle;
|
|
30
|
+
|
|
31
|
+
async function generateEcdhPair(curve: 'P-256' | 'P-384' = 'P-256'): Promise<CryptoKeyPair> {
|
|
32
|
+
return (await subtle.generateKey({ name: 'ECDH', namedCurve: curve }, true, [
|
|
33
|
+
'deriveKey',
|
|
34
|
+
'deriveBits'
|
|
35
|
+
])) as CryptoKeyPair;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function generateEcdsaPair(): Promise<CryptoKeyPair> {
|
|
39
|
+
return (await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
|
|
40
|
+
'sign',
|
|
41
|
+
'verify'
|
|
42
|
+
])) as CryptoKeyPair;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('BrowserCryptoProvider — wrapBytes/unwrapBytes', () => {
|
|
46
|
+
const defaultOptions: CryptoUtils.IWrapBytesOptions = {
|
|
47
|
+
salt: new TextEncoder().encode('test-salt'),
|
|
48
|
+
info: new TextEncoder().encode('test-info')
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
describe('round-trip', () => {
|
|
52
|
+
test.each<[string, Uint8Array]>([
|
|
53
|
+
['32-byte plaintext (AES-256 key shape)', globalThis.crypto.getRandomValues(new Uint8Array(32))],
|
|
54
|
+
['1-byte plaintext', new Uint8Array([0x42])],
|
|
55
|
+
['1KB plaintext', globalThis.crypto.getRandomValues(new Uint8Array(1024))],
|
|
56
|
+
['empty plaintext', new Uint8Array(0)],
|
|
57
|
+
['high-bit-set bytes', new Uint8Array(64).fill(0xff)]
|
|
58
|
+
])('round-trips %s', async (__label, plaintext) => {
|
|
59
|
+
const pair = await generateEcdhPair();
|
|
60
|
+
const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
61
|
+
expect(wrapped.ephemeralPublicKey.kty).toBe('EC');
|
|
62
|
+
expect(wrapped.ephemeralPublicKey.crv).toBe('P-256');
|
|
63
|
+
const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, defaultOptions)).orThrow();
|
|
64
|
+
expect(new Uint8Array(recovered)).toEqual(plaintext);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('determinism / freshness', () => {
|
|
69
|
+
test('two wraps of identical inputs produce different ephemeral keys and ciphertexts', async () => {
|
|
70
|
+
const pair = await generateEcdhPair();
|
|
71
|
+
const plaintext = new TextEncoder().encode('same payload');
|
|
72
|
+
const w1 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
73
|
+
const w2 = (await provider.wrapBytes(plaintext, pair.publicKey, defaultOptions)).orThrow();
|
|
74
|
+
expect(w1.ephemeralPublicKey).not.toEqual(w2.ephemeralPublicKey);
|
|
75
|
+
expect(w1.ciphertext).not.toEqual(w2.ciphertext);
|
|
76
|
+
expect(w1.nonce).not.toEqual(w2.nonce);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe('tampering', () => {
|
|
81
|
+
test('flipping a bit in the nonce fails GCM authentication', async () => {
|
|
82
|
+
const pair = await generateEcdhPair();
|
|
83
|
+
const wrapped = (
|
|
84
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
85
|
+
).orThrow();
|
|
86
|
+
const nonce = provider.fromBase64(wrapped.nonce).orThrow();
|
|
87
|
+
nonce[0] ^= 0xff;
|
|
88
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(nonce) };
|
|
89
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
90
|
+
/unwrapBytes failed/i
|
|
91
|
+
);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('flipping a bit in the ciphertext fails GCM authentication', async () => {
|
|
95
|
+
const pair = await generateEcdhPair();
|
|
96
|
+
const wrapped = (
|
|
97
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
98
|
+
).orThrow();
|
|
99
|
+
const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
|
|
100
|
+
ct[0] ^= 0x01;
|
|
101
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(ct) };
|
|
102
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
103
|
+
/unwrapBytes failed/i
|
|
104
|
+
);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('truncating ciphertext by one byte fails GCM authentication (still ≥ 16 bytes)', async () => {
|
|
108
|
+
const pair = await generateEcdhPair();
|
|
109
|
+
// 16-byte plaintext → 32-byte ciphertext (16 ct + 16 tag); truncate by 1 → 31 bytes ≥ 16
|
|
110
|
+
const wrapped = (
|
|
111
|
+
await provider.wrapBytes(new Uint8Array(16).fill(0xab), pair.publicKey, defaultOptions)
|
|
112
|
+
).orThrow();
|
|
113
|
+
const ct = provider.fromBase64(wrapped.ciphertext).orThrow();
|
|
114
|
+
const truncated = ct.slice(0, ct.length - 1);
|
|
115
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(truncated) };
|
|
116
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
117
|
+
/unwrapBytes failed/i
|
|
118
|
+
);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('substituting a different ephemeral public key fails authentication', async () => {
|
|
122
|
+
const pair = await generateEcdhPair();
|
|
123
|
+
const wrapped = (
|
|
124
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
125
|
+
).orThrow();
|
|
126
|
+
const other = (
|
|
127
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
128
|
+
).orThrow();
|
|
129
|
+
const tampered: CryptoUtils.IWrappedBytes = {
|
|
130
|
+
...wrapped,
|
|
131
|
+
ephemeralPublicKey: other.ephemeralPublicKey
|
|
132
|
+
};
|
|
133
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
134
|
+
/unwrapBytes failed/i
|
|
135
|
+
);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('wrong-key / wrong-options', () => {
|
|
140
|
+
test('unwrap with a different recipient private key fails', async () => {
|
|
141
|
+
const pair = await generateEcdhPair();
|
|
142
|
+
const other = await generateEcdhPair();
|
|
143
|
+
const wrapped = (
|
|
144
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
145
|
+
).orThrow();
|
|
146
|
+
expect(await provider.unwrapBytes(wrapped, other.privateKey, defaultOptions)).toFailWith(
|
|
147
|
+
/unwrapBytes failed/i
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('unwrap with a different HKDF salt fails authentication', async () => {
|
|
152
|
+
const pair = await generateEcdhPair();
|
|
153
|
+
const wrapped = (
|
|
154
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
155
|
+
).orThrow();
|
|
156
|
+
const wrongSalt: CryptoUtils.IWrapBytesOptions = {
|
|
157
|
+
salt: new TextEncoder().encode('different-salt'),
|
|
158
|
+
info: defaultOptions.info
|
|
159
|
+
};
|
|
160
|
+
expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongSalt)).toFailWith(
|
|
161
|
+
/unwrapBytes failed/i
|
|
162
|
+
);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('unwrap with a different HKDF info fails authentication', async () => {
|
|
166
|
+
const pair = await generateEcdhPair();
|
|
167
|
+
const wrapped = (
|
|
168
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
169
|
+
).orThrow();
|
|
170
|
+
const wrongInfo: CryptoUtils.IWrapBytesOptions = {
|
|
171
|
+
salt: defaultOptions.salt,
|
|
172
|
+
info: new TextEncoder().encode('different-info')
|
|
173
|
+
};
|
|
174
|
+
expect(await provider.unwrapBytes(wrapped, pair.privateKey, wrongInfo)).toFailWith(
|
|
175
|
+
/unwrapBytes failed/i
|
|
176
|
+
);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test('empty salt and info round-trip when both sides agree', async () => {
|
|
180
|
+
const pair = await generateEcdhPair();
|
|
181
|
+
const empty: CryptoUtils.IWrapBytesOptions = { salt: new Uint8Array(0), info: new Uint8Array(0) };
|
|
182
|
+
const plaintext = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
183
|
+
const wrapped = (await provider.wrapBytes(plaintext, pair.publicKey, empty)).orThrow();
|
|
184
|
+
const recovered = (await provider.unwrapBytes(wrapped, pair.privateKey, empty)).orThrow();
|
|
185
|
+
expect(new Uint8Array(recovered)).toEqual(plaintext);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
describe('malformed input', () => {
|
|
190
|
+
test('malformed ephemeralPublicKey JWK fails', async () => {
|
|
191
|
+
const pair = await generateEcdhPair();
|
|
192
|
+
const wrapped = (
|
|
193
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
194
|
+
).orThrow();
|
|
195
|
+
const bogus: CryptoUtils.IWrappedBytes = {
|
|
196
|
+
...wrapped,
|
|
197
|
+
ephemeralPublicKey: { kty: 'EC', crv: 'P-256' } as JsonWebKey
|
|
198
|
+
};
|
|
199
|
+
expect(await provider.unwrapBytes(bogus, pair.privateKey, defaultOptions)).toFailWith(
|
|
200
|
+
/unwrapBytes failed/i
|
|
201
|
+
);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test('ephemeralPublicKey on the wrong curve (P-384) fails', async () => {
|
|
205
|
+
const pair = await generateEcdhPair();
|
|
206
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
207
|
+
const wrongJwk = await subtle.exportKey('jwk', wrongCurve.publicKey);
|
|
208
|
+
const wrapped = (
|
|
209
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
210
|
+
).orThrow();
|
|
211
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ephemeralPublicKey: wrongJwk };
|
|
212
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
213
|
+
/unwrapBytes failed/i
|
|
214
|
+
);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test('non-base64 nonce fails with a clean error', async () => {
|
|
218
|
+
const pair = await generateEcdhPair();
|
|
219
|
+
const wrapped = (
|
|
220
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
221
|
+
).orThrow();
|
|
222
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: 'not!base64!' };
|
|
223
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
224
|
+
/unwrapBytes failed: nonce/i
|
|
225
|
+
);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test('non-base64 ciphertext fails with a clean error', async () => {
|
|
229
|
+
const pair = await generateEcdhPair();
|
|
230
|
+
const wrapped = (
|
|
231
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
232
|
+
).orThrow();
|
|
233
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: 'not!base64!' };
|
|
234
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
235
|
+
/unwrapBytes failed: ciphertext/i
|
|
236
|
+
);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('wrong-length nonce (after base64 decode) fails before reaching AES-GCM', async () => {
|
|
240
|
+
const pair = await generateEcdhPair();
|
|
241
|
+
const wrapped = (
|
|
242
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
243
|
+
).orThrow();
|
|
244
|
+
const shortNonce = new Uint8Array(8);
|
|
245
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, nonce: provider.toBase64(shortNonce) };
|
|
246
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
247
|
+
/unwrapBytes failed: nonce must be 12 bytes \(got 8\)/i
|
|
248
|
+
);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
test('ciphertext shorter than the GCM auth tag fails before reaching AES-GCM', async () => {
|
|
252
|
+
const pair = await generateEcdhPair();
|
|
253
|
+
const wrapped = (
|
|
254
|
+
await provider.wrapBytes(new TextEncoder().encode('payload'), pair.publicKey, defaultOptions)
|
|
255
|
+
).orThrow();
|
|
256
|
+
const shortCt = new Uint8Array(8);
|
|
257
|
+
const tampered: CryptoUtils.IWrappedBytes = { ...wrapped, ciphertext: provider.toBase64(shortCt) };
|
|
258
|
+
expect(await provider.unwrapBytes(tampered, pair.privateKey, defaultOptions)).toFailWith(
|
|
259
|
+
/unwrapBytes failed: ciphertext must be at least 16 bytes \(got 8\)/i
|
|
260
|
+
);
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe('algorithm / type mismatch on recipient key', () => {
|
|
265
|
+
test('wrap fails when recipient public key is RSA-OAEP, not ECDH', async () => {
|
|
266
|
+
const rsa = (await subtle.generateKey(
|
|
267
|
+
{
|
|
268
|
+
name: 'RSA-OAEP',
|
|
269
|
+
modulusLength: 2048,
|
|
270
|
+
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
|
271
|
+
hash: 'SHA-256'
|
|
272
|
+
},
|
|
273
|
+
true,
|
|
274
|
+
['encrypt', 'decrypt']
|
|
275
|
+
)) as CryptoKeyPair;
|
|
276
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), rsa.publicKey, defaultOptions);
|
|
277
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*RSA-OAEP/i);
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test('wrap fails when recipient public key is ECDSA P-256, not ECDH', async () => {
|
|
281
|
+
const ecdsa = await generateEcdsaPair();
|
|
282
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), ecdsa.publicKey, defaultOptions);
|
|
283
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*ECDSA/i);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test('wrap fails when recipient public key is ECDH P-384, not P-256', async () => {
|
|
287
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
288
|
+
const result = await provider.wrapBytes(
|
|
289
|
+
new Uint8Array([1, 2, 3]),
|
|
290
|
+
wrongCurve.publicKey,
|
|
291
|
+
defaultOptions
|
|
292
|
+
);
|
|
293
|
+
expect(result).toFailWith(/wrapBytes failed: recipient public key must be ECDH P-256.*P-384/i);
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test('unwrap fails when recipient private key is ECDH P-384, not P-256', async () => {
|
|
297
|
+
const pair = await generateEcdhPair();
|
|
298
|
+
const wrapped = (
|
|
299
|
+
await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)
|
|
300
|
+
).orThrow();
|
|
301
|
+
const wrongCurve = await generateEcdhPair('P-384');
|
|
302
|
+
const result = await provider.unwrapBytes(wrapped, wrongCurve.privateKey, defaultOptions);
|
|
303
|
+
expect(result).toFailWith(/unwrapBytes failed: recipient private key must be ECDH P-256.*P-384/i);
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test('wrap fails when recipient is an ECDH private key (not public)', async () => {
|
|
307
|
+
const pair = await generateEcdhPair();
|
|
308
|
+
const result = await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.privateKey, defaultOptions);
|
|
309
|
+
expect(result).toFailWith(
|
|
310
|
+
/wrapBytes failed: recipient public key must be a public CryptoKey \(got 'private'\)/i
|
|
311
|
+
);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
test('unwrap fails when recipient is an ECDH public key (not private)', async () => {
|
|
315
|
+
const pair = await generateEcdhPair();
|
|
316
|
+
const wrapped = (
|
|
317
|
+
await provider.wrapBytes(new Uint8Array([1, 2, 3]), pair.publicKey, defaultOptions)
|
|
318
|
+
).orThrow();
|
|
319
|
+
const result = await provider.unwrapBytes(wrapped, pair.publicKey, defaultOptions);
|
|
320
|
+
expect(result).toFailWith(
|
|
321
|
+
/unwrapBytes failed: recipient private key must be a private CryptoKey \(got 'public'\)/i
|
|
322
|
+
);
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
});
|