micro509 0.12.0 → 0.14.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 (123) hide show
  1. package/README.md +78 -30
  2. package/dist/crypto/crypto.d.ts +73 -0
  3. package/dist/crypto/crypto.js +74 -0
  4. package/dist/crypto/crypto.js.map +1 -0
  5. package/dist/crypto.d.ts +4 -0
  6. package/dist/crypto.js +2 -0
  7. package/dist/der/der.d.ts +127 -0
  8. package/dist/der/der.js +171 -0
  9. package/dist/der/der.js.map +1 -0
  10. package/dist/der.d.ts +4 -0
  11. package/dist/der.js +4 -0
  12. package/dist/index.d.ts +13 -9
  13. package/dist/index.js +17 -15
  14. package/dist/internal/asn1/asn1.d.ts +20 -0
  15. package/dist/internal/asn1/asn1.js +80 -37
  16. package/dist/internal/asn1/asn1.js.map +1 -1
  17. package/dist/internal/asn1/der.d.ts +173 -0
  18. package/dist/internal/asn1/der.js +116 -38
  19. package/dist/internal/asn1/der.js.map +1 -1
  20. package/dist/internal/asn1/oids.js +7 -1
  21. package/dist/internal/asn1/oids2.js +9 -2
  22. package/dist/internal/asn1/oids2.js.map +1 -1
  23. package/dist/internal/crypto/algorithm-names.js +4 -0
  24. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  25. package/dist/internal/crypto/pbes2.d.ts +38 -0
  26. package/dist/internal/crypto/pbes2.js +9 -10
  27. package/dist/internal/crypto/pbes2.js.map +1 -1
  28. package/dist/internal/crypto/rsa-pss.js +2 -0
  29. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  30. package/dist/internal/crypto/sig-verify.d.ts +31 -0
  31. package/dist/internal/crypto/sig-verify.js +10 -8
  32. package/dist/internal/crypto/sig-verify.js.map +1 -1
  33. package/dist/internal/shared/base64.js +7 -1
  34. package/dist/internal/shared/base64.js.map +1 -1
  35. package/dist/internal/shared/dn.d.ts +16 -0
  36. package/dist/internal/shared/dn.js +149 -12
  37. package/dist/internal/shared/dn.js.map +1 -1
  38. package/dist/internal/shared/ip.d.ts +69 -0
  39. package/dist/internal/shared/ip.js +18 -1
  40. package/dist/internal/shared/ip.js.map +1 -1
  41. package/dist/internal/shared/rfc3454-tables.js +1782 -0
  42. package/dist/internal/shared/rfc3454-tables.js.map +1 -0
  43. package/dist/internal/verify/name-constraints-engine.js +47 -15
  44. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  45. package/dist/internal/verify/policy-engine.js +85 -94
  46. package/dist/internal/verify/policy-engine.js.map +1 -1
  47. package/dist/internal/verify/verify-path.d.ts +7 -0
  48. package/dist/internal/verify/verify-path.js +49 -45
  49. package/dist/internal/verify/verify-path.js.map +1 -1
  50. package/dist/internal/x509/directory-name.js +24 -0
  51. package/dist/internal/x509/directory-name.js.map +1 -0
  52. package/dist/internal/x509/extension-bits.js +14 -11
  53. package/dist/internal/x509/extension-bits.js.map +1 -1
  54. package/dist/internal/x509/extension-errors.d.ts +6 -0
  55. package/dist/internal/x509/extension-errors.js +20 -0
  56. package/dist/internal/x509/extension-errors.js.map +1 -0
  57. package/dist/internal/x509/extension-registry.js +113 -55
  58. package/dist/internal/x509/extension-registry.js.map +1 -1
  59. package/dist/internal/x509/general-name-tags.js +28 -0
  60. package/dist/internal/x509/general-name-tags.js.map +1 -0
  61. package/dist/internal/x509/general-name.js +97 -0
  62. package/dist/internal/x509/general-name.js.map +1 -0
  63. package/dist/internal/x509/name-fields.js +20 -10
  64. package/dist/internal/x509/name-fields.js.map +1 -1
  65. package/dist/keys/keys.d.ts +16 -2
  66. package/dist/keys/keys.js +311 -170
  67. package/dist/keys/keys.js.map +1 -1
  68. package/dist/keys.d.ts +3 -2
  69. package/dist/keys.js +3 -2
  70. package/dist/pem/pem.d.ts +3 -2
  71. package/dist/pem/pem.js +112 -30
  72. package/dist/pem/pem.js.map +1 -1
  73. package/dist/pkcs/pkcs12-mac.js +3 -3
  74. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  75. package/dist/pkcs/pkcs7.d.ts +85 -21
  76. package/dist/pkcs/pkcs7.js +261 -186
  77. package/dist/pkcs/pkcs7.js.map +1 -1
  78. package/dist/pkcs.d.ts +2 -2
  79. package/dist/result/result.d.ts +18 -10
  80. package/dist/result/result.js +20 -12
  81. package/dist/result/result.js.map +1 -1
  82. package/dist/result.d.ts +2 -2
  83. package/dist/result.js +2 -2
  84. package/dist/revocation/chain.js +154 -103
  85. package/dist/revocation/chain.js.map +1 -1
  86. package/dist/revocation/crl.d.ts +13 -2
  87. package/dist/revocation/crl.js +415 -236
  88. package/dist/revocation/crl.js.map +1 -1
  89. package/dist/revocation/ocsp.d.ts +58 -17
  90. package/dist/revocation/ocsp.js +186 -174
  91. package/dist/revocation/ocsp.js.map +1 -1
  92. package/dist/revocation/revocation.d.ts +4 -4
  93. package/dist/revocation/revocation.js +48 -30
  94. package/dist/revocation/revocation.js.map +1 -1
  95. package/dist/revocation.d.ts +4 -4
  96. package/dist/revocation.js +5 -5
  97. package/dist/verify/identity.d.ts +2 -1
  98. package/dist/verify/identity.js +2 -1
  99. package/dist/verify/identity.js.map +1 -1
  100. package/dist/verify/policy.d.ts +6 -1
  101. package/dist/verify/verify.d.ts +18 -3
  102. package/dist/verify/verify.js +66 -41
  103. package/dist/verify/verify.js.map +1 -1
  104. package/dist/verify.d.ts +2 -1
  105. package/dist/verify.js +4 -3
  106. package/dist/x509/certificate.d.ts +36 -13
  107. package/dist/x509/certificate.js +36 -19
  108. package/dist/x509/certificate.js.map +1 -1
  109. package/dist/x509/csr.d.ts +6 -3
  110. package/dist/x509/extensions.d.ts +59 -22
  111. package/dist/x509/extensions.js +384 -117
  112. package/dist/x509/extensions.js.map +1 -1
  113. package/dist/x509/name-text.js +2 -0
  114. package/dist/x509/name-text.js.map +1 -1
  115. package/dist/x509/name.d.ts +8 -5
  116. package/dist/x509/name.js +17 -12
  117. package/dist/x509/name.js.map +1 -1
  118. package/dist/x509/parse.d.ts +104 -18
  119. package/dist/x509/parse.js +127 -163
  120. package/dist/x509/parse.js.map +1 -1
  121. package/dist/x509.d.ts +8 -5
  122. package/dist/x509.js +10 -8
  123. package/package.json +52 -34
package/README.md CHANGED
@@ -10,10 +10,6 @@
10
10
  [![JSR](https://img.shields.io/jsr/v/@kjanat/micro509?logoColor=083344&logo=jsr&logoSize=auto&label=&labelColor=f7df1e&color=black)][jsr]
11
11
  [![Socket](https://badge.socket.dev/npm/package/micro509)][socket]
12
12
 
13
- [npm]: https://npm.im/micro509
14
- [jsr]: https://jsr.io/@kjanat/micro509
15
- [socket]: https://socket.dev/npm/package/micro509
16
-
17
13
  A zero-dependency TypeScript PKI toolkit for certificates, verification, revocation, and PKCS workflows.
18
14
 
19
15
  Zero dependencies. Tree-shakeable subpath entrypoints. Pure WebCrypto. Runs everywhere: Node, Bun, Deno, browsers, Cloudflare Workers.
@@ -34,11 +30,13 @@ In a browser, no build step — it is WebCrypto and nothing else:
34
30
  </script>
35
31
  ```
36
32
 
37
- Two runnable examples: [`examples/browser`] is one HTML file you can open, and
38
- [`examples/vite`] is the same demo with types and a dev server. Both open in StackBlitz.
33
+ Two runnable examples:
39
34
 
40
- [`examples/browser`]: ./examples/browser/README.md
41
- [`examples/vite`]: ./examples/vite/README.md
35
+ - [`examples/browser`][browser-example] is that, in full: one HTML file that
36
+ issues a certificate and parses it back, with nothing installed and nothing
37
+ built. [open in stackblitz][browser-example:stackblitz]
38
+ - [`examples/vite`][vite-example]: the same demo with types and a dev server.
39
+ [open in stackblitz][vite-example:stackblitz]
42
40
 
43
41
  ## Why micro509
44
42
 
@@ -59,13 +57,36 @@ And when verification fails, you get typed results your code
59
57
  can act on: [a typed error code for every failure mode], the failing
60
58
  certificate index, and structured failure details instead of `false`.
61
59
 
62
- [a typed error code for every failure mode]: https://micro509.kjanat.dev/guide/verification#error-codes
63
-
64
60
  ```ts
61
+ import { createSelfSignedCertificate, unwrap, verifyCertificateChain } from 'micro509';
62
+
63
+ const { certificate } = await createSelfSignedCertificate({
64
+ subject: { commonName: 'app.example.com' },
65
+ extensions: {
66
+ subjectAltNames: [{ type: 'dns', value: 'app.example.com' }],
67
+ },
68
+ });
69
+
70
+ const result = await verifyCertificateChain({
71
+ leaf: certificate.pem,
72
+ roots: [certificate.pem],
73
+ allowSelfSignedLeaf: true,
74
+ serviceIdentity: { type: 'dns', value: 'evil.example.com' },
75
+ });
76
+
65
77
  if (!result.ok) {
66
- // result.error.code: 'signature_invalid' | 'certificate_expired' | 'name_constraints_violated' | ...
67
- // result.error.index: which certificate in the chain failed
68
- // result.error.details: { expected, actual } for identity mismatches
78
+ switch (result.error.code) {
79
+ case 'certificate_expired':
80
+ console.log('renew the certificate at index', result.error.index);
81
+ break;
82
+ case 'subject_alt_name_mismatch': {
83
+ const { expected, actual } = result.error.details ?? {};
84
+ console.log(`identity mismatch: wanted ${expected}, presented ${actual}`);
85
+ break;
86
+ }
87
+ default:
88
+ unwrap(result); // rethrows the typed error
89
+ }
69
90
  }
70
91
  ```
71
92
 
@@ -74,10 +95,11 @@ in a single zero-dependency JS package:
74
95
 
75
96
  - **OCSP** — build requests, parse and validate responses, verify responder authorization
76
97
  - **PFX / PKCS#12** — create and parse password-protected key+cert bundles
77
- - **PKCS#7 / CMS** — sign content, parse and verify SignedData, extract cert bags
98
+ - **PKCS#7 / CMS** — sign content, parse and verify SignedData with each signer's certificate resolved, extract cert bags
78
99
  - **CRLs** — create, parse, verify, and check revocation status
79
- - **Encrypted keys** — PBES2 PKCS#8, legacy OpenSSL encrypted PEM, PKCS#1, SEC1
100
+ - **Encrypted keys** — PBES2 PKCS#8, legacy OpenSSL encrypted PEM, PKCS#1, SEC1, parameter inspection without the password
80
101
  - **Key import/export** — PKCS#8, SPKI, JWK, PKCS#1, SEC1 with generation for RSA, ECDSA, Ed25519
102
+ - **Detached signatures** — sign and verify raw bytes, ECDSA DER/raw signature conversion
81
103
  - **Service identity** — wildcard DNS, IPv6 normalization, URI-ID, SRV-ID, explicit CN opt-in
82
104
 
83
105
  Narrow defaults, explicit escape hatches — dangerous operations like CN
@@ -133,13 +155,17 @@ console.log(csr.pem);
133
155
  Parse a certificate:
134
156
 
135
157
  ```ts
136
- import { parseCertificatePem, unwrap } from 'micro509';
158
+ import { createSelfSignedCertificate, parseCertificatePem, unwrap } from 'micro509';
159
+
160
+ const { certificate } = await createSelfSignedCertificate({
161
+ subject: { commonName: 'example.com' },
162
+ extensions: { extendedKeyUsage: ['serverAuth'] },
163
+ });
137
164
 
138
- // Using certificate from previous example
139
165
  const parsed = unwrap(parseCertificatePem(certificate.pem));
140
166
  console.log(parsed.subject.values.commonName);
167
+ console.log(parsed.serialNumberHex);
141
168
  console.log(parsed.extendedKeyUsage);
142
- console.log(parsed.authorityInfoAccess);
143
169
  ```
144
170
 
145
171
  `parseCertificatePem` returns a typed `Result` — check `result.ok`, or
@@ -148,19 +174,27 @@ console.log(parsed.authorityInfoAccess);
148
174
  Verify a chain:
149
175
 
150
176
  ```ts
151
- import { verifyCertificateChain } from 'micro509';
177
+ import { createSelfSignedCertificate, verifyCertificateChain } from 'micro509';
152
178
 
153
- // Assuming you have a self-signed certificate used as both leaf and root; no intermediates
179
+ const { certificate } = await createSelfSignedCertificate({
180
+ subject: { commonName: 'example.com' },
181
+ extensions: {
182
+ extendedKeyUsage: ['serverAuth'],
183
+ subjectAltNames: [{ type: 'dns', value: 'example.com' }],
184
+ },
185
+ });
186
+
187
+ // Self-signed leaf as its own root: development shape, explicit opt-in
154
188
  const result = await verifyCertificateChain({
155
189
  leaf: certificate.pem,
156
- intermediates: [],
157
- roots: [certificate.pem], // Using self-signed cert as root for demo
190
+ roots: [certificate.pem],
158
191
  purpose: 'serverAuth',
159
192
  serviceIdentity: { type: 'dns', value: 'example.com' },
193
+ allowSelfSignedLeaf: true,
160
194
  });
161
195
 
162
196
  if (result.ok) {
163
- console.log(result.value.chain.length);
197
+ console.log(result.value.chain.length, result.value.leaf.serialNumberHex);
164
198
  } else {
165
199
  console.log(result.error.code);
166
200
  }
@@ -183,7 +217,7 @@ The core stays ESM-only and side-effect-free.
183
217
  | Area | Shipped support |
184
218
  | ------------------------------ | -------------------------------------------------------------------- |
185
219
  | Certificate and CSR signatures | RSA PKCS#1 v1.5, RSA-PSS, ECDSA `P-256` / `P-384` / `P-521`, Ed25519 |
186
- | RSA key APIs | `scheme: 'pkcs1-v1_5'` |
220
+ | RSA key APIs | `scheme: 'pkcs1-v1_5'`, `'pss'`, `'oaep'` (encryption) |
187
221
  | ECDSA key APIs | `P-256`, `P-384`, `P-521` |
188
222
  | Encrypted PKCS#8 and PFX | PBES2 with AES-CBC plus PBKDF2 HMAC-SHA1/HMAC-SHA256 |
189
223
  | Encrypted traditional PEM | AES-128-CBC, AES-192-CBC, AES-256-CBC for RSA and EC private keys |
@@ -193,12 +227,15 @@ It intentionally excludes niche, blockchain-specific, or key-agreement-only prim
193
227
 
194
228
  ## Standards status
195
229
 
196
- | Area | Status |
197
- | -------------------------- | -------- |
198
- | RFC 5280 path validation | complete |
199
- | RFC 6960 OCSP | complete |
200
- | RFC 6125 service identity | complete |
201
- | RFC 9618 policy validation | complete |
230
+ | Area | Status |
231
+ | ------------------------------------- | -------- |
232
+ | RFC 5280 path validation | complete |
233
+ | RFC 6960 + 9919 OCSP | complete |
234
+ | RFC 9525 service identity | complete |
235
+ | RFC 9618 policy validation | complete |
236
+ | RFC 7468 PEM textual encodings | complete |
237
+ | RFC 8410 + 9295 safe-curve profiles | complete |
238
+ | PKCS containers: RFC 5652, 7292, 8018 | partial |
202
239
 
203
240
  See [`docs/PKIX-SCOPE.md`](./docs/PKIX-SCOPE.md) for the detailed scope boundary
204
241
  and the [API reference](https://micro509.kjanat.dev/api/) for the public module surface.
@@ -219,8 +256,10 @@ import { parseCertificatePem } from 'micro509/x509';
219
256
  import { verifyCertificateChain, matchServiceIdentity } from 'micro509/verify';
220
257
  import { createOcspRequest, checkCertificateRevocation } from 'micro509/revocation';
221
258
  import { createPfx } from 'micro509/pkcs';
259
+ import { signData, verifySignature } from 'micro509/crypto';
222
260
  import { generateKeyPair } from 'micro509/keys';
223
261
  import { pemDecode, pemEncode } from 'micro509/pem';
262
+ import { readDerRoot, decodeDerOid } from 'micro509/der';
224
263
  import type { Micro509Error } from 'micro509/result';
225
264
  ```
226
265
 
@@ -237,3 +276,12 @@ The full stable subpath list lives in the [API reference](https://micro509.kjana
237
276
  ## License
238
277
 
239
278
  [MIT](./LICENSE)
279
+
280
+ [npm]: https://npm.im/micro509
281
+ [jsr]: https://jsr.io/@kjanat/micro509
282
+ [socket]: https://socket.dev/npm/package/micro509
283
+ [browser-example]: ./examples/browser/README.md 'GitHub'
284
+ [browser-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/browser?title=micro509%20in%20the%20browser 'Stackblitz'
285
+ [vite-example]: ./examples/vite/README.md 'GitHub'
286
+ [vite-example:stackblitz]: https://stackblitz.com/github/kjanat/micro509/tree/master/examples/vite?title=micro509%20with%20Vite 'Stackblitz'
287
+ [a typed error code for every failure mode]: https://micro509.kjanat.dev/guide/verification#error-codes
@@ -0,0 +1,73 @@
1
+ import { EcNamedCurve } from "../keys/keys.js";
2
+ import { VerifySignatureConfigFailure, VerifySignedDataFailure, VerifySignedDataResult, VerifySignedDataSuccess } from "../internal/crypto/sig-verify.js";
3
+ import { SignatureProfileInput } from "../internal/crypto/signing.js";
4
+ //#region src/crypto/crypto.d.ts
5
+ /** Input for {@linkcode verifySignature}. */
6
+ interface VerifySignatureInput {
7
+ /** DER `SubjectPublicKeyInfo` of the signer (`subjectPublicKeyInfoDer` on a parsed certificate). */
8
+ readonly signerSpkiDer: Uint8Array;
9
+ /** The signature algorithm as carried beside the signature. */
10
+ readonly signatureAlgorithm: {
11
+ /** Dotted-decimal signature algorithm OID. */
12
+ readonly oid: string;
13
+ /** DER algorithm parameters when the algorithm carries them (RSA-PSS). */
14
+ readonly parametersDer?: Uint8Array;
15
+ };
16
+ /** The signer's public key algorithm as carried in its SPKI. */
17
+ readonly publicKeyAlgorithm: {
18
+ /** Dotted-decimal public key algorithm OID. */
19
+ readonly oid: string;
20
+ /** Named-curve or scheme parameters OID, when present. */
21
+ readonly parametersOid?: string;
22
+ };
23
+ /** The signature bytes. ECDSA accepts DER or raw encoding. */
24
+ readonly signature: Uint8Array;
25
+ /** The exact bytes the signature covers. */
26
+ readonly data: Uint8Array;
27
+ }
28
+ /** Result of {@linkcode signData}: the signature plus its on-wire algorithm identity. */
29
+ interface SignDataResult {
30
+ /** The signature bytes. ECDSA is DER `ECDSA-Sig-Value`, everything else raw. */
31
+ readonly signature: Uint8Array;
32
+ /** Dotted-decimal signature algorithm OID. */
33
+ readonly algorithmOid: string;
34
+ /** DER algorithm parameters when the algorithm carries them (NULL for PKCS#1 v1.5, RSA-PSS params). */
35
+ readonly parametersDer?: Uint8Array;
36
+ }
37
+ /**
38
+ * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.
39
+ *
40
+ * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,
41
+ * ECDSA P-256/P-384/P-521, and Ed25519. When an ECDSA signature fails to
42
+ * verify under one encoding, the alternate DER/raw encoding is retried.
43
+ *
44
+ * Returns a typed union: `{ ok: true, valid }` when verification ran,
45
+ * `unsupported_signature_algorithm_parameters` or `verification_error`
46
+ * failures otherwise.
47
+ */
48
+ declare function verifySignature(input: VerifySignatureInput): Promise<VerifySignedDataResult>;
49
+ /**
50
+ * Signs `data` with a WebCrypto private key and returns the signature beside
51
+ * the resolved `AlgorithmIdentifier` material for embedding in a signed
52
+ * structure.
53
+ *
54
+ * The algorithm is inferred from the key (RSASSA-PKCS1-v1_5, ECDSA, Ed25519);
55
+ * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA
56
+ * signatures are returned DER-encoded. Throws on unsupported key algorithms.
57
+ */
58
+ declare function signData(privateKey: CryptoKey, data: Uint8Array, profile?: SignatureProfileInput): Promise<SignDataResult>;
59
+ /**
60
+ * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)
61
+ * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.
62
+ * Throws on malformed DER or integers too large for the curve.
63
+ */
64
+ declare function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
65
+ /**
66
+ * Converts a fixed-width raw `r || s` ECDSA signature to the DER
67
+ * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.
68
+ * Throws when the input length does not match the curve.
69
+ */
70
+ declare function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array;
71
+ //#endregion
72
+ export { SignDataResult, type SignatureProfileInput, type VerifySignatureConfigFailure, VerifySignatureInput, type VerifySignedDataFailure, type VerifySignedDataResult, type VerifySignedDataSuccess, ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature };
73
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { derEcdsaSignatureToRaw as e, rawEcdsaSignatureToDer as t } from "../internal/crypto/ecdsa.js";
2
+ import { verifySignedDataDetailed as n } from "../internal/crypto/sig-verify.js";
3
+ import { getSignatureAlgorithm as r, signBytes as i } from "../internal/crypto/signing.js";
4
+ //#region src/crypto/crypto.ts
5
+ /**
6
+ * Detached-signature primitives: verify a signature against a signer's SPKI,
7
+ * sign arbitrary bytes with a WebCrypto private key, and convert ECDSA
8
+ * signatures between DER `ECDSA-Sig-Value` and fixed-width raw encodings.
9
+ *
10
+ * @module
11
+ */
12
+ /**
13
+ * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.
14
+ *
15
+ * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,
16
+ * ECDSA P-256/P-384/P-521, and Ed25519. When an ECDSA signature fails to
17
+ * verify under one encoding, the alternate DER/raw encoding is retried.
18
+ *
19
+ * Returns a typed union: `{ ok: true, valid }` when verification ran,
20
+ * `unsupported_signature_algorithm_parameters` or `verification_error`
21
+ * failures otherwise.
22
+ */
23
+ function verifySignature(e) {
24
+ return n(e.signatureAlgorithm.oid, e.signatureAlgorithm.parametersDer, e.publicKeyAlgorithm.oid, e.publicKeyAlgorithm.parametersOid, e.signerSpkiDer, e.signature, e.data);
25
+ }
26
+ /**
27
+ * Signs `data` with a WebCrypto private key and returns the signature beside
28
+ * the resolved `AlgorithmIdentifier` material for embedding in a signed
29
+ * structure.
30
+ *
31
+ * The algorithm is inferred from the key (RSASSA-PKCS1-v1_5, ECDSA, Ed25519);
32
+ * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA
33
+ * signatures are returned DER-encoded. Throws on unsupported key algorithms.
34
+ */
35
+ async function signData(e, t, n) {
36
+ let a = r(e, n), o = await i(e, a, t);
37
+ return a.parameters === void 0 ? {
38
+ signature: o,
39
+ algorithmOid: a.algorithmOid
40
+ } : {
41
+ signature: o,
42
+ algorithmOid: a.algorithmOid,
43
+ parametersDer: a.parameters
44
+ };
45
+ }
46
+ /**
47
+ * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)
48
+ * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.
49
+ * Throws on malformed DER or integers too large for the curve.
50
+ */
51
+ function ecdsaSignatureDerToRaw(t, n) {
52
+ return e(t, ecdsaPartLength(n));
53
+ }
54
+ /**
55
+ * Converts a fixed-width raw `r || s` ECDSA signature to the DER
56
+ * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.
57
+ * Throws when the input length does not match the curve.
58
+ */
59
+ function ecdsaSignatureRawToDer(e, n) {
60
+ return t(e, ecdsaPartLength(n));
61
+ }
62
+ /** Byte width of one ECDSA signature integer for the given curve. */
63
+ function ecdsaPartLength(e) {
64
+ switch (e) {
65
+ case "P-256": return 32;
66
+ case "P-384": return 48;
67
+ case "P-521": return 66;
68
+ default: throw Error(`Unhandled EcNamedCurve: ${String(e)}`);
69
+ }
70
+ }
71
+ //#endregion
72
+ export { ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature };
73
+
74
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","names":["_exhaustive"],"sources":["../../src/crypto/crypto.ts"],"sourcesContent":["/**\n * Detached-signature primitives: verify a signature against a signer's SPKI,\n * sign arbitrary bytes with a WebCrypto private key, and convert ECDSA\n * signatures between DER `ECDSA-Sig-Value` and fixed-width raw encodings.\n *\n * @module\n */\n\nimport { derEcdsaSignatureToRaw, rawEcdsaSignatureToDer } from '#micro509/internal/crypto/ecdsa';\nimport type { VerifySignedDataResult } from '#micro509/internal/crypto/sig-verify';\nimport { verifySignedDataDetailed } from '#micro509/internal/crypto/sig-verify';\nimport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\nimport { getSignatureAlgorithm, signBytes } from '#micro509/internal/crypto/signing';\nimport type { EcNamedCurve } from '#micro509/keys/keys';\n\nexport type {\n\tVerifySignatureConfigFailure,\n\tVerifySignedDataFailure,\n\tVerifySignedDataResult,\n\tVerifySignedDataSuccess,\n} from '#micro509/internal/crypto/sig-verify';\nexport type { SignatureProfileInput } from '#micro509/internal/crypto/signing';\n\n/** Input for {@linkcode verifySignature}. */\nexport interface VerifySignatureInput {\n\t/** DER `SubjectPublicKeyInfo` of the signer (`subjectPublicKeyInfoDer` on a parsed certificate). */\n\treadonly signerSpkiDer: Uint8Array;\n\t/** The signature algorithm as carried beside the signature. */\n\treadonly signatureAlgorithm: {\n\t\t/** Dotted-decimal signature algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** DER algorithm parameters when the algorithm carries them (RSA-PSS). */\n\t\treadonly parametersDer?: Uint8Array;\n\t};\n\t/** The signer's public key algorithm as carried in its SPKI. */\n\treadonly publicKeyAlgorithm: {\n\t\t/** Dotted-decimal public key algorithm OID. */\n\t\treadonly oid: string;\n\t\t/** Named-curve or scheme parameters OID, when present. */\n\t\treadonly parametersOid?: string;\n\t};\n\t/** The signature bytes. ECDSA accepts DER or raw encoding. */\n\treadonly signature: Uint8Array;\n\t/** The exact bytes the signature covers. */\n\treadonly data: Uint8Array;\n}\n\n/** Result of {@linkcode signData}: the signature plus its on-wire algorithm identity. */\nexport interface SignDataResult {\n\t/** The signature bytes. ECDSA is DER `ECDSA-Sig-Value`, everything else raw. */\n\treadonly signature: Uint8Array;\n\t/** Dotted-decimal signature algorithm OID. */\n\treadonly algorithmOid: string;\n\t/** DER algorithm parameters when the algorithm carries them (NULL for PKCS#1 v1.5, RSA-PSS params). */\n\treadonly parametersDer?: Uint8Array;\n}\n\n/**\n * Verifies a detached signature against the signer's DER `SubjectPublicKeyInfo`.\n *\n * Supports RSA PKCS#1 v1.5 (SHA-256/384/512), RSA-PSS with parsed parameters,\n * ECDSA P-256/P-384/P-521, and Ed25519. When an ECDSA signature fails to\n * verify under one encoding, the alternate DER/raw encoding is retried.\n *\n * Returns a typed union: `{ ok: true, valid }` when verification ran,\n * `unsupported_signature_algorithm_parameters` or `verification_error`\n * failures otherwise.\n */\nexport function verifySignature(input: VerifySignatureInput): Promise<VerifySignedDataResult> {\n\treturn verifySignedDataDetailed(\n\t\tinput.signatureAlgorithm.oid,\n\t\tinput.signatureAlgorithm.parametersDer,\n\t\tinput.publicKeyAlgorithm.oid,\n\t\tinput.publicKeyAlgorithm.parametersOid,\n\t\tinput.signerSpkiDer,\n\t\tinput.signature,\n\t\tinput.data,\n\t);\n}\n\n/**\n * Signs `data` with a WebCrypto private key and returns the signature beside\n * the resolved `AlgorithmIdentifier` material for embedding in a signed\n * structure.\n *\n * The algorithm is inferred from the key (RSASSA-PKCS1-v1_5, ECDSA, Ed25519);\n * RSA-PSS keys require an explicit `{ kind: 'rsa-pss' }` profile. ECDSA\n * signatures are returned DER-encoded. Throws on unsupported key algorithms.\n */\nexport async function signData(\n\tprivateKey: CryptoKey,\n\tdata: Uint8Array,\n\tprofile?: SignatureProfileInput,\n): Promise<SignDataResult> {\n\tconst algorithm = getSignatureAlgorithm(privateKey, profile);\n\tconst signature = await signBytes(privateKey, algorithm, data);\n\treturn algorithm.parameters === undefined\n\t\t? { signature, algorithmOid: algorithm.algorithmOid }\n\t\t: { signature, algorithmOid: algorithm.algorithmOid, parametersDer: algorithm.parameters };\n}\n\n/**\n * Converts a DER `ECDSA-Sig-Value` (RFC 5480: SEQUENCE of INTEGERs r and s)\n * to the fixed-width raw `r || s` encoding WebCrypto and JOSE use.\n * Throws on malformed DER or integers too large for the curve.\n */\nexport function ecdsaSignatureDerToRaw(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn derEcdsaSignatureToRaw(signature, ecdsaPartLength(curve));\n}\n\n/**\n * Converts a fixed-width raw `r || s` ECDSA signature to the DER\n * `ECDSA-Sig-Value` encoding X.509 and CMS structures embed.\n * Throws when the input length does not match the curve.\n */\nexport function ecdsaSignatureRawToDer(signature: Uint8Array, curve: EcNamedCurve): Uint8Array {\n\treturn rawEcdsaSignatureToDer(signature, ecdsaPartLength(curve));\n}\n\n/** Byte width of one ECDSA signature integer for the given curve. */\nfunction ecdsaPartLength(curve: EcNamedCurve): number {\n\tswitch (curve) {\n\t\tcase 'P-256':\n\t\t\treturn 32;\n\t\tcase 'P-384':\n\t\t\treturn 48;\n\t\tcase 'P-521':\n\t\t\treturn 66;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = curve;\n\t\t\tthrow new Error(`Unhandled EcNamedCurve: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,gBAAgB,GAA8D;CAC7F,OAAO,EACN,EAAM,mBAAmB,KACzB,EAAM,mBAAmB,eACzB,EAAM,mBAAmB,KACzB,EAAM,mBAAmB,eACzB,EAAM,eACN,EAAM,WACN,EAAM,IACP;AACD;;;;;;;;;;AAWA,eAAsB,SACrB,GACA,GACA,GAC0B;CAC1B,IAAM,IAAY,EAAsB,GAAY,CAAO,GACrD,IAAY,MAAM,EAAU,GAAY,GAAW,CAAI;CAC7D,OAAO,EAAU,eAAe,KAAA,IAC7B;EAAE;EAAW,cAAc,EAAU;CAAa,IAClD;EAAE;EAAW,cAAc,EAAU;EAAc,eAAe,EAAU;CAAW;AAC3F;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAO,EAAuB,GAAW,gBAAgB,CAAK,CAAC;AAChE;;;;;;AAOA,SAAgB,uBAAuB,GAAuB,GAAiC;CAC9F,OAAO,EAAuB,GAAW,gBAAgB,CAAK,CAAC;AAChE;;AAGA,SAAS,gBAAgB,GAA6B;CACrD,QAAQ,GAAR;EACC,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,KAAK,SACJ,OAAO;EACR,SAEC,MAAU,MAAM,2BAA2B,OAAOA,CAAW,GAAG;CAElE;AACD"}
@@ -0,0 +1,4 @@
1
+ import { VerifySignatureConfigFailure, VerifySignedDataFailure, VerifySignedDataResult, VerifySignedDataSuccess } from "./internal/crypto/sig-verify.js";
2
+ import { SignatureProfileInput } from "./internal/crypto/signing.js";
3
+ import { SignDataResult, VerifySignatureInput, ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature } from "./crypto/crypto.js";
4
+ export { type SignDataResult, type SignatureProfileInput, type VerifySignatureConfigFailure, type VerifySignatureInput, type VerifySignedDataFailure, type VerifySignedDataResult, type VerifySignedDataSuccess, ecdsaSignatureDerToRaw, ecdsaSignatureRawToDer, signData, verifySignature };
package/dist/crypto.js ADDED
@@ -0,0 +1,2 @@
1
+ import { ecdsaSignatureDerToRaw as e, ecdsaSignatureRawToDer as t, signData as n, verifySignature as r } from "./crypto/crypto.js";
2
+ export { e as ecdsaSignatureDerToRaw, t as ecdsaSignatureRawToDer, n as signData, r as verifySignature };
@@ -0,0 +1,127 @@
1
+ import { ErrorResult, Micro509Error } from "../result/result.js";
2
+ import { DerElement, ReadRootElementOptions, ReadSequenceChildrenOptions } from "../internal/asn1/der.js";
3
+ import { DerBitString } from "../internal/asn1/asn1.js";
4
+ //#region src/der/der.d.ts
5
+ /** Machine-readable failure reason for the DER readers and decoders. */
6
+ type DecodeDerErrorCode = "malformed";
7
+ /** Structured failure payload for DER reading and decoding. */
8
+ interface DecodeDerFailure extends Micro509Error<DecodeDerErrorCode> {
9
+ /** Always `false` for failures. */
10
+ readonly ok: false;
11
+ }
12
+ /** Success-or-failure result from a DER reader or decoder. */
13
+ type DecodeDerResult<TValue> = {
14
+ readonly ok: true;
15
+ readonly value: TValue;
16
+ } | ErrorResult<DecodeDerErrorCode, Record<never, never>, DecodeDerFailure>;
17
+ /**
18
+ * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.
19
+ *
20
+ * @param offset Byte position of the tag octet. Defaults to 0.
21
+ * @throws if the element is truncated, indefinite-length, or non-minimally encoded.
22
+ */
23
+ declare function readDerElementOrThrow(bytes: Uint8Array, offset?: number): DerElement;
24
+ /**
25
+ * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.
26
+ *
27
+ * @param offset Byte position of the tag octet. Defaults to 0.
28
+ */
29
+ declare function readDerElement(bytes: Uint8Array, offset?: number): DecodeDerResult<DerElement>;
30
+ /**
31
+ * Reads the single top-level TLV element from {@linkcode bytes}.
32
+ *
33
+ * @throws if {@linkcode bytes} carries trailing data, or nesting exceeds the depth guard.
34
+ */
35
+ declare function readDerRootOrThrow(bytes: Uint8Array, options?: ReadRootElementOptions): DerElement;
36
+ /** Reads the single top-level TLV element from {@linkcode bytes}. */
37
+ declare function readDerRoot(bytes: Uint8Array, options?: ReadRootElementOptions): DecodeDerResult<DerElement>;
38
+ /**
39
+ * Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children.
40
+ *
41
+ * @throws if the root element is not a SEQUENCE, or if child boundaries are inconsistent.
42
+ */
43
+ declare function readDerSequenceOrThrow(bytes: Uint8Array, options?: ReadSequenceChildrenOptions): DerElement[];
44
+ /** Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children. */
45
+ declare function readDerSequence(bytes: Uint8Array, options?: ReadSequenceChildrenOptions): DecodeDerResult<DerElement[]>;
46
+ /**
47
+ * Reads the direct children of a constructed {@linkcode parent} within {@linkcode source}.
48
+ *
49
+ * @throws if a child overflows {@linkcode parent}, or data is left between the last child and its end.
50
+ */
51
+ declare function derChildrenOrThrow(source: Uint8Array, parent: DerElement): DerElement[];
52
+ /** Reads the direct children of a constructed {@linkcode parent} within {@linkcode source}. */
53
+ declare function derChildren(source: Uint8Array, parent: DerElement): DecodeDerResult<DerElement[]>;
54
+ /**
55
+ * Decodes a BOOLEAN element (tag `0x01`).
56
+ *
57
+ * @throws if {@linkcode element} is mis-tagged, or holds anything but `0x00` or `0xff`.
58
+ */
59
+ declare function decodeDerBooleanOrThrow(element: DerElement): boolean;
60
+ /** Decodes a BOOLEAN element (tag `0x01`). */
61
+ declare function decodeDerBoolean(element: DerElement): DecodeDerResult<boolean>;
62
+ /**
63
+ * Decodes an INTEGER element (tag `0x02`) into a `number`.
64
+ *
65
+ * @throws if {@linkcode element} is mis-tagged, negative, non-minimally encoded,
66
+ * or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.
67
+ */
68
+ declare function decodeDerIntegerOrThrow(element: DerElement): number;
69
+ /** Decodes an INTEGER element (tag `0x02`) into a `number`. */
70
+ declare function decodeDerInteger(element: DerElement): DecodeDerResult<number>;
71
+ /**
72
+ * Decodes an OCTET STRING element (tag `0x04`) into its payload bytes.
73
+ *
74
+ * @throws if {@linkcode element} is mis-tagged.
75
+ */
76
+ declare function decodeDerOctetStringOrThrow(element: DerElement): Uint8Array;
77
+ /** Decodes an OCTET STRING element (tag `0x04`) into its payload bytes. */
78
+ declare function decodeDerOctetString(element: DerElement): DecodeDerResult<Uint8Array>;
79
+ /**
80
+ * Decodes an OBJECT IDENTIFIER element (tag `0x06`) into dotted-decimal form.
81
+ *
82
+ * @throws if {@linkcode element} is mis-tagged, or holds a malformed sub-identifier.
83
+ */
84
+ declare function decodeDerOidOrThrow(element: DerElement): string;
85
+ /** Decodes an OBJECT IDENTIFIER element (tag `0x06`) into dotted-decimal form. */
86
+ declare function decodeDerOid(element: DerElement): DecodeDerResult<string>;
87
+ /**
88
+ * Decodes a BIT STRING element (tag `0x03`) into a {@linkcode DerBitString}.
89
+ *
90
+ * Unused trailing bits are returned as encoded, with a violation of {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} reported
91
+ * through {@linkcode DerBitString.nonZeroPadding}, since certificates in the wild carry them.
92
+ *
93
+ * @throws if {@linkcode element} is mis-tagged, or claims more than seven unused bits.
94
+ */
95
+ declare function decodeDerBitStringOrThrow(element: DerElement): DerBitString;
96
+ /**
97
+ * Decodes a BIT STRING element (tag `0x03`) into a {@linkcode DerBitString}.
98
+ *
99
+ * Unused trailing bits are returned as encoded, with a violation of {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} reported
100
+ * through {@linkcode DerBitString.nonZeroPadding}, since certificates in the wild carry them.
101
+ */
102
+ declare function decodeDerBitString(element: DerElement): DecodeDerResult<DerBitString>;
103
+ /**
104
+ * Decodes a string element into text, dispatching on its tag.
105
+ *
106
+ * Supports UTF8String, PrintableString, IA5String, UniversalString, and BMPString.
107
+ *
108
+ * @throws on TeletexString, and on every other string tag.
109
+ */
110
+ declare function decodeDerStringOrThrow(element: DerElement): string;
111
+ /**
112
+ * Decodes a string element into text, dispatching on its tag.
113
+ *
114
+ * Supports UTF8String, PrintableString, IA5String, UniversalString, and BMPString.
115
+ */
116
+ declare function decodeDerString(element: DerElement): DecodeDerResult<string>;
117
+ /**
118
+ * Decodes a UTCTime (tag `0x17`) or GeneralizedTime (tag `0x18`) element into a {@linkcode Date}.
119
+ *
120
+ * @throws if {@linkcode element} carries any other tag, or a malformed time value.
121
+ */
122
+ declare function decodeDerTimeOrThrow(element: DerElement): Date;
123
+ /** Decodes a UTCTime (tag `0x17`) or GeneralizedTime (tag `0x18`) element into a {@linkcode Date}. */
124
+ declare function decodeDerTime(element: DerElement): DecodeDerResult<Date>;
125
+ //#endregion
126
+ export { DecodeDerErrorCode, DecodeDerFailure, DecodeDerResult, decodeDerBitString, decodeDerBitStringOrThrow, decodeDerBoolean, decodeDerBooleanOrThrow, decodeDerInteger, decodeDerIntegerOrThrow, decodeDerOctetString, decodeDerOctetStringOrThrow, decodeDerOid, decodeDerOidOrThrow, decodeDerString, decodeDerStringOrThrow, decodeDerTime, decodeDerTimeOrThrow, derChildren, derChildrenOrThrow, readDerElement, readDerElementOrThrow, readDerRoot, readDerRootOrThrow, readDerSequence, readDerSequenceOrThrow };
127
+ //# sourceMappingURL=der.d.ts.map
@@ -0,0 +1,171 @@
1
+ import { readElement as e, readRootElement as t, readSequenceChildren as n } from "../internal/asn1/der.js";
2
+ import { childrenOf as r, decodeBitString as i, decodeBoolean as a, decodeIntegerNumber as o, decodeObjectIdentifier as s, decodeString as c, parseTime as l } from "../internal/asn1/asn1.js";
3
+ import { failureResult as u, rethrowIfInvariant as d, successResult as f } from "../result/result.js";
4
+ //#region src/der/der.ts
5
+ function attempt(e, t) {
6
+ try {
7
+ return f(e());
8
+ } catch (e) {
9
+ return d(e), u("malformed", e instanceof Error ? e.message : t);
10
+ }
11
+ }
12
+ function requireTag(e, t, n) {
13
+ if (e.tag !== t) throw Error(`Expected ${n}`);
14
+ return e;
15
+ }
16
+ /**
17
+ * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.
18
+ *
19
+ * @param offset Byte position of the tag octet. Defaults to 0.
20
+ * @throws if the element is truncated, indefinite-length, or non-minimally encoded.
21
+ */
22
+ function readDerElementOrThrow(t, n = 0) {
23
+ return e(t, n);
24
+ }
25
+ /**
26
+ * Reads one TLV element from {@linkcode bytes} starting at {@linkcode offset}.
27
+ *
28
+ * @param offset Byte position of the tag octet. Defaults to 0.
29
+ */
30
+ function readDerElement(e, t = 0) {
31
+ return attempt(() => readDerElementOrThrow(e, t), "Malformed DER element");
32
+ }
33
+ /**
34
+ * Reads the single top-level TLV element from {@linkcode bytes}.
35
+ *
36
+ * @throws if {@linkcode bytes} carries trailing data, or nesting exceeds the depth guard.
37
+ */
38
+ function readDerRootOrThrow(e, n) {
39
+ return t(e, n);
40
+ }
41
+ /** Reads the single top-level TLV element from {@linkcode bytes}. */
42
+ function readDerRoot(e, t) {
43
+ return attempt(() => readDerRootOrThrow(e, t), "Malformed DER element");
44
+ }
45
+ /**
46
+ * Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children.
47
+ *
48
+ * @throws if the root element is not a SEQUENCE, or if child boundaries are inconsistent.
49
+ */
50
+ function readDerSequenceOrThrow(e, t) {
51
+ return n(e, t);
52
+ }
53
+ /** Reads a DER-encoded SEQUENCE from {@linkcode bytes} and returns its direct children. */
54
+ function readDerSequence(e, t) {
55
+ return attempt(() => readDerSequenceOrThrow(e, t), "Malformed DER sequence");
56
+ }
57
+ /**
58
+ * Reads the direct children of a constructed {@linkcode parent} within {@linkcode source}.
59
+ *
60
+ * @throws if a child overflows {@linkcode parent}, or data is left between the last child and its end.
61
+ */
62
+ function derChildrenOrThrow(e, t) {
63
+ return r(e, t);
64
+ }
65
+ /** Reads the direct children of a constructed {@linkcode parent} within {@linkcode source}. */
66
+ function derChildren(e, t) {
67
+ return attempt(() => derChildrenOrThrow(e, t), "Malformed DER container");
68
+ }
69
+ /**
70
+ * Decodes a BOOLEAN element (tag `0x01`).
71
+ *
72
+ * @throws if {@linkcode element} is mis-tagged, or holds anything but `0x00` or `0xff`.
73
+ */
74
+ function decodeDerBooleanOrThrow(e) {
75
+ return a(requireTag(e, 1, "BOOLEAN").value);
76
+ }
77
+ /** Decodes a BOOLEAN element (tag `0x01`). */
78
+ function decodeDerBoolean(e) {
79
+ return attempt(() => decodeDerBooleanOrThrow(e), "Malformed BOOLEAN");
80
+ }
81
+ /**
82
+ * Decodes an INTEGER element (tag `0x02`) into a `number`.
83
+ *
84
+ * @throws if {@linkcode element} is mis-tagged, negative, non-minimally encoded,
85
+ * or exceeds {@linkcode Number.MAX_SAFE_INTEGER}.
86
+ */
87
+ function decodeDerIntegerOrThrow(e) {
88
+ return o(requireTag(e, 2, "INTEGER").value);
89
+ }
90
+ /** Decodes an INTEGER element (tag `0x02`) into a `number`. */
91
+ function decodeDerInteger(e) {
92
+ return attempt(() => decodeDerIntegerOrThrow(e), "Malformed INTEGER");
93
+ }
94
+ /**
95
+ * Decodes an OCTET STRING element (tag `0x04`) into its payload bytes.
96
+ *
97
+ * @throws if {@linkcode element} is mis-tagged.
98
+ */
99
+ function decodeDerOctetStringOrThrow(e) {
100
+ return requireTag(e, 4, "OCTET STRING").value;
101
+ }
102
+ /** Decodes an OCTET STRING element (tag `0x04`) into its payload bytes. */
103
+ function decodeDerOctetString(e) {
104
+ return attempt(() => decodeDerOctetStringOrThrow(e), "Malformed OCTET STRING");
105
+ }
106
+ /**
107
+ * Decodes an OBJECT IDENTIFIER element (tag `0x06`) into dotted-decimal form.
108
+ *
109
+ * @throws if {@linkcode element} is mis-tagged, or holds a malformed sub-identifier.
110
+ */
111
+ function decodeDerOidOrThrow(e) {
112
+ return s(requireTag(e, 6, "OBJECT IDENTIFIER").value);
113
+ }
114
+ /** Decodes an OBJECT IDENTIFIER element (tag `0x06`) into dotted-decimal form. */
115
+ function decodeDerOid(e) {
116
+ return attempt(() => decodeDerOidOrThrow(e), "Malformed OBJECT IDENTIFIER");
117
+ }
118
+ /**
119
+ * Decodes a BIT STRING element (tag `0x03`) into a {@linkcode DerBitString}.
120
+ *
121
+ * Unused trailing bits are returned as encoded, with a violation of {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} reported
122
+ * through {@linkcode DerBitString.nonZeroPadding}, since certificates in the wild carry them.
123
+ *
124
+ * @throws if {@linkcode element} is mis-tagged, or claims more than seven unused bits.
125
+ */
126
+ function decodeDerBitStringOrThrow(e) {
127
+ return i(e);
128
+ }
129
+ /**
130
+ * Decodes a BIT STRING element (tag `0x03`) into a {@linkcode DerBitString}.
131
+ *
132
+ * Unused trailing bits are returned as encoded, with a violation of {@linkcode https://www.itu.int/rec/T-REC-X.690-202102-I/en | X.690 §11.2.1} reported
133
+ * through {@linkcode DerBitString.nonZeroPadding}, since certificates in the wild carry them.
134
+ */
135
+ function decodeDerBitString(e) {
136
+ return attempt(() => decodeDerBitStringOrThrow(e), "Malformed BIT STRING");
137
+ }
138
+ /**
139
+ * Decodes a string element into text, dispatching on its tag.
140
+ *
141
+ * Supports UTF8String, PrintableString, IA5String, UniversalString, and BMPString.
142
+ *
143
+ * @throws on TeletexString, and on every other string tag.
144
+ */
145
+ function decodeDerStringOrThrow(e) {
146
+ return c(e.tag, e.value);
147
+ }
148
+ /**
149
+ * Decodes a string element into text, dispatching on its tag.
150
+ *
151
+ * Supports UTF8String, PrintableString, IA5String, UniversalString, and BMPString.
152
+ */
153
+ function decodeDerString(e) {
154
+ return attempt(() => decodeDerStringOrThrow(e), "Malformed string");
155
+ }
156
+ /**
157
+ * Decodes a UTCTime (tag `0x17`) or GeneralizedTime (tag `0x18`) element into a {@linkcode Date}.
158
+ *
159
+ * @throws if {@linkcode element} carries any other tag, or a malformed time value.
160
+ */
161
+ function decodeDerTimeOrThrow(e) {
162
+ return l(e);
163
+ }
164
+ /** Decodes a UTCTime (tag `0x17`) or GeneralizedTime (tag `0x18`) element into a {@linkcode Date}. */
165
+ function decodeDerTime(e) {
166
+ return attempt(() => decodeDerTimeOrThrow(e), "Malformed time");
167
+ }
168
+ //#endregion
169
+ export { decodeDerBitString, decodeDerBitStringOrThrow, decodeDerBoolean, decodeDerBooleanOrThrow, decodeDerInteger, decodeDerIntegerOrThrow, decodeDerOctetString, decodeDerOctetStringOrThrow, decodeDerOid, decodeDerOidOrThrow, decodeDerString, decodeDerStringOrThrow, decodeDerTime, decodeDerTimeOrThrow, derChildren, derChildrenOrThrow, readDerElement, readDerElementOrThrow, readDerRoot, readDerRootOrThrow, readDerSequence, readDerSequenceOrThrow };
170
+
171
+ //# sourceMappingURL=der.js.map