micro509 0.8.0 → 0.10.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 (108) hide show
  1. package/dist/index.d.ts +4 -4
  2. package/dist/index.js +15 -15
  3. package/dist/internal/asn1/asn1.js +145 -186
  4. package/dist/internal/asn1/asn1.js.map +1 -0
  5. package/dist/internal/asn1/der.js +210 -227
  6. package/dist/internal/asn1/der.js.map +1 -0
  7. package/dist/internal/asn1/oids.js +297 -101
  8. package/dist/internal/asn1/oids.js.map +1 -0
  9. package/dist/internal/asn1/oids2.js +69 -0
  10. package/dist/internal/asn1/oids2.js.map +1 -0
  11. package/dist/internal/crypto/algorithm-names.js +37 -35
  12. package/dist/internal/crypto/algorithm-names.js.map +1 -0
  13. package/dist/internal/crypto/ecdsa.js +25 -28
  14. package/dist/internal/crypto/ecdsa.js.map +1 -0
  15. package/dist/internal/crypto/hash.js +56 -117
  16. package/dist/internal/crypto/hash.js.map +1 -0
  17. package/dist/internal/crypto/pbes2.js +122 -133
  18. package/dist/internal/crypto/pbes2.js.map +1 -0
  19. package/dist/internal/crypto/rsa-pss.js +118 -124
  20. package/dist/internal/crypto/rsa-pss.js.map +1 -0
  21. package/dist/internal/crypto/sig-verify.js +87 -99
  22. package/dist/internal/crypto/sig-verify.js.map +1 -0
  23. package/dist/internal/crypto/signing.d.ts +12 -8
  24. package/dist/internal/crypto/signing.js +53 -55
  25. package/dist/internal/crypto/signing.js.map +1 -0
  26. package/dist/internal/crypto/webcrypto.js +5 -3
  27. package/dist/internal/crypto/webcrypto.js.map +1 -0
  28. package/dist/internal/shared/base64.js +10 -9
  29. package/dist/internal/shared/base64.js.map +1 -0
  30. package/dist/internal/shared/dn.js +50 -57
  31. package/dist/internal/shared/dn.js.map +1 -0
  32. package/dist/internal/shared/ip.js +43 -53
  33. package/dist/internal/shared/ip.js.map +1 -0
  34. package/dist/internal/verify/name-constraints-engine.js +211 -239
  35. package/dist/internal/verify/name-constraints-engine.js.map +1 -0
  36. package/dist/internal/verify/policy-engine.js +228 -247
  37. package/dist/internal/verify/policy-engine.js.map +1 -0
  38. package/dist/internal/verify/verify-path.js +213 -228
  39. package/dist/internal/verify/verify-path.js.map +1 -0
  40. package/dist/internal/x509/extension-bits.js +62 -59
  41. package/dist/internal/x509/extension-bits.js.map +1 -0
  42. package/dist/internal/x509/extension-registry.js +133 -164
  43. package/dist/internal/x509/extension-registry.js.map +1 -0
  44. package/dist/internal/x509/name-fields.js +35 -41
  45. package/dist/internal/x509/name-fields.js.map +1 -0
  46. package/dist/keys/keys.d.ts +626 -447
  47. package/dist/keys/keys.js +652 -404
  48. package/dist/keys/keys.js.map +1 -0
  49. package/dist/keys.d.ts +2 -2
  50. package/dist/keys.js +2 -2
  51. package/dist/pem/pem.d.ts +46 -46
  52. package/dist/pem/pem.js +62 -81
  53. package/dist/pem/pem.js.map +1 -0
  54. package/dist/pem.js +2 -2
  55. package/dist/pkcs/pfx.d.ts +96 -80
  56. package/dist/pkcs/pfx.js +191 -231
  57. package/dist/pkcs/pfx.js.map +1 -0
  58. package/dist/pkcs/pkcs12-mac.d.ts +20 -18
  59. package/dist/pkcs/pkcs12-mac.js +90 -111
  60. package/dist/pkcs/pkcs12-mac.js.map +1 -0
  61. package/dist/pkcs/pkcs7.d.ts +118 -69
  62. package/dist/pkcs/pkcs7.js +401 -443
  63. package/dist/pkcs/pkcs7.js.map +1 -0
  64. package/dist/pkcs.d.ts +2 -2
  65. package/dist/pkcs.js +4 -4
  66. package/dist/result/result.d.ts +37 -32
  67. package/dist/result/result.js +46 -44
  68. package/dist/result/result.js.map +1 -0
  69. package/dist/result.js +2 -2
  70. package/dist/revocation/chain.d.ts +138 -119
  71. package/dist/revocation/chain.js +248 -281
  72. package/dist/revocation/chain.js.map +1 -0
  73. package/dist/revocation/crl.d.ts +125 -123
  74. package/dist/revocation/crl.js +653 -745
  75. package/dist/revocation/crl.js.map +1 -0
  76. package/dist/revocation/ocsp.d.ts +183 -177
  77. package/dist/revocation/ocsp.js +581 -638
  78. package/dist/revocation/ocsp.js.map +1 -0
  79. package/dist/revocation/revocation.d.ts +26 -26
  80. package/dist/revocation/revocation.js +104 -125
  81. package/dist/revocation/revocation.js.map +1 -0
  82. package/dist/revocation.js +5 -5
  83. package/dist/verify/identity.d.ts +42 -42
  84. package/dist/verify/identity.js +158 -167
  85. package/dist/verify/identity.js.map +1 -0
  86. package/dist/verify/name-constraints.d.ts +7 -7
  87. package/dist/verify/policy.d.ts +10 -10
  88. package/dist/verify/verify.d.ts +163 -163
  89. package/dist/verify/verify.js +396 -392
  90. package/dist/verify/verify.js.map +1 -0
  91. package/dist/verify.js +3 -3
  92. package/dist/x509/certificate.d.ts +117 -117
  93. package/dist/x509/certificate.js +51 -60
  94. package/dist/x509/certificate.js.map +1 -0
  95. package/dist/x509/csr.d.ts +25 -25
  96. package/dist/x509/csr.js +26 -30
  97. package/dist/x509/csr.js.map +1 -0
  98. package/dist/x509/extensions.d.ts +228 -184
  99. package/dist/x509/extensions.js +175 -200
  100. package/dist/x509/extensions.js.map +1 -0
  101. package/dist/x509/name.d.ts +94 -93
  102. package/dist/x509/name.js +30 -29
  103. package/dist/x509/name.js.map +1 -0
  104. package/dist/x509/parse.d.ts +185 -185
  105. package/dist/x509/parse.js +638 -676
  106. package/dist/x509/parse.js.map +1 -0
  107. package/dist/x509.js +6 -6
  108. package/package.json +79 -41
package/dist/keys/keys.js CHANGED
@@ -1,76 +1,79 @@
1
- import { nullValue, objectIdentifier, octetString, readRootElement, readSequenceChildren, sequence } from "../internal/asn1/der.js";
2
- import { decodeObjectIdentifier, extractBitStringValue, hexToBytes, toArrayBuffer, toHex } from "../internal/asn1/asn1.js";
3
- import { OIDS } from "../internal/asn1/oids.js";
4
- import { md5 } from "../internal/crypto/hash.js";
5
- import { getCrypto } from "../internal/crypto/webcrypto.js";
6
- import { decryptPbes2, encryptPbes2, isWrongPasswordError, wrongPasswordError } from "../internal/crypto/pbes2.js";
7
- import { base64Decode, base64Encode } from "../internal/shared/base64.js";
8
- import { failureResult, rethrowIfInvariant, successResult } from "../result/result.js";
9
- import { pemDecodeOrThrow, pemEncode } from "../pem/pem.js";
1
+ import { explicitContext as e, nullValue as t, objectIdentifier as n, octetString as r, readRootElement as i, readSequenceChildren as a, sequence as o } from "../internal/asn1/der.js";
2
+ import { decodeObjectIdentifier as s, extractBitStringValue as c, hexToBytes as l, toArrayBuffer as u, toHex as d } from "../internal/asn1/asn1.js";
3
+ import { OIDS as f } from "../internal/asn1/oids2.js";
4
+ import { md5 as p } from "../internal/crypto/hash.js";
5
+ import { getCrypto as m } from "../internal/crypto/webcrypto.js";
6
+ import { decryptPbes2 as h, encryptPbes2 as g, isWrongPasswordError as _, wrongPasswordError as v } from "../internal/crypto/pbes2.js";
7
+ import { base64Decode as y, base64Encode as b } from "../internal/shared/base64.js";
8
+ import { failureResult as x, rethrowIfInvariant as S, successResult as C } from "../result/result.js";
9
+ import { pemDecodeOrThrow as w, pemEncode as T } from "../pem/pem.js";
10
10
  //#region src/keys/keys.ts
11
11
  /**
12
12
  * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.
13
13
  *
14
- * Supports RSA (PKCS#1v1.5 and PSS), ECDSA (P-256, P-384, P-521), and Ed25519 keys.
14
+ * Supports RSA (PKCS#1v1.5, PSS, and OAEP), ECDSA (P-256, P-384, P-521), and Ed25519 keys.
15
15
  * All functions use the WebCrypto API and return extractable keys.
16
16
  *
17
17
  * @example
18
18
  * ```ts
19
- * import { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';
19
+ * import { unwrap } from 'micro509';
20
+ * import { generateKeyPair, exportSpkiPem, importSpkiPem } from 'micro509/keys';
20
21
  *
21
22
  * // Generate and export
22
23
  * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });
23
- * const privatePem = await exportPkcs8Pem(keys.privateKey);
24
+ * const publicPem = await exportSpkiPem(keys.publicKey);
24
25
  *
25
- * // Import
26
- * const publicKey = await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' });
26
+ * // Import — Result-returning; unwrap() throws on failure
27
+ * const publicKey = unwrap(await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' }));
27
28
  * ```
28
29
  *
29
30
  * @module
30
31
  */
31
32
  /**
32
- * Generate an asymmetric key pair for signing and verification.
33
+ * Generate an asymmetric key pair for signing and verification, or — with
34
+ * `{ kind: 'rsa', scheme: 'oaep' }` — for RSA-OAEP encryption and decryption.
33
35
  *
34
36
  * @example
35
37
  * ```ts
36
38
  * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });
37
39
  * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });
38
40
  * const edKeys = await generateKeyPair({ kind: 'ed25519' });
41
+ * const oaepKeys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
39
42
  *
40
43
  * // Default: ECDSA P-256
41
44
  * const keys = await generateKeyPair();
42
45
  * const pem = await keys.exportPkcs8Pem();
43
46
  * ```
44
47
  */
45
- async function generateKeyPair(algorithm = {
48
+ async function generateKeyPair(e = {
46
49
  kind: "ecdsa",
47
50
  curve: "P-256"
48
51
  }) {
49
- const generated = await getCrypto().subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, ["sign", "verify"]);
50
- if (!("publicKey" in generated) || !("privateKey" in generated)) throw new Error("Expected an asymmetric key pair");
51
- return wrapKeyPair(generated.publicKey, generated.privateKey);
52
+ let t = m().subtle, n = isRsaOaepInput(e) ? ["encrypt", "decrypt"] : ["sign", "verify"], r = await t.generateKey(toGenerateKeyAlgorithm(e), !0, n);
53
+ if (!("publicKey" in r) || !("privateKey" in r)) throw Error("Expected an asymmetric key pair");
54
+ return wrapKeyPair(r.publicKey, r.privateKey);
52
55
  }
53
- function wrapKeyPair(publicKey, privateKey) {
56
+ function wrapKeyPair(e, t) {
54
57
  return {
55
- publicKey,
56
- privateKey,
58
+ publicKey: e,
59
+ privateKey: t,
57
60
  async exportSpkiDer() {
58
- return new Uint8Array(await getCrypto().subtle.exportKey("spki", publicKey));
61
+ return new Uint8Array(await m().subtle.exportKey("spki", e));
59
62
  },
60
63
  async exportSpkiPem() {
61
- return pemEncode("PUBLIC KEY", await this.exportSpkiDer());
64
+ return T("PUBLIC KEY", await this.exportSpkiDer());
62
65
  },
63
66
  async exportPkcs8Der() {
64
- return new Uint8Array(await getCrypto().subtle.exportKey("pkcs8", privateKey));
67
+ return new Uint8Array(await m().subtle.exportKey("pkcs8", t));
65
68
  },
66
69
  async exportPkcs8Pem() {
67
- return pemEncode("PRIVATE KEY", await this.exportPkcs8Der());
70
+ return T("PRIVATE KEY", await this.exportPkcs8Der());
68
71
  },
69
72
  exportPublicJwk() {
70
- return getCrypto().subtle.exportKey("jwk", publicKey);
73
+ return m().subtle.exportKey("jwk", e);
71
74
  },
72
75
  exportPrivateJwk() {
73
- return getCrypto().subtle.exportKey("jwk", privateKey);
76
+ return m().subtle.exportKey("jwk", t);
74
77
  }
75
78
  };
76
79
  }
@@ -80,8 +83,8 @@ function wrapKeyPair(publicKey, privateKey) {
80
83
  * @see {@linkcode importSpkiDer} for the inverse operation
81
84
  * @see {@linkcode exportSpkiPem} for PEM output
82
85
  */
83
- async function exportSpkiDer(publicKey) {
84
- return new Uint8Array(await getCrypto().subtle.exportKey("spki", publicKey));
86
+ async function exportSpkiDer(e) {
87
+ return new Uint8Array(await m().subtle.exportKey("spki", e));
85
88
  }
86
89
  /**
87
90
  * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.
@@ -90,8 +93,8 @@ async function exportSpkiDer(publicKey) {
90
93
  * @see {@linkcode exportPkcs8Pem} for PEM output
91
94
  * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export
92
95
  */
93
- async function exportPkcs8Der(privateKey) {
94
- return new Uint8Array(await getCrypto().subtle.exportKey("pkcs8", privateKey));
96
+ async function exportPkcs8Der(e) {
97
+ return new Uint8Array(await m().subtle.exportKey("pkcs8", e));
95
98
  }
96
99
  /**
97
100
  * Export a public key as a JSON Web Key.
@@ -102,8 +105,8 @@ async function exportPkcs8Der(privateKey) {
102
105
  * const jwk = await exportPublicJwk(keys.publicKey);
103
106
  * ```
104
107
  */
105
- function exportPublicJwk(publicKey) {
106
- return getCrypto().subtle.exportKey("jwk", publicKey);
108
+ function exportPublicJwk(e) {
109
+ return m().subtle.exportKey("jwk", e);
107
110
  }
108
111
  /**
109
112
  * Export a private key as a JSON Web Key.
@@ -111,8 +114,8 @@ function exportPublicJwk(publicKey) {
111
114
  * @see {@linkcode importPrivateJwk} for the inverse operation
112
115
  * @see {@linkcode exportPublicJwk} for public key export
113
116
  */
114
- function exportPrivateJwk(privateKey) {
115
- return getCrypto().subtle.exportKey("jwk", privateKey);
117
+ function exportPrivateJwk(e) {
118
+ return m().subtle.exportKey("jwk", e);
116
119
  }
117
120
  /**
118
121
  * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.
@@ -129,8 +132,8 @@ function exportPrivateJwk(privateKey) {
129
132
  * @see {@linkcode importPkcs8Pem} for the inverse operation
130
133
  * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export
131
134
  */
132
- async function exportPkcs8Pem(privateKey) {
133
- return pemEncode("PRIVATE KEY", await exportPkcs8Der(privateKey));
135
+ async function exportPkcs8Pem(e) {
136
+ return T("PRIVATE KEY", await exportPkcs8Der(e));
134
137
  }
135
138
  /**
136
139
  * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
@@ -143,9 +146,9 @@ async function exportPkcs8Pem(privateKey) {
143
146
  * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation
144
147
  * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output
145
148
  */
146
- async function exportEncryptedPkcs8Der(privateKey, options) {
147
- const encryption = await encryptPbes2(await exportPkcs8Der(privateKey), options);
148
- return sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);
149
+ async function exportEncryptedPkcs8Der(e, t) {
150
+ let n = await g(await exportPkcs8Der(e), t);
151
+ return o([n.algorithmIdentifierDer, r(n.encryptedData)]);
149
152
  }
150
153
  /**
151
154
  * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
@@ -161,8 +164,8 @@ async function exportEncryptedPkcs8Der(privateKey, options) {
161
164
  *
162
165
  * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation
163
166
  */
164
- async function exportEncryptedPkcs8Pem(privateKey, options) {
165
- return pemEncode("ENCRYPTED PRIVATE KEY", await exportEncryptedPkcs8Der(privateKey, options));
167
+ async function exportEncryptedPkcs8Pem(e, t) {
168
+ return T("ENCRYPTED PRIVATE KEY", await exportEncryptedPkcs8Der(e, t));
166
169
  }
167
170
  /**
168
171
  * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.
@@ -175,10 +178,10 @@ async function exportEncryptedPkcs8Pem(privateKey, options) {
175
178
  * @see {@linkcode importPkcs1Der} for the inverse operation
176
179
  * @see {@linkcode exportPkcs1Pem} for PEM output
177
180
  */
178
- async function exportPkcs1Der(privateKey) {
179
- const parsed = parsePkcs8PrivateKey(await exportPkcs8Der(privateKey));
180
- if (parsed.algorithmOid !== OIDS.rsaEncryption) throw new Error("PKCS#1 export requires an RSA private key");
181
- return parsed.privateKeyDer;
181
+ async function exportPkcs1Der(e) {
182
+ let t = parsePkcs8PrivateKey(await exportPkcs8Der(e));
183
+ if (t.algorithmOid !== f.rsaEncryption) throw Error("PKCS#1 export requires an RSA private key");
184
+ return t.privateKeyDer;
182
185
  }
183
186
  /**
184
187
  * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.
@@ -188,8 +191,8 @@ async function exportPkcs1Der(privateKey) {
188
191
  * @see {@linkcode importPkcs1Pem} for the inverse operation
189
192
  * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export
190
193
  */
191
- async function exportPkcs1Pem(privateKey) {
192
- return pemEncode("RSA PRIVATE KEY", await exportPkcs1Der(privateKey));
194
+ async function exportPkcs1Pem(e) {
195
+ return T("RSA PRIVATE KEY", await exportPkcs1Der(e));
193
196
  }
194
197
  /**
195
198
  * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
@@ -201,8 +204,8 @@ async function exportPkcs1Pem(privateKey) {
201
204
  *
202
205
  * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation
203
206
  */
204
- async function exportEncryptedPkcs1Pem(privateKey, options) {
205
- return encryptTraditionalPem("RSA PRIVATE KEY", await exportPkcs1Der(privateKey), options);
207
+ async function exportEncryptedPkcs1Pem(e, t) {
208
+ return encryptTraditionalPem("RSA PRIVATE KEY", await exportPkcs1Der(e), t);
206
209
  }
207
210
  /**
208
211
  * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.
@@ -210,15 +213,19 @@ async function exportEncryptedPkcs1Pem(privateKey, options) {
210
213
  * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use
211
214
  * {@linkcode exportPkcs8Der}.
212
215
  *
216
+ * The output always carries the RFC 5915 `parameters [0]` named curve
217
+ * (matching OpenSSL), so it re-imports via {@linkcode importSec1Der} without
218
+ * an explicit curve.
219
+ *
213
220
  * @throws {Error} If the key is not an EC key
214
221
  *
215
222
  * @see {@linkcode importSec1Der} for the inverse operation
216
223
  * @see {@linkcode exportSec1Pem} for PEM output
217
224
  */
218
- async function exportSec1Der(privateKey) {
219
- const parsed = parsePkcs8PrivateKey(await exportPkcs8Der(privateKey));
220
- if (parsed.algorithmOid !== OIDS.ecPublicKey) throw new Error("SEC1 export requires an EC private key");
221
- return parsed.privateKeyDer;
225
+ async function exportSec1Der(e) {
226
+ let t = parsePkcs8PrivateKey(await exportPkcs8Der(e));
227
+ if (t.algorithmOid !== f.ecPublicKey) throw Error("SEC1 export requires an EC private key");
228
+ return ensureSec1NamedCurveParameters(t.privateKeyDer, t.parametersOid);
222
229
  }
223
230
  /**
224
231
  * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.
@@ -228,8 +235,8 @@ async function exportSec1Der(privateKey) {
228
235
  * @see {@linkcode importSec1Pem} for the inverse operation
229
236
  * @see {@linkcode exportEncryptedSec1Pem} for password-protected export
230
237
  */
231
- async function exportSec1Pem(privateKey) {
232
- return pemEncode("EC PRIVATE KEY", await exportSec1Der(privateKey));
238
+ async function exportSec1Pem(e) {
239
+ return T("EC PRIVATE KEY", await exportSec1Der(e));
233
240
  }
234
241
  /**
235
242
  * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
@@ -241,8 +248,8 @@ async function exportSec1Pem(privateKey) {
241
248
  *
242
249
  * @see {@linkcode importEncryptedSec1Pem} for the inverse operation
243
250
  */
244
- async function exportEncryptedSec1Pem(privateKey, options) {
245
- return encryptTraditionalPem("EC PRIVATE KEY", await exportSec1Der(privateKey), options);
251
+ async function exportEncryptedSec1Pem(e, t) {
252
+ return encryptTraditionalPem("EC PRIVATE KEY", await exportSec1Der(e), t);
246
253
  }
247
254
  /**
248
255
  * Export a public key as PEM-encoded SubjectPublicKeyInfo.
@@ -253,25 +260,26 @@ async function exportEncryptedSec1Pem(privateKey, options) {
253
260
  * const pem = await exportSpkiPem(keys.publicKey);
254
261
  * ```
255
262
  */
256
- async function exportSpkiPem(publicKey) {
257
- return pemEncode("PUBLIC KEY", await exportSpkiDer(publicKey));
263
+ async function exportSpkiPem(e) {
264
+ return T("PUBLIC KEY", await exportSpkiDer(e));
258
265
  }
259
266
  /**
260
267
  * Derive the matching public key from an imported (or generated) private key.
261
268
  *
262
269
  * The `import*` functions that read a PKCS#8 / PKCS#1 / SEC 1 / JWK private key
263
- * return a bare `CryptoKey` with only `sign` usage — there is no accompanying
264
- * public handle. This bridges that gap: it exports the private key's JWK,
265
- * strips the private components, and re-imports the public half with `verify`
266
- * usage, so callers can go straight to {@linkcode exportSpkiDer} /
267
- * {@linkcode exportSpkiPem} (e.g. to rebuild a self-signed cert or distribute
268
- * the public key when only the private key is on disk).
270
+ * return a bare `CryptoKey` with only `sign` (or, for RSA-OAEP, `decrypt`)
271
+ * usage — there is no accompanying public handle. This bridges that gap: it
272
+ * exports the private key's JWK, strips the private components, and re-imports
273
+ * the public half with `verify` (RSA-OAEP: `encrypt`) usage, so callers can go
274
+ * straight to {@linkcode exportSpkiDer} / {@linkcode exportSpkiPem} (e.g. to
275
+ * rebuild a self-signed cert or distribute the public key when only the
276
+ * private key is on disk).
269
277
  *
270
278
  * Supports RSA (`n`/`e`), ECDSA (`x`/`y`), and Ed25519 (`x`). The derived key
271
279
  * inherits the private key's algorithm parameters (hash, curve).
272
280
  *
273
281
  * @param privateKey - An extractable private `CryptoKey`
274
- * @returns Extractable public `CryptoKey` with `verify` usage
282
+ * @returns Extractable public `CryptoKey` with `verify` (RSA-OAEP: `encrypt`) usage
275
283
  *
276
284
  * @throws {Error} If the key is not a private key, is non-extractable, or uses
277
285
  * an unsupported key type
@@ -285,12 +293,11 @@ async function exportSpkiPem(publicKey) {
285
293
  *
286
294
  * @see {@linkcode exportSpkiDer} for exporting the derived key
287
295
  */
288
- async function derivePublicKey(privateKey) {
289
- if (privateKey.type !== "private") throw new Error("derivePublicKey requires a private CryptoKey");
290
- if (!privateKey.extractable) throw new Error("Cannot derive public key from a non-extractable private key");
291
- const subtle = getCrypto().subtle;
292
- const privateJwk = await subtle.exportKey("jwk", privateKey);
293
- return subtle.importKey("jwk", toPublicJwk(privateJwk), privateKey.algorithm, true, ["verify"]);
296
+ async function derivePublicKey(e) {
297
+ if (e.type !== "private") throw Error("derivePublicKey requires a private CryptoKey");
298
+ if (!e.extractable) throw Error("Cannot derive public key from a non-extractable private key");
299
+ let t = m().subtle, n = e.algorithm.name === "RSA-OAEP" ? "encrypt" : "verify", r = await t.exportKey("jwk", e);
300
+ return t.importKey("jwk", toPublicJwk(r, n), e.algorithm, !0, [n]);
294
301
  }
295
302
  /**
296
303
  * Export a key as raw base64 (no PEM headers).
@@ -303,10 +310,10 @@ async function derivePublicKey(privateKey) {
303
310
  * @see {@linkcode importSpkiBase64} for public key import
304
311
  * @see {@linkcode importPkcs8Base64} for private key import
305
312
  */
306
- async function exportBinaryBase64(key) {
307
- if (key.type === "public") return base64Encode(await exportSpkiDer(key));
308
- if (key.type === "private") return base64Encode(await exportPkcs8Der(key));
309
- throw new Error("Cannot export secret/symmetric CryptoKey");
313
+ async function exportBinaryBase64(e) {
314
+ if (e.type === "public") return b(await exportSpkiDer(e));
315
+ if (e.type === "private") return b(await exportPkcs8Der(e));
316
+ throw Error("Cannot export secret/symmetric CryptoKey");
310
317
  }
311
318
  /**
312
319
  * Import a public key from DER-encoded SubjectPublicKeyInfo.
@@ -325,37 +332,29 @@ async function exportBinaryBase64(key) {
325
332
  * @see {@linkcode exportSpkiDer} for the inverse operation
326
333
  * @see {@linkcode importSpkiPem} for PEM input
327
334
  */
328
- async function importSpkiDerOrThrow(der, algorithm) {
329
- const parsedSpki = parseSpkiDer(der);
330
- let importInput;
331
- if (algorithm === void 0) importInput = inferPublicKeyImportInput(parsedSpki);
332
- else {
333
- assertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);
334
- importInput = algorithm;
335
- }
335
+ async function importSpkiDerOrThrow(e, t) {
336
+ let n = parseSpkiDer(e), r;
337
+ t === void 0 ? r = inferKeyImportInput(n, "Unsupported SubjectPublicKeyInfo algorithm") : (assertSpkiMatchesRequestedAlgorithm(n, t), r = t);
336
338
  try {
337
- return await getCrypto().subtle.importKey("spki", new Uint8Array(der), toImportAlgorithm(importInput), true, ["verify"]);
339
+ return await m().subtle.importKey("spki", new Uint8Array(e), toImportAlgorithm(r), !0, publicKeyUsages(r));
338
340
  } catch {
339
- throw new Error("Malformed SubjectPublicKeyInfo");
341
+ throw Error("Malformed SubjectPublicKeyInfo");
340
342
  }
341
343
  }
342
344
  /** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` result; invariants rethrow. */
343
- async function importResult(run) {
345
+ async function importResult(e) {
344
346
  try {
345
- return successResult(await run());
346
- } catch (error) {
347
- rethrowIfInvariant(error);
348
- return failureResult("malformed", error instanceof Error ? error.message : "Malformed key");
347
+ return C(await e());
348
+ } catch (e) {
349
+ return S(e), x("malformed", e instanceof Error ? e.message : "Malformed key");
349
350
  }
350
351
  }
351
352
  /** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */
352
- async function encryptedImportResult(run) {
353
+ async function encryptedImportResult(e) {
353
354
  try {
354
- return successResult(await run());
355
- } catch (error) {
356
- rethrowIfInvariant(error);
357
- if (isWrongPasswordError(error)) return failureResult("invalid_password", error.message);
358
- return failureResult("malformed", error instanceof Error ? error.message : "Malformed encrypted key");
355
+ return C(await e());
356
+ } catch (e) {
357
+ return S(e), _(e) ? x("invalid_password", e.message) : x("malformed", e instanceof Error ? e.message : "Malformed encrypted key");
359
358
  }
360
359
  }
361
360
  /**
@@ -363,8 +362,8 @@ async function encryptedImportResult(run) {
363
362
  *
364
363
  * @see `importSpkiDerOrThrow` for the throwing variant
365
364
  */
366
- function importSpkiDer(der, algorithm) {
367
- return importResult(() => importSpkiDerOrThrow(der, algorithm));
365
+ function importSpkiDer(e, t) {
366
+ return importResult(() => importSpkiDerOrThrow(e, t));
368
367
  }
369
368
  /**
370
369
  * Import a public key from PEM-encoded SubjectPublicKeyInfo.
@@ -374,21 +373,21 @@ function importSpkiDer(der, algorithm) {
374
373
  * const pem = `-----BEGIN PUBLIC KEY-----
375
374
  * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
376
375
  * -----END PUBLIC KEY-----`;
377
- * const key = await importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });
376
+ * const key = await importSpkiPemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });
378
377
  * ```
379
378
  *
380
379
  * @see {@linkcode exportSpkiPem} for the inverse operation
381
380
  */
382
- function importSpkiPemOrThrow(pem, algorithm) {
383
- return importSpkiDerOrThrow(pemDecodeOrThrow("PUBLIC KEY", pem), algorithm);
381
+ function importSpkiPemOrThrow(e, t) {
382
+ return importSpkiDerOrThrow(w("PUBLIC KEY", e), t);
384
383
  }
385
384
  /**
386
385
  * Import a public key from PEM-encoded SubjectPublicKeyInfo.
387
386
  *
388
387
  * @see `importSpkiPemOrThrow` for the throwing variant
389
388
  */
390
- function importSpkiPem(pem, algorithm) {
391
- return importResult(() => importSpkiPemOrThrow(pem, algorithm));
389
+ function importSpkiPem(e, t) {
390
+ return importResult(() => importSpkiPemOrThrow(e, t));
392
391
  }
393
392
  /**
394
393
  * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
@@ -396,48 +395,54 @@ function importSpkiPem(pem, algorithm) {
396
395
  * @see {@linkcode exportBinaryBase64} for the inverse operation
397
396
  * @see {@linkcode importSpkiPem} for PEM input with headers
398
397
  */
399
- function importSpkiBase64OrThrow(base64, algorithm) {
400
- let decoded;
398
+ function importSpkiBase64OrThrow(e, t) {
399
+ let n;
401
400
  try {
402
- decoded = base64Decode(base64);
401
+ n = y(e);
403
402
  } catch {
404
- throw new Error("Invalid base64 SubjectPublicKeyInfo");
403
+ throw Error("Invalid base64 SubjectPublicKeyInfo");
405
404
  }
406
- return importSpkiDerOrThrow(decoded, algorithm);
405
+ return importSpkiDerOrThrow(n, t);
407
406
  }
408
407
  /**
409
408
  * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
410
409
  *
411
410
  * @see `importSpkiBase64OrThrow` for the throwing variant
412
411
  */
413
- function importSpkiBase64(base64, algorithm) {
414
- return importResult(() => importSpkiBase64OrThrow(base64, algorithm));
412
+ function importSpkiBase64(e, t) {
413
+ return importResult(() => importSpkiBase64OrThrow(e, t));
415
414
  }
416
415
  /**
417
416
  * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.
418
417
  *
418
+ * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is
419
+ * inferred from the PrivateKeyInfo's own `privateKeyAlgorithm` — useful for
420
+ * keys whose type isn't known ahead of time. Pass `algorithm` to additionally
421
+ * assert that the DER matches an expected algorithm.
422
+ *
419
423
  * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes
420
- * @param algorithm - Expected algorithm (must match key contents)
424
+ * @param algorithm - Optional expected algorithm; must match key contents when given
421
425
  * @returns Extractable CryptoKey with `sign` usage
422
426
  *
423
- * @throws {Error} If DER is malformed or algorithm doesn't match key
427
+ * @throws {Error} If DER is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`
424
428
  *
425
429
  * @see {@linkcode exportPkcs8Der} for the inverse operation
426
430
  * @see {@linkcode importPkcs8Pem} for PEM input
427
431
  * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8
428
432
  */
429
- async function importPkcs8DerOrThrow(der, algorithm) {
430
- let parsedPrivateKey;
433
+ async function importPkcs8DerOrThrow(e, t) {
434
+ let n;
431
435
  try {
432
- parsedPrivateKey = parsePkcs8PrivateKey(der);
436
+ n = parsePkcs8PrivateKey(e);
433
437
  } catch {
434
- throw new Error("Malformed PKCS#8 private key");
438
+ throw Error("Malformed PKCS#8 private key");
435
439
  }
436
- assertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);
440
+ let r;
441
+ t === void 0 ? r = inferKeyImportInput(n, "Unsupported PKCS#8 private key algorithm") : (assertPkcs8MatchesRequestedAlgorithm(n, t), r = t);
437
442
  try {
438
- return await getCrypto().subtle.importKey("pkcs8", new Uint8Array(der), toImportAlgorithm(algorithm), true, ["sign"]);
443
+ return await m().subtle.importKey("pkcs8", new Uint8Array(e), toImportAlgorithm(r), !0, privateKeyUsages(r));
439
444
  } catch {
440
- throw new Error("Malformed PKCS#8 private key");
445
+ throw Error("Malformed PKCS#8 private key");
441
446
  }
442
447
  }
443
448
  /**
@@ -445,85 +450,95 @@ async function importPkcs8DerOrThrow(der, algorithm) {
445
450
  *
446
451
  * @see `importPkcs8DerOrThrow` for the throwing variant
447
452
  */
448
- function importPkcs8Der(der, algorithm) {
449
- return importResult(() => importPkcs8DerOrThrow(der, algorithm));
453
+ function importPkcs8Der(e, t) {
454
+ return importResult(() => importPkcs8DerOrThrow(e, t));
450
455
  }
451
456
  /**
452
457
  * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
453
458
  *
459
+ * When `algorithm` is omitted, it is inferred from the key's own
460
+ * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).
461
+ *
454
462
  * @example
455
463
  * ```ts
456
- * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });
464
+ * const key = await importPkcs8PemOrThrow(pemString, { kind: 'ecdsa', curve: 'P-256' });
465
+ * const inferred = await importPkcs8PemOrThrow(pemString);
457
466
  * ```
458
467
  */
459
- function importPkcs8PemOrThrow(pem, algorithm) {
460
- return importPkcs8DerOrThrow(pemDecodeOrThrow("PRIVATE KEY", pem), algorithm);
468
+ function importPkcs8PemOrThrow(e, t) {
469
+ return importPkcs8DerOrThrow(w("PRIVATE KEY", e), t);
461
470
  }
462
471
  /**
463
472
  * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
464
473
  *
465
474
  * @see `importPkcs8PemOrThrow` for the throwing variant
466
475
  */
467
- function importPkcs8Pem(pem, algorithm) {
468
- return importResult(() => importPkcs8PemOrThrow(pem, algorithm));
476
+ function importPkcs8Pem(e, t) {
477
+ return importResult(() => importPkcs8PemOrThrow(e, t));
469
478
  }
470
479
  /**
471
480
  * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
472
481
  *
473
482
  * Decrypts the PBES2 envelope using the provided password, then imports the key.
474
483
  *
484
+ * When `algorithm` is omitted, it is inferred from the decrypted key's own
485
+ * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).
486
+ *
475
487
  * @param der - DER-encoded EncryptedPrivateKeyInfo bytes
476
488
  * @param password - Decryption password
477
- * @param algorithm - Expected algorithm (must match decrypted key)
489
+ * @param algorithm - Optional expected algorithm; must match decrypted key when given
478
490
  *
479
491
  * @throws {Error} If DER is malformed, password is wrong, or algorithm doesn't match
480
492
  *
481
493
  * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation
482
494
  */
483
- async function importEncryptedPkcs8DerOrThrow(der, password, algorithm) {
484
- let children;
495
+ async function importEncryptedPkcs8DerOrThrow(e, t, n) {
496
+ let r;
485
497
  try {
486
- children = readSequenceChildren(der);
498
+ r = a(e);
487
499
  } catch {
488
- throw new Error("Malformed EncryptedPrivateKeyInfo");
500
+ throw Error("Malformed EncryptedPrivateKeyInfo");
489
501
  }
490
- const algorithmIdentifier = children[0];
491
- const encryptedData = children[1];
492
- if (children.length !== 2 || algorithmIdentifier === void 0 || encryptedData === void 0 || encryptedData.tag !== 4) throw new Error("Malformed EncryptedPrivateKeyInfo");
493
- const decrypted = await decryptPbes2(der.slice(algorithmIdentifier.start - algorithmIdentifier.headerLength, algorithmIdentifier.end), encryptedData.value, password);
502
+ let i = r[0], o = r[1];
503
+ if (r.length !== 2 || i === void 0 || o === void 0 || o.tag !== 4) throw Error("Malformed EncryptedPrivateKeyInfo");
504
+ let s = await h(e.slice(i.start - i.headerLength, i.end), o.value, t);
494
505
  try {
495
- parsePkcs8PrivateKey(decrypted);
506
+ parsePkcs8PrivateKey(s);
496
507
  } catch {
497
- throw wrongPasswordError("Invalid password or encrypted content");
508
+ throw v("Invalid password or encrypted content");
498
509
  }
499
- return importPkcs8DerOrThrow(decrypted, algorithm);
510
+ return importPkcs8DerOrThrow(s, n);
500
511
  }
501
512
  /**
502
513
  * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
503
514
  *
504
515
  * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant
505
516
  */
506
- function importEncryptedPkcs8Der(der, password, algorithm) {
507
- return encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));
517
+ function importEncryptedPkcs8Der(e, t, n) {
518
+ return encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(e, t, n));
508
519
  }
509
520
  /**
510
521
  * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
511
522
  *
523
+ * When `algorithm` is omitted, it is inferred from the decrypted key's own
524
+ * `privateKeyAlgorithm` (see {@linkcode importPkcs8DerOrThrow}).
525
+ *
512
526
  * @example
513
527
  * ```ts
514
- * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });
528
+ * const key = await importEncryptedPkcs8PemOrThrow(pem, 'secret', { kind: 'rsa' });
529
+ * const inferred = await importEncryptedPkcs8PemOrThrow(pem, 'secret');
515
530
  * ```
516
531
  */
517
- function importEncryptedPkcs8PemOrThrow(pem, password, algorithm) {
518
- return importEncryptedPkcs8DerOrThrow(pemDecodeOrThrow("ENCRYPTED PRIVATE KEY", pem), password, algorithm);
532
+ function importEncryptedPkcs8PemOrThrow(e, t, n) {
533
+ return importEncryptedPkcs8DerOrThrow(w("ENCRYPTED PRIVATE KEY", e), t, n);
519
534
  }
520
535
  /**
521
536
  * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
522
537
  *
523
538
  * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant
524
539
  */
525
- function importEncryptedPkcs8Pem(pem, password, algorithm) {
526
- return encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));
540
+ function importEncryptedPkcs8Pem(e, t, n) {
541
+ return encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(e, t, n));
527
542
  }
528
543
  /**
529
544
  * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
@@ -533,16 +548,16 @@ function importEncryptedPkcs8Pem(pem, password, algorithm) {
533
548
  * @see {@linkcode exportPkcs1Der} for the inverse operation
534
549
  * @see {@linkcode importPkcs1Pem} for PEM input
535
550
  */
536
- function importPkcs1DerOrThrow(der, algorithm = { kind: "rsa" }) {
537
- return importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);
551
+ function importPkcs1DerOrThrow(e, t = { kind: "rsa" }) {
552
+ return importPkcs8DerOrThrow(wrapPkcs1InPkcs8(e), t);
538
553
  }
539
554
  /**
540
555
  * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
541
556
  *
542
557
  * @see `importPkcs1DerOrThrow` for the throwing variant
543
558
  */
544
- function importPkcs1Der(der, algorithm = { kind: "rsa" }) {
545
- return importResult(() => importPkcs1DerOrThrow(der, algorithm));
559
+ function importPkcs1Der(e, t = { kind: "rsa" }) {
560
+ return importResult(() => importPkcs1DerOrThrow(e, t));
546
561
  }
547
562
  /**
548
563
  * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
@@ -552,16 +567,16 @@ function importPkcs1Der(der, algorithm = { kind: "rsa" }) {
552
567
  * @see {@linkcode exportPkcs1Pem} for the inverse operation
553
568
  * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM
554
569
  */
555
- function importPkcs1PemOrThrow(pem, algorithm = { kind: "rsa" }) {
556
- return importPkcs1DerOrThrow(pemDecodeOrThrow("RSA PRIVATE KEY", pem), algorithm);
570
+ function importPkcs1PemOrThrow(e, t = { kind: "rsa" }) {
571
+ return importPkcs1DerOrThrow(w("RSA PRIVATE KEY", e), t);
557
572
  }
558
573
  /**
559
574
  * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
560
575
  *
561
576
  * @see `importPkcs1PemOrThrow` for the throwing variant
562
577
  */
563
- function importPkcs1Pem(pem, algorithm = { kind: "rsa" }) {
564
- return importResult(() => importPkcs1PemOrThrow(pem, algorithm));
578
+ function importPkcs1Pem(e, t = { kind: "rsa" }) {
579
+ return importResult(() => importPkcs1PemOrThrow(e, t));
565
580
  }
566
581
  /**
567
582
  * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
@@ -571,16 +586,16 @@ function importPkcs1Pem(pem, algorithm = { kind: "rsa" }) {
571
586
  * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation
572
587
  * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption
573
588
  */
574
- async function importEncryptedPkcs1PemOrThrow(pem, password, algorithm = { kind: "rsa" }) {
575
- return importPkcs1DerOrThrow(await decryptTraditionalPem("RSA PRIVATE KEY", pem, password), algorithm);
589
+ async function importEncryptedPkcs1PemOrThrow(e, t, n = { kind: "rsa" }) {
590
+ return importPkcs1DerOrThrow(await decryptTraditionalPem("RSA PRIVATE KEY", e, t), n);
576
591
  }
577
592
  /**
578
593
  * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
579
594
  *
580
595
  * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant
581
596
  */
582
- function importEncryptedPkcs1Pem(pem, password, algorithm = { kind: "rsa" }) {
583
- return encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));
597
+ function importEncryptedPkcs1Pem(e, t, n = { kind: "rsa" }) {
598
+ return encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(e, t, n));
584
599
  }
585
600
  /**
586
601
  * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
@@ -588,22 +603,22 @@ function importEncryptedPkcs1Pem(pem, password, algorithm = { kind: "rsa" }) {
588
603
  * @see {@linkcode exportBinaryBase64} for the inverse operation
589
604
  * @see {@linkcode importPkcs8Pem} for PEM input with headers
590
605
  */
591
- function importPkcs8Base64OrThrow(base64, algorithm) {
592
- let decoded;
606
+ function importPkcs8Base64OrThrow(e, t) {
607
+ let n;
593
608
  try {
594
- decoded = base64Decode(base64);
609
+ n = y(e);
595
610
  } catch {
596
- throw new Error("Invalid base64 PKCS#8 private key");
611
+ throw Error("Invalid base64 PKCS#8 private key");
597
612
  }
598
- return importPkcs8DerOrThrow(decoded, algorithm);
613
+ return importPkcs8DerOrThrow(n, t);
599
614
  }
600
615
  /**
601
616
  * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
602
617
  *
603
618
  * @see `importPkcs8Base64OrThrow` for the throwing variant
604
619
  */
605
- function importPkcs8Base64(base64, algorithm) {
606
- return importResult(() => importPkcs8Base64OrThrow(base64, algorithm));
620
+ function importPkcs8Base64(e, t) {
621
+ return importResult(() => importPkcs8Base64OrThrow(e, t));
607
622
  }
608
623
  /**
609
624
  * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
@@ -613,47 +628,53 @@ function importPkcs8Base64(base64, algorithm) {
613
628
  * (OpenSSL always writes it), its named-curve OID must match `algorithm.curve`;
614
629
  * when the field is absent, the caller-supplied curve is trusted.
615
630
  *
616
- * @throws {Error} If DER is not an ECPrivateKey or its embedded curve doesn't match `algorithm`
631
+ * When `algorithm` is omitted, the curve is inferred from the embedded
632
+ * `parameters [0]` field; a key without a supported named curve then fails.
633
+ *
634
+ * @throws {Error} If DER is not an ECPrivateKey, its embedded curve doesn't
635
+ * match `algorithm`, or no curve is available (neither embedded nor supplied)
617
636
  *
618
637
  * @see {@linkcode exportSec1Der} for the inverse operation
619
638
  * @see {@linkcode importSec1Pem} for PEM input
620
639
  */
621
- async function importSec1DerOrThrow(der, algorithm) {
622
- let parsedSec1;
640
+ async function importSec1DerOrThrow(e, t) {
641
+ let n;
623
642
  try {
624
- parsedSec1 = parseSec1PrivateKey(der);
643
+ n = parseSec1PrivateKey(e);
625
644
  } catch {
626
- throw new Error("Malformed SEC 1 private key");
645
+ throw Error("Malformed SEC 1 private key");
627
646
  }
628
- assertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm);
629
- return await importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);
647
+ let r;
648
+ return t === void 0 ? r = inferSec1ImportInput(n) : (assertSec1MatchesRequestedAlgorithm(n, t), r = t), await importPkcs8DerOrThrow(wrapSec1InPkcs8(e, r.curve), r);
630
649
  }
631
650
  /**
632
651
  * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
633
652
  *
634
653
  * @see `importSec1DerOrThrow` for the throwing variant
635
654
  */
636
- function importSec1Der(der, algorithm) {
637
- return importResult(() => importSec1DerOrThrow(der, algorithm));
655
+ function importSec1Der(e, t) {
656
+ return importResult(() => importSec1DerOrThrow(e, t));
638
657
  }
639
658
  /**
640
659
  * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
641
660
  *
642
- * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label.
661
+ * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label. When `algorithm` is
662
+ * omitted, the curve is inferred from the embedded `parameters [0]` field
663
+ * (see {@linkcode importSec1DerOrThrow}).
643
664
  *
644
665
  * @see {@linkcode exportSec1Pem} for the inverse operation
645
666
  * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM
646
667
  */
647
- function importSec1PemOrThrow(pem, algorithm) {
648
- return importSec1DerOrThrow(pemDecodeOrThrow("EC PRIVATE KEY", pem), algorithm);
668
+ function importSec1PemOrThrow(e, t) {
669
+ return importSec1DerOrThrow(w("EC PRIVATE KEY", e), t);
649
670
  }
650
671
  /**
651
672
  * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
652
673
  *
653
674
  * @see `importSec1PemOrThrow` for the throwing variant
654
675
  */
655
- function importSec1Pem(pem, algorithm) {
656
- return importResult(() => importSec1PemOrThrow(pem, algorithm));
676
+ function importSec1Pem(e, t) {
677
+ return importResult(() => importSec1PemOrThrow(e, t));
657
678
  }
658
679
  /**
659
680
  * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
@@ -663,34 +684,40 @@ function importSec1Pem(pem, algorithm) {
663
684
  * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation
664
685
  * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption
665
686
  */
666
- async function importEncryptedSec1PemOrThrow(pem, password, algorithm) {
667
- return importSec1DerOrThrow(await decryptTraditionalPem("EC PRIVATE KEY", pem, password), algorithm);
687
+ async function importEncryptedSec1PemOrThrow(e, t, n) {
688
+ return importSec1DerOrThrow(await decryptTraditionalPem("EC PRIVATE KEY", e, t), n);
668
689
  }
669
690
  /**
670
691
  * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
671
692
  *
672
693
  * @see `importEncryptedSec1PemOrThrow` for the throwing variant
673
694
  */
674
- function importEncryptedSec1Pem(pem, password, algorithm) {
675
- return encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));
695
+ function importEncryptedSec1Pem(e, t, n) {
696
+ return encryptedImportResult(() => importEncryptedSec1PemOrThrow(e, t, n));
676
697
  }
677
698
  /**
678
699
  * Import a public verification key from a JSON Web Key.
679
700
  *
701
+ * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,
702
+ * and `alg` members (e.g. `PS256` → RSA-PSS/SHA-256, `RSA-OAEP-256` →
703
+ * RSA-OAEP/SHA-256; an RSA JWK without `alg` defaults to PKCS#1 v1.5 with
704
+ * SHA-256). Pass `algorithm` to additionally assert an expected algorithm.
705
+ *
680
706
  * @param jwk - JSON Web Key object with public key components
681
- * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)
707
+ * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given
682
708
  * @returns Extractable CryptoKey with `verify` usage
683
709
  *
684
- * @throws {Error} If JWK is malformed or algorithm doesn't match
710
+ * @throws {Error} If JWK is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`
685
711
  *
686
712
  * @see {@linkcode exportPublicJwk} for the inverse operation
687
713
  */
688
- async function importPublicJwkOrThrow(jwk, algorithm) {
689
- assertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);
714
+ async function importPublicJwkOrThrow(e, t) {
715
+ let n = t ?? inferJwkImportInput(e);
716
+ assertPublicJwkMatchesRequestedAlgorithm(e, n);
690
717
  try {
691
- return await getCrypto().subtle.importKey("jwk", jwk, toImportAlgorithm(algorithm), true, ["verify"]);
718
+ return await m().subtle.importKey("jwk", e, toImportAlgorithm(n), !0, publicKeyUsages(n));
692
719
  } catch {
693
- throw new Error("Malformed public JWK");
720
+ throw Error("Malformed public JWK");
694
721
  }
695
722
  }
696
723
  /**
@@ -698,32 +725,38 @@ async function importPublicJwkOrThrow(jwk, algorithm) {
698
725
  *
699
726
  * @see `importPublicJwkOrThrow` for the throwing variant
700
727
  */
701
- function importPublicJwk(jwk, algorithm) {
702
- return importResult(() => importPublicJwkOrThrow(jwk, algorithm));
728
+ function importPublicJwk(e, t) {
729
+ return importResult(() => importPublicJwkOrThrow(e, t));
703
730
  }
704
731
  /**
705
732
  * Import a private signing key from a JSON Web Key.
706
733
  *
734
+ * When `algorithm` is omitted, it is inferred from the JWK's own `kty`, `crv`,
735
+ * and `alg` members (see {@linkcode importPublicJwkOrThrow}).
736
+ *
707
737
  * @param jwk - JSON Web Key object with private key components
708
- * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)
738
+ * @param algorithm - Optional expected algorithm; must match JWK's `kty` and `crv` when given
709
739
  * @returns Extractable CryptoKey with `sign` usage
710
740
  *
711
- * @throws {Error} If JWK is malformed, lacks private key material, or algorithm doesn't match
741
+ * @throws {Error} If JWK is malformed, lacks private key material, encodes an
742
+ * unsupported algorithm, or doesn't match `algorithm`
712
743
  *
713
744
  * @example
714
745
  * ```ts
715
746
  * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };
716
- * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });
747
+ * const key = await importPrivateJwkOrThrow(jwk, { kind: 'ecdsa', curve: 'P-256' });
748
+ * const inferred = await importPrivateJwkOrThrow(jwk);
717
749
  * ```
718
750
  *
719
751
  * @see {@linkcode exportPrivateJwk} for the inverse operation
720
752
  */
721
- async function importPrivateJwkOrThrow(jwk, algorithm) {
722
- assertPrivateJwkMatchesRequestedAlgorithm(jwk, algorithm);
753
+ async function importPrivateJwkOrThrow(e, t) {
754
+ let n = t ?? inferJwkImportInput(e);
755
+ assertPrivateJwkMatchesRequestedAlgorithm(e, n);
723
756
  try {
724
- return await getCrypto().subtle.importKey("jwk", jwk, toImportAlgorithm(algorithm), true, ["sign"]);
757
+ return await m().subtle.importKey("jwk", e, toImportAlgorithm(n), !0, privateKeyUsages(n));
725
758
  } catch {
726
- throw new Error("Malformed private JWK");
759
+ throw Error("Malformed private JWK");
727
760
  }
728
761
  }
729
762
  /**
@@ -731,54 +764,167 @@ async function importPrivateJwkOrThrow(jwk, algorithm) {
731
764
  *
732
765
  * @see `importPrivateJwkOrThrow` for the throwing variant
733
766
  */
734
- function importPrivateJwk(jwk, algorithm) {
735
- return importResult(() => importPrivateJwkOrThrow(jwk, algorithm));
767
+ function importPrivateJwk(e, t) {
768
+ return importResult(() => importPrivateJwkOrThrow(e, t));
769
+ }
770
+ /**
771
+ * Encrypt a small message with an RSA-OAEP public key.
772
+ *
773
+ * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`.
774
+ * RSA-OAEP encrypts at most modulus bytes − 2 × hash bytes − 2 per call
775
+ * (190 bytes for a 2048-bit key with SHA-256) — encrypt a symmetric key, not
776
+ * bulk data.
777
+ *
778
+ * @param publicKey - RSA-OAEP public `CryptoKey` with `encrypt` usage
779
+ * @param plaintext - Message bytes, at most the OAEP capacity of the key
780
+ * @param options - Optional OAEP label bound to the ciphertext
781
+ *
782
+ * @throws {Error} If the key is not an RSA-OAEP public encryption key, or the
783
+ * plaintext exceeds the key's OAEP capacity
784
+ *
785
+ * @example
786
+ * ```ts
787
+ * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
788
+ * const ciphertext = await encryptRsaOaepOrThrow(
789
+ * keys.publicKey,
790
+ * new TextEncoder().encode('session key'),
791
+ * );
792
+ * ```
793
+ *
794
+ * @see {@linkcode decryptRsaOaepOrThrow} for the inverse operation
795
+ * @see `encryptRsaOaep` for the Result-returning variant
796
+ */
797
+ async function encryptRsaOaepOrThrow(e, t, n = {}) {
798
+ let r = validateRsaOaepKey(e, "public", "encrypt");
799
+ if (r !== void 0) throw Error(r);
800
+ try {
801
+ return new Uint8Array(await m().subtle.encrypt(toRsaOaepParams(n), e, u(t)));
802
+ } catch (e) {
803
+ throw S(e), Error("Plaintext exceeds the RSA-OAEP capacity of the key (modulus bytes − 2 × hash bytes − 2)");
804
+ }
805
+ }
806
+ /**
807
+ * Encrypt a small message with an RSA-OAEP public key.
808
+ *
809
+ * @example
810
+ * ```ts
811
+ * const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
812
+ * const encrypted = await encryptRsaOaep(keys.publicKey, plaintext);
813
+ * if (!encrypted.ok) {
814
+ * // encrypted.code: 'invalid_key' | 'message_too_long'
815
+ * throw new Error(encrypted.message);
816
+ * }
817
+ * const ciphertext = encrypted.value;
818
+ * ```
819
+ *
820
+ * @see `encryptRsaOaepOrThrow` for the throwing variant
821
+ */
822
+ async function encryptRsaOaep(e, t, n = {}) {
823
+ let r = validateRsaOaepKey(e, "public", "encrypt");
824
+ if (r !== void 0) return x("invalid_key", r);
825
+ try {
826
+ return C(await encryptRsaOaepOrThrow(e, t, n));
827
+ } catch (e) {
828
+ return S(e), x("message_too_long", e instanceof Error ? e.message : "Plaintext exceeds the RSA-OAEP capacity");
829
+ }
830
+ }
831
+ /**
832
+ * Decrypt an RSA-OAEP ciphertext with the matching private key.
833
+ *
834
+ * The key must have been generated or imported with `{ kind: 'rsa', scheme: 'oaep' }`,
835
+ * and `options.label` must repeat the label used at encryption time (if any).
836
+ *
837
+ * @param privateKey - RSA-OAEP private `CryptoKey` with `decrypt` usage
838
+ * @param ciphertext - Ciphertext produced by {@linkcode encryptRsaOaep} (or any RSA-OAEP encryptor)
839
+ * @param options - OAEP label matching the one bound at encryption
840
+ *
841
+ * @throws {Error} If the key is not an RSA-OAEP private decryption key, or
842
+ * decryption fails — wrong key, wrong label, or corrupted ciphertext (OAEP
843
+ * deliberately does not reveal which)
844
+ *
845
+ * @example
846
+ * ```ts
847
+ * const plaintext = await decryptRsaOaepOrThrow(keys.privateKey, ciphertext);
848
+ * ```
849
+ *
850
+ * @see {@linkcode encryptRsaOaepOrThrow} for the inverse operation
851
+ * @see `decryptRsaOaep` for the Result-returning variant
852
+ */
853
+ async function decryptRsaOaepOrThrow(e, t, n = {}) {
854
+ let r = validateRsaOaepKey(e, "private", "decrypt");
855
+ if (r !== void 0) throw Error(r);
856
+ try {
857
+ return new Uint8Array(await m().subtle.decrypt(toRsaOaepParams(n), e, u(t)));
858
+ } catch (e) {
859
+ throw S(e), Error("RSA-OAEP decryption failed: wrong key, wrong label, or corrupted ciphertext");
860
+ }
861
+ }
862
+ /**
863
+ * Decrypt an RSA-OAEP ciphertext with the matching private key.
864
+ *
865
+ * @example
866
+ * ```ts
867
+ * const decrypted = await decryptRsaOaep(keys.privateKey, ciphertext);
868
+ * if (!decrypted.ok) {
869
+ * // decrypted.code: 'invalid_key' | 'decryption_failed'
870
+ * throw new Error(decrypted.message);
871
+ * }
872
+ * const plaintext = decrypted.value;
873
+ * ```
874
+ *
875
+ * @see `decryptRsaOaepOrThrow` for the throwing variant
876
+ */
877
+ async function decryptRsaOaep(e, t, n = {}) {
878
+ let r = validateRsaOaepKey(e, "private", "decrypt");
879
+ if (r !== void 0) return x("invalid_key", r);
880
+ try {
881
+ return C(await decryptRsaOaepOrThrow(e, t, n));
882
+ } catch (e) {
883
+ return S(e), x("decryption_failed", e instanceof Error ? e.message : "RSA-OAEP decryption failed");
884
+ }
736
885
  }
737
886
  /** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */
738
- function toGenerateKeyAlgorithm(algorithm) {
739
- switch (algorithm.kind) {
887
+ function toGenerateKeyAlgorithm(e) {
888
+ switch (e.kind) {
740
889
  case "rsa": return {
741
- name: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),
742
- modulusLength: algorithm.modulusLength ?? 2048,
890
+ name: rsaSchemeToWebCryptoAlgorithmName(e.scheme),
891
+ modulusLength: e.modulusLength ?? 2048,
743
892
  publicExponent: Uint8Array.of(1, 0, 1),
744
- hash: algorithm.hash ?? "SHA-256"
893
+ hash: e.hash ?? "SHA-256"
745
894
  };
746
895
  case "ecdsa": return {
747
896
  name: "ECDSA",
748
- namedCurve: algorithm.curve ?? "P-256"
897
+ namedCurve: e.curve ?? "P-256"
749
898
  };
750
899
  case "ed25519": return { name: "Ed25519" };
751
900
  }
752
901
  }
753
902
  /** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */
754
- function toImportAlgorithm(algorithm) {
755
- switch (algorithm.kind) {
903
+ function toImportAlgorithm(e) {
904
+ switch (e.kind) {
756
905
  case "rsa": return {
757
- name: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),
758
- hash: algorithm.hash ?? "SHA-256"
906
+ name: rsaSchemeToWebCryptoAlgorithmName(e.scheme),
907
+ hash: e.hash ?? "SHA-256"
759
908
  };
760
909
  case "ecdsa": return {
761
910
  name: "ECDSA",
762
- namedCurve: algorithm.curve
911
+ namedCurve: e.curve
763
912
  };
764
913
  case "ed25519": return { name: "Ed25519" };
765
914
  }
766
915
  }
767
916
  /** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */
768
- function parsePkcs8PrivateKey(der) {
769
- const children = readSequenceChildren(der);
770
- const algorithm = children[1];
771
- const privateKey = children[2];
772
- if (children.length < 3 || children.length > 4 || algorithm === void 0 || algorithm.tag !== 48 || privateKey === void 0 || privateKey.tag !== 4) throw new Error("Malformed PKCS#8 private key");
773
- const algorithmChildren = readSequenceChildren(der.slice(algorithm.start - algorithm.headerLength, algorithm.end));
774
- const algorithmOid = algorithmChildren[0];
775
- if (algorithmOid === void 0 || algorithmOid.tag !== 6 || algorithmChildren.length < 1 || algorithmChildren.length > 2) throw new Error("Malformed PKCS#8 private key");
776
- const parameters = algorithmChildren[1];
917
+ function parsePkcs8PrivateKey(e) {
918
+ let t = a(e), n = t[1], r = t[2];
919
+ if (t.length < 3 || t.length > 4 || n === void 0 || n.tag !== 48 || r === void 0 || r.tag !== 4) throw Error("Malformed PKCS#8 private key");
920
+ let i = a(e.slice(n.start - n.headerLength, n.end)), o = i[0];
921
+ if (o === void 0 || o.tag !== 6 || i.length < 1 || i.length > 2) throw Error("Malformed PKCS#8 private key");
922
+ let c = i[1];
777
923
  return {
778
- algorithmOid: decodeObjectIdentifier(algorithmOid.value),
779
- ...parameters === void 0 ? {} : { parametersTag: parameters.tag },
780
- ...parameters?.tag === 6 ? { parametersOid: decodeObjectIdentifier(parameters.value) } : {},
781
- privateKeyDer: privateKey.value
924
+ algorithmOid: s(o.value),
925
+ ...c === void 0 ? {} : { parametersTag: c.tag },
926
+ ...c?.tag === 6 ? { parametersOid: s(c.value) } : {},
927
+ privateKeyDer: r.value
782
928
  };
783
929
  }
784
930
  /**
@@ -787,42 +933,56 @@ function parsePkcs8PrivateKey(der) {
787
933
  * RFC 5915: `ECPrivateKey ::= SEQUENCE { version INTEGER, privateKey OCTET STRING,
788
934
  * parameters [0] ECParameters OPTIONAL, publicKey [1] BIT STRING OPTIONAL }`.
789
935
  */
790
- function parseSec1PrivateKey(der) {
791
- const children = readSequenceChildren(der);
792
- const version = children[0];
793
- const privateKey = children[1];
794
- const third = children[2];
795
- const fourth = children[3];
796
- if (children.length < 2 || children.length > 4 || version === void 0 || version.tag !== 2 || privateKey === void 0 || privateKey.tag !== 4 || third !== void 0 && third.tag !== 160 && third.tag !== 161 || fourth !== void 0 && (third?.tag !== 160 || fourth.tag !== 161)) throw new Error("Malformed SEC 1 private key");
797
- const parameters = third?.tag === 160 ? third : void 0;
798
- if (parameters === void 0) return {};
799
- const ecParameters = readRootElement(parameters.value);
936
+ function parseSec1PrivateKey(e) {
937
+ let t = a(e), n = t[0], r = t[1], o = t[2], c = t[3];
938
+ if (t.length < 2 || t.length > 4 || n === void 0 || n.tag !== 2 || r === void 0 || r.tag !== 4 || o !== void 0 && o.tag !== 160 && o.tag !== 161 || c !== void 0 && (o?.tag !== 160 || c.tag !== 161)) throw Error("Malformed SEC 1 private key");
939
+ let l = o?.tag === 160 ? o : void 0;
940
+ if (l === void 0) return {};
941
+ let u = i(l.value);
800
942
  return {
801
- parametersTag: ecParameters.tag,
802
- ...ecParameters.tag === 6 ? { parametersOid: decodeObjectIdentifier(ecParameters.value) } : {}
943
+ parametersTag: u.tag,
944
+ ...u.tag === 6 ? { parametersOid: s(u.value) } : {}
803
945
  };
804
946
  }
947
+ /**
948
+ * Ensure a SEC 1 ECPrivateKey carries the RFC 5915 `parameters [0]` named
949
+ * curve. WebCrypto's PKCS#8 export omits it from the inner ECPrivateKey (the
950
+ * curve lives in the envelope's privateKeyAlgorithm), but RFC 5915 wants it in
951
+ * standalone SEC 1 — and OpenSSL always writes it. Injecting it keeps exports
952
+ * self-describing, so they re-import without an explicit curve.
953
+ */
954
+ function ensureSec1NamedCurveParameters(t, r) {
955
+ let i = a(t);
956
+ if (i.some((e) => e.tag === 160)) return new Uint8Array(t);
957
+ if (r === void 0) throw Error("SEC1 export requires a named curve in the PKCS#8 privateKeyAlgorithm");
958
+ let raw = (e) => t.slice(e.start - e.headerLength, e.end);
959
+ return o([
960
+ ...i.slice(0, 2).map(raw),
961
+ e(0, n(r)),
962
+ ...i.slice(2).map(raw)
963
+ ]);
964
+ }
805
965
  /** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */
806
- function wrapPkcs1InPkcs8(der) {
807
- return sequence([
966
+ function wrapPkcs1InPkcs8(e) {
967
+ return o([
808
968
  Uint8Array.of(2, 1, 0),
809
- sequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),
810
- octetString(new Uint8Array(der))
969
+ o([n(f.rsaEncryption), t()]),
970
+ r(new Uint8Array(e))
811
971
  ]);
812
972
  }
813
973
  /** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */
814
- function wrapSec1InPkcs8(der, curve) {
815
- return sequence([
974
+ function wrapSec1InPkcs8(e, t) {
975
+ return o([
816
976
  Uint8Array.of(2, 1, 0),
817
- sequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),
818
- octetString(new Uint8Array(der))
977
+ o([n(f.ecPublicKey), n(curveToOid(t))]),
978
+ r(new Uint8Array(e))
819
979
  ]);
820
980
  }
821
981
  /** Project a private JWK onto its public-only members, discarding private key material. */
822
- function toPublicJwk(jwk) {
823
- if (jwk.kty !== "RSA" && jwk.kty !== "EC" && jwk.kty !== "OKP") throw new Error(`Cannot derive public key: unsupported JWK key type ${String(jwk.kty)}`);
824
- const publicJwk = { ...jwk };
825
- for (const field of [
982
+ function toPublicJwk(e, t) {
983
+ if (e.kty !== "RSA" && e.kty !== "EC" && e.kty !== "OKP") throw Error(`Cannot derive public key: unsupported JWK key type ${String(e.kty)}`);
984
+ let n = { ...e };
985
+ for (let e of [
826
986
  "d",
827
987
  "p",
828
988
  "q",
@@ -831,257 +991,345 @@ function toPublicJwk(jwk) {
831
991
  "qi",
832
992
  "oth",
833
993
  "k"
834
- ]) delete publicJwk[field];
835
- publicJwk.key_ops = ["verify"];
836
- publicJwk.ext = true;
837
- return publicJwk;
994
+ ]) delete n[e];
995
+ return n.key_ops = [t], n.ext = !0, n;
838
996
  }
839
997
  /**
840
998
  * Single source of truth for the NIST curve ↔ named-curve OID mapping, read in
841
999
  * both directions by {@linkcode curveToOid} and {@linkcode oidToCurve}.
842
1000
  */
843
- const EC_CURVE_OIDS = [
844
- ["P-256", OIDS.prime256v1],
845
- ["P-384", OIDS.secp384r1],
846
- ["P-521", OIDS.secp521r1]
1001
+ const E = [
1002
+ ["P-256", f.prime256v1],
1003
+ ["P-384", f.secp384r1],
1004
+ ["P-521", f.secp521r1]
847
1005
  ];
848
1006
  /** Map a curve name to its ASN.1 OID string. */
849
- function curveToOid(curve) {
850
- for (const [name, oid] of EC_CURVE_OIDS) if (name === curve) return oid;
851
- throw new Error(`Unsupported EC curve: ${curve}`);
1007
+ function curveToOid(e) {
1008
+ for (let [t, n] of E) if (t === e) return n;
1009
+ throw Error(`Unsupported EC curve: ${e}`);
852
1010
  }
853
1011
  /** Map an ASN.1 curve OID string back to its curve name, or `undefined` if unrecognized. */
854
- function oidToCurve(oid) {
855
- for (const [name, curveOid] of EC_CURVE_OIDS) if (curveOid === oid) return name;
1012
+ function oidToCurve(e) {
1013
+ for (let [t, n] of E) if (n === e) return t;
856
1014
  }
857
1015
  /** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */
858
- function rsaSchemeToWebCryptoAlgorithmName(scheme) {
859
- if (scheme === "pss") return "RSA-PSS";
860
- return "RSASSA-PKCS1-v1_5";
1016
+ function rsaSchemeToWebCryptoAlgorithmName(e) {
1017
+ return e === "pss" ? "RSA-PSS" : e === "oaep" ? "RSA-OAEP" : "RSASSA-PKCS1-v1_5";
1018
+ }
1019
+ /** `true` when the algorithm input selects RSA-OAEP, whose keys carry encrypt/decrypt usages. */
1020
+ function isRsaOaepInput(e) {
1021
+ return e.kind === "rsa" && e.scheme === "oaep";
1022
+ }
1023
+ /** Key usages for an imported public key: `verify`, or `encrypt` for RSA-OAEP. */
1024
+ function publicKeyUsages(e) {
1025
+ return isRsaOaepInput(e) ? ["encrypt"] : ["verify"];
1026
+ }
1027
+ /** Key usages for an imported private key: `sign`, or `decrypt` for RSA-OAEP. */
1028
+ function privateKeyUsages(e) {
1029
+ return isRsaOaepInput(e) ? ["decrypt"] : ["sign"];
1030
+ }
1031
+ /**
1032
+ * Diagnose a key unfit for the given RSA-OAEP operation.
1033
+ *
1034
+ * Returns a human-readable problem description, or `undefined` when the key is
1035
+ * usable — keeping key-level failures (`'invalid_key'`) separable from
1036
+ * ciphertext-level failures before WebCrypto is ever called.
1037
+ */
1038
+ function validateRsaOaepKey(e, t, n) {
1039
+ let r = n === "encrypt" ? "encryption" : "decryption";
1040
+ if (e.type !== t) return `RSA-OAEP ${r} requires a ${t} CryptoKey`;
1041
+ if (e.algorithm.name !== "RSA-OAEP") return `RSA-OAEP ${r} requires an RSA-OAEP key (got ${e.algorithm.name}); generate or import the key with scheme: 'oaep'`;
1042
+ if (!e.usages.includes(n)) return `RSA-OAEP ${r} requires a key with '${n}' usage`;
1043
+ }
1044
+ /** Build the WebCrypto RSA-OAEP params, attaching the optional label. */
1045
+ function toRsaOaepParams(e) {
1046
+ return {
1047
+ name: "RSA-OAEP",
1048
+ ...e.label === void 0 ? {} : { label: u(e.label) }
1049
+ };
861
1050
  }
862
1051
  /** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */
863
- async function encryptTraditionalPem(label, der, options) {
864
- const iv = options.iv ?? getCrypto().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
865
- if (iv.length !== 16) throw new Error("Traditional PEM encryption requires a 16-byte IV");
866
- const cipher = options.cipher ?? "AES-256-CBC";
867
- const key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, ["encrypt"]);
868
- const body = base64Encode(new Uint8Array(await getCrypto().subtle.encrypt({
1052
+ async function encryptTraditionalPem(e, t, n) {
1053
+ let r = n.iv ?? m().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
1054
+ if (r.length !== 16) throw Error("Traditional PEM encryption requires a 16-byte IV");
1055
+ let i = n.cipher ?? "AES-256-CBC", a = await importTraditionalPemAesKey(n.password, r.slice(0, 8), i, ["encrypt"]), o = b(new Uint8Array(await m().subtle.encrypt({
869
1056
  name: "AES-CBC",
870
- iv: toArrayBuffer(iv)
871
- }, key, toArrayBuffer(der)))).match(/.{1,64}/g)?.join("\n") ?? "";
1057
+ iv: u(r)
1058
+ }, a, u(t)))).match(/.{1,64}/g)?.join("\n") ?? "";
872
1059
  return [
873
- `-----BEGIN ${label}-----`,
1060
+ `-----BEGIN ${e}-----`,
874
1061
  "Proc-Type: 4,ENCRYPTED",
875
- `DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,
1062
+ `DEK-Info: ${i},${d(r).toUpperCase()}`,
876
1063
  "",
877
- body,
878
- `-----END ${label}-----`
1064
+ o,
1065
+ `-----END ${e}-----`
879
1066
  ].join("\n");
880
1067
  }
881
1068
  /** Decrypt an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back to plaintext DER. */
882
- async function decryptTraditionalPem(expectedLabel, pem, password) {
883
- const parsed = parseTraditionalPem(pem);
884
- if (parsed.label !== expectedLabel) throw new Error(`Expected ${expectedLabel} PEM block`);
885
- const dekInfo = parsed.headers.get("DEK-Info");
886
- if (parsed.headers.get("Proc-Type") !== "4,ENCRYPTED" || dekInfo === void 0) throw new Error("Traditional PEM encryption headers missing");
887
- const [cipher, ivHex] = dekInfo.split(",");
888
- if (!isTraditionalPemCipher(cipher) || ivHex === void 0) throw new Error("Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported");
889
- if (!isTraditionalPemIvHex(ivHex)) throw new Error("Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters");
890
- const iv = hexToBytes(ivHex);
891
- const key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ["decrypt"]);
1069
+ async function decryptTraditionalPem(e, t, n) {
1070
+ let r = parseTraditionalPem(t);
1071
+ if (r.label !== e) throw Error(`Expected ${e} PEM block`);
1072
+ let i = r.headers.get("DEK-Info");
1073
+ if (r.headers.get("Proc-Type") !== "4,ENCRYPTED" || i === void 0) throw Error("Traditional PEM encryption headers missing");
1074
+ let [a, o] = i.split(",");
1075
+ if (!isTraditionalPemCipher(a) || o === void 0) throw Error("Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported");
1076
+ if (!isTraditionalPemIvHex(o)) throw Error("Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters");
1077
+ let s = l(o), c = await importTraditionalPemAesKey(n, s.slice(0, 8), a, ["decrypt"]);
892
1078
  try {
893
- return new Uint8Array(await getCrypto().subtle.decrypt({
1079
+ return new Uint8Array(await m().subtle.decrypt({
894
1080
  name: "AES-CBC",
895
- iv: toArrayBuffer(iv)
896
- }, key, toArrayBuffer(base64Decode(parsed.base64Body))));
1081
+ iv: u(s)
1082
+ }, c, u(y(r.base64Body))));
897
1083
  } catch {
898
- throw wrongPasswordError("Invalid password or encrypted PEM content");
1084
+ throw v("Invalid password or encrypted PEM content");
899
1085
  }
900
1086
  }
901
1087
  /** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */
902
- function importTraditionalPemAesKey(password, salt, cipher, usages) {
903
- const keyLength = traditionalPemCipherKeyLength(cipher);
904
- const keyBytes = opensslBytesToKey(password, salt, keyLength / 8);
905
- return getCrypto().subtle.importKey("raw", toArrayBuffer(keyBytes), {
1088
+ function importTraditionalPemAesKey(e, t, n, r) {
1089
+ let i = traditionalPemCipherKeyLength(n), a = opensslBytesToKey(e, t, i / 8);
1090
+ return m().subtle.importKey("raw", u(a), {
906
1091
  name: "AES-CBC",
907
- length: keyLength
908
- }, false, usages);
1092
+ length: i
1093
+ }, !1, r);
909
1094
  }
910
1095
  /** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */
911
- function isTraditionalPemCipher(cipher) {
912
- return cipher === "AES-128-CBC" || cipher === "AES-192-CBC" || cipher === "AES-256-CBC";
1096
+ function isTraditionalPemCipher(e) {
1097
+ return e === "AES-128-CBC" || e === "AES-192-CBC" || e === "AES-256-CBC";
913
1098
  }
914
- function isTraditionalPemIvHex(value) {
915
- return value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);
1099
+ function isTraditionalPemIvHex(e) {
1100
+ return e.length === 32 && /^[0-9A-Fa-f]+$/.test(e);
916
1101
  }
917
1102
  /** Return the AES key size in bits for a given cipher name. */
918
- function traditionalPemCipherKeyLength(cipher) {
919
- switch (cipher) {
1103
+ function traditionalPemCipherKeyLength(e) {
1104
+ switch (e) {
920
1105
  case "AES-128-CBC": return 128;
921
1106
  case "AES-192-CBC": return 192;
922
1107
  case "AES-256-CBC": return 256;
923
1108
  }
924
1109
  }
925
1110
  /** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */
926
- function opensslBytesToKey(password, salt, length) {
927
- const passwordBytes = new TextEncoder().encode(password);
928
- const chunks = [];
929
- let previous = /* @__PURE__ */ new Uint8Array();
930
- let total = 0;
931
- while (total < length) {
932
- const input = new Uint8Array(previous.length + passwordBytes.length + salt.length);
933
- input.set(previous, 0);
934
- input.set(passwordBytes, previous.length);
935
- input.set(salt, previous.length + passwordBytes.length);
936
- previous = md5(input);
937
- chunks.push(previous);
938
- total += previous.length;
1111
+ function opensslBytesToKey(e, t, n) {
1112
+ let r = new TextEncoder().encode(e), i = [], a = /* @__PURE__ */ new Uint8Array(), o = 0;
1113
+ for (; o < n;) {
1114
+ let e = new Uint8Array(a.length + r.length + t.length);
1115
+ e.set(a, 0), e.set(r, a.length), e.set(t, a.length + r.length), a = p(e), i.push(a), o += a.length;
939
1116
  }
940
- const out = new Uint8Array(length);
941
- let offset = 0;
942
- for (const chunk of chunks) {
943
- const slice = chunk.slice(0, Math.min(chunk.length, length - offset));
944
- out.set(slice, offset);
945
- offset += slice.length;
946
- if (offset >= length) break;
1117
+ let s = new Uint8Array(n), c = 0;
1118
+ for (let e of i) {
1119
+ let t = e.slice(0, Math.min(e.length, n - c));
1120
+ if (s.set(t, c), c += t.length, c >= n) break;
947
1121
  }
948
- return out;
1122
+ return s;
949
1123
  }
950
1124
  /** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */
951
- function parseTraditionalPem(pem) {
952
- const lines = pem.replace(/\r/g, "").trim().split("\n");
953
- const begin = lines[0];
954
- const end = lines[lines.length - 1];
955
- if (begin === void 0 || end === void 0 || !begin.startsWith("-----BEGIN ") || !end.startsWith("-----END ")) throw new Error("Invalid PEM block");
956
- const label = begin.slice(11, -5);
957
- if (end !== `-----END ${label}-----`) throw new Error("PEM boundaries do not match");
958
- const headers = /* @__PURE__ */ new Map();
959
- let index = 1;
960
- while (index < lines.length - 1) {
961
- const line = lines[index];
962
- if (line === void 0) break;
963
- if (line.length === 0) {
964
- index += 1;
1125
+ function parseTraditionalPem(e) {
1126
+ let t = e.replace(/\r/g, "").trim().split("\n"), n = t[0], r = t[t.length - 1];
1127
+ if (n === void 0 || r === void 0 || !n.startsWith("-----BEGIN ") || !r.startsWith("-----END ")) throw Error("Invalid PEM block");
1128
+ let i = n.slice(11, -5);
1129
+ if (r !== `-----END ${i}-----`) throw Error("PEM boundaries do not match");
1130
+ let a = /* @__PURE__ */ new Map(), o = 1;
1131
+ for (; o < t.length - 1;) {
1132
+ let e = t[o];
1133
+ if (e === void 0) break;
1134
+ if (e.length === 0) {
1135
+ o += 1;
965
1136
  break;
966
1137
  }
967
- const delimiter = line.indexOf(": ");
968
- if (delimiter === -1) break;
969
- const headerName = line.slice(0, delimiter);
970
- if (headers.has(headerName)) throw new Error(`Duplicate PEM header: ${headerName}`);
971
- headers.set(headerName, line.slice(delimiter + 2));
972
- index += 1;
1138
+ let n = e.indexOf(": ");
1139
+ if (n === -1) break;
1140
+ let r = e.slice(0, n);
1141
+ if (a.has(r)) throw Error(`Duplicate PEM header: ${r}`);
1142
+ a.set(r, e.slice(n + 2)), o += 1;
973
1143
  }
974
1144
  return {
975
- label,
976
- headers,
977
- base64Body: lines.slice(index, lines.length - 1).join("")
1145
+ label: i,
1146
+ headers: a,
1147
+ base64Body: t.slice(o, t.length - 1).join("")
978
1148
  };
979
1149
  }
980
- function parseSpkiDer(der) {
1150
+ function parseSpkiDer(e) {
981
1151
  try {
982
- const children = readSequenceChildren(der);
983
- if (children.length !== 2) throw new Error("Malformed SubjectPublicKeyInfo");
984
- const algorithm = children[0];
985
- const subjectPublicKey = children[1];
986
- if (algorithm === void 0 || algorithm.tag !== 48 || subjectPublicKey === void 0 || subjectPublicKey.tag !== 3) throw new Error("Malformed SubjectPublicKeyInfo");
987
- extractBitStringValue(subjectPublicKey);
988
- const algorithmChildren = readSequenceChildren(der.slice(algorithm.start - algorithm.headerLength, algorithm.end));
989
- const algorithmOid = algorithmChildren[0];
990
- if (algorithmOid === void 0 || algorithmOid.tag !== 6 || algorithmChildren.length < 1 || algorithmChildren.length > 2) throw new Error("Malformed SubjectPublicKeyInfo");
991
- const parameters = algorithmChildren[1];
1152
+ let t = a(e);
1153
+ if (t.length !== 2) throw Error("Malformed SubjectPublicKeyInfo");
1154
+ let n = t[0], r = t[1];
1155
+ if (n === void 0 || n.tag !== 48 || r === void 0 || r.tag !== 3) throw Error("Malformed SubjectPublicKeyInfo");
1156
+ c(r);
1157
+ let i = a(e.slice(n.start - n.headerLength, n.end)), o = i[0];
1158
+ if (o === void 0 || o.tag !== 6 || i.length < 1 || i.length > 2) throw Error("Malformed SubjectPublicKeyInfo");
1159
+ let l = i[1];
992
1160
  return {
993
- algorithmOid: decodeObjectIdentifier(algorithmOid.value),
994
- ...parameters === void 0 ? {} : { parametersTag: parameters.tag },
995
- ...parameters?.tag === 6 ? { parametersOid: decodeObjectIdentifier(parameters.value) } : {}
1161
+ algorithmOid: s(o.value),
1162
+ ...l === void 0 ? {} : { parametersTag: l.tag },
1163
+ ...l?.tag === 6 ? { parametersOid: s(l.value) } : {}
996
1164
  };
997
1165
  } catch {
998
- throw new Error("Malformed SubjectPublicKeyInfo");
1166
+ throw Error("Malformed SubjectPublicKeyInfo");
999
1167
  }
1000
1168
  }
1001
1169
  /**
1002
- * Derive the import algorithm from a parsed SPKI's own AlgorithmIdentifier.
1170
+ * Derive the import algorithm from a key envelope's own AlgorithmIdentifier
1171
+ * (SPKI `algorithm` or PKCS#8 `privateKeyAlgorithm` — both share the shape).
1003
1172
  *
1004
1173
  * RSA keys default to the `pkcs1-v1_5`/`SHA-256` import parameters (a plain
1005
- * `rsaEncryption` SPKI does not encode padding scheme or hash); EC keys carry
1006
- * their curve in the DER; Ed25519 is fully determined by its OID.
1174
+ * `rsaEncryption` AlgorithmIdentifier does not encode padding scheme or hash);
1175
+ * EC keys carry their curve in the DER; Ed25519 is fully determined by its OID.
1007
1176
  */
1008
- function inferPublicKeyImportInput(parsedSpki) {
1009
- switch (parsedSpki.algorithmOid) {
1010
- case OIDS.rsaEncryption:
1011
- if (parsedSpki.parametersTag === void 0 || parsedSpki.parametersTag === 5) return { kind: "rsa" };
1177
+ function inferKeyImportInput(e, t) {
1178
+ switch (e.algorithmOid) {
1179
+ case f.rsaEncryption:
1180
+ if (e.parametersTag === void 0 || e.parametersTag === 5) return { kind: "rsa" };
1012
1181
  break;
1013
- case OIDS.ecPublicKey: {
1014
- const curve = parsedSpki.parametersTag === 6 && parsedSpki.parametersOid !== void 0 ? oidToCurve(parsedSpki.parametersOid) : void 0;
1015
- if (curve !== void 0) return {
1182
+ case f.ecPublicKey: {
1183
+ let t = e.parametersTag === 6 && e.parametersOid !== void 0 ? oidToCurve(e.parametersOid) : void 0;
1184
+ if (t !== void 0) return {
1016
1185
  kind: "ecdsa",
1017
- curve
1186
+ curve: t
1018
1187
  };
1019
1188
  break;
1020
1189
  }
1021
- case OIDS.ed25519:
1022
- if (parsedSpki.parametersTag === void 0) return { kind: "ed25519" };
1190
+ case f.ed25519:
1191
+ if (e.parametersTag === void 0) return { kind: "ed25519" };
1023
1192
  break;
1024
1193
  }
1025
- throw new Error("Unsupported SubjectPublicKeyInfo algorithm");
1194
+ throw Error(t);
1195
+ }
1196
+ /**
1197
+ * Derive the import curve from a SEC 1 ECPrivateKey's own RFC 5915
1198
+ * `parameters [0]` field. SEC 1 encodes no algorithm family (it is EC by
1199
+ * definition), so only the named curve needs recovering — and it may be
1200
+ * absent, in which case the caller must supply it.
1201
+ */
1202
+ function inferSec1ImportInput(e) {
1203
+ let t = e.parametersTag === 6 && e.parametersOid !== void 0 ? oidToCurve(e.parametersOid) : void 0;
1204
+ if (t === void 0) throw Error("SEC 1 private key does not encode a supported named curve; pass the algorithm explicitly");
1205
+ return {
1206
+ kind: "ecdsa",
1207
+ curve: t
1208
+ };
1209
+ }
1210
+ /**
1211
+ * Derive the import algorithm from a JWK's own `kty`, `crv`, and `alg` members.
1212
+ *
1213
+ * `alg` disambiguates the RSA scheme and hash (`RS*`, `PS*`, `RSA-OAEP-*`) —
1214
+ * WebCrypto rejects a JWK whose `alg` disagrees with the import algorithm, so
1215
+ * it must be honored rather than defaulted over. An RSA JWK without `alg`
1216
+ * defaults to `pkcs1-v1_5`/`SHA-256`, mirroring SPKI inference.
1217
+ */
1218
+ function inferJwkImportInput(e) {
1219
+ if (e.kty === "RSA") return rsaImportInputFromJwkAlg(e.alg);
1220
+ if (e.kty === "EC") {
1221
+ if (e.crv === "P-256" || e.crv === "P-384" || e.crv === "P-521") return {
1222
+ kind: "ecdsa",
1223
+ curve: e.crv
1224
+ };
1225
+ throw Error(`Unsupported EC JWK curve: ${String(e.crv)}`);
1226
+ }
1227
+ if (e.kty === "OKP" && e.crv === "Ed25519") return { kind: "ed25519" };
1228
+ throw Error("Unsupported JWK key type");
1229
+ }
1230
+ /** Map a JWA `alg` identifier to the RSA scheme + hash it pins down. */
1231
+ function rsaImportInputFromJwkAlg(e) {
1232
+ switch (e) {
1233
+ case void 0:
1234
+ case "RS256": return { kind: "rsa" };
1235
+ case "RS384": return {
1236
+ kind: "rsa",
1237
+ hash: "SHA-384"
1238
+ };
1239
+ case "RS512": return {
1240
+ kind: "rsa",
1241
+ hash: "SHA-512"
1242
+ };
1243
+ case "PS256": return {
1244
+ kind: "rsa",
1245
+ scheme: "pss"
1246
+ };
1247
+ case "PS384": return {
1248
+ kind: "rsa",
1249
+ scheme: "pss",
1250
+ hash: "SHA-384"
1251
+ };
1252
+ case "PS512": return {
1253
+ kind: "rsa",
1254
+ scheme: "pss",
1255
+ hash: "SHA-512"
1256
+ };
1257
+ case "RSA-OAEP-256": return {
1258
+ kind: "rsa",
1259
+ scheme: "oaep"
1260
+ };
1261
+ case "RSA-OAEP-384": return {
1262
+ kind: "rsa",
1263
+ scheme: "oaep",
1264
+ hash: "SHA-384"
1265
+ };
1266
+ case "RSA-OAEP-512": return {
1267
+ kind: "rsa",
1268
+ scheme: "oaep",
1269
+ hash: "SHA-512"
1270
+ };
1271
+ default: throw Error(`Unsupported RSA JWK alg: ${e}`);
1272
+ }
1026
1273
  }
1027
- function assertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm) {
1028
- switch (algorithm.kind) {
1274
+ function assertSpkiMatchesRequestedAlgorithm(e, t) {
1275
+ switch (t.kind) {
1029
1276
  case "rsa":
1030
- if (parsedSpki.algorithmOid !== OIDS.rsaEncryption || parsedSpki.parametersTag !== void 0 && parsedSpki.parametersTag !== 5) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1277
+ if (e.algorithmOid !== f.rsaEncryption || e.parametersTag !== void 0 && e.parametersTag !== 5) throw Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1031
1278
  return;
1032
1279
  case "ecdsa":
1033
- if (parsedSpki.algorithmOid !== OIDS.ecPublicKey || parsedSpki.parametersTag !== 6 || parsedSpki.parametersOid !== curveToOid(algorithm.curve)) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1280
+ if (e.algorithmOid !== f.ecPublicKey || e.parametersTag !== 6 || e.parametersOid !== curveToOid(t.curve)) throw Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1034
1281
  return;
1035
1282
  case "ed25519":
1036
- if (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== void 0) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1283
+ if (e.algorithmOid !== f.ed25519 || e.parametersTag !== void 0) throw Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1037
1284
  return;
1038
1285
  }
1039
1286
  }
1040
- function assertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm) {
1041
- switch (algorithm.kind) {
1287
+ function assertPkcs8MatchesRequestedAlgorithm(e, t) {
1288
+ switch (t.kind) {
1042
1289
  case "rsa":
1043
- if (parsedPrivateKey.algorithmOid !== OIDS.rsaEncryption || parsedPrivateKey.parametersTag !== void 0 && parsedPrivateKey.parametersTag !== 5) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1290
+ if (e.algorithmOid !== f.rsaEncryption || e.parametersTag !== void 0 && e.parametersTag !== 5) throw Error("PKCS#8 private key algorithm does not match requested import algorithm");
1044
1291
  return;
1045
1292
  case "ecdsa":
1046
- if (parsedPrivateKey.algorithmOid !== OIDS.ecPublicKey || parsedPrivateKey.parametersTag !== 6 || parsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1293
+ if (e.algorithmOid !== f.ecPublicKey || e.parametersTag !== 6 || e.parametersOid !== curveToOid(t.curve)) throw Error("PKCS#8 private key algorithm does not match requested import algorithm");
1047
1294
  return;
1048
1295
  case "ed25519":
1049
- if (parsedPrivateKey.algorithmOid !== OIDS.ed25519 || parsedPrivateKey.parametersTag !== void 0) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1296
+ if (e.algorithmOid !== f.ed25519 || e.parametersTag !== void 0) throw Error("PKCS#8 private key algorithm does not match requested import algorithm");
1050
1297
  return;
1051
1298
  }
1052
1299
  }
1053
- function assertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm) {
1054
- if (parsedSec1.parametersTag === void 0) return;
1055
- if (parsedSec1.parametersTag !== 6 || parsedSec1.parametersOid !== curveToOid(algorithm.curve)) throw new Error("SEC 1 private key curve does not match requested import algorithm");
1300
+ function assertSec1MatchesRequestedAlgorithm(e, t) {
1301
+ if (e.parametersTag !== void 0 && (e.parametersTag !== 6 || e.parametersOid !== curveToOid(t.curve))) throw Error("SEC 1 private key curve does not match requested import algorithm");
1056
1302
  }
1057
- function assertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm) {
1058
- if (jwk.k !== void 0 || jwk.d !== void 0 || jwk.p !== void 0 || jwk.q !== void 0 || jwk.dp !== void 0 || jwk.dq !== void 0 || jwk.qi !== void 0 || jwk.oth !== void 0) throw new Error("Public JWK must not contain private key material");
1059
- switch (algorithm.kind) {
1303
+ function assertPublicJwkMatchesRequestedAlgorithm(e, t) {
1304
+ if (e.k !== void 0 || e.d !== void 0 || e.p !== void 0 || e.q !== void 0 || e.dp !== void 0 || e.dq !== void 0 || e.qi !== void 0 || e.oth !== void 0) throw Error("Public JWK must not contain private key material");
1305
+ switch (t.kind) {
1060
1306
  case "rsa":
1061
- if (jwk.kty !== "RSA" || typeof jwk.n !== "string" || typeof jwk.e !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1307
+ if (e.kty !== "RSA" || typeof e.n != "string" || typeof e.e != "string") throw Error("Public JWK algorithm does not match requested import algorithm");
1062
1308
  return;
1063
1309
  case "ecdsa":
1064
- if (jwk.kty !== "EC" || jwk.crv !== algorithm.curve || typeof jwk.x !== "string" || typeof jwk.y !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1310
+ if (e.kty !== "EC" || e.crv !== t.curve || typeof e.x != "string" || typeof e.y != "string") throw Error("Public JWK algorithm does not match requested import algorithm");
1065
1311
  return;
1066
1312
  case "ed25519":
1067
- if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1313
+ if (e.kty !== "OKP" || e.crv !== "Ed25519" || typeof e.x != "string") throw Error("Public JWK algorithm does not match requested import algorithm");
1068
1314
  return;
1069
1315
  }
1070
1316
  }
1071
- function assertPrivateJwkMatchesRequestedAlgorithm(jwk, algorithm) {
1072
- if (jwk.k !== void 0 || jwk.oth !== void 0) throw new Error("Private JWK must not contain symmetric or multi-prime key material");
1073
- if (typeof jwk.d !== "string") throw new Error("Private JWK must contain private key material");
1074
- switch (algorithm.kind) {
1317
+ function assertPrivateJwkMatchesRequestedAlgorithm(e, t) {
1318
+ if (e.k !== void 0 || e.oth !== void 0) throw Error("Private JWK must not contain symmetric or multi-prime key material");
1319
+ if (typeof e.d != "string") throw Error("Private JWK must contain private key material");
1320
+ switch (t.kind) {
1075
1321
  case "rsa":
1076
- if (jwk.kty !== "RSA" || typeof jwk.n !== "string" || typeof jwk.e !== "string" || typeof jwk.p !== "string" || typeof jwk.q !== "string" || typeof jwk.dp !== "string" || typeof jwk.dq !== "string" || typeof jwk.qi !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1322
+ if (e.kty !== "RSA" || typeof e.n != "string" || typeof e.e != "string" || typeof e.p != "string" || typeof e.q != "string" || typeof e.dp != "string" || typeof e.dq != "string" || typeof e.qi != "string") throw Error("Private JWK algorithm does not match requested import algorithm");
1077
1323
  return;
1078
1324
  case "ecdsa":
1079
- if (jwk.kty !== "EC" || jwk.crv !== algorithm.curve || typeof jwk.x !== "string" || typeof jwk.y !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1325
+ if (e.kty !== "EC" || e.crv !== t.curve || typeof e.x != "string" || typeof e.y != "string") throw Error("Private JWK algorithm does not match requested import algorithm");
1080
1326
  return;
1081
1327
  case "ed25519":
1082
- if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1328
+ if (e.kty !== "OKP" || e.crv !== "Ed25519" || typeof e.x != "string") throw Error("Private JWK algorithm does not match requested import algorithm");
1083
1329
  return;
1084
1330
  }
1085
1331
  }
1086
1332
  //#endregion
1087
- export { derivePublicKey, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs1PemOrThrow, importEncryptedPkcs8Der, importEncryptedPkcs8DerOrThrow, importEncryptedPkcs8Pem, importEncryptedPkcs8PemOrThrow, importEncryptedSec1Pem, importEncryptedSec1PemOrThrow, importPkcs1Der, importPkcs1DerOrThrow, importPkcs1Pem, importPkcs1PemOrThrow, importPkcs8Base64, importPkcs8Base64OrThrow, importPkcs8Der, importPkcs8DerOrThrow, importPkcs8Pem, importPkcs8PemOrThrow, importPrivateJwk, importPrivateJwkOrThrow, importPublicJwk, importPublicJwkOrThrow, importSec1Der, importSec1DerOrThrow, importSec1Pem, importSec1PemOrThrow, importSpkiBase64, importSpkiBase64OrThrow, importSpkiDer, importSpkiDerOrThrow, importSpkiPem, importSpkiPemOrThrow };
1333
+ export { decryptRsaOaep, decryptRsaOaepOrThrow, derivePublicKey, encryptRsaOaep, encryptRsaOaepOrThrow, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs1PemOrThrow, importEncryptedPkcs8Der, importEncryptedPkcs8DerOrThrow, importEncryptedPkcs8Pem, importEncryptedPkcs8PemOrThrow, importEncryptedSec1Pem, importEncryptedSec1PemOrThrow, importPkcs1Der, importPkcs1DerOrThrow, importPkcs1Pem, importPkcs1PemOrThrow, importPkcs8Base64, importPkcs8Base64OrThrow, importPkcs8Der, importPkcs8DerOrThrow, importPkcs8Pem, importPkcs8PemOrThrow, importPrivateJwk, importPrivateJwkOrThrow, importPublicJwk, importPublicJwkOrThrow, importSec1Der, importSec1DerOrThrow, importSec1Pem, importSec1PemOrThrow, importSpkiBase64, importSpkiBase64OrThrow, importSpkiDer, importSpkiDerOrThrow, importSpkiPem, importSpkiPemOrThrow };
1334
+
1335
+ //# sourceMappingURL=keys.js.map