micro509 0.18.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +109 -1
- package/dist/crypto/crypto.d.ts +11 -2
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +2 -2
- package/dist/der/der.js.map +1 -1
- package/dist/index.d.ts +7 -6
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js +64 -64
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.js +3 -3
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +40 -0
- package/dist/internal/crypto/sig-verify.js +152 -65
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js.map +1 -1
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna-tables.js +3 -3
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.js +222 -116
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.js.map +1 -1
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.js.map +1 -1
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.js +2 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/keys/keys.d.ts +7 -2
- package/dist/keys/keys.js +10 -6
- package/dist/keys/keys.js.map +1 -1
- package/dist/pem/pem.d.ts +20 -7
- package/dist/pem/pem.js +24 -20
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +2 -2
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.js +3 -3
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +10 -0
- package/dist/pkcs/pkcs7.js +106 -88
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/result/result.js.map +1 -1
- package/dist/revocation/chain.d.ts +67 -13
- package/dist/revocation/chain.js +429 -301
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +65 -11
- package/dist/revocation/crl.js +472 -182
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +79 -24
- package/dist/revocation/ocsp.js +417 -231
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -13
- package/dist/revocation/revocation.js +194 -73
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +4 -4
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.js.map +1 -1
- package/dist/verify/identity.d.ts +2 -2
- package/dist/verify/identity.js +2 -2
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/verify.d.ts +84 -32
- package/dist/verify/verify.js +221 -175
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +3 -2
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.js +1 -1
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.js +1 -1
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +6 -2
- package/dist/x509/parse.js +121 -121
- package/dist/x509/parse.js.map +1 -1
- package/package.json +16 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ecdsa.js","names":["
|
|
1
|
+
{"version":3,"file":"ecdsa.js","names":["integer","readSequenceChildren","sequence","signature","partLength","parts","r","s","rawSignatureBytes","left","right","out","bytes","first","second"],"sources":["../../../src/internal/crypto/ecdsa.ts"],"sourcesContent":["/**\n * ECDSA signature encoding conversion between ASN.1 DER (r, s INTEGER) and the\n * fixed-width raw format used by WebCrypto.\n *\n * @module\n */\n\nimport { integer, readSequenceChildren, sequence } from '#micro509/internal/asn1/der';\n\n/** Convert a DER-encoded ECDSA signature (SEQUENCE of two INTEGERs) to fixed-width raw `r || s`. */\nexport function derEcdsaSignatureToRaw(signature: Uint8Array, partLength: number): Uint8Array {\n\tconst parts = readSequenceChildren(signature);\n\tconst r = parts[0];\n\tconst s = parts[1];\n\tif (r === undefined || s === undefined || parts.length !== 2) {\n\t\tthrow new Error('Malformed ECDSA DER signature');\n\t}\n\tif (r.tag !== 0x02 || s.tag !== 0x02) {\n\t\tthrow new Error('ECDSA DER signature must contain two INTEGERs');\n\t}\n\treturn concatFixedWidth(derIntegerMagnitude(r.value), derIntegerMagnitude(s.value), partLength);\n}\n\n/** Convert a fixed-width raw `r || s` ECDSA signature to DER-encoded SEQUENCE of two INTEGERs. */\nexport function rawEcdsaSignatureToDer(signature: Uint8Array, partLength: number): Uint8Array {\n\tif (signature.length !== partLength * 2) {\n\t\tthrow new Error('Unexpected ECDSA raw signature length');\n\t}\n\treturn sequence([integer(signature.slice(0, partLength)), integer(signature.slice(partLength))]);\n}\n\n/**\n * Normalize a WebCrypto ECDSA signature to DER.\n *\n * Spec-compliant WebCrypto always returns fixed-width raw `r || s`\n * (exactly `rawSignatureBytes` long), which needs conversion. Detection is\n * by length, never by sniffing the first byte: a raw signature whose `r`\n * happens to start with `0x30` (1-in-256 per signature) is\n * indistinguishable from DER by tag, and embedding it unconverted produces\n * a certificate/CRL that OpenSSL rejects with a signature failure.\n */\nexport function ecdsaSignatureToDer(signature: Uint8Array, rawSignatureBytes: number): Uint8Array {\n\tif (signature.length === rawSignatureBytes) {\n\t\treturn rawEcdsaSignatureToDer(signature, rawSignatureBytes / 2);\n\t}\n\treturn signature;\n}\n\n/**\n * Try the opposite ECDSA encoding: DER→raw or raw→DER.\n *\n * Returns `undefined` if conversion fails, letting callers retry verification\n * with the alternate encoding.\n */\nexport function alternateEcdsaSignatureEncoding(\n\tsignature: Uint8Array,\n\tpartLength: number,\n): Uint8Array | undefined {\n\t// Try DER→raw first if it looks like DER (starts with SEQUENCE tag)\n\tif (signature[0] === 0x30) {\n\t\ttry {\n\t\t\treturn derEcdsaSignatureToRaw(signature, partLength);\n\t\t} catch {\n\t\t\t// Fall through to try raw→DER\n\t\t}\n\t}\n\t// Try raw→DER\n\ttry {\n\t\treturn rawEcdsaSignatureToDer(signature, partLength);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Left-pad and concatenate `r` and `s` into a fixed-width `partLength * 2` byte buffer. */\nexport function concatFixedWidth(\n\tleft: Uint8Array,\n\tright: Uint8Array,\n\tpartLength: number,\n): Uint8Array {\n\tif (left.length > partLength || right.length > partLength) {\n\t\tthrow new Error('ECDSA signature integer too large');\n\t}\n\tconst out = new Uint8Array(partLength * 2);\n\tout.set(left, partLength - left.length);\n\tout.set(right, out.length - right.length);\n\treturn out;\n}\n\n/** Validate a non-negative DER INTEGER and return its unsigned magnitude. */\nfunction derIntegerMagnitude(bytes: Uint8Array): Uint8Array {\n\tconst first = bytes[0];\n\tif (first === undefined) {\n\t\tthrow new Error('ECDSA DER signature INTEGER must not be empty');\n\t}\n\tif ((first & 0x80) !== 0) {\n\t\tthrow new Error('ECDSA DER signature INTEGER must be non-negative');\n\t}\n\tif (first === 0 && bytes.length > 1) {\n\t\tconst second = bytes[1];\n\t\tif (second === undefined || (second & 0x80) === 0) {\n\t\t\tthrow new Error('ECDSA DER signature INTEGER must use minimal encoding');\n\t\t}\n\t\treturn bytes.slice(1);\n\t}\n\treturn bytes;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,uBAAuBG,GAAuBC,GAAgC;CAC7F,IAAMC,IAAQJ,EAAqBE,CAAS,GACtCG,IAAID,EAAM,IACVE,IAAIF,EAAM;CAChB,IAAIC,MAAM,KAAA,KAAaC,MAAM,KAAA,KAAaF,EAAM,WAAW,GAC1D,MAAU,MAAM,+BAA+B;CAEhD,IAAIC,EAAE,QAAQ,KAAQC,EAAE,QAAQ,GAC/B,MAAU,MAAM,+CAA+C;CAEhE,OAAO,iBAAiB,oBAAoBD,EAAE,KAAK,GAAG,oBAAoBC,EAAE,KAAK,GAAGH,CAAU;AAC/F;;A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21
|
|
98
98
|
], t = [
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
0xd76aa478,
|
|
100
|
+
0xe8c7b756,
|
|
101
101
|
606105819,
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
102
|
+
0xc1bdceee,
|
|
103
|
+
0xf57c0faf,
|
|
104
|
+
0x4787c62a,
|
|
105
|
+
0xa8304613,
|
|
106
|
+
0xfd469501,
|
|
107
|
+
0x698098d8,
|
|
108
|
+
0x8b44f7af,
|
|
109
|
+
0xffff5bb1,
|
|
110
|
+
0x895cd7be,
|
|
111
|
+
0x6b901122,
|
|
112
|
+
0xfd987193,
|
|
113
|
+
0xa679438e,
|
|
114
|
+
0x49b40821,
|
|
115
|
+
0xf61e2562,
|
|
116
|
+
0xc040b340,
|
|
117
117
|
643717713,
|
|
118
|
-
|
|
119
|
-
|
|
118
|
+
0xe9b6c7aa,
|
|
119
|
+
0xd62f105d,
|
|
120
120
|
38016083,
|
|
121
|
-
|
|
122
|
-
|
|
121
|
+
0xd8a1e681,
|
|
122
|
+
0xe7d3fbc8,
|
|
123
123
|
568446438,
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
124
|
+
0xc33707d6,
|
|
125
|
+
0xf4d50d87,
|
|
126
|
+
0x455a14ed,
|
|
127
|
+
0xa9e3e905,
|
|
128
|
+
0xfcefa3f8,
|
|
129
|
+
0x676f02d9,
|
|
130
|
+
0x8d2a4c8a,
|
|
131
|
+
0xfffa3942,
|
|
132
|
+
0x8771f681,
|
|
133
|
+
0x6d9d6122,
|
|
134
|
+
0xfde5380c,
|
|
135
|
+
0xa4beea44,
|
|
136
|
+
0x4bdecfa9,
|
|
137
|
+
0xf6bb4b60,
|
|
138
|
+
0xbebfbc70,
|
|
139
139
|
681279174,
|
|
140
|
-
|
|
141
|
-
|
|
140
|
+
0xeaa127fa,
|
|
141
|
+
0xd4ef3085,
|
|
142
142
|
76029189,
|
|
143
|
-
|
|
144
|
-
|
|
143
|
+
0xd9d4d039,
|
|
144
|
+
0xe6db99e5,
|
|
145
145
|
530742520,
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
146
|
+
0xc4ac5665,
|
|
147
|
+
0xf4292244,
|
|
148
|
+
0x432aff97,
|
|
149
|
+
0xab9423a7,
|
|
150
|
+
0xfc93a039,
|
|
151
|
+
0x655b59c3,
|
|
152
|
+
0x8f0ccc92,
|
|
153
|
+
0xffeff47d,
|
|
154
|
+
0x85845dd1,
|
|
155
|
+
0x6fa87e4f,
|
|
156
|
+
0xfe2ce6e0,
|
|
157
|
+
0xa3014314,
|
|
158
|
+
0x4e0811a1,
|
|
159
|
+
0xf7537e82,
|
|
160
|
+
0xbd3af235,
|
|
161
161
|
718787259,
|
|
162
|
-
|
|
162
|
+
0xeb86d391
|
|
163
163
|
];
|
|
164
164
|
/** Compute a 16-byte MD5 digest (RFC 1321). Used by `EVP_BytesToKey` key derivation. */
|
|
165
165
|
function md5(n) {
|
|
166
166
|
let r = mdPad(n, !0), [i, a, o, s] = [
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
167
|
+
0x67452301,
|
|
168
|
+
0xefcdab89,
|
|
169
|
+
0x98badcfe,
|
|
170
170
|
271733878
|
|
171
171
|
], c = /* @__PURE__ */ new Uint32Array(16);
|
|
172
172
|
for (let n = 0; n < r.length; n += 64) {
|
|
@@ -192,11 +192,11 @@ function md5(n) {
|
|
|
192
192
|
/** Compute a 20-byte SHA-1 digest (RFC 3174). Used by PKCS#12 MAC verification. */
|
|
193
193
|
function sha1(e) {
|
|
194
194
|
let t = mdPad(e, !1), [n, r, i, a, o] = [
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
195
|
+
0x67452301,
|
|
196
|
+
0xefcdab89,
|
|
197
|
+
0x98badcfe,
|
|
198
198
|
271733878,
|
|
199
|
-
|
|
199
|
+
0xc3d2e1f0
|
|
200
200
|
], s = /* @__PURE__ */ new Uint32Array(80), c = new DataView(t.buffer, t.byteOffset, t.byteLength);
|
|
201
201
|
for (let e = 0; e < t.length; e += 64) {
|
|
202
202
|
for (let t = 0; t < 16; t++) s[t] = c.getUint32(e + t * 4, !1);
|
|
@@ -210,7 +210,7 @@ function sha1(e) {
|
|
|
210
210
|
];
|
|
211
211
|
for (let e = 0; e < 80; e++) {
|
|
212
212
|
let n, r;
|
|
213
|
-
e <= 19 ? (n = (l & u | ~l & d) >>> 0, r =
|
|
213
|
+
e <= 19 ? (n = (l & u | ~l & d) >>> 0, r = 0x5a827999) : e <= 39 ? (n = (l ^ u ^ d) >>> 0, r = 0x6ed9eba1) : e <= 59 ? (n = (l & u | l & d | u & d) >>> 0, r = 0x8f1bbcdc) : (n = (l ^ u ^ d) >>> 0, r = 0xca62c1d6);
|
|
214
214
|
let i = rotl(t, 5) + n + f + r + w32(s, e) >>> 0;
|
|
215
215
|
f = d, d = u, u = rotl(l, 30), l = t, t = i;
|
|
216
216
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.js","names":["x","n","bitLen","data","padded","littleEndian","v","arr","i","MD5_S","MD5_K","a0","b0","c0","d0","M","offset","view","j","A","B","C","D","F","g","oldD","out","dv","h0","h1","h2","h3","h4","W","pv","off","a","b","c","e","f","k","temp"],"sources":["../../../src/internal/crypto/hash.ts"],"sourcesContent":["/**\n * Synchronous digest implementations for MD5 and SHA-1, used where WebCrypto's\n * async API is impractical (e.g. `EVP_BytesToKey` key derivation, PKCS#12 MAC).\n *\n * @module\n */\n\n// Shared Merkle–Damgård primitives\n\n/** Unsigned 32-bit left-rotate. */\nfunction rotl(x: number, n: number): number {\n\treturn ((x << n) | (x >>> (32 - n))) >>> 0;\n}\n\n/**\n * Merkle–Damgård padding: append 0x80, zero-pad to 56 mod 64,\n * append original bit-length as 64-bit integer.\n */\nfunction mdPad(data: Uint8Array, littleEndian: boolean): Uint8Array {\n\tconst bitLen = BigInt(data.length) * 8n;\n\tconst padded = new Uint8Array(Math.ceil((data.length + 1 + 8) / 64) * 64);\n\tpadded.set(data);\n\tpadded[data.length] = 0x80;\n\tconst view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\tview.setBigUint64(padded.length - 8, bitLen, littleEndian);\n\treturn padded;\n}\n\n/** Bounds-checked read from a readonly number table. */\nfunction tbl(arr: readonly number[], i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`table index ${i}`);\n\treturn v;\n}\n\n/** Bounds-checked read from a Uint32Array. */\nfunction w32(arr: Uint32Array, i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`word index ${i}`);\n\treturn v;\n}\n\n// MD5 (RFC 1321)\n\n/** Per-round left-rotate amounts for MD5 (RFC 1321 §3.4). */\nconst MD5_S = /* dprint-ignore */ [\n\t7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,\n\t20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,\n\t10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n] as const satisfies readonly number[];\n\n/** Pre-computed sine-derived constants for MD5 (RFC 1321 §3.4). */\nconst MD5_K = /* dprint-ignore */ [\n\t0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n\t0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n\t0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n\t0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n\t0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n\t0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n\t0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n\t0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n] as const satisfies readonly number[];\n\n/** Compute a 16-byte MD5 digest (RFC 1321). Used by `EVP_BytesToKey` key derivation. */\nexport function md5(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, true);\n\n\tlet [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];\n\n\tconst M = new Uint32Array(16);\n\n\tfor (let offset = 0; offset < padded.length; offset += 64) {\n\t\tconst view = new DataView(padded.buffer, padded.byteOffset + offset, 64);\n\t\tfor (let j = 0; j < 16; j++) {\n\t\t\tM[j] = view.getUint32(j * 4, true);\n\t\t}\n\n\t\tlet [A, B, C, D] = [a0, b0, c0, d0];\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tlet F: number;\n\t\t\tlet g: number;\n\n\t\t\tif (i < 16) {\n\t\t\t\tF = ((B & C) | (~B & D)) >>> 0;\n\t\t\t\tg = i;\n\t\t\t} else if (i < 32) {\n\t\t\t\tF = ((D & B) | (~D & C)) >>> 0;\n\t\t\t\tg = (5 * i + 1) & 15;\n\t\t\t} else if (i < 48) {\n\t\t\t\tF = (B ^ C ^ D) >>> 0;\n\t\t\t\tg = (3 * i + 5) & 15;\n\t\t\t} else {\n\t\t\t\tF = (C ^ (B | ~D)) >>> 0;\n\t\t\t\tg = (7 * i) & 15;\n\t\t\t}\n\n\t\t\tF = (F + A + tbl(MD5_K, i) + w32(M, g)) >>> 0;\n\t\t\tconst oldD = D;\n\t\t\tD = C;\n\t\t\tC = B;\n\t\t\tB = (B + rotl(F, tbl(MD5_S, i))) >>> 0;\n\t\t\tA = oldD;\n\t\t}\n\n\t\ta0 = (a0 + A) >>> 0;\n\t\tb0 = (b0 + B) >>> 0;\n\t\tc0 = (c0 + C) >>> 0;\n\t\td0 = (d0 + D) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(16);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, a0, true);\n\tdv.setUint32(4, b0, true);\n\tdv.setUint32(8, c0, true);\n\tdv.setUint32(12, d0, true);\n\treturn out;\n}\n\n// SHA-1 (RFC 3174)\n\n/** Compute a 20-byte SHA-1 digest (RFC 3174). Used by PKCS#12 MAC verification. */\nexport function sha1(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, false);\n\n\tlet [h0, h1, h2, h3, h4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n\tconst W = new Uint32Array(80);\n\tconst pv = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\n\tfor (let off = 0; off < padded.length; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tW[i] = pv.getUint32(off + i * 4, false);\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) {\n\t\t\tW[i] = rotl(w32(W, i - 3) ^ w32(W, i - 8) ^ w32(W, i - 14) ^ w32(W, i - 16), 1);\n\t\t}\n\n\t\tlet [a, b, c, d, e] = [h0, h1, h2, h3, h4];\n\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f: number;\n\t\t\tlet k: number;\n\n\t\t\tif (i <= 19) {\n\t\t\t\tf = ((b & c) | (~b & d)) >>> 0;\n\t\t\t\tk = 0x5a827999;\n\t\t\t} else if (i <= 39) {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0x6ed9eba1;\n\t\t\t} else if (i <= 59) {\n\t\t\t\tf = ((b & c) | (b & d) | (c & d)) >>> 0;\n\t\t\t\tk = 0x8f1bbcdc;\n\t\t\t} else {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0xca62c1d6;\n\t\t\t}\n\n\t\t\tconst temp = (rotl(a, 5) + f + e + k + w32(W, i)) >>> 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(20);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, h0, false);\n\tdv.setUint32(4, h1, false);\n\tdv.setUint32(8, h2, false);\n\tdv.setUint32(12, h3, false);\n\tdv.setUint32(16, h4, false);\n\treturn out;\n}\n"],"mappings":";;;;;;;;AAUA,SAAS,KAAK,GAAW,GAAmB;CAC3C,QAASA,KAAKC,IAAMD,MAAO,KAAKC,OAAS;AAC1C;;;;;AAMA,SAAS,MAAM,GAAkB,GAAmC;CACnE,IAAMC,IAAS,OAAOC,EAAK,MAAM,IAAI,IAC/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ACD,IAAI,OAAQ,GAC7B,IAAI,cACM7B,KAAK,MACf,KAAK6B,IAAIC,IAAI,OAAO,GACpB,IAAI,cACM9B,KAAK,MACf,KAAM6B,IAAIC,IAAMD,IAAI,IAAMC,IAAI,OAAQ,GACtC,IAAI,eAEJ,KAAKD,IAAIC,IAAI,OAAO,GACpB,IAAI;GAGL,IAAMI,IAAQ,KAAKN,GAAG,CAAC,IAAII,IAAID,IAAIE,IAAI,IAAIR,GAAGzB,CAAC,MAAO;GAKtD,AAJA,IAAI,GACJ,IAAI8B,GACJ,IAAI,KAAKD,GAAG,EAAE,GACd,IAAID,GACJ,IAAIM;EACL;EAMA,AAJA,IAAMd,IAAKQ,MAAO,GAClB,IAAMP,IAAKQ,MAAO,GAClB,IAAMP,IAAKQ,MAAO,GAClB,IAAMP,IAAK,MAAO,GAClB,IAAMC,IAAKO,MAAO;CACnB;CAEA,IAAMb,oBAAM,IAAI,WAAW,EAAE,GACvBC,IAAK,IAAI,SAASD,EAAI,QAAQA,EAAI,YAAYA,EAAI,UAAU;CAMlE,OALAC,EAAG,UAAU,GAAGC,GAAI,EAAK,GACzBD,EAAG,UAAU,GAAGE,GAAI,EAAK,GACzBF,EAAG,UAAU,GAAGG,GAAI,EAAK,GACzBH,EAAG,UAAU,IAAII,GAAI,EAAK,GAC1BJ,EAAG,UAAU,IAAIK,GAAI,EAAK,GACnBN;AACR"}
|
|
1
|
+
{"version":3,"file":"hash.js","names":["x","n","data","littleEndian","bitLen","padded","arr","i","v","MD5_S","MD5_K","a0","b0","c0","d0","M","offset","view","j","A","B","C","D","F","g","oldD","out","dv","h0","h1","h2","h3","h4","W","pv","off","a","b","c","e","f","k","temp"],"sources":["../../../src/internal/crypto/hash.ts"],"sourcesContent":["/**\n * Synchronous digest implementations for MD5 and SHA-1, used where WebCrypto's\n * async API is impractical (e.g. `EVP_BytesToKey` key derivation, PKCS#12 MAC).\n *\n * @module\n */\n\n// Shared Merkle–Damgård primitives\n\n/** Unsigned 32-bit left-rotate. */\nfunction rotl(x: number, n: number): number {\n\treturn ((x << n) | (x >>> (32 - n))) >>> 0;\n}\n\n/**\n * Merkle–Damgård padding: append 0x80, zero-pad to 56 mod 64,\n * append original bit-length as 64-bit integer.\n */\nfunction mdPad(data: Uint8Array, littleEndian: boolean): Uint8Array {\n\tconst bitLen = BigInt(data.length) * 8n;\n\tconst padded = new Uint8Array(Math.ceil((data.length + 1 + 8) / 64) * 64);\n\tpadded.set(data);\n\tpadded[data.length] = 0x80;\n\tconst view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\tview.setBigUint64(padded.length - 8, bitLen, littleEndian);\n\treturn padded;\n}\n\n/** Bounds-checked read from a readonly number table. */\nfunction tbl(arr: readonly number[], i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`table index ${i}`);\n\treturn v;\n}\n\n/** Bounds-checked read from a Uint32Array. */\nfunction w32(arr: Uint32Array, i: number): number {\n\tconst v = arr[i];\n\tif (v === undefined) throw new RangeError(`word index ${i}`);\n\treturn v;\n}\n\n// MD5 (RFC 1321)\n\n/** Per-round left-rotate amounts for MD5 (RFC 1321 §3.4). */\nconst MD5_S = /* dprint-ignore */ [\n\t7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,\n\t20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,\n\t10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,\n] as const satisfies readonly number[];\n\n/** Pre-computed sine-derived constants for MD5 (RFC 1321 §3.4). */\nconst MD5_K = /* dprint-ignore */ [\n\t0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n\t0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n\t0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n\t0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n\t0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n\t0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n\t0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n\t0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n] as const satisfies readonly number[];\n\n/** Compute a 16-byte MD5 digest (RFC 1321). Used by `EVP_BytesToKey` key derivation. */\nexport function md5(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, true);\n\n\tlet [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];\n\n\tconst M = new Uint32Array(16);\n\n\tfor (let offset = 0; offset < padded.length; offset += 64) {\n\t\tconst view = new DataView(padded.buffer, padded.byteOffset + offset, 64);\n\t\tfor (let j = 0; j < 16; j++) {\n\t\t\tM[j] = view.getUint32(j * 4, true);\n\t\t}\n\n\t\tlet [A, B, C, D] = [a0, b0, c0, d0];\n\n\t\tfor (let i = 0; i < 64; i++) {\n\t\t\tlet F: number;\n\t\t\tlet g: number;\n\n\t\t\tif (i < 16) {\n\t\t\t\tF = ((B & C) | (~B & D)) >>> 0;\n\t\t\t\tg = i;\n\t\t\t} else if (i < 32) {\n\t\t\t\tF = ((D & B) | (~D & C)) >>> 0;\n\t\t\t\tg = (5 * i + 1) & 15;\n\t\t\t} else if (i < 48) {\n\t\t\t\tF = (B ^ C ^ D) >>> 0;\n\t\t\t\tg = (3 * i + 5) & 15;\n\t\t\t} else {\n\t\t\t\tF = (C ^ (B | ~D)) >>> 0;\n\t\t\t\tg = (7 * i) & 15;\n\t\t\t}\n\n\t\t\tF = (F + A + tbl(MD5_K, i) + w32(M, g)) >>> 0;\n\t\t\tconst oldD = D;\n\t\t\tD = C;\n\t\t\tC = B;\n\t\t\tB = (B + rotl(F, tbl(MD5_S, i))) >>> 0;\n\t\t\tA = oldD;\n\t\t}\n\n\t\ta0 = (a0 + A) >>> 0;\n\t\tb0 = (b0 + B) >>> 0;\n\t\tc0 = (c0 + C) >>> 0;\n\t\td0 = (d0 + D) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(16);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, a0, true);\n\tdv.setUint32(4, b0, true);\n\tdv.setUint32(8, c0, true);\n\tdv.setUint32(12, d0, true);\n\treturn out;\n}\n\n// SHA-1 (RFC 3174)\n\n/** Compute a 20-byte SHA-1 digest (RFC 3174). Used by PKCS#12 MAC verification. */\nexport function sha1(data: Uint8Array): Uint8Array<ArrayBuffer> {\n\tconst padded = mdPad(data, false);\n\n\tlet [h0, h1, h2, h3, h4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n\tconst W = new Uint32Array(80);\n\tconst pv = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n\n\tfor (let off = 0; off < padded.length; off += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tW[i] = pv.getUint32(off + i * 4, false);\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) {\n\t\t\tW[i] = rotl(w32(W, i - 3) ^ w32(W, i - 8) ^ w32(W, i - 14) ^ w32(W, i - 16), 1);\n\t\t}\n\n\t\tlet [a, b, c, d, e] = [h0, h1, h2, h3, h4];\n\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f: number;\n\t\t\tlet k: number;\n\n\t\t\tif (i <= 19) {\n\t\t\t\tf = ((b & c) | (~b & d)) >>> 0;\n\t\t\t\tk = 0x5a827999;\n\t\t\t} else if (i <= 39) {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0x6ed9eba1;\n\t\t\t} else if (i <= 59) {\n\t\t\t\tf = ((b & c) | (b & d) | (c & d)) >>> 0;\n\t\t\t\tk = 0x8f1bbcdc;\n\t\t\t} else {\n\t\t\t\tf = (b ^ c ^ d) >>> 0;\n\t\t\t\tk = 0xca62c1d6;\n\t\t\t}\n\n\t\t\tconst temp = (rotl(a, 5) + f + e + k + w32(W, i)) >>> 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\n\t\th0 = (h0 + a) >>> 0;\n\t\th1 = (h1 + b) >>> 0;\n\t\th2 = (h2 + c) >>> 0;\n\t\th3 = (h3 + d) >>> 0;\n\t\th4 = (h4 + e) >>> 0;\n\t}\n\n\tconst out = new Uint8Array(20);\n\tconst dv = new DataView(out.buffer, out.byteOffset, out.byteLength);\n\tdv.setUint32(0, h0, false);\n\tdv.setUint32(4, h1, false);\n\tdv.setUint32(8, h2, false);\n\tdv.setUint32(12, h3, false);\n\tdv.setUint32(16, h4, false);\n\treturn out;\n}\n"],"mappings":";;;;;;;;AAUA,SAAS,KAAKA,GAAWC,GAAmB;CAC3C,QAASD,KAAKC,IAAMD,MAAO,KAAKC,OAAS;AAC1C;;;;;AAMA,SAAS,MAAMC,GAAkBC,GAAmC;CACnE,IAAMC,IAAS,OAAOF,EAAK,MAAM,IAAI,IAC/BG,IAAS,IAAI,WAAW,KAAK,MAAMH,EAAK,SAAS,IAAI,KAAK,EAAE,IAAI,EAAE;CAKxE,OAJAG,EAAO,IAAIH,CAAI,GACfG,EAAOH,EAAK,UAAU,KAEtB,IADiB,SAAS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H,IAAIC,IAAMD,IAAI,IAAMC,IAAI,OAAQ,GACtCG,IAAI,eAEJD,KAAKH,IAAIC,IAAI,OAAO,GACpBG,IAAI;GAGL,IAAMC,IAAQ,KAAKN,GAAG,CAAC,IAAII,IAAID,IAAIE,IAAI,IAAIR,GAAG1B,CAAC,MAAO;GACtDgC,IAAI,GACJ,IAAID,GACJA,IAAI,KAAKD,GAAG,EAAE,GACdA,IAAID,GACJA,IAAIM;EACL;EAEAd,IAAMA,IAAKQ,MAAO,GAClBP,IAAMA,IAAKQ,MAAO,GAClBP,IAAMA,IAAKQ,MAAO,GAClBP,IAAMA,IAAK,MAAO,GAClBC,IAAMA,IAAKO,MAAO;CACnB;CAEA,IAAMb,oBAAM,IAAI,WAAW,EAAE,GACvBC,IAAK,IAAI,SAASD,EAAI,QAAQA,EAAI,YAAYA,EAAI,UAAU;CAMlE,OALAC,EAAG,UAAU,GAAGC,GAAI,EAAK,GACzBD,EAAG,UAAU,GAAGE,GAAI,EAAK,GACzBF,EAAG,UAAU,GAAGG,GAAI,EAAK,GACzBH,EAAG,UAAU,IAAII,GAAI,EAAK,GAC1BJ,EAAG,UAAU,IAAIK,GAAI,EAAK,GACnBN;AACR"}
|
|
@@ -52,7 +52,7 @@ function chargeKdfBudget(e, t) {
|
|
|
52
52
|
if (t > e.remaining) throw kdfIterationLimitError(t, e.remaining);
|
|
53
53
|
e.remaining -= t;
|
|
54
54
|
}
|
|
55
|
-
const h =
|
|
55
|
+
const h = 0xffffffff;
|
|
56
56
|
async function derivePbkdf2Bytes(e, t, r, i, a) {
|
|
57
57
|
assertPbkdf2IterationCount(r);
|
|
58
58
|
let o = await u().subtle.importKey("raw", n(e), "PBKDF2", !1, ["deriveBits"]);
|
|
@@ -140,7 +140,7 @@ function parsePbes2AlgorithmIdentifier(n) {
|
|
|
140
140
|
if (f && e(d.value) !== y.keyLengthBytes) throw Error("Unsupported PBKDF2 key length");
|
|
141
141
|
let b = parsePbkdf2Prf(o, p), x = e(u.value), S = new Uint8Array(l.value), C = new Uint8Array(v.value);
|
|
142
142
|
if (x < 1) throw Error(`Invalid PBES2 iterations: must be >= 1, got ${x}`);
|
|
143
|
-
if (x >
|
|
143
|
+
if (x > 0xffffffff) throw Error(`Invalid PBES2 iterations: must be <= ${h}, got ${x}`);
|
|
144
144
|
if (C.length !== 16) throw Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${C.length}`);
|
|
145
145
|
return {
|
|
146
146
|
salt: S,
|
|
@@ -151,7 +151,7 @@ function parsePbes2AlgorithmIdentifier(n) {
|
|
|
151
151
|
};
|
|
152
152
|
}
|
|
153
153
|
function assertPbkdf2IterationCount(e) {
|
|
154
|
-
if (!Number.isInteger(e) || e < 1 || e >
|
|
154
|
+
if (!Number.isInteger(e) || e < 1 || e > 0xffffffff) throw RangeError(`Invalid iterations: must be an integer from 1 to ${h}, got ${e}`);
|
|
155
155
|
}
|
|
156
156
|
/** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */
|
|
157
157
|
function parsePbes2OuterFields(e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pbes2.js","names":["_exhaustive","wrongPasswordBrand","message","value","DEFAULT_MAX_KDF_ITERATIONS","DEFAULT_MAX_PKCS12_MAC_ITERATIONS","kdfIterationLimitBrand","iterations","remaining","limit","options","defaultLimit","budget","WEBCRYPTO_MAX_PBKDF2_ITERATIONS","passwordKey","getCrypto","toArrayBuffer","password","salt","length","iv","encryption","prf","key","encryptedData","data","parameters","algorithmIdentifierDer","pbkdf2Params","octetString","integerFromNumber","sequence","objectIdentifier","nullValue","OIDS","paramsDer","kdf","keyLengthElement","hasExplicitKeyLength","prfElement","schemeDer","scheme","schemeChildren","readSequenceChildren","schemeOid","decodeObjectIdentifier","decodeIntegerNumber","pbkdf2Der","iterationsValue","saltValue","ivValue","topLevel","oid","params","pbes2Params","kdfDer","kdfChildren","kdfOid","kdfParams","encryptionName","prfName","usages","element","profile","name"],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\n\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** Upper bound on PBKDF2 iteration counts accepted from untrusted input. */\nexport const DEFAULT_MAX_KDF_ITERATIONS = 2_000_000;\n\n/**\n * Upper bound on PKCS#12 KDF iteration counts accepted from untrusted input.\n * RFC 7292 Appendix B hashes once per round, and each round is a separate\n * WebCrypto digest call, so a round costs more than a PBKDF2 round.\n */\nexport const DEFAULT_MAX_PKCS12_MAC_ITERATIONS = 100_000;\n\nconst kdfIterationLimitBrand = Symbol('micro509.KdfIterationLimitError');\n\n/** Thrown before key derivation when an encoded iteration count exceeds the caller's limit. */\nexport function kdfIterationLimitError(iterations: number, remaining: number): Error {\n\treturn Object.assign(\n\t\tnew Error(`KDF iteration count ${iterations} exceeds the remaining budget of ${remaining}`),\n\t\t{ name: 'KdfIterationLimitError', [kdfIterationLimitBrand]: true },\n\t);\n}\n\n/** Type guard: was derivation refused because the iteration count exceeds the limit? */\nexport function isKdfIterationLimitError(value: unknown): value is Error {\n\treturn value instanceof Error && kdfIterationLimitBrand in value;\n}\n\n/** Caller-supplied bound on password-based KDF work. */\nexport interface KdfLimitOptions {\n\t/**\n\t * Maximum KDF iteration count accepted from the input. Higher counts fail\n\t * before any derivation runs. Defaults to `2_000_000` for PBKDF2 and\n\t * `100_000` for the PKCS#12 KDF, which costs more per round. In a PFX the\n\t * PBES2-encrypted entries share one budget of this size and the MAC has a\n\t * separate budget of this size.\n\t */\n\treadonly maxKdfIterations?: number;\n}\n\n/**\n * KDF iterations one operation may still spend. A container decrypting many\n * entries shares a single budget, so entries that each sit under the ceiling\n * cannot sum past it.\n */\nexport interface KdfBudget {\n\t/** Iterations still available. */\n\tremaining: number;\n}\n\n/** Opens a budget from the caller's limit. Throws when that limit is not a positive integer. */\nexport function createKdfBudget(\n\toptions: KdfLimitOptions | undefined,\n\tdefaultLimit: number = DEFAULT_MAX_KDF_ITERATIONS,\n): KdfBudget {\n\tconst limit = options?.maxKdfIterations ?? defaultLimit;\n\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\tthrow new RangeError(`Invalid maxKdfIterations: must be an integer >= 1, got ${limit}`);\n\t}\n\treturn { remaining: limit };\n}\n\n/** Charges iterations against the budget, throwing before any derivation runs. */\nexport function chargeKdfBudget(budget: KdfBudget, iterations: number): void {\n\tif (iterations > budget.remaining) {\n\t\tthrow kdfIterationLimitError(iterations, budget.remaining);\n\t}\n\tbudget.remaining -= iterations;\n}\n\nexport const WEBCRYPTO_MAX_PBKDF2_ITERATIONS = 0xffff_ffff;\n\nexport type Pbkdf2Hash = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\nexport async function derivePbkdf2Bytes(\n\tpassword: Uint8Array,\n\tsalt: Uint8Array,\n\titerations: number,\n\thash: Pbkdf2Hash,\n\tlength: number,\n): Promise<Uint8Array> {\n\tassertPbkdf2IterationCount(iterations);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveBits'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.deriveBits(\n\t\t\t{ name: 'PBKDF2', salt: toArrayBuffer(salt), iterations, hash },\n\t\t\tpasswordKey,\n\t\t\tlength * 8,\n\t\t),\n\t);\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\n/** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */\nexport type Pbes2Prf = 'HMAC-SHA-1' | 'HMAC-SHA-256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly cipher: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.cipher ?? 'AES-256-CBC';\n\tconst prf = options.prf ?? 'HMAC-SHA-256';\n\n\t// Validate inputs before any WebCrypto calls\n\tassertPbkdf2IterationCount(iterations);\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tcipher: encryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, cipher: encryption, prf },\n\t};\n}\n\n/**\n * Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password.\n * Throws on wrong password, and before derivation when the encoded iteration\n * count exceeds what `budget` still allows.\n */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n\tbudget: KdfBudget = createKdfBudget(undefined),\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tchargeKdfBudget(budget, parameters.iterations);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.cipher,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/**\n * DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters.\n *\n * @throws {RangeError} if `parameters.iterations` is not an integer from 1 to 4294967295.\n */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tassertPbkdf2IterationCount(parameters.iterations);\n\tconst encryption = resolveEncryptionProfile(parameters.cipher);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\tconst pbkdf2Params = [\n\t\toctetString(parameters.salt),\n\t\tintegerFromNumber(parameters.iterations),\n\t\t// keyLength is OPTIONAL (kept); prf AlgorithmIdentifier DEFAULT\n\t\t// algid-hmacWithSHA1, which X.690 §11.5 forbids encoding under DER.\n\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t...(parameters.prf === 'HMAC-SHA-1'\n\t\t\t? []\n\t\t\t: [sequence([objectIdentifier(prf.oid), nullValue()])]),\n\t];\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([objectIdentifier(OIDS.pbkdf2), sequence(pbkdf2Params)]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/**\n * Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}.\n *\n * @throws if the encoding is malformed, names an unsupported KDF, PRF or cipher, or carries an\n * iteration count outside 1 to 4294967295.\n */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst { paramsDer, kdf, scheme } = parsePbes2OuterFields(algorithmIdentifierDer);\n\tconst { pbkdf2Der, pbkdf2Params } = parsePbes2KdfFields(paramsDer, kdf);\n\t// RFC 8018 A.2 PBKDF2-params: SEQUENCE { salt CHOICE { specified OCTET STRING,\n\t// otherSource AlgorithmIdentifier }, iterationCount INTEGER (1..MAX), keyLength\n\t// INTEGER (1..MAX) OPTIONAL, prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1 }.\n\t// Only the `specified` salt alternative is accepted.\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\titerations.tag !== 0x02\n\t) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new Error(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (iterationsValue > WEBCRYPTO_MAX_PBKDF2_ITERATIONS) {\n\t\tthrow new Error(\n\t\t\t`Invalid PBES2 iterations: must be <= ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterationsValue}`,\n\t\t);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tcipher: encryption.name,\n\t\tprf,\n\t};\n}\n\nfunction assertPbkdf2IterationCount(iterations: number): void {\n\tif (\n\t\t!Number.isInteger(iterations) ||\n\t\titerations < 1 ||\n\t\titerations > WEBCRYPTO_MAX_PBKDF2_ITERATIONS\n\t) {\n\t\tthrow new RangeError(\n\t\t\t`Invalid iterations: must be an integer from 1 to ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterations}`,\n\t\t);\n\t}\n}\n\n/** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */\nfunction parsePbes2OuterFields(algorithmIdentifierDer: Uint8Array): {\n\treadonly paramsDer: Uint8Array;\n\treadonly kdf: ReturnType<typeof readSequenceChildren>[number];\n\treadonly scheme: ReturnType<typeof readSequenceChildren>[number];\n} {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\treturn { paramsDer, kdf, scheme };\n}\n\nfunction parsePbes2KdfFields(\n\tparamsDer: Uint8Array,\n\tkdf: ReturnType<typeof readSequenceChildren>[number],\n): {\n\treadonly pbkdf2Der: Uint8Array;\n\treadonly pbkdf2Params: ReturnType<typeof readSequenceChildren>;\n} {\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\treturn { pbkdf2Der, pbkdf2Params: readSequenceChildren(pbkdf2Der) };\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'HMAC-SHA-1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'AES-128-CBC', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'AES-192-CBC', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'AES-256-CBC', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'HMAC-SHA-1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'AES-128-CBC'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'AES-192-CBC'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled Pbes2Prf: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAMC,IAAqB,OAAO,6BAA6B;;;;;;AAO/D,SAAgB,mBAAmB,GAAwB;CAC1D,OAAO,OAAO,OAAW,MAAMC,CAAO,GAAG;EACxC,MAAM;GACLD,IAAqB;CACvB,CAAC;AACF;;AAGA,SAAgB,qBAAqB,GAAgC;CACpE,OAAOE,aAAiB,SAASF,KAAsBE;AACxD;;AAGA,MAAaC,IAA6B,KAO7BC,IAAoC,KAE3CC,IAAyB,OAAO,iCAAiC;;AAGvE,SAAgB,uBAAuB,GAAoB,GAA0B;CACpF,OAAO,OAAO,OACb,gBAAI,MAAM,uBAAuBC,EAAW,mCAAmCC,GAAW,GAC1F;EAAE,MAAM;GAA2BF,IAAyB;CAAK,CAClE;AACD;;AAGA,SAAgB,yBAAyB,GAAgC;CACxE,OAAOH,aAAiB,SAASG,KAA0BH;AAC5D;;AAyBA,SAAgB,gBACf,GACA,IAAuBC,GACX;CACZ,IAAMK,IAAQC,GAAS,oBAAoBC;CAC3C,IAAI,CAAC,OAAO,cAAcF,CAAK,KAAKA,IAAQ,GAC3C,MAAU,WAAW,0DAA0DA,GAAO;CAEvF,OAAO,EAAE,WAAWA,EAAM;AAC3B;;AAGA,SAAgB,gBAAgB,GAAmB,GAA0B;CAC5E,IAAIF,IAAaK,EAAO,WACvB,MAAM,uBAAuBL,GAAYK,EAAO,SAAS;CAE1D,EAAO,aAAaL;AACrB;AAEA,MA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AAGA,SAAS,kBAAkB,GAGzB;CACD,QAAQC,GAAR;EACC,KAAK,cACJ,OAAO;GAAE,KAAK9B,EAAK;GAAc,MAAM;EAAQ;EAChD,KAAK,gBACJ,OAAO;GAAE,KAAKA,EAAK;GAAgB,MAAM;EAAU;EACpD,SAEC,MAAU,MAAM,uBAAuB,OAAOlC,CAAW,GAAG;CAE9D;AACD"}
|
|
1
|
+
{"version":3,"file":"pbes2.js","names":["_exhaustive","decodeIntegerNumber","decodeObjectIdentifier","toArrayBuffer","integerFromNumber","nullValue","objectIdentifier","octetString","readSequenceChildren","sequence","OIDS","getCrypto","wrongPasswordBrand","message","value","DEFAULT_MAX_KDF_ITERATIONS","DEFAULT_MAX_PKCS12_MAC_ITERATIONS","kdfIterationLimitBrand","iterations","remaining","options","defaultLimit","limit","budget","WEBCRYPTO_MAX_PBKDF2_ITERATIONS","password","salt","hash","length","passwordKey","data","iv","encryption","prf","key","encryptedData","algorithmIdentifierDer","parameters","pbkdf2Params","paramsDer","kdf","scheme","pbkdf2Der","keyLengthElement","hasExplicitKeyLength","prfElement","schemeDer","schemeChildren","schemeOid","iterationsValue","saltValue","ivValue","topLevel","oid","params","pbes2Params","kdfDer","kdfChildren","kdfOid","kdfParams","encryptionName","prfName","usages","element","name","profile"],"sources":["../../../src/internal/crypto/pbes2.ts"],"sourcesContent":["/**\n * PBES2 password-based encryption and decryption (RFC 8018).\n *\n * Supports AES-CBC-128/192/256 with PBKDF2 using HMAC-SHA-1 or HMAC-SHA-256.\n * Used internally by encrypted PKCS#8 and PFX flows.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n} from '#micro509/internal/asn1/asn1';\nimport {\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\n\n/** Module-private brand so {@link isWrongPasswordError} cannot be fooled by look-alike errors. */\nconst wrongPasswordBrand = Symbol('micro509.WrongPasswordError');\n\n/**\n * Thrown when PBES2 / AES-CBC decryption fails its integrity check, which in\n * practice means the supplied password was wrong (or the ciphertext was\n * corrupted). Lets callers distinguish a bad password from malformed input.\n */\nexport function wrongPasswordError(message: string): Error {\n\treturn Object.assign(new Error(message), {\n\t\tname: 'WrongPasswordError',\n\t\t[wrongPasswordBrand]: true,\n\t});\n}\n\n/** Type guard: was decryption rejected for a wrong password / corrupt content? */\nexport function isWrongPasswordError(value: unknown): value is Error {\n\treturn value instanceof Error && wrongPasswordBrand in value;\n}\n\n/** Upper bound on PBKDF2 iteration counts accepted from untrusted input. */\nexport const DEFAULT_MAX_KDF_ITERATIONS = 2_000_000;\n\n/**\n * Upper bound on PKCS#12 KDF iteration counts accepted from untrusted input.\n * RFC 7292 Appendix B hashes once per round, and each round is a separate\n * WebCrypto digest call, so a round costs more than a PBKDF2 round.\n */\nexport const DEFAULT_MAX_PKCS12_MAC_ITERATIONS = 100_000;\n\nconst kdfIterationLimitBrand = Symbol('micro509.KdfIterationLimitError');\n\n/** Thrown before key derivation when an encoded iteration count exceeds the caller's limit. */\nexport function kdfIterationLimitError(iterations: number, remaining: number): Error {\n\treturn Object.assign(\n\t\tnew Error(`KDF iteration count ${iterations} exceeds the remaining budget of ${remaining}`),\n\t\t{ name: 'KdfIterationLimitError', [kdfIterationLimitBrand]: true },\n\t);\n}\n\n/** Type guard: was derivation refused because the iteration count exceeds the limit? */\nexport function isKdfIterationLimitError(value: unknown): value is Error {\n\treturn value instanceof Error && kdfIterationLimitBrand in value;\n}\n\n/** Caller-supplied bound on password-based KDF work. */\nexport interface KdfLimitOptions {\n\t/**\n\t * Maximum KDF iteration count accepted from the input. Higher counts fail\n\t * before any derivation runs. Defaults to `2_000_000` for PBKDF2 and\n\t * `100_000` for the PKCS#12 KDF, which costs more per round. In a PFX the\n\t * PBES2-encrypted entries share one budget of this size and the MAC has a\n\t * separate budget of this size.\n\t */\n\treadonly maxKdfIterations?: number;\n}\n\n/**\n * KDF iterations one operation may still spend. A container decrypting many\n * entries shares a single budget, so entries that each sit under the ceiling\n * cannot sum past it.\n */\nexport interface KdfBudget {\n\t/** Iterations still available. */\n\tremaining: number;\n}\n\n/** Opens a budget from the caller's limit. Throws when that limit is not a positive integer. */\nexport function createKdfBudget(\n\toptions: KdfLimitOptions | undefined,\n\tdefaultLimit: number = DEFAULT_MAX_KDF_ITERATIONS,\n): KdfBudget {\n\tconst limit = options?.maxKdfIterations ?? defaultLimit;\n\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\tthrow new RangeError(`Invalid maxKdfIterations: must be an integer >= 1, got ${limit}`);\n\t}\n\treturn { remaining: limit };\n}\n\n/** Charges iterations against the budget, throwing before any derivation runs. */\nexport function chargeKdfBudget(budget: KdfBudget, iterations: number): void {\n\tif (iterations > budget.remaining) {\n\t\tthrow kdfIterationLimitError(iterations, budget.remaining);\n\t}\n\tbudget.remaining -= iterations;\n}\n\nexport const WEBCRYPTO_MAX_PBKDF2_ITERATIONS = 0xffff_ffff;\n\nexport type Pbkdf2Hash = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512';\n\nexport async function derivePbkdf2Bytes(\n\tpassword: Uint8Array,\n\tsalt: Uint8Array,\n\titerations: number,\n\thash: Pbkdf2Hash,\n\tlength: number,\n): Promise<Uint8Array> {\n\tassertPbkdf2IterationCount(iterations);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveBits'],\n\t);\n\treturn new Uint8Array(\n\t\tawait getCrypto().subtle.deriveBits(\n\t\t\t{ name: 'PBKDF2', salt: toArrayBuffer(salt), iterations, hash },\n\t\t\tpasswordKey,\n\t\t\tlength * 8,\n\t\t),\n\t);\n}\n\n/** AES-CBC key sizes supported by this PBES2 implementation. */\nexport type Pbes2EncryptionScheme = 'AES-128-CBC' | 'AES-192-CBC' | 'AES-256-CBC';\n\n/** PBKDF2 pseudo-random function choices. `HMAC-SHA-1` is the RFC default; `HMAC-SHA-256` is preferred. */\nexport type Pbes2Prf = 'HMAC-SHA-1' | 'HMAC-SHA-256';\n\n/** Input for `encryptPbes2`. */\nexport interface Pbes2EncryptionOptions {\n\t/** Password fed to PBKDF2 for key derivation. */\n\treadonly password: string;\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\treadonly iterations?: number;\n\t/** PBKDF2 salt. Default: 16 cryptographically random bytes. */\n\treadonly salt?: Uint8Array;\n\t/** AES-CBC initialization vector. Default: 16 cryptographically random bytes. */\n\treadonly iv?: Uint8Array;\n\t/** AES-CBC cipher. Default: `'AES-256-CBC'`. */\n\treadonly cipher?: Pbes2EncryptionScheme;\n\t/** PBKDF2 PRF. Default: `'HMAC-SHA-256'`. */\n\treadonly prf?: Pbes2Prf;\n}\n\n/** Resolved PBES2 algorithm parameters, either parsed from DER or built by `encryptPbes2`. */\nexport interface Pbes2Parameters {\n\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. */\n\treadonly iterations: number;\n\t/** PBKDF2 salt bytes. */\n\treadonly salt: Uint8Array;\n\t/** AES-CBC initialization vector. */\n\treadonly iv: Uint8Array;\n\t/** AES-CBC key-size variant. */\n\treadonly cipher: Pbes2EncryptionScheme;\n\t/** PBKDF2 pseudo-random function. */\n\treadonly prf: Pbes2Prf;\n}\n\n/** Output of `encryptPbes2`: ciphertext plus the DER-encoded AlgorithmIdentifier. */\nexport interface Pbes2EncryptionResult {\n\t/** DER-encoded PBES2 AlgorithmIdentifier SEQUENCE (embeds KDF + cipher params). */\n\treadonly algorithmIdentifierDer: Uint8Array;\n\t/** AES-CBC ciphertext (includes PKCS#7 padding). */\n\treadonly encryptedData: Uint8Array;\n\t/** Resolved algorithm parameters used during encryption. */\n\treadonly parameters: Pbes2Parameters;\n}\n\n/** Encrypts `data` using PBES2 (PBKDF2 + AES-CBC) and returns ciphertext with algorithm params. */\nexport async function encryptPbes2(\n\tdata: Uint8Array,\n\toptions: Pbes2EncryptionOptions,\n): Promise<Pbes2EncryptionResult> {\n\tconst iterations = options.iterations ?? 100_000;\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst iv = options.iv ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst encryption = options.cipher ?? 'AES-256-CBC';\n\tconst prf = options.prf ?? 'HMAC-SHA-256';\n\n\t// Validate inputs before any WebCrypto calls\n\tassertPbkdf2IterationCount(iterations);\n\tif (!(salt instanceof Uint8Array) || salt.length < 8) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid salt: must be Uint8Array with length >= 8, got length ${salt.length}`,\n\t\t);\n\t}\n\tif (!(iv instanceof Uint8Array) || iv.length !== 16) {\n\t\tthrow new TypeError(\n\t\t\t`Invalid IV: must be Uint8Array of exactly 16 bytes, got length ${iv.length}`,\n\t\t);\n\t}\n\n\tconst key = await deriveAesKey(options.password, salt, iterations, encryption, prf, ['encrypt']);\n\tconst encryptedData = new Uint8Array(\n\t\tawait getCrypto().subtle.encrypt(\n\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(iv) },\n\t\t\tkey,\n\t\t\ttoArrayBuffer(data),\n\t\t),\n\t);\n\treturn {\n\t\talgorithmIdentifierDer: encodePbes2AlgorithmIdentifier({\n\t\t\titerations,\n\t\t\tsalt,\n\t\t\tiv,\n\t\t\tcipher: encryption,\n\t\t\tprf,\n\t\t}),\n\t\tencryptedData,\n\t\tparameters: { iterations, salt, iv, cipher: encryption, prf },\n\t};\n}\n\n/**\n * Decrypts PBES2 ciphertext given the DER AlgorithmIdentifier and password.\n * Throws on wrong password, and before derivation when the encoded iteration\n * count exceeds what `budget` still allows.\n */\nexport async function decryptPbes2(\n\talgorithmIdentifierDer: Uint8Array,\n\tencryptedData: Uint8Array,\n\tpassword: string,\n\tbudget: KdfBudget = createKdfBudget(undefined),\n): Promise<Uint8Array> {\n\tconst parameters = parsePbes2AlgorithmIdentifier(algorithmIdentifierDer);\n\tchargeKdfBudget(budget, parameters.iterations);\n\tconst key = await deriveAesKey(\n\t\tpassword,\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\tparameters.cipher,\n\t\tparameters.prf,\n\t\t['decrypt'],\n\t);\n\ttry {\n\t\treturn new Uint8Array(\n\t\t\tawait getCrypto().subtle.decrypt(\n\t\t\t\t{ name: 'AES-CBC', iv: toArrayBuffer(parameters.iv) },\n\t\t\t\tkey,\n\t\t\t\ttoArrayBuffer(encryptedData),\n\t\t\t),\n\t\t);\n\t} catch {\n\t\tthrow wrongPasswordError('Invalid password or encrypted content');\n\t}\n}\n\n/**\n * DER-encodes a PBES2 AlgorithmIdentifier SEQUENCE from resolved parameters.\n *\n * @throws {RangeError} if `parameters.iterations` is not an integer from 1 to 4294967295.\n */\nexport function encodePbes2AlgorithmIdentifier(parameters: Pbes2Parameters): Uint8Array {\n\tassertPbkdf2IterationCount(parameters.iterations);\n\tconst encryption = resolveEncryptionProfile(parameters.cipher);\n\tconst prf = resolvePrfProfile(parameters.prf);\n\tconst pbkdf2Params = [\n\t\toctetString(parameters.salt),\n\t\tintegerFromNumber(parameters.iterations),\n\t\t// keyLength is OPTIONAL (kept); prf AlgorithmIdentifier DEFAULT\n\t\t// algid-hmacWithSHA1, which X.690 §11.5 forbids encoding under DER.\n\t\tintegerFromNumber(encryption.keyLengthBytes),\n\t\t...(parameters.prf === 'HMAC-SHA-1'\n\t\t\t? []\n\t\t\t: [sequence([objectIdentifier(prf.oid), nullValue()])]),\n\t];\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pbes2),\n\t\tsequence([\n\t\t\tsequence([objectIdentifier(OIDS.pbkdf2), sequence(pbkdf2Params)]),\n\t\t\tsequence([objectIdentifier(encryption.oid), octetString(parameters.iv)]),\n\t\t]),\n\t]);\n}\n\n/**\n * Decodes a DER-encoded PBES2 AlgorithmIdentifier into structured {@linkcode Pbes2Parameters}.\n *\n * @throws if the encoding is malformed, names an unsupported KDF, PRF or cipher, or carries an\n * iteration count outside 1 to 4294967295.\n */\nexport function parsePbes2AlgorithmIdentifier(algorithmIdentifierDer: Uint8Array): Pbes2Parameters {\n\tconst { paramsDer, kdf, scheme } = parsePbes2OuterFields(algorithmIdentifierDer);\n\tconst { pbkdf2Der, pbkdf2Params } = parsePbes2KdfFields(paramsDer, kdf);\n\t// RFC 8018 A.2 PBKDF2-params: SEQUENCE { salt CHOICE { specified OCTET STRING,\n\t// otherSource AlgorithmIdentifier }, iterationCount INTEGER (1..MAX), keyLength\n\t// INTEGER (1..MAX) OPTIONAL, prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1 }.\n\t// Only the `specified` salt alternative is accepted.\n\tconst salt = pbkdf2Params[0];\n\tconst iterations = pbkdf2Params[1];\n\tif (\n\t\tsalt === undefined ||\n\t\titerations === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\titerations.tag !== 0x02\n\t) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tconst keyLengthElement = pbkdf2Params[2];\n\tconst hasExplicitKeyLength = keyLengthElement?.tag === 0x02;\n\tconst prfElement = hasExplicitKeyLength ? pbkdf2Params[3] : keyLengthElement;\n\tconst schemeDer = paramsDer.slice(scheme.start - scheme.headerLength, scheme.end);\n\tconst schemeChildren = readSequenceChildren(schemeDer);\n\tconst schemeOid = schemeChildren[0];\n\tconst iv = schemeChildren[1];\n\tif (schemeOid === undefined || iv === undefined || iv.tag !== 0x04) {\n\t\tthrow new Error('Malformed encryption scheme');\n\t}\n\tconst encryption = encryptionSchemeFromOid(decodeObjectIdentifier(schemeOid.value));\n\tif (encryption === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\tif (keyLengthElement !== undefined && !hasExplicitKeyLength && keyLengthElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 params');\n\t}\n\tif (\n\t\thasExplicitKeyLength &&\n\t\tdecodeIntegerNumber(keyLengthElement.value) !== encryption.keyLengthBytes\n\t) {\n\t\tthrow new Error('Unsupported PBKDF2 key length');\n\t}\n\tconst prf = parsePbkdf2Prf(pbkdf2Der, prfElement);\n\n\t// Validate parsed parameters before returning\n\tconst iterationsValue = decodeIntegerNumber(iterations.value);\n\tconst saltValue = new Uint8Array(salt.value);\n\tconst ivValue = new Uint8Array(iv.value);\n\n\tif (iterationsValue < 1) {\n\t\tthrow new Error(`Invalid PBES2 iterations: must be >= 1, got ${iterationsValue}`);\n\t}\n\tif (iterationsValue > WEBCRYPTO_MAX_PBKDF2_ITERATIONS) {\n\t\tthrow new Error(\n\t\t\t`Invalid PBES2 iterations: must be <= ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterationsValue}`,\n\t\t);\n\t}\n\tif (ivValue.length !== 16) {\n\t\tthrow new Error(`Invalid PBES2 IV: must be exactly 16 bytes, got ${ivValue.length}`);\n\t}\n\n\treturn {\n\t\tsalt: saltValue,\n\t\titerations: iterationsValue,\n\t\tiv: ivValue,\n\t\tcipher: encryption.name,\n\t\tprf,\n\t};\n}\n\nfunction assertPbkdf2IterationCount(iterations: number): void {\n\tif (\n\t\t!Number.isInteger(iterations) ||\n\t\titerations < 1 ||\n\t\titerations > WEBCRYPTO_MAX_PBKDF2_ITERATIONS\n\t) {\n\t\tthrow new RangeError(\n\t\t\t`Invalid iterations: must be an integer from 1 to ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterations}`,\n\t\t);\n\t}\n}\n\n/** Extracts the KDF and encryption-scheme fields from a PBES2 AlgorithmIdentifier. */\nfunction parsePbes2OuterFields(algorithmIdentifierDer: Uint8Array): {\n\treadonly paramsDer: Uint8Array;\n\treadonly kdf: ReturnType<typeof readSequenceChildren>[number];\n\treadonly scheme: ReturnType<typeof readSequenceChildren>[number];\n} {\n\tconst topLevel = readSequenceChildren(algorithmIdentifierDer);\n\tconst oid = topLevel[0];\n\tconst params = topLevel[1];\n\tif (oid === undefined || params === undefined) {\n\t\tthrow new Error('Malformed PBES2 algorithm identifier');\n\t}\n\tif (decodeObjectIdentifier(oid.value) !== OIDS.pbes2) {\n\t\tthrow new Error('Unsupported encryption algorithm');\n\t}\n\tconst paramsDer = algorithmIdentifierDer.slice(params.start - params.headerLength, params.end);\n\tconst pbes2Params = readSequenceChildren(paramsDer);\n\tconst kdf = pbes2Params[0];\n\tconst scheme = pbes2Params[1];\n\tif (kdf === undefined || scheme === undefined) {\n\t\tthrow new Error('Malformed PBES2 params');\n\t}\n\treturn { paramsDer, kdf, scheme };\n}\n\nfunction parsePbes2KdfFields(\n\tparamsDer: Uint8Array,\n\tkdf: ReturnType<typeof readSequenceChildren>[number],\n): {\n\treadonly pbkdf2Der: Uint8Array;\n\treadonly pbkdf2Params: ReturnType<typeof readSequenceChildren>;\n} {\n\tconst kdfDer = paramsDer.slice(kdf.start - kdf.headerLength, kdf.end);\n\tconst kdfChildren = readSequenceChildren(kdfDer);\n\tconst kdfOid = kdfChildren[0];\n\tconst kdfParams = kdfChildren[1];\n\tif (kdfOid === undefined || kdfParams === undefined) {\n\t\tthrow new Error('Malformed KDF params');\n\t}\n\tif (decodeObjectIdentifier(kdfOid.value) !== OIDS.pbkdf2) {\n\t\tthrow new Error('Unsupported KDF');\n\t}\n\tconst pbkdf2Der = kdfDer.slice(kdfParams.start - kdfParams.headerLength, kdfParams.end);\n\treturn { pbkdf2Der, pbkdf2Params: readSequenceChildren(pbkdf2Der) };\n}\n\n/** Derives an AES-CBC `CryptoKey` from a password via PBKDF2. */\nasync function deriveAesKey(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tencryptionName: Pbes2EncryptionScheme,\n\tprfName: Pbes2Prf,\n\tusages: KeyUsage[],\n): Promise<CryptoKey> {\n\tconst encryption = resolveEncryptionProfile(encryptionName);\n\tconst prf = resolvePrfProfile(prfName);\n\tconst passwordKey = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(password),\n\t\t'PBKDF2',\n\t\tfalse,\n\t\t['deriveKey'],\n\t);\n\treturn getCrypto().subtle.deriveKey(\n\t\t{\n\t\t\tname: 'PBKDF2',\n\t\t\tsalt: toArrayBuffer(salt),\n\t\t\titerations,\n\t\t\thash: prf.hash,\n\t\t},\n\t\tpasswordKey,\n\t\t{ name: 'AES-CBC', length: encryption.keyLengthBits },\n\t\tfalse,\n\t\tusages,\n\t);\n}\n\n/** Parses the optional PRF AlgorithmIdentifier from PBKDF2 params. Absent means HMAC-SHA-1. */\nfunction parsePbkdf2Prf(\n\tpbkdf2Der: Uint8Array,\n\telement: ReturnType<typeof readSequenceChildren>[number] | undefined,\n): Pbes2Prf {\n\tif (element === undefined) {\n\t\treturn 'HMAC-SHA-1';\n\t}\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prfDer = readSequenceChildren(\n\t\tpbkdf2Der.slice(element.start - element.headerLength, element.end),\n\t);\n\tconst oid = prfDer[0];\n\tif (oid === undefined) {\n\t\tthrow new Error('Malformed PBKDF2 PRF');\n\t}\n\tconst prf = prfFromOid(decodeObjectIdentifier(oid.value));\n\tif (prf === undefined) {\n\t\tthrow new Error('Unsupported PBKDF2 PRF');\n\t}\n\treturn prf;\n}\n\n/** Maps an AES-CBC OID to the encryption profile, or `undefined` if unsupported. */\nfunction encryptionSchemeFromOid(oid: string):\n\t| {\n\t\t\treadonly name: Pbes2EncryptionScheme;\n\t\t\treadonly oid: string;\n\t\t\treadonly keyLengthBits: 128 | 192 | 256;\n\t\t\treadonly keyLengthBytes: 16 | 24 | 32;\n\t }\n\t| undefined {\n\tswitch (oid) {\n\t\tcase OIDS.aes128Cbc:\n\t\t\treturn { name: 'AES-128-CBC', oid, keyLengthBits: 128, keyLengthBytes: 16 };\n\t\tcase OIDS.aes192Cbc:\n\t\t\treturn { name: 'AES-192-CBC', oid, keyLengthBits: 192, keyLengthBytes: 24 };\n\t\tcase OIDS.aes256Cbc:\n\t\t\treturn { name: 'AES-256-CBC', oid, keyLengthBits: 256, keyLengthBytes: 32 };\n\t}\n\treturn undefined;\n}\n\n/** Maps an HMAC OID to the PRF name, or `undefined` if unsupported. */\nfunction prfFromOid(oid: string): Pbes2Prf | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.hmacWithSHA1:\n\t\t\treturn 'HMAC-SHA-1';\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t}\n\treturn undefined;\n}\n\n/** Looks up the full encryption profile for a scheme name. Throws if unsupported. */\nfunction resolveEncryptionProfile(name: Pbes2EncryptionScheme): {\n\treadonly name: Pbes2EncryptionScheme;\n\treadonly oid: string;\n\treadonly keyLengthBits: 128 | 192 | 256;\n\treadonly keyLengthBytes: 16 | 24 | 32;\n} {\n\tconst profile = encryptionSchemeFromOid(\n\t\tname === 'AES-128-CBC'\n\t\t\t? OIDS.aes128Cbc\n\t\t\t: name === 'AES-192-CBC'\n\t\t\t\t? OIDS.aes192Cbc\n\t\t\t\t: OIDS.aes256Cbc,\n\t);\n\tif (profile === undefined) {\n\t\tthrow new Error('Unsupported content encryption scheme');\n\t}\n\treturn profile;\n}\n\n/** Looks up OID and WebCrypto hash name for a PRF. */\nfunction resolvePrfProfile(name: Pbes2Prf): {\n\treadonly oid: string;\n\treadonly hash: 'SHA-1' | 'SHA-256';\n} {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-1':\n\t\t\treturn { oid: OIDS.hmacWithSHA1, hash: 'SHA-1' };\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn { oid: OIDS.hmacWithSHA256, hash: 'SHA-256' };\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled Pbes2Prf: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,MAAMY,IAAqB,OAAO,6BAA6B;;;;;;AAO/D,SAAgB,mBAAmBC,GA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ec.js","names":["PRIME_EC_CURVES","curve","x","
|
|
1
|
+
{"version":3,"file":"prime-ec.js","names":["toHex","PRIME_EC_CURVES","curve","x","y","size","prime","b","xValue","yValue","rhs"],"sources":["../../../src/internal/crypto/prime-ec.ts"],"sourcesContent":["/** Prime-field curve parameters and membership checks for public affine coordinates. @module */\n\nimport { toHex } from '#micro509/internal/asn1/asn1';\n\n/** NIST prime curves used by existing key and SSH workflows. */\ntype PrimeEcCurveName = 'P-256' | 'P-384' | 'P-521';\n\n/** Public parameters of a curve with equation y² = x³ - 3x + b over its prime field. */\ninterface PrimeEcCurve {\n\treadonly size: number;\n\treadonly prime: bigint;\n\treadonly b: bigint;\n}\n\n/** Shared parameters, including those used to decompress SSH public points. */\nexport const PRIME_EC_CURVES: Readonly<Record<PrimeEcCurveName, PrimeEcCurve>> = {\n\t'P-256': {\n\t\tsize: 32,\n\t\tprime: 2n ** 256n - 2n ** 224n + 2n ** 192n + 2n ** 96n - 1n,\n\t\tb: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n\t},\n\t'P-384': {\n\t\tsize: 48,\n\t\tprime: 2n ** 384n - 2n ** 128n - 2n ** 96n + 2n ** 32n - 1n,\n\t\tb: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n\t},\n\t'P-521': {\n\t\tsize: 66,\n\t\tprime: 2n ** 521n - 1n,\n\t\tb: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n\t},\n};\n\n/**\n * Checks fixed-width public coordinates before synchronous key selection. These curves have\n * cofactor one; finite field coordinates satisfying the equation represent a valid public point.\n * Signature operations and key import still run through WebCrypto.\n */\nexport function isPrimeEcPoint(curve: PrimeEcCurveName, x: Uint8Array, y: Uint8Array): boolean {\n\tconst { size, prime, b } = PRIME_EC_CURVES[curve];\n\tif (x.length !== size || y.length !== size) return false;\n\tconst xValue = BigInt(`0x${toHex(x)}`);\n\tconst yValue = BigInt(`0x${toHex(y)}`);\n\tif (xValue >= prime || yValue >= prime) return false;\n\tconst rhs = ((((xValue * xValue - 3n) * xValue + b) % prime) + prime) % prime;\n\treturn (yValue * yValue) % prime === rhs;\n}\n"],"mappings":";;;;AAeA,MAAaC,IAAoE;CAChF,SAAS;EACR,MAAM;EACN,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM;EAC1D,GAAG;CACJ;CACA,SAAS;EACR,MAAM;EACN,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,MAAM;EACzD,GAAG;CACJ;CACA,SAAS;EACR,MAAM;EACN,OAAO,MAAM,OAAO;EACpB,GAAG;CACJ;AACD;;;;;;AAOA,SAAgB,eAAeC,GAAyBC,GAAeC,GAAwB;CAC9F,IAAM,EAAEC,SAAMC,UAAOC,SAAMN,EAAgBC;CAC3C,IAAIC,EAAE,WAAWE,KAAQD,EAAE,WAAWC,GAAM,OAAO;CACnD,IAAMG,IAAS,OAAO,KAAKR,EAAMG,CAAC,GAAG,GAC/BM,IAAS,OAAO,KAAKT,EAAMI,CAAC,GAAG;CACrC,IAAII,KAAUF,KAASG,KAAUH,GAAO,OAAO;CAC/C,IAAMI,OAAUF,IAASA,IAAS,MAAMA,IAASD,KAAKD,IAASA,KAASA;CACxE,OAAQG,IAASA,IAAUH,MAAUI;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsa-pss.js","names":["_exhaustive","hash","hashOid","parameters","hashAlgorithmIdentifier","sequence","explicitContext","objectIdentifier","OIDS","integerFromNumber","parametersDer","element","readRootElement","error","rethrowDecodeRefusal","DECODE_LIMIT_CODES","state","child","childrenOf","alreadySeen","fieldName","integerLabel","supportedHash","mgfHash","supported","children","source","label","requireElement","integerElement","decodeNonNegativeIntegerNumber","oid","decodeObjectIdentifier","oidElement","nullValue"],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 8017 Appendix A.2.3 default salt length when hash is SHA-1. */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n *\n * @throws `limit_exceeded` on an OID sub-identifier over 64 octets.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;AAsIA,SAAgB,wBAAwB,GAAoC;CAC3E,QAAQC,GAAR;EACC,KAAK,WACJ,OAAO;GACN,MAA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B,IAAIpB,EAAQ,QAAQ,IACnB,MAAU,MAAM,6CAA6C;CAE9D,IAAMc,IAAWP,EAAWQ,GAAQf,CAAO;CAC3C,IAAIc,EAAS,WAAW,KAAKA,EAAS,SAAS,GAC9C,MAAU,MAAM,wDAAwD;CAEzE,IAAMQ,IAAaL,EAAeH,EAAS,IAAI,sBAAsB;CACrE,IAAIQ,EAAW,QAAQ,GACtB,MAAU,MAAM,wDAAwD;CAEzE,IAAMF,IAAMC,EAAuBC,EAAW,KAAK;CAKnD,OAJIF,MAAQvB,EAAK,OAIV;EAAE;EAAK,SAAS,6BAA6BkB,GADjCE,EAAeH,EAAS,IAAI,6BACsB,GAAG,oBAAoB;CAAE,IAHtF,EAAE,OAAI;AAIf;;AAGA,SAAS,8BAA8B,GAAyB;CAC/D,OAAOpB,EAAS,CAACE,EAAiBwB,CAAG,GAAGG,EAAU,CAAC,CAAC;AACrD;;AAGA,SAAS,eAAe,GAA0B;CACjD,QAAQjC,GAAR;EACC,KAAK,WACJ,OAAOO,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,SAEC,MAAU,MAAM,yBAAyB,OAAOR,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAS,gBAAgB,GAAiD;CACzE,QAAQ+B,GAAR;EACC,KAAKvB,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACR,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACN;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rsa-pss.js","names":["_exhaustive","childrenOf","decodeNonNegativeIntegerNumber","decodeObjectIdentifier","requireElement","DECODE_LIMIT_CODES","rethrowDecodeRefusal","explicitContext","integerFromNumber","nullValue","objectIdentifier","readRootElement","sequence","OIDS","hash","parameters","hashOid","hashAlgorithmIdentifier","parametersDer","element","error","state","child","alreadySeen","fieldName","integerLabel","supportedHash","mgfHash","supported","source","label","children","integerElement","oid","oidElement","reason"],"sources":["../../../src/internal/crypto/rsa-pss.ts"],"sourcesContent":["/**\n * RSA-PSS `AlgorithmIdentifier` parameter parsing, validation, and encoding.\n *\n * Only the three hash-matched profiles (SHA-256/384/512 with MGF1 and matching salt\n * length) are accepted; SHA-1 defaults and mismatched MGF hashes are rejected.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeNonNegativeIntegerNumber,\n\tdecodeObjectIdentifier,\n\trequireElement,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, rethrowDecodeRefusal } from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tDEFAULT_MAX_DER_DEPTH,\n\texplicitContext,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\treadRootElement,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\n\n/** Hash algorithm accepted for RSA-PSS signatures in this library. */\nexport type RsaPssHash = 'SHA-256' | 'SHA-384' | 'SHA-512';\n\n/**\n * One of the three supported RSA-PSS parameter profiles.\n *\n * Hash, MGF1 hash, and salt length are always matched (e.g. SHA-256 / SHA-256 / 32).\n */\nexport type RsaPssParameters =\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-256';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-256';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 32;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-384';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-384';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 48;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t }\n\t| {\n\t\t\t/** Message digest algorithm. */\n\t\t\treadonly hash: 'SHA-512';\n\t\t\t/** MGF1 hash — always matches `hash`. */\n\t\t\treadonly mgfHash: 'SHA-512';\n\t\t\t/** Salt length in bytes — equals the hash digest size. */\n\t\t\treadonly saltLength: 64;\n\t\t\t/** Trailer field (always 0xBC per RFC 8017 Appendix A.2.3). */\n\t\t\treadonly trailerField: 1;\n\t };\n\n/** Machine-readable reason why an RSA-PSS parameter set is not supported. */\nexport type UnsupportedRsaPssParametersReason =\n\t| 'default_hash_sha1'\n\t| 'unsupported_hash'\n\t| 'unsupported_mgf_algorithm'\n\t| 'unsupported_mgf_hash'\n\t| 'mgf_hash_mismatch'\n\t| 'unsupported_salt_length'\n\t| 'unsupported_trailer_field';\n\n/** Success branch of {@linkcode ParsedRsaPssParametersResult}. */\nexport interface ParsedRsaPssParametersSuccess {\n\t/** Discriminant for the success branch. */\n\treadonly ok: true;\n\t/** The validated RSA-PSS parameter profile. */\n\treadonly value: RsaPssParameters;\n}\n\n/** Failure: valid ASN.1 but an unsupported parameter combination. */\nexport interface ParsedRsaPssParametersUnsupported {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'unsupported_rsa_pss_parameters';\n\t/** Which specific parameter is unsupported. */\n\treadonly reason: UnsupportedRsaPssParametersReason;\n}\n\n/** Failure: the DER encoding is structurally invalid. */\nexport interface ParsedRsaPssParametersMalformed {\n\t/** Discriminant for the failure branch. */\n\treadonly ok: false;\n\t/** Machine-readable failure code. */\n\treadonly code: 'malformed_rsa_pss_parameters';\n\t/** Human-readable description of the structural defect. */\n\treadonly reason: string;\n}\n\n/** Result of {@linkcode parseRsaPssParameters}: success, unsupported, or malformed. */\nexport type ParsedRsaPssParametersResult =\n\t| ParsedRsaPssParametersSuccess\n\t| ParsedRsaPssParametersUnsupported\n\t| ParsedRsaPssParametersMalformed;\n\n/** Parsed MGF AlgorithmIdentifier from an RSA-PSS parameter SEQUENCE. */\ninterface ParsedMaskGenAlgorithm {\n\t/** OID of the mask generation function (expected: id-mgf1). */\n\treadonly oid: string;\n\t/** OID of the hash algorithm used by MGF1, if present. */\n\treadonly hashOid?: string;\n}\n\ninterface MutableRsaPssParameterState {\n\thashOid: string;\n\tmaskGenAlgorithm: ParsedMaskGenAlgorithm;\n\tsaltLength: number;\n\ttrailerField: number;\n\tsawHash: boolean;\n\tsawMaskGen: boolean;\n\tsawSaltLength: boolean;\n\tsawTrailerField: boolean;\n}\n\n/** RFC 8017 Appendix A.2.3 default salt length when hash is SHA-1. */\nconst SHA1_SALT_LENGTH = 20;\n\n/** Return the canonical {@linkcode RsaPssParameters} profile for a given hash algorithm. */\nexport function rsaPssParametersForHash(hash: RsaPssHash): RsaPssParameters {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-256',\n\t\t\t\tmgfHash: 'SHA-256',\n\t\t\t\tsaltLength: 32,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-384':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-384',\n\t\t\t\tmgfHash: 'SHA-384',\n\t\t\t\tsaltLength: 48,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tcase 'SHA-512':\n\t\t\treturn {\n\t\t\t\thash: 'SHA-512',\n\t\t\t\tmgfHash: 'SHA-512',\n\t\t\t\tsaltLength: 64,\n\t\t\t\ttrailerField: 1,\n\t\t\t};\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** DER-encode an {@linkcode RsaPssParameters} profile as an ASN.1 RSASSA-PSS-params SEQUENCE. */\nexport function encodeRsaPssParameters(parameters: RsaPssParameters): Uint8Array {\n\tconst hashOid = hashOidForName(parameters.hash);\n\tconst hashAlgorithmIdentifier = encodeHashAlgorithmIdentifier(hashOid);\n\treturn sequence([\n\t\texplicitContext(0, hashAlgorithmIdentifier),\n\t\texplicitContext(\n\t\t\t1,\n\t\t\tsequence([objectIdentifier(OIDS.mgf1), encodeHashAlgorithmIdentifier(hashOid)]),\n\t\t),\n\t\texplicitContext(2, integerFromNumber(parameters.saltLength)),\n\t\t...(parameters.trailerField === 1\n\t\t\t? []\n\t\t\t: [explicitContext(3, integerFromNumber(parameters.trailerField))]),\n\t]);\n}\n\n/**\n * Parse and validate DER-encoded RSASSA-PSS-params.\n *\n * Returns a typed result: success with a supported profile, unsupported with\n * a reason code, or malformed with an error message.\n *\n * @throws `limit_exceeded` on an OID sub-identifier over 64 octets.\n */\nexport function parseRsaPssParameters(\n\tparametersDer: Uint8Array | undefined,\n): ParsedRsaPssParametersResult {\n\tif (parametersDer === undefined) {\n\t\treturn unsupportedResult('default_hash_sha1');\n\t}\n\n\ttry {\n\t\tconst element = readRootElement(parametersDer, { maxDepth: DEFAULT_MAX_DER_DEPTH });\n\t\tif (element.tag !== 0x30) {\n\t\t\tthrow new Error('RSA-PSS parameters must be a SEQUENCE');\n\t\t}\n\t\tconst state = parseRsaPssParameterFields(parametersDer, element);\n\t\treturn validateRsaPssParameterProfile(state);\n\t} catch (error) {\n\t\trethrowDecodeRefusal(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: 'malformed_rsa_pss_parameters',\n\t\t\treason: error instanceof Error ? error.message : 'Malformed RSA-PSS parameters',\n\t\t};\n\t}\n}\n\n/** Parses the optional context-specific RSA-PSS fields into their defaulted state. */\nfunction parseRsaPssParameterFields(\n\tparametersDer: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): MutableRsaPssParameterState {\n\tconst state: MutableRsaPssParameterState = {\n\t\thashOid: OIDS.sha1,\n\t\tmaskGenAlgorithm: { oid: OIDS.mgf1, hashOid: OIDS.sha1 },\n\t\tsaltLength: SHA1_SALT_LENGTH,\n\t\ttrailerField: 1,\n\t\tsawHash: false,\n\t\tsawMaskGen: false,\n\t\tsawSaltLength: false,\n\t\tsawTrailerField: false,\n\t};\n\tfor (const child of childrenOf(parametersDer, element)) {\n\t\tparseRsaPssParameterField(parametersDer, child, state);\n\t}\n\treturn state;\n}\n\nfunction parseRsaPssParameterField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\tstate: MutableRsaPssParameterState,\n): void {\n\tswitch (child.tag) {\n\t\tcase 0xa0:\n\t\t\tif (state.sawHash) throw new Error('RSA-PSS parameters contain duplicate hashAlgorithm');\n\t\t\tstate.hashOid = parseHashAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'hashAlgorithm'),\n\t\t\t\t'hashAlgorithm',\n\t\t\t);\n\t\t\tstate.sawHash = true;\n\t\t\treturn;\n\t\tcase 0xa1:\n\t\t\tif (state.sawMaskGen)\n\t\t\t\tthrow new Error('RSA-PSS parameters contain duplicate maskGenAlgorithm');\n\t\t\tstate.maskGenAlgorithm = parseMaskGenAlgorithmIdentifier(\n\t\t\t\tparametersDer,\n\t\t\t\trequireSingleExplicitChild(parametersDer, child, 'maskGenAlgorithm'),\n\t\t\t);\n\t\t\tstate.sawMaskGen = true;\n\t\t\treturn;\n\t\tcase 0xa2:\n\t\t\tstate.saltLength = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawSaltLength,\n\t\t\t\t'saltLength',\n\t\t\t\t'RSA-PSS saltLength',\n\t\t\t);\n\t\t\tstate.sawSaltLength = true;\n\t\t\treturn;\n\t\tcase 0xa3:\n\t\t\tstate.trailerField = parseUniqueRsaPssIntegerField(\n\t\t\t\tparametersDer,\n\t\t\t\tchild,\n\t\t\t\tstate.sawTrailerField,\n\t\t\t\t'trailerField',\n\t\t\t\t'RSA-PSS trailerField',\n\t\t\t);\n\t\t\tstate.sawTrailerField = true;\n\t\t\treturn;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`RSA-PSS parameters contain unexpected field tag 0x${child.tag.toString(16)}`,\n\t\t\t);\n\t}\n}\n\nfunction parseUniqueRsaPssIntegerField(\n\tparametersDer: Uint8Array,\n\tchild: ReturnType<typeof readRootElement>,\n\talreadySeen: boolean,\n\tfieldName: string,\n\tintegerLabel: string,\n): number {\n\tif (alreadySeen) throw new Error(`RSA-PSS parameters contain duplicate ${fieldName}`);\n\treturn parseExplicitInteger(parametersDer, child, fieldName, integerLabel);\n}\n\nfunction validateRsaPssParameterProfile(\n\tstate: MutableRsaPssParameterState,\n): ParsedRsaPssParametersResult {\n\tconst supportedHash = hashNameFromOid(state.hashOid);\n\tif (supportedHash === undefined) {\n\t\treturn state.hashOid === OIDS.sha1\n\t\t\t? unsupportedResult('default_hash_sha1')\n\t\t\t: unsupportedResult('unsupported_hash');\n\t}\n\tif (state.maskGenAlgorithm.oid !== OIDS.mgf1)\n\t\treturn unsupportedResult('unsupported_mgf_algorithm');\n\tconst mgfHash = hashNameFromOid(state.maskGenAlgorithm.hashOid);\n\tif (mgfHash === undefined) return unsupportedResult('unsupported_mgf_hash');\n\tif (mgfHash !== supportedHash) return unsupportedResult('mgf_hash_mismatch');\n\tconst supported = rsaPssParametersForHash(supportedHash);\n\tif (state.saltLength !== supported.saltLength)\n\t\treturn unsupportedResult('unsupported_salt_length');\n\tif (state.trailerField !== 1) return unsupportedResult('unsupported_trailer_field');\n\treturn { ok: true, value: supported };\n}\n\n/** Unwrap an explicit context tag and assert it contains exactly one child element. */\nfunction requireSingleExplicitChild(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): ReturnType<typeof readRootElement> {\n\tconst children = childrenOf(source, element);\n\tif (children.length !== 1) {\n\t\tthrow new Error(`RSA-PSS ${label} must wrap exactly one value`);\n\t}\n\treturn requireElement(children[0], `RSA-PSS ${label}`);\n}\n\n/** Extract a non-negative integer from an explicit context-tagged wrapper. */\nfunction parseExplicitInteger(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n\tintegerLabel: string,\n): number {\n\tconst integerElement = requireSingleExplicitChild(source, element, label);\n\tif (integerElement.tag !== 0x02) {\n\t\tthrow new Error(`RSA-PSS ${label} must be an INTEGER`);\n\t}\n\treturn decodeNonNegativeIntegerNumber(integerElement.value, integerLabel);\n}\n\n/** Parse an AlgorithmIdentifier SEQUENCE and return the algorithm OID. */\nfunction parseHashAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n\tlabel: string,\n): string {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`RSA-PSS ${label} must be a SEQUENCE`);\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tconst oid = requireElement(children[0], `${label} OID`);\n\tif (oid.tag !== 0x06) {\n\t\tthrow new Error(`Malformed RSA-PSS ${label} AlgorithmIdentifier`);\n\t}\n\tif (children.length === 2 && requireElement(children[1], `${label} parameters`).tag !== 0x05) {\n\t\tthrow new Error(`RSA-PSS ${label} AlgorithmIdentifier parameters must be NULL when present`);\n\t}\n\treturn decodeObjectIdentifier(oid.value);\n}\n\n/** Parse an MGF AlgorithmIdentifier SEQUENCE into OID and optional inner hash OID. */\nfunction parseMaskGenAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: ReturnType<typeof readRootElement>,\n): ParsedMaskGenAlgorithm {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error('RSA-PSS maskGenAlgorithm must be a SEQUENCE');\n\t}\n\tconst children = childrenOf(source, element);\n\tif (children.length === 0 || children.length > 2) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oidElement = requireElement(children[0], 'maskGenAlgorithm OID');\n\tif (oidElement.tag !== 0x06) {\n\t\tthrow new Error('Malformed RSA-PSS maskGenAlgorithm AlgorithmIdentifier');\n\t}\n\tconst oid = decodeObjectIdentifier(oidElement.value);\n\tif (oid !== OIDS.mgf1) {\n\t\treturn { oid };\n\t}\n\tconst parameters = requireElement(children[1], 'maskGenAlgorithm parameters');\n\treturn { oid, hashOid: parseHashAlgorithmIdentifier(source, parameters, 'MGF1 hashAlgorithm') };\n}\n\n/** DER-encode a hash AlgorithmIdentifier as `SEQUENCE { OID, NULL }`. */\nfunction encodeHashAlgorithmIdentifier(oid: string): Uint8Array {\n\treturn sequence([objectIdentifier(oid), nullValue()]);\n}\n\n/** Map a hash algorithm name to its ASN.1 OID string. */\nfunction hashOidForName(hash: RsaPssHash): string {\n\tswitch (hash) {\n\t\tcase 'SHA-256':\n\t\t\treturn OIDS.sha256;\n\t\tcase 'SHA-384':\n\t\t\treturn OIDS.sha384;\n\t\tcase 'SHA-512':\n\t\t\treturn OIDS.sha512;\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = hash;\n\t\t\tthrow new Error(`Unhandled RsaPssHash: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\n/** Reverse-map a hash OID to a supported {@linkcode RsaPssHash} name, or `undefined` if unsupported. */\nfunction hashNameFromOid(oid: string | undefined): RsaPssHash | undefined {\n\tswitch (oid) {\n\t\tcase OIDS.sha256:\n\t\t\treturn 'SHA-256';\n\t\tcase OIDS.sha384:\n\t\t\treturn 'SHA-384';\n\t\tcase OIDS.sha512:\n\t\t\treturn 'SHA-512';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\n/** Build an unsupported-parameters failure result. */\nfunction unsupportedResult(\n\treason: UnsupportedRsaPssParametersReason,\n): ParsedRsaPssParametersUnsupported {\n\treturn {\n\t\tok: false,\n\t\tcode: 'unsupported_rsa_pss_parameters',\n\t\treason,\n\t};\n}\n"],"mappings":";;;;;AAsIA,SAAgB,wBAAwBc,GAAoC;CAC3E,QAAQ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O3B,EAAuB8B,EAAI,KAAK;AACxC;;AAGA,SAAS,gCACRJ,GACAV,GACyB;CACzB,IAAIA,EAAQ,QAAQ,IACnB,MAAU,MAAM,6CAA6C;CAE9D,IAAMY,IAAW9B,EAAW4B,GAAQV,CAAO;CAC3C,IAAIY,EAAS,WAAW,KAAKA,EAAS,SAAS,GAC9C,MAAU,MAAM,wDAAwD;CAEzE,IAAMG,IAAa9B,EAAe2B,EAAS,IAAI,sBAAsB;CACrE,IAAIG,EAAW,QAAQ,GACtB,MAAU,MAAM,wDAAwD;CAEzE,IAAMD,IAAM9B,EAAuB+B,EAAW,KAAK;CAKnD,OAJID,MAAQpB,EAAK,OAIV;EAAEoB;EAAK,SAAS,6BAA6BJ,GADjCzB,EAAe2B,EAAS,IAAI,6BACsB,GAAG,oBAAoB;CAAE,IAHtF,EAAEE,OAAI;AAIf;;AAGA,SAAS,8BAA8BA,GAAyB;CAC/D,OAAOrB,EAAS,CAACF,EAAiBuB,CAAG,GAAGxB,EAAU,CAAC,CAAC;AACrD;;AAGA,SAAS,eAAeK,GAA0B;CACjD,QAAQA,GAAR;EACC,KAAK,WACJ,OAAOD,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,KAAK,WACJ,OAAOA,EAAK;EACb,SAEC,MAAU,MAAM,yBAAyB,OAAOb,CAAW,GAAG;CAEhE;AACD;;AAGA,SAAS,gBAAgBiC,GAAiD;CACzE,QAAQA,GAAR;EACC,KAAKpB,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,KAAKA,EAAK,QACT,OAAO;EACR,SACC;CACF;AACD;;AAGA,SAAS,kBACRsB,GACoC;CACpC,OAAO;EACN,IAAI;EACJ,MAAM;EACNA;CACD;AACD"}
|
|
@@ -1,3 +1,43 @@
|
|
|
1
|
+
/** One signature handed to a {@linkcode SignatureVerifier}. */
|
|
2
|
+
export interface SignatureVerifierInput {
|
|
3
|
+
/** The signature algorithm as carried beside the signature. */
|
|
4
|
+
readonly signatureAlgorithm: {
|
|
5
|
+
/** Dotted-decimal signature algorithm OID. */
|
|
6
|
+
readonly oid: string;
|
|
7
|
+
/** DER algorithm parameters, when the signature carries them. */
|
|
8
|
+
readonly parametersDer?: Uint8Array;
|
|
9
|
+
};
|
|
10
|
+
/** DER `SubjectPublicKeyInfo` of the signer. */
|
|
11
|
+
readonly signerSpkiDer: Uint8Array;
|
|
12
|
+
/**
|
|
13
|
+
* DER parameters to verify with: RFC 5280 §6.1 `working_public_key_parameters`.
|
|
14
|
+
* These are the signer's own key parameters, or the parameters it inherits along
|
|
15
|
+
* the certification path when its own are absent or NULL (RFC 5280 §6.1.4 (e),
|
|
16
|
+
* RFC 3279 §2.3.2). Absent when the path leaves none.
|
|
17
|
+
*/
|
|
18
|
+
readonly signerPublicKeyParametersDer?: Uint8Array;
|
|
19
|
+
/** The signature bytes as carried. */
|
|
20
|
+
readonly signature: Uint8Array;
|
|
21
|
+
/**
|
|
22
|
+
* Unused bits in the final octet of `signature`, from a `signatureValue`
|
|
23
|
+
* BIT STRING. `0` for a signature carried as octets.
|
|
24
|
+
*/
|
|
25
|
+
readonly signatureUnusedBits: number;
|
|
26
|
+
/** The exact bytes the signature covers. */
|
|
27
|
+
readonly data: Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Caller-supplied verification for a signature algorithm micro509 does not run
|
|
31
|
+
* through WebCrypto. Resolves `true` only for a valid signature. A rejection is
|
|
32
|
+
* reported as a verification error.
|
|
33
|
+
*/
|
|
34
|
+
export type SignatureVerifier = (input: SignatureVerifierInput) => Promise<boolean>;
|
|
35
|
+
/**
|
|
36
|
+
* Caller verifiers keyed by dotted-decimal signature algorithm OID. A key that
|
|
37
|
+
* micro509 verifies natively throws `RangeError`, so a caller verifier never
|
|
38
|
+
* replaces WebCrypto verification.
|
|
39
|
+
*/
|
|
40
|
+
export type SignatureVerifiers = Readonly<Record<string, SignatureVerifier>>;
|
|
1
41
|
/** Failure: the signature algorithm or its parameters are not supported. */
|
|
2
42
|
export interface VerifySignatureConfigFailure {
|
|
3
43
|
/** Discriminant for the failure branch. */
|