micro509 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +5 -5
  3. package/dist/index.js +15 -1
  4. package/dist/internal/asn1/asn1.js +280 -2
  5. package/dist/internal/asn1/der.js +378 -2
  6. package/dist/internal/asn1/oids.js +103 -2
  7. package/dist/internal/crypto/algorithm-names.js +58 -2
  8. package/dist/internal/crypto/ecdsa.js +68 -2
  9. package/dist/internal/crypto/hash.js +286 -2
  10. package/dist/internal/crypto/pbes2.js +213 -2
  11. package/dist/internal/crypto/rsa-pss.js +184 -2
  12. package/dist/internal/crypto/sig-verify.js +192 -2
  13. package/dist/internal/crypto/signing.d.ts +1 -2
  14. package/dist/internal/crypto/signing.js +123 -2
  15. package/dist/internal/crypto/webcrypto.js +14 -2
  16. package/dist/internal/shared/base64.js +16 -2
  17. package/dist/internal/shared/dn.js +84 -2
  18. package/dist/internal/shared/ip.js +164 -2
  19. package/dist/internal/verify/name-constraints-engine.js +450 -2
  20. package/dist/internal/verify/policy-engine.js +382 -2
  21. package/dist/internal/verify/verify-path.js +298 -2
  22. package/dist/internal/x509/extension-bits.js +132 -2
  23. package/dist/internal/x509/extension-registry.js +229 -2
  24. package/dist/internal/x509/name-fields.js +93 -2
  25. package/dist/keys/keys.d.ts +231 -7
  26. package/dist/keys/keys.js +1087 -5
  27. package/dist/keys.d.ts +2 -2
  28. package/dist/keys.js +2 -1
  29. package/dist/pem/pem.d.ts +2 -2
  30. package/dist/pem/pem.js +172 -6
  31. package/dist/pem.js +2 -1
  32. package/dist/pkcs/pfx.d.ts +4 -5
  33. package/dist/pkcs/pfx.js +395 -2
  34. package/dist/pkcs/pkcs12-mac.d.ts +2 -2
  35. package/dist/pkcs/pkcs12-mac.js +175 -2
  36. package/dist/pkcs/pkcs7.d.ts +1 -2
  37. package/dist/pkcs/pkcs7.js +653 -2
  38. package/dist/pkcs.d.ts +2 -2
  39. package/dist/pkcs.js +4 -1
  40. package/dist/result/result.d.ts +1 -2
  41. package/dist/result/result.js +111 -2
  42. package/dist/result.js +2 -1
  43. package/dist/revocation/chain.d.ts +4 -5
  44. package/dist/revocation/chain.js +536 -2
  45. package/dist/revocation/crl.d.ts +2 -2
  46. package/dist/revocation/crl.js +1119 -2
  47. package/dist/revocation/ocsp.d.ts +3 -2
  48. package/dist/revocation/ocsp.js +958 -2
  49. package/dist/revocation/revocation.d.ts +1 -2
  50. package/dist/revocation/revocation.js +261 -2
  51. package/dist/revocation.d.ts +2 -2
  52. package/dist/revocation.js +5 -1
  53. package/dist/verify/identity.d.ts +1 -2
  54. package/dist/verify/identity.js +270 -2
  55. package/dist/verify/name-constraints.d.ts +1 -2
  56. package/dist/verify/policy.d.ts +1 -2
  57. package/dist/verify/verify.d.ts +1 -2
  58. package/dist/verify/verify.js +764 -2
  59. package/dist/verify.js +3 -1
  60. package/dist/x509/certificate.d.ts +1 -2
  61. package/dist/x509/certificate.js +151 -2
  62. package/dist/x509/csr.d.ts +1 -2
  63. package/dist/x509/csr.js +71 -2
  64. package/dist/x509/extensions.d.ts +1 -2
  65. package/dist/x509/extensions.js +387 -2
  66. package/dist/x509/name.d.ts +1 -2
  67. package/dist/x509/name.js +173 -2
  68. package/dist/x509/parse.d.ts +84 -2
  69. package/dist/x509/parse.js +1090 -2
  70. package/dist/x509.d.ts +2 -2
  71. package/dist/x509.js +6 -1
  72. package/package.json +74 -34
  73. package/dist/internal/asn1/asn1.js.map +0 -1
  74. package/dist/internal/asn1/der.js.map +0 -1
  75. package/dist/internal/asn1/oids.js.map +0 -1
  76. package/dist/internal/crypto/algorithm-names.js.map +0 -1
  77. package/dist/internal/crypto/ecdsa.js.map +0 -1
  78. package/dist/internal/crypto/hash.js.map +0 -1
  79. package/dist/internal/crypto/pbes2.d.ts +0 -23
  80. package/dist/internal/crypto/pbes2.js.map +0 -1
  81. package/dist/internal/crypto/rsa-pss.js.map +0 -1
  82. package/dist/internal/crypto/sig-verify.js.map +0 -1
  83. package/dist/internal/crypto/signing.js.map +0 -1
  84. package/dist/internal/crypto/webcrypto.js.map +0 -1
  85. package/dist/internal/shared/base64.js.map +0 -1
  86. package/dist/internal/shared/dn.js.map +0 -1
  87. package/dist/internal/shared/ip.js.map +0 -1
  88. package/dist/internal/verify/name-constraints-engine.js.map +0 -1
  89. package/dist/internal/verify/policy-engine.js.map +0 -1
  90. package/dist/internal/verify/verify-path.js.map +0 -1
  91. package/dist/internal/x509/extension-bits.js.map +0 -1
  92. package/dist/internal/x509/extension-registry.js.map +0 -1
  93. package/dist/internal/x509/name-fields.js.map +0 -1
  94. package/dist/keys/keys.js.map +0 -1
  95. package/dist/pem/pem.js.map +0 -1
  96. package/dist/pkcs/pfx.js.map +0 -1
  97. package/dist/pkcs/pkcs12-mac.js.map +0 -1
  98. package/dist/pkcs/pkcs7.js.map +0 -1
  99. package/dist/result/result.js.map +0 -1
  100. package/dist/revocation/chain.js.map +0 -1
  101. package/dist/revocation/crl.js.map +0 -1
  102. package/dist/revocation/ocsp.js.map +0 -1
  103. package/dist/revocation/revocation.js.map +0 -1
  104. package/dist/verify/identity.js.map +0 -1
  105. package/dist/verify/verify.js.map +0 -1
  106. package/dist/x509/certificate.js.map +0 -1
  107. package/dist/x509/csr.js.map +0 -1
  108. package/dist/x509/extensions.js.map +0 -1
  109. package/dist/x509/name.js.map +0 -1
  110. package/dist/x509/parse.js.map +0 -1
package/dist/keys/keys.js CHANGED
@@ -1,5 +1,1087 @@
1
- import{nullValue as e,objectIdentifier as t,octetString as n,readSequenceChildren as r,sequence as i}from"../internal/asn1/der.js";import{decodeObjectIdentifier as a,extractBitStringValue as o,hexToBytes as s,toArrayBuffer as c,toHex as l}from"../internal/asn1/asn1.js";import{OIDS as u}from"../internal/asn1/oids.js";import{md5 as ee}from"../internal/crypto/hash.js";import{getCrypto as d}from"../internal/crypto/webcrypto.js";import{decryptPbes2 as te,encryptPbes2 as ne,isWrongPasswordError as re,wrongPasswordError as ie}from"../internal/crypto/pbes2.js";import{base64Decode as f,base64Encode as p}from"../internal/shared/base64.js";import{failureResult as m,rethrowIfInvariant as h,successResult as g}from"../result/result.js";import{pemDecodeOrThrow as _,pemEncode as v}from"../pem/pem.js";async function ae(e={kind:`ecdsa`,curve:`P-256`}){let t=await d().subtle.generateKey(Oe(e),!0,[`sign`,`verify`]);if(!(`publicKey`in t)||!(`privateKey`in t))throw Error(`Expected an asymmetric key pair`);return y(t.publicKey,t.privateKey)}function y(e,t){return{publicKey:e,privateKey:t,async exportSpkiDer(){return new Uint8Array(await d().subtle.exportKey(`spki`,e))},async exportSpkiPem(){return v(`PUBLIC KEY`,await this.exportSpkiDer())},async exportPkcs8Der(){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,t))},async exportPkcs8Pem(){return v(`PRIVATE KEY`,await this.exportPkcs8Der())},async exportPublicJwk(){return d().subtle.exportKey(`jwk`,e)},async exportPrivateJwk(){return d().subtle.exportKey(`jwk`,t)}}}async function b(e){return new Uint8Array(await d().subtle.exportKey(`spki`,e))}async function x(e){return new Uint8Array(await d().subtle.exportKey(`pkcs8`,e))}async function oe(e){return d().subtle.exportKey(`jwk`,e)}async function se(e){return d().subtle.exportKey(`jwk`,e)}async function ce(e){return v(`PRIVATE KEY`,await x(e))}async function S(e,t){let r=await ne(await x(e),t);return i([r.algorithmIdentifierDer,n(r.encryptedData)])}async function le(e,t){return v(`ENCRYPTED PRIVATE KEY`,await S(e,t))}async function C(e){let t=J(await x(e));if(t.algorithmOid!==u.rsaEncryption)throw Error(`PKCS#1 export requires an RSA private key`);return t.privateKeyDer}async function ue(e){return v(`RSA PRIVATE KEY`,await C(e))}async function de(e,t){return Z(`RSA PRIVATE KEY`,await C(e),t)}async function w(e){let t=J(await x(e));if(t.algorithmOid!==u.ecPublicKey)throw Error(`SEC1 export requires an EC private key`);return t.privateKeyDer}async function fe(e){return v(`EC PRIVATE KEY`,await w(e))}async function T(e,t){return Z(`EC PRIVATE KEY`,await w(e),t)}async function pe(e){return v(`PUBLIC KEY`,await b(e))}async function me(e){if(e.type===`public`)return p(await b(e));if(e.type===`private`)return p(await x(e));throw Error(`Cannot export secret/symmetric CryptoKey`)}async function E(e,t){Le(Ie(e),t);try{return await d().subtle.importKey(`spki`,new Uint8Array(e),q(t),!0,[`verify`])}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}async function D(e){try{return g(await e())}catch(e){return h(e),m(`malformed`,e instanceof Error?e.message:`Malformed key`)}}async function O(e){try{return g(await e())}catch(e){return h(e),re(e)?m(`invalid_password`,e.message):m(`malformed`,e instanceof Error?e.message:`Malformed encrypted key`)}}function he(e,t){return D(()=>E(e,t))}async function k(e,t){return E(_(`PUBLIC KEY`,e),t)}function ge(e,t){return D(()=>k(e,t))}async function A(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 SubjectPublicKeyInfo`)}return E(n,t)}function _e(e,t){return D(()=>A(e,t))}async function j(e,t){let n;try{n=J(e)}catch{throw Error(`Malformed PKCS#8 private key`)}Re(n,t);try{return await d().subtle.importKey(`pkcs8`,new Uint8Array(e),q(t),!0,[`sign`])}catch{throw Error(`Malformed PKCS#8 private key`)}}function ve(e,t){return D(()=>j(e,t))}async function M(e,t){return j(_(`PRIVATE KEY`,e),t)}function N(e,t){return D(()=>M(e,t))}async function P(e,t,n){let i;try{i=r(e)}catch{throw Error(`Malformed EncryptedPrivateKeyInfo`)}let a=i[0],o=i[1];if(i.length!==2||a===void 0||o===void 0||o.tag!==4)throw Error(`Malformed EncryptedPrivateKeyInfo`);return j(await te(e.slice(a.start-a.headerLength,a.end),o.value,t),n)}function F(e,t,n){return O(()=>P(e,t,n))}async function I(e,t,n){return P(_(`ENCRYPTED PRIVATE KEY`,e),t,n)}function ye(e,t,n){return O(()=>I(e,t,n))}async function L(e,t={kind:`rsa`}){return j(ke(e),t)}function be(e,t={kind:`rsa`}){return D(()=>L(e,t))}async function R(e,t={kind:`rsa`}){return L(_(`RSA PRIVATE KEY`,e),t)}function z(e,t={kind:`rsa`}){return D(()=>R(e,t))}async function B(e,t,n={kind:`rsa`}){return L(await Q(`RSA PRIVATE KEY`,e,t),n)}function xe(e,t,n={kind:`rsa`}){return O(()=>B(e,t,n))}async function V(e,t){let n;try{n=f(e)}catch{throw Error(`Invalid base64 PKCS#8 private key`)}return j(n,t)}function Se(e,t){return D(()=>V(e,t))}async function H(e,t){return j(Ae(e,t.curve),t)}function Ce(e,t){return D(()=>H(e,t))}async function U(e,t){return H(_(`EC PRIVATE KEY`,e),t)}function we(e,t){return D(()=>U(e,t))}async function W(e,t,n){return H(await Q(`EC PRIVATE KEY`,e,t),n)}function Te(e,t,n){return O(()=>W(e,t,n))}async function G(e,t){ze(e,t);try{return await d().subtle.importKey(`jwk`,e,q(t),!0,[`verify`])}catch{throw Error(`Malformed public JWK`)}}function Ee(e,t){return D(()=>G(e,t))}async function K(e,t){return d().subtle.importKey(`jwk`,e,q(t),!0,[`sign`])}function De(e,t){return D(()=>K(e,t))}function Oe(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),modulusLength:e.modulusLength??2048,publicExponent:Uint8Array.of(1,0,1),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve??`P-256`};case`ed25519`:return{name:`Ed25519`}}}function q(e){switch(e.kind){case`rsa`:return{name:X(e.scheme),hash:e.hash??`SHA-256`};case`ecdsa`:return{name:`ECDSA`,namedCurve:e.curve};case`ed25519`:return{name:`Ed25519`}}}function J(e){let t=r(e),n=t[1],i=t[2];if(t.length<3||t.length>4||n===void 0||n.tag!==48||i===void 0||i.tag!==4)throw Error(`Malformed PKCS#8 private key`);let o=r(e.slice(n.start-n.headerLength,n.end)),s=o[0];if(s===void 0||s.tag!==6||o.length<1||o.length>2)throw Error(`Malformed PKCS#8 private key`);let c=o[1];return{algorithmOid:a(s.value),...c===void 0?{}:{parametersTag:c.tag},...c?.tag===6?{parametersOid:a(c.value)}:{},privateKeyDer:i.value}}function ke(r){return i([Uint8Array.of(2,1,0),i([t(u.rsaEncryption),e()]),n(new Uint8Array(r))])}function Ae(e,r){return i([Uint8Array.of(2,1,0),i([t(u.ecPublicKey),t(Y(r))]),n(new Uint8Array(e))])}function Y(e){switch(e){case`P-256`:return u.prime256v1;case`P-384`:return u.secp384r1;case`P-521`:return u.secp521r1}}function X(e){return e===`pss`?`RSA-PSS`:`RSASSA-PKCS1-v1_5`}async function Z(e,t,n){let r=n.iv??d().getRandomValues(new Uint8Array(16));if(r.length!==16)throw Error(`Traditional PEM encryption requires a 16-byte IV`);let i=n.cipher??`AES-256-CBC`,a=await $(n.password,r.slice(0,8),i,[`encrypt`]),o=p(new Uint8Array(await d().subtle.encrypt({name:`AES-CBC`,iv:c(r)},a,c(t)))).match(/.{1,64}/g)?.join(`
2
- `)??``;return[`-----BEGIN ${e}-----`,`Proc-Type: 4,ENCRYPTED`,`DEK-Info: ${i},${l(r).toUpperCase()}`,``,o,`-----END ${e}-----`].join(`
3
- `)}async function Q(e,t,n){let r=Fe(t);if(r.label!==e)throw Error(`Expected ${e} PEM block`);let i=r.headers.get(`DEK-Info`);if(r.headers.get(`Proc-Type`)!==`4,ENCRYPTED`||i===void 0)throw Error(`Traditional PEM encryption headers missing`);let[a,o]=i.split(`,`);if(!je(a)||o===void 0)throw Error(`Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported`);if(!Me(o))throw Error(`Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters`);let l=s(o),u=await $(n,l.slice(0,8),a,[`decrypt`]);try{return new Uint8Array(await d().subtle.decrypt({name:`AES-CBC`,iv:c(l)},u,c(f(r.base64Body))))}catch{throw ie(`Invalid password or encrypted PEM content`)}}async function $(e,t,n,r){let i=Ne(n),a=Pe(e,t,i/8);return d().subtle.importKey(`raw`,c(a),{name:`AES-CBC`,length:i},!1,r)}function je(e){return e===`AES-128-CBC`||e===`AES-192-CBC`||e===`AES-256-CBC`}function Me(e){return e.length===32&&/^[0-9A-Fa-f]+$/.test(e)}function Ne(e){switch(e){case`AES-128-CBC`:return 128;case`AES-192-CBC`:return 192;case`AES-256-CBC`:return 256}}function Pe(e,t,n){let r=new TextEncoder().encode(e),i=[],a=new Uint8Array,o=0;for(;o<n;){let e=new Uint8Array(a.length+r.length+t.length);e.set(a,0),e.set(r,a.length),e.set(t,a.length+r.length),a=ee(e),i.push(a),o+=a.length}let s=new Uint8Array(n),c=0;for(let e of i){let t=e.slice(0,Math.min(e.length,n-c));if(s.set(t,c),c+=t.length,c>=n)break}return s}function Fe(e){let t=e.replace(/\r/g,``).trim().split(`
4
- `),n=t[0],r=t[t.length-1];if(n===void 0||r===void 0||!n.startsWith(`-----BEGIN `)||!r.startsWith(`-----END `))throw Error(`Invalid PEM block`);let i=n.slice(11,-5);if(r!==`-----END ${i}-----`)throw Error(`PEM boundaries do not match`);let a=new Map,o=1;for(;o<t.length-1;){let e=t[o];if(e===void 0)break;if(e.length===0){o+=1;break}let n=e.indexOf(`: `);if(n===-1)break;let r=e.slice(0,n);if(a.has(r))throw Error(`Duplicate PEM header: ${r}`);a.set(r,e.slice(n+2)),o+=1}return{label:i,headers:a,base64Body:t.slice(o,t.length-1).join(``)}}function Ie(e){try{let t=r(e);if(t.length!==2)throw Error(`Malformed SubjectPublicKeyInfo`);let n=t[0],i=t[1];if(n===void 0||n.tag!==48||i===void 0||i.tag!==3)throw Error(`Malformed SubjectPublicKeyInfo`);o(i);let s=r(e.slice(n.start-n.headerLength,n.end)),c=s[0];if(c===void 0||c.tag!==6||s.length<1||s.length>2)throw Error(`Malformed SubjectPublicKeyInfo`);let l=s[1];return{algorithmOid:a(c.value),...l===void 0?{}:{parametersTag:l.tag},...l?.tag===6?{parametersOid:a(l.value)}:{}}}catch{throw Error(`Malformed SubjectPublicKeyInfo`)}}function Le(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`SubjectPublicKeyInfo algorithm does not match requested import algorithm`);return}}function Re(e,t){switch(t.kind){case`rsa`:if(e.algorithmOid!==u.rsaEncryption||e.parametersTag!==void 0&&e.parametersTag!==5)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.algorithmOid!==u.ecPublicKey||e.parametersTag!==6||e.parametersOid!==Y(t.curve))throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.algorithmOid!==u.ed25519||e.parametersTag!==void 0)throw Error(`PKCS#8 private key algorithm does not match requested import algorithm`);return}}function ze(e,t){if(e.k!==void 0||e.d!==void 0||e.p!==void 0||e.q!==void 0||e.dp!==void 0||e.dq!==void 0||e.qi!==void 0||e.oth!==void 0)throw Error(`Public JWK must not contain private key material`);switch(t.kind){case`rsa`:if(e.kty!==`RSA`||typeof e.n!=`string`||typeof e.e!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ecdsa`:if(e.kty!==`EC`||e.crv!==t.curve||typeof e.x!=`string`||typeof e.y!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return;case`ed25519`:if(e.kty!==`OKP`||e.crv!==`Ed25519`||typeof e.x!=`string`)throw Error(`Public JWK algorithm does not match requested import algorithm`);return}}export{me as exportBinaryBase64,de as exportEncryptedPkcs1Pem,S as exportEncryptedPkcs8Der,le as exportEncryptedPkcs8Pem,T as exportEncryptedSec1Pem,C as exportPkcs1Der,ue as exportPkcs1Pem,x as exportPkcs8Der,ce as exportPkcs8Pem,se as exportPrivateJwk,oe as exportPublicJwk,w as exportSec1Der,fe as exportSec1Pem,b as exportSpkiDer,pe as exportSpkiPem,ae as generateKeyPair,xe as importEncryptedPkcs1Pem,B as importEncryptedPkcs1PemOrThrow,F as importEncryptedPkcs8Der,P as importEncryptedPkcs8DerOrThrow,ye as importEncryptedPkcs8Pem,I as importEncryptedPkcs8PemOrThrow,Te as importEncryptedSec1Pem,W as importEncryptedSec1PemOrThrow,be as importPkcs1Der,L as importPkcs1DerOrThrow,z as importPkcs1Pem,R as importPkcs1PemOrThrow,Se as importPkcs8Base64,V as importPkcs8Base64OrThrow,ve as importPkcs8Der,j as importPkcs8DerOrThrow,N as importPkcs8Pem,M as importPkcs8PemOrThrow,De as importPrivateJwk,K as importPrivateJwkOrThrow,Ee as importPublicJwk,G as importPublicJwkOrThrow,Ce as importSec1Der,H as importSec1DerOrThrow,we as importSec1Pem,U as importSec1PemOrThrow,_e as importSpkiBase64,A as importSpkiBase64OrThrow,he as importSpkiDer,E as importSpkiDerOrThrow,ge as importSpkiPem,k as importSpkiPemOrThrow};
5
- //# sourceMappingURL=keys.js.map
1
+ import { nullValue, objectIdentifier, octetString, readRootElement, readSequenceChildren, sequence } from "../internal/asn1/der.js";
2
+ import { decodeObjectIdentifier, extractBitStringValue, hexToBytes, toArrayBuffer, toHex } from "../internal/asn1/asn1.js";
3
+ import { OIDS } from "../internal/asn1/oids.js";
4
+ import { md5 } from "../internal/crypto/hash.js";
5
+ import { getCrypto } from "../internal/crypto/webcrypto.js";
6
+ import { decryptPbes2, encryptPbes2, isWrongPasswordError, wrongPasswordError } from "../internal/crypto/pbes2.js";
7
+ import { base64Decode, base64Encode } from "../internal/shared/base64.js";
8
+ import { failureResult, rethrowIfInvariant, successResult } from "../result/result.js";
9
+ import { pemDecodeOrThrow, pemEncode } from "../pem/pem.js";
10
+ //#region src/keys/keys.ts
11
+ /**
12
+ * WebCrypto key generation plus import/export for PKCS#1, PKCS#8, SEC1, SPKI, and JWK.
13
+ *
14
+ * Supports RSA (PKCS#1v1.5 and PSS), ECDSA (P-256, P-384, P-521), and Ed25519 keys.
15
+ * All functions use the WebCrypto API and return extractable keys.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { generateKeyPair, exportPkcs8Pem, importSpkiPem } from 'micro509/keys';
20
+ *
21
+ * // Generate and export
22
+ * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });
23
+ * const privatePem = await exportPkcs8Pem(keys.privateKey);
24
+ *
25
+ * // Import
26
+ * const publicKey = await importSpkiPem(publicPem, { kind: 'ecdsa', curve: 'P-256' });
27
+ * ```
28
+ *
29
+ * @module
30
+ */
31
+ /**
32
+ * Generate an asymmetric key pair for signing and verification.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });
37
+ * const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });
38
+ * const edKeys = await generateKeyPair({ kind: 'ed25519' });
39
+ *
40
+ * // Default: ECDSA P-256
41
+ * const keys = await generateKeyPair();
42
+ * const pem = await keys.exportPkcs8Pem();
43
+ * ```
44
+ */
45
+ async function generateKeyPair(algorithm = {
46
+ kind: "ecdsa",
47
+ curve: "P-256"
48
+ }) {
49
+ const generated = await getCrypto().subtle.generateKey(toGenerateKeyAlgorithm(algorithm), true, ["sign", "verify"]);
50
+ if (!("publicKey" in generated) || !("privateKey" in generated)) throw new Error("Expected an asymmetric key pair");
51
+ return wrapKeyPair(generated.publicKey, generated.privateKey);
52
+ }
53
+ function wrapKeyPair(publicKey, privateKey) {
54
+ return {
55
+ publicKey,
56
+ privateKey,
57
+ async exportSpkiDer() {
58
+ return new Uint8Array(await getCrypto().subtle.exportKey("spki", publicKey));
59
+ },
60
+ async exportSpkiPem() {
61
+ return pemEncode("PUBLIC KEY", await this.exportSpkiDer());
62
+ },
63
+ async exportPkcs8Der() {
64
+ return new Uint8Array(await getCrypto().subtle.exportKey("pkcs8", privateKey));
65
+ },
66
+ async exportPkcs8Pem() {
67
+ return pemEncode("PRIVATE KEY", await this.exportPkcs8Der());
68
+ },
69
+ exportPublicJwk() {
70
+ return getCrypto().subtle.exportKey("jwk", publicKey);
71
+ },
72
+ exportPrivateJwk() {
73
+ return getCrypto().subtle.exportKey("jwk", privateKey);
74
+ }
75
+ };
76
+ }
77
+ /**
78
+ * Export a public key as DER-encoded SubjectPublicKeyInfo.
79
+ *
80
+ * @see {@linkcode importSpkiDer} for the inverse operation
81
+ * @see {@linkcode exportSpkiPem} for PEM output
82
+ */
83
+ async function exportSpkiDer(publicKey) {
84
+ return new Uint8Array(await getCrypto().subtle.exportKey("spki", publicKey));
85
+ }
86
+ /**
87
+ * Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.
88
+ *
89
+ * @see {@linkcode importPkcs8Der} for the inverse operation
90
+ * @see {@linkcode exportPkcs8Pem} for PEM output
91
+ * @see {@linkcode exportEncryptedPkcs8Der} for password-protected export
92
+ */
93
+ async function exportPkcs8Der(privateKey) {
94
+ return new Uint8Array(await getCrypto().subtle.exportKey("pkcs8", privateKey));
95
+ }
96
+ /**
97
+ * Export a public key as a JSON Web Key.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });
102
+ * const jwk = await exportPublicJwk(keys.publicKey);
103
+ * ```
104
+ */
105
+ function exportPublicJwk(publicKey) {
106
+ return getCrypto().subtle.exportKey("jwk", publicKey);
107
+ }
108
+ /**
109
+ * Export a private key as a JSON Web Key.
110
+ *
111
+ * @see {@linkcode importPrivateJwk} for the inverse operation
112
+ * @see {@linkcode exportPublicJwk} for public key export
113
+ */
114
+ function exportPrivateJwk(privateKey) {
115
+ return getCrypto().subtle.exportKey("jwk", privateKey);
116
+ }
117
+ /**
118
+ * Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * const keys = await generateKeyPair();
123
+ * const pem = await exportPkcs8Pem(keys.privateKey);
124
+ * // -----BEGIN PRIVATE KEY-----
125
+ * // MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...
126
+ * // -----END PRIVATE KEY-----
127
+ * ```
128
+ *
129
+ * @see {@linkcode importPkcs8Pem} for the inverse operation
130
+ * @see {@linkcode exportEncryptedPkcs8Pem} for password-protected export
131
+ */
132
+ async function exportPkcs8Pem(privateKey) {
133
+ return pemEncode("PRIVATE KEY", await exportPkcs8Der(privateKey));
134
+ }
135
+ /**
136
+ * Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
137
+ *
138
+ * Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.
139
+ *
140
+ * @param privateKey - The private key to export
141
+ * @param options - Encryption options including password and optional algorithm settings
142
+ *
143
+ * @see {@linkcode importEncryptedPkcs8Der} for the inverse operation
144
+ * @see {@linkcode exportEncryptedPkcs8Pem} for PEM output
145
+ */
146
+ async function exportEncryptedPkcs8Der(privateKey, options) {
147
+ const encryption = await encryptPbes2(await exportPkcs8Der(privateKey), options);
148
+ return sequence([encryption.algorithmIdentifierDer, octetString(encryption.encryptedData)]);
149
+ }
150
+ /**
151
+ * Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
152
+ *
153
+ * @example
154
+ * ```ts
155
+ * const keys = await generateKeyPair();
156
+ * const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });
157
+ * // -----BEGIN ENCRYPTED PRIVATE KEY-----
158
+ * // MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...
159
+ * // -----END ENCRYPTED PRIVATE KEY-----
160
+ * ```
161
+ *
162
+ * @see {@linkcode importEncryptedPkcs8Pem} for the inverse operation
163
+ */
164
+ async function exportEncryptedPkcs8Pem(privateKey, options) {
165
+ return pemEncode("ENCRYPTED PRIVATE KEY", await exportEncryptedPkcs8Der(privateKey, options));
166
+ }
167
+ /**
168
+ * Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.
169
+ *
170
+ * PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use
171
+ * {@linkcode exportPkcs8Der}.
172
+ *
173
+ * @throws {Error} If the key is not an RSA key
174
+ *
175
+ * @see {@linkcode importPkcs1Der} for the inverse operation
176
+ * @see {@linkcode exportPkcs1Pem} for PEM output
177
+ */
178
+ async function exportPkcs1Der(privateKey) {
179
+ const parsed = parsePkcs8PrivateKey(await exportPkcs8Der(privateKey));
180
+ if (parsed.algorithmOid !== OIDS.rsaEncryption) throw new Error("PKCS#1 export requires an RSA private key");
181
+ return parsed.privateKeyDer;
182
+ }
183
+ /**
184
+ * Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.
185
+ *
186
+ * @throws {Error} If the key is not an RSA key
187
+ *
188
+ * @see {@linkcode importPkcs1Pem} for the inverse operation
189
+ * @see {@linkcode exportEncryptedPkcs1Pem} for password-protected export
190
+ */
191
+ async function exportPkcs1Pem(privateKey) {
192
+ return pemEncode("RSA PRIVATE KEY", await exportPkcs1Der(privateKey));
193
+ }
194
+ /**
195
+ * Export an RSA private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
196
+ *
197
+ * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.
198
+ * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.
199
+ *
200
+ * @throws {Error} If the key is not an RSA key
201
+ *
202
+ * @see {@linkcode importEncryptedPkcs1Pem} for the inverse operation
203
+ */
204
+ async function exportEncryptedPkcs1Pem(privateKey, options) {
205
+ return encryptTraditionalPem("RSA PRIVATE KEY", await exportPkcs1Der(privateKey), options);
206
+ }
207
+ /**
208
+ * Export an EC private key as DER-encoded SEC 1 ECPrivateKey.
209
+ *
210
+ * SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use
211
+ * {@linkcode exportPkcs8Der}.
212
+ *
213
+ * @throws {Error} If the key is not an EC key
214
+ *
215
+ * @see {@linkcode importSec1Der} for the inverse operation
216
+ * @see {@linkcode exportSec1Pem} for PEM output
217
+ */
218
+ async function exportSec1Der(privateKey) {
219
+ const parsed = parsePkcs8PrivateKey(await exportPkcs8Der(privateKey));
220
+ if (parsed.algorithmOid !== OIDS.ecPublicKey) throw new Error("SEC1 export requires an EC private key");
221
+ return parsed.privateKeyDer;
222
+ }
223
+ /**
224
+ * Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.
225
+ *
226
+ * @throws {Error} If the key is not an EC key
227
+ *
228
+ * @see {@linkcode importSec1Pem} for the inverse operation
229
+ * @see {@linkcode exportEncryptedSec1Pem} for password-protected export
230
+ */
231
+ async function exportSec1Pem(privateKey) {
232
+ return pemEncode("EC PRIVATE KEY", await exportSec1Der(privateKey));
233
+ }
234
+ /**
235
+ * Export an EC private key as legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
236
+ *
237
+ * Uses OpenSSL's traditional PEM encryption with MD5-based key derivation.
238
+ * For modern encryption, prefer {@linkcode exportEncryptedPkcs8Pem}.
239
+ *
240
+ * @throws {Error} If the key is not an EC key
241
+ *
242
+ * @see {@linkcode importEncryptedSec1Pem} for the inverse operation
243
+ */
244
+ async function exportEncryptedSec1Pem(privateKey, options) {
245
+ return encryptTraditionalPem("EC PRIVATE KEY", await exportSec1Der(privateKey), options);
246
+ }
247
+ /**
248
+ * Export a public key as PEM-encoded SubjectPublicKeyInfo.
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * const keys = await generateKeyPair();
253
+ * const pem = await exportSpkiPem(keys.publicKey);
254
+ * ```
255
+ */
256
+ async function exportSpkiPem(publicKey) {
257
+ return pemEncode("PUBLIC KEY", await exportSpkiDer(publicKey));
258
+ }
259
+ /**
260
+ * Derive the matching public key from an imported (or generated) private key.
261
+ *
262
+ * The `import*` functions that read a PKCS#8 / PKCS#1 / SEC 1 / JWK private key
263
+ * return a bare `CryptoKey` with only `sign` usage — there is no accompanying
264
+ * public handle. This bridges that gap: it exports the private key's JWK,
265
+ * strips the private components, and re-imports the public half with `verify`
266
+ * usage, so callers can go straight to {@linkcode exportSpkiDer} /
267
+ * {@linkcode exportSpkiPem} (e.g. to rebuild a self-signed cert or distribute
268
+ * the public key when only the private key is on disk).
269
+ *
270
+ * Supports RSA (`n`/`e`), ECDSA (`x`/`y`), and Ed25519 (`x`). The derived key
271
+ * inherits the private key's algorithm parameters (hash, curve).
272
+ *
273
+ * @param privateKey - An extractable private `CryptoKey`
274
+ * @returns Extractable public `CryptoKey` with `verify` usage
275
+ *
276
+ * @throws {Error} If the key is not a private key, is non-extractable, or uses
277
+ * an unsupported key type
278
+ *
279
+ * @example
280
+ * ```ts
281
+ * const privateKey = await importPkcs8PemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });
282
+ * const publicKey = await derivePublicKey(privateKey);
283
+ * const spkiPem = await exportSpkiPem(publicKey);
284
+ * ```
285
+ *
286
+ * @see {@linkcode exportSpkiDer} for exporting the derived key
287
+ */
288
+ async function derivePublicKey(privateKey) {
289
+ if (privateKey.type !== "private") throw new Error("derivePublicKey requires a private CryptoKey");
290
+ if (!privateKey.extractable) throw new Error("Cannot derive public key from a non-extractable private key");
291
+ const subtle = getCrypto().subtle;
292
+ const privateJwk = await subtle.exportKey("jwk", privateKey);
293
+ return subtle.importKey("jwk", toPublicJwk(privateJwk), privateKey.algorithm, true, ["verify"]);
294
+ }
295
+ /**
296
+ * Export a key as raw base64 (no PEM headers).
297
+ *
298
+ * Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys.
299
+ * Useful for compact storage or transmission where PEM overhead is undesirable.
300
+ *
301
+ * @throws {Error} If the key is a symmetric/secret key
302
+ *
303
+ * @see {@linkcode importSpkiBase64} for public key import
304
+ * @see {@linkcode importPkcs8Base64} for private key import
305
+ */
306
+ async function exportBinaryBase64(key) {
307
+ if (key.type === "public") return base64Encode(await exportSpkiDer(key));
308
+ if (key.type === "private") return base64Encode(await exportPkcs8Der(key));
309
+ throw new Error("Cannot export secret/symmetric CryptoKey");
310
+ }
311
+ /**
312
+ * Import a public key from DER-encoded SubjectPublicKeyInfo.
313
+ *
314
+ * When `algorithm` is omitted, the algorithm (and, for EC keys, the curve) is
315
+ * inferred from the SPKI's own AlgorithmIdentifier — useful for keys whose type
316
+ * isn't known ahead of time. Pass `algorithm` to additionally assert that the
317
+ * DER matches an expected algorithm.
318
+ *
319
+ * @param der - DER-encoded SubjectPublicKeyInfo bytes
320
+ * @param algorithm - Optional expected algorithm; must match key contents when given
321
+ * @returns Extractable CryptoKey with `verify` usage
322
+ *
323
+ * @throws {Error} If DER is malformed, encodes an unsupported algorithm, or doesn't match `algorithm`
324
+ *
325
+ * @see {@linkcode exportSpkiDer} for the inverse operation
326
+ * @see {@linkcode importSpkiPem} for PEM input
327
+ */
328
+ async function importSpkiDerOrThrow(der, algorithm) {
329
+ const parsedSpki = parseSpkiDer(der);
330
+ let importInput;
331
+ if (algorithm === void 0) importInput = inferPublicKeyImportInput(parsedSpki);
332
+ else {
333
+ assertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm);
334
+ importInput = algorithm;
335
+ }
336
+ try {
337
+ return await getCrypto().subtle.importKey("spki", new Uint8Array(der), toImportAlgorithm(importInput), true, ["verify"]);
338
+ } catch {
339
+ throw new Error("Malformed SubjectPublicKeyInfo");
340
+ }
341
+ }
342
+ /** Runs a throwing key import and maps an EXPECTED failure to a `'malformed'` result; invariants rethrow. */
343
+ async function importResult(run) {
344
+ try {
345
+ return successResult(await run());
346
+ } catch (error) {
347
+ rethrowIfInvariant(error);
348
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed key");
349
+ }
350
+ }
351
+ /** Like {@link importResult} but distinguishes a typed wrong-password failure (`'invalid_password'`). */
352
+ async function encryptedImportResult(run) {
353
+ try {
354
+ return successResult(await run());
355
+ } catch (error) {
356
+ rethrowIfInvariant(error);
357
+ if (isWrongPasswordError(error)) return failureResult("invalid_password", error.message);
358
+ return failureResult("malformed", error instanceof Error ? error.message : "Malformed encrypted key");
359
+ }
360
+ }
361
+ /**
362
+ * Import a public key from DER-encoded SubjectPublicKeyInfo.
363
+ *
364
+ * @see `importSpkiDerOrThrow` for the throwing variant
365
+ */
366
+ function importSpkiDer(der, algorithm) {
367
+ return importResult(() => importSpkiDerOrThrow(der, algorithm));
368
+ }
369
+ /**
370
+ * Import a public key from PEM-encoded SubjectPublicKeyInfo.
371
+ *
372
+ * @example
373
+ * ```ts
374
+ * const pem = `-----BEGIN PUBLIC KEY-----
375
+ * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
376
+ * -----END PUBLIC KEY-----`;
377
+ * const key = await importSpkiPem(pem, { kind: 'ecdsa', curve: 'P-256' });
378
+ * ```
379
+ *
380
+ * @see {@linkcode exportSpkiPem} for the inverse operation
381
+ */
382
+ function importSpkiPemOrThrow(pem, algorithm) {
383
+ return importSpkiDerOrThrow(pemDecodeOrThrow("PUBLIC KEY", pem), algorithm);
384
+ }
385
+ /**
386
+ * Import a public key from PEM-encoded SubjectPublicKeyInfo.
387
+ *
388
+ * @see `importSpkiPemOrThrow` for the throwing variant
389
+ */
390
+ function importSpkiPem(pem, algorithm) {
391
+ return importResult(() => importSpkiPemOrThrow(pem, algorithm));
392
+ }
393
+ /**
394
+ * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
395
+ *
396
+ * @see {@linkcode exportBinaryBase64} for the inverse operation
397
+ * @see {@linkcode importSpkiPem} for PEM input with headers
398
+ */
399
+ function importSpkiBase64OrThrow(base64, algorithm) {
400
+ let decoded;
401
+ try {
402
+ decoded = base64Decode(base64);
403
+ } catch {
404
+ throw new Error("Invalid base64 SubjectPublicKeyInfo");
405
+ }
406
+ return importSpkiDerOrThrow(decoded, algorithm);
407
+ }
408
+ /**
409
+ * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
410
+ *
411
+ * @see `importSpkiBase64OrThrow` for the throwing variant
412
+ */
413
+ function importSpkiBase64(base64, algorithm) {
414
+ return importResult(() => importSpkiBase64OrThrow(base64, algorithm));
415
+ }
416
+ /**
417
+ * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.
418
+ *
419
+ * @param der - DER-encoded PKCS#8 PrivateKeyInfo bytes
420
+ * @param algorithm - Expected algorithm (must match key contents)
421
+ * @returns Extractable CryptoKey with `sign` usage
422
+ *
423
+ * @throws {Error} If DER is malformed or algorithm doesn't match key
424
+ *
425
+ * @see {@linkcode exportPkcs8Der} for the inverse operation
426
+ * @see {@linkcode importPkcs8Pem} for PEM input
427
+ * @see {@linkcode importEncryptedPkcs8Der} for encrypted PKCS#8
428
+ */
429
+ async function importPkcs8DerOrThrow(der, algorithm) {
430
+ let parsedPrivateKey;
431
+ try {
432
+ parsedPrivateKey = parsePkcs8PrivateKey(der);
433
+ } catch {
434
+ throw new Error("Malformed PKCS#8 private key");
435
+ }
436
+ assertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm);
437
+ try {
438
+ return await getCrypto().subtle.importKey("pkcs8", new Uint8Array(der), toImportAlgorithm(algorithm), true, ["sign"]);
439
+ } catch {
440
+ throw new Error("Malformed PKCS#8 private key");
441
+ }
442
+ }
443
+ /**
444
+ * Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.
445
+ *
446
+ * @see `importPkcs8DerOrThrow` for the throwing variant
447
+ */
448
+ function importPkcs8Der(der, algorithm) {
449
+ return importResult(() => importPkcs8DerOrThrow(der, algorithm));
450
+ }
451
+ /**
452
+ * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
453
+ *
454
+ * @example
455
+ * ```ts
456
+ * const key = await importPkcs8Pem(pemString, { kind: 'ecdsa', curve: 'P-256' });
457
+ * ```
458
+ */
459
+ function importPkcs8PemOrThrow(pem, algorithm) {
460
+ return importPkcs8DerOrThrow(pemDecodeOrThrow("PRIVATE KEY", pem), algorithm);
461
+ }
462
+ /**
463
+ * Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
464
+ *
465
+ * @see `importPkcs8PemOrThrow` for the throwing variant
466
+ */
467
+ function importPkcs8Pem(pem, algorithm) {
468
+ return importResult(() => importPkcs8PemOrThrow(pem, algorithm));
469
+ }
470
+ /**
471
+ * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
472
+ *
473
+ * Decrypts the PBES2 envelope using the provided password, then imports the key.
474
+ *
475
+ * @param der - DER-encoded EncryptedPrivateKeyInfo bytes
476
+ * @param password - Decryption password
477
+ * @param algorithm - Expected algorithm (must match decrypted key)
478
+ *
479
+ * @throws {Error} If DER is malformed, password is wrong, or algorithm doesn't match
480
+ *
481
+ * @see {@linkcode exportEncryptedPkcs8Der} for the inverse operation
482
+ */
483
+ async function importEncryptedPkcs8DerOrThrow(der, password, algorithm) {
484
+ let children;
485
+ try {
486
+ children = readSequenceChildren(der);
487
+ } catch {
488
+ throw new Error("Malformed EncryptedPrivateKeyInfo");
489
+ }
490
+ const algorithmIdentifier = children[0];
491
+ const encryptedData = children[1];
492
+ if (children.length !== 2 || algorithmIdentifier === void 0 || encryptedData === void 0 || encryptedData.tag !== 4) throw new Error("Malformed EncryptedPrivateKeyInfo");
493
+ const decrypted = await decryptPbes2(der.slice(algorithmIdentifier.start - algorithmIdentifier.headerLength, algorithmIdentifier.end), encryptedData.value, password);
494
+ try {
495
+ parsePkcs8PrivateKey(decrypted);
496
+ } catch {
497
+ throw wrongPasswordError("Invalid password or encrypted content");
498
+ }
499
+ return importPkcs8DerOrThrow(decrypted, algorithm);
500
+ }
501
+ /**
502
+ * Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
503
+ *
504
+ * @see `importEncryptedPkcs8DerOrThrow` for the throwing variant
505
+ */
506
+ function importEncryptedPkcs8Der(der, password, algorithm) {
507
+ return encryptedImportResult(() => importEncryptedPkcs8DerOrThrow(der, password, algorithm));
508
+ }
509
+ /**
510
+ * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * const key = await importEncryptedPkcs8Pem(pem, 'secret', { kind: 'rsa' });
515
+ * ```
516
+ */
517
+ function importEncryptedPkcs8PemOrThrow(pem, password, algorithm) {
518
+ return importEncryptedPkcs8DerOrThrow(pemDecodeOrThrow("ENCRYPTED PRIVATE KEY", pem), password, algorithm);
519
+ }
520
+ /**
521
+ * Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
522
+ *
523
+ * @see `importEncryptedPkcs8PemOrThrow` for the throwing variant
524
+ */
525
+ function importEncryptedPkcs8Pem(pem, password, algorithm) {
526
+ return encryptedImportResult(() => importEncryptedPkcs8PemOrThrow(pem, password, algorithm));
527
+ }
528
+ /**
529
+ * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
530
+ *
531
+ * PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.
532
+ *
533
+ * @see {@linkcode exportPkcs1Der} for the inverse operation
534
+ * @see {@linkcode importPkcs1Pem} for PEM input
535
+ */
536
+ function importPkcs1DerOrThrow(der, algorithm = { kind: "rsa" }) {
537
+ return importPkcs8DerOrThrow(wrapPkcs1InPkcs8(der), algorithm);
538
+ }
539
+ /**
540
+ * Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
541
+ *
542
+ * @see `importPkcs1DerOrThrow` for the throwing variant
543
+ */
544
+ function importPkcs1Der(der, algorithm = { kind: "rsa" }) {
545
+ return importResult(() => importPkcs1DerOrThrow(der, algorithm));
546
+ }
547
+ /**
548
+ * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
549
+ *
550
+ * Expects the `-----BEGIN RSA PRIVATE KEY-----` PEM label.
551
+ *
552
+ * @see {@linkcode exportPkcs1Pem} for the inverse operation
553
+ * @see {@linkcode importEncryptedPkcs1Pem} for encrypted PEM
554
+ */
555
+ function importPkcs1PemOrThrow(pem, algorithm = { kind: "rsa" }) {
556
+ return importPkcs1DerOrThrow(pemDecodeOrThrow("RSA PRIVATE KEY", pem), algorithm);
557
+ }
558
+ /**
559
+ * Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
560
+ *
561
+ * @see `importPkcs1PemOrThrow` for the throwing variant
562
+ */
563
+ function importPkcs1Pem(pem, algorithm = { kind: "rsa" }) {
564
+ return importResult(() => importPkcs1PemOrThrow(pem, algorithm));
565
+ }
566
+ /**
567
+ * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
568
+ *
569
+ * Decrypts OpenSSL's traditional PEM encryption format.
570
+ *
571
+ * @see {@linkcode exportEncryptedPkcs1Pem} for the inverse operation
572
+ * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption
573
+ */
574
+ async function importEncryptedPkcs1PemOrThrow(pem, password, algorithm = { kind: "rsa" }) {
575
+ return importPkcs1DerOrThrow(await decryptTraditionalPem("RSA PRIVATE KEY", pem, password), algorithm);
576
+ }
577
+ /**
578
+ * Import an RSA private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (PKCS#1).
579
+ *
580
+ * @see `importEncryptedPkcs1PemOrThrow` for the throwing variant
581
+ */
582
+ function importEncryptedPkcs1Pem(pem, password, algorithm = { kind: "rsa" }) {
583
+ return encryptedImportResult(() => importEncryptedPkcs1PemOrThrow(pem, password, algorithm));
584
+ }
585
+ /**
586
+ * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
587
+ *
588
+ * @see {@linkcode exportBinaryBase64} for the inverse operation
589
+ * @see {@linkcode importPkcs8Pem} for PEM input with headers
590
+ */
591
+ function importPkcs8Base64OrThrow(base64, algorithm) {
592
+ let decoded;
593
+ try {
594
+ decoded = base64Decode(base64);
595
+ } catch {
596
+ throw new Error("Invalid base64 PKCS#8 private key");
597
+ }
598
+ return importPkcs8DerOrThrow(decoded, algorithm);
599
+ }
600
+ /**
601
+ * Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
602
+ *
603
+ * @see `importPkcs8Base64OrThrow` for the throwing variant
604
+ */
605
+ function importPkcs8Base64(base64, algorithm) {
606
+ return importResult(() => importPkcs8Base64OrThrow(base64, algorithm));
607
+ }
608
+ /**
609
+ * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
610
+ *
611
+ * SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import.
612
+ * When the ECPrivateKey carries the optional RFC 5915 `parameters [0]` field
613
+ * (OpenSSL always writes it), its named-curve OID must match `algorithm.curve`;
614
+ * when the field is absent, the caller-supplied curve is trusted.
615
+ *
616
+ * @throws {Error} If DER is not an ECPrivateKey or its embedded curve doesn't match `algorithm`
617
+ *
618
+ * @see {@linkcode exportSec1Der} for the inverse operation
619
+ * @see {@linkcode importSec1Pem} for PEM input
620
+ */
621
+ async function importSec1DerOrThrow(der, algorithm) {
622
+ let parsedSec1;
623
+ try {
624
+ parsedSec1 = parseSec1PrivateKey(der);
625
+ } catch {
626
+ throw new Error("Malformed SEC 1 private key");
627
+ }
628
+ assertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm);
629
+ return await importPkcs8DerOrThrow(wrapSec1InPkcs8(der, algorithm.curve), algorithm);
630
+ }
631
+ /**
632
+ * Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
633
+ *
634
+ * @see `importSec1DerOrThrow` for the throwing variant
635
+ */
636
+ function importSec1Der(der, algorithm) {
637
+ return importResult(() => importSec1DerOrThrow(der, algorithm));
638
+ }
639
+ /**
640
+ * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
641
+ *
642
+ * Expects the `-----BEGIN EC PRIVATE KEY-----` PEM label.
643
+ *
644
+ * @see {@linkcode exportSec1Pem} for the inverse operation
645
+ * @see {@linkcode importEncryptedSec1Pem} for encrypted PEM
646
+ */
647
+ function importSec1PemOrThrow(pem, algorithm) {
648
+ return importSec1DerOrThrow(pemDecodeOrThrow("EC PRIVATE KEY", pem), algorithm);
649
+ }
650
+ /**
651
+ * Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
652
+ *
653
+ * @see `importSec1PemOrThrow` for the throwing variant
654
+ */
655
+ function importSec1Pem(pem, algorithm) {
656
+ return importResult(() => importSec1PemOrThrow(pem, algorithm));
657
+ }
658
+ /**
659
+ * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
660
+ *
661
+ * Decrypts OpenSSL's traditional PEM encryption format.
662
+ *
663
+ * @see {@linkcode exportEncryptedSec1Pem} for the inverse operation
664
+ * @see {@linkcode importEncryptedPkcs8Pem} for modern PBES2 encryption
665
+ */
666
+ async function importEncryptedSec1PemOrThrow(pem, password, algorithm) {
667
+ return importSec1DerOrThrow(await decryptTraditionalPem("EC PRIVATE KEY", pem, password), algorithm);
668
+ }
669
+ /**
670
+ * Import an EC private key from legacy `Proc-Type: 4,ENCRYPTED` PEM (SEC 1).
671
+ *
672
+ * @see `importEncryptedSec1PemOrThrow` for the throwing variant
673
+ */
674
+ function importEncryptedSec1Pem(pem, password, algorithm) {
675
+ return encryptedImportResult(() => importEncryptedSec1PemOrThrow(pem, password, algorithm));
676
+ }
677
+ /**
678
+ * Import a public verification key from a JSON Web Key.
679
+ *
680
+ * @param jwk - JSON Web Key object with public key components
681
+ * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)
682
+ * @returns Extractable CryptoKey with `verify` usage
683
+ *
684
+ * @throws {Error} If JWK is malformed or algorithm doesn't match
685
+ *
686
+ * @see {@linkcode exportPublicJwk} for the inverse operation
687
+ */
688
+ async function importPublicJwkOrThrow(jwk, algorithm) {
689
+ assertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm);
690
+ try {
691
+ return await getCrypto().subtle.importKey("jwk", jwk, toImportAlgorithm(algorithm), true, ["verify"]);
692
+ } catch {
693
+ throw new Error("Malformed public JWK");
694
+ }
695
+ }
696
+ /**
697
+ * Import a public verification key from a JSON Web Key.
698
+ *
699
+ * @see `importPublicJwkOrThrow` for the throwing variant
700
+ */
701
+ function importPublicJwk(jwk, algorithm) {
702
+ return importResult(() => importPublicJwkOrThrow(jwk, algorithm));
703
+ }
704
+ /**
705
+ * Import a private signing key from a JSON Web Key.
706
+ *
707
+ * @param jwk - JSON Web Key object with private key components
708
+ * @param algorithm - Expected algorithm (must match JWK's `kty` and `crv`)
709
+ * @returns Extractable CryptoKey with `sign` usage
710
+ *
711
+ * @throws {Error} If JWK is malformed, lacks private key material, or algorithm doesn't match
712
+ *
713
+ * @example
714
+ * ```ts
715
+ * const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };
716
+ * const key = await importPrivateJwk(jwk, { kind: 'ecdsa', curve: 'P-256' });
717
+ * ```
718
+ *
719
+ * @see {@linkcode exportPrivateJwk} for the inverse operation
720
+ */
721
+ async function importPrivateJwkOrThrow(jwk, algorithm) {
722
+ assertPrivateJwkMatchesRequestedAlgorithm(jwk, algorithm);
723
+ try {
724
+ return await getCrypto().subtle.importKey("jwk", jwk, toImportAlgorithm(algorithm), true, ["sign"]);
725
+ } catch {
726
+ throw new Error("Malformed private JWK");
727
+ }
728
+ }
729
+ /**
730
+ * Import a private signing key from a JSON Web Key.
731
+ *
732
+ * @see `importPrivateJwkOrThrow` for the throwing variant
733
+ */
734
+ function importPrivateJwk(jwk, algorithm) {
735
+ return importResult(() => importPrivateJwkOrThrow(jwk, algorithm));
736
+ }
737
+ /** Map a {@linkcode KeyAlgorithmInput} to the WebCrypto `generateKey` algorithm parameter. */
738
+ function toGenerateKeyAlgorithm(algorithm) {
739
+ switch (algorithm.kind) {
740
+ case "rsa": return {
741
+ name: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),
742
+ modulusLength: algorithm.modulusLength ?? 2048,
743
+ publicExponent: Uint8Array.of(1, 0, 1),
744
+ hash: algorithm.hash ?? "SHA-256"
745
+ };
746
+ case "ecdsa": return {
747
+ name: "ECDSA",
748
+ namedCurve: algorithm.curve ?? "P-256"
749
+ };
750
+ case "ed25519": return { name: "Ed25519" };
751
+ }
752
+ }
753
+ /** Map a {@linkcode PublicKeyImportInput} to the WebCrypto `importKey` algorithm parameter. */
754
+ function toImportAlgorithm(algorithm) {
755
+ switch (algorithm.kind) {
756
+ case "rsa": return {
757
+ name: rsaSchemeToWebCryptoAlgorithmName(algorithm.scheme),
758
+ hash: algorithm.hash ?? "SHA-256"
759
+ };
760
+ case "ecdsa": return {
761
+ name: "ECDSA",
762
+ namedCurve: algorithm.curve
763
+ };
764
+ case "ed25519": return { name: "Ed25519" };
765
+ }
766
+ }
767
+ /** Extract algorithm OID and inner key bytes from a PKCS#8 PrivateKeyInfo envelope. */
768
+ function parsePkcs8PrivateKey(der) {
769
+ const children = readSequenceChildren(der);
770
+ const algorithm = children[1];
771
+ const privateKey = children[2];
772
+ if (children.length < 3 || children.length > 4 || algorithm === void 0 || algorithm.tag !== 48 || privateKey === void 0 || privateKey.tag !== 4) throw new Error("Malformed PKCS#8 private key");
773
+ const algorithmChildren = readSequenceChildren(der.slice(algorithm.start - algorithm.headerLength, algorithm.end));
774
+ const algorithmOid = algorithmChildren[0];
775
+ if (algorithmOid === void 0 || algorithmOid.tag !== 6 || algorithmChildren.length < 1 || algorithmChildren.length > 2) throw new Error("Malformed PKCS#8 private key");
776
+ const parameters = algorithmChildren[1];
777
+ return {
778
+ algorithmOid: decodeObjectIdentifier(algorithmOid.value),
779
+ ...parameters === void 0 ? {} : { parametersTag: parameters.tag },
780
+ ...parameters?.tag === 6 ? { parametersOid: decodeObjectIdentifier(parameters.value) } : {},
781
+ privateKeyDer: privateKey.value
782
+ };
783
+ }
784
+ /**
785
+ * Extract the optional `parameters [0]` curve identifier from a SEC 1 ECPrivateKey.
786
+ *
787
+ * RFC 5915: `ECPrivateKey ::= SEQUENCE { version INTEGER, privateKey OCTET STRING,
788
+ * parameters [0] ECParameters OPTIONAL, publicKey [1] BIT STRING OPTIONAL }`.
789
+ */
790
+ function parseSec1PrivateKey(der) {
791
+ const children = readSequenceChildren(der);
792
+ const version = children[0];
793
+ const privateKey = children[1];
794
+ const third = children[2];
795
+ const fourth = children[3];
796
+ if (children.length < 2 || children.length > 4 || version === void 0 || version.tag !== 2 || privateKey === void 0 || privateKey.tag !== 4 || third !== void 0 && third.tag !== 160 && third.tag !== 161 || fourth !== void 0 && (third?.tag !== 160 || fourth.tag !== 161)) throw new Error("Malformed SEC 1 private key");
797
+ const parameters = third?.tag === 160 ? third : void 0;
798
+ if (parameters === void 0) return {};
799
+ const ecParameters = readRootElement(parameters.value);
800
+ return {
801
+ parametersTag: ecParameters.tag,
802
+ ...ecParameters.tag === 6 ? { parametersOid: decodeObjectIdentifier(ecParameters.value) } : {}
803
+ };
804
+ }
805
+ /** Wrap a PKCS#1 RSAPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */
806
+ function wrapPkcs1InPkcs8(der) {
807
+ return sequence([
808
+ Uint8Array.of(2, 1, 0),
809
+ sequence([objectIdentifier(OIDS.rsaEncryption), nullValue()]),
810
+ octetString(new Uint8Array(der))
811
+ ]);
812
+ }
813
+ /** Wrap a SEC 1 ECPrivateKey in a PKCS#8 PrivateKeyInfo envelope for WebCrypto import. */
814
+ function wrapSec1InPkcs8(der, curve) {
815
+ return sequence([
816
+ Uint8Array.of(2, 1, 0),
817
+ sequence([objectIdentifier(OIDS.ecPublicKey), objectIdentifier(curveToOid(curve))]),
818
+ octetString(new Uint8Array(der))
819
+ ]);
820
+ }
821
+ /** Project a private JWK onto its public-only members, discarding private key material. */
822
+ function toPublicJwk(jwk) {
823
+ if (jwk.kty !== "RSA" && jwk.kty !== "EC" && jwk.kty !== "OKP") throw new Error(`Cannot derive public key: unsupported JWK key type ${String(jwk.kty)}`);
824
+ const publicJwk = { ...jwk };
825
+ for (const field of [
826
+ "d",
827
+ "p",
828
+ "q",
829
+ "dp",
830
+ "dq",
831
+ "qi",
832
+ "oth",
833
+ "k"
834
+ ]) delete publicJwk[field];
835
+ publicJwk.key_ops = ["verify"];
836
+ publicJwk.ext = true;
837
+ return publicJwk;
838
+ }
839
+ /**
840
+ * Single source of truth for the NIST curve ↔ named-curve OID mapping, read in
841
+ * both directions by {@linkcode curveToOid} and {@linkcode oidToCurve}.
842
+ */
843
+ const EC_CURVE_OIDS = [
844
+ ["P-256", OIDS.prime256v1],
845
+ ["P-384", OIDS.secp384r1],
846
+ ["P-521", OIDS.secp521r1]
847
+ ];
848
+ /** Map a curve name to its ASN.1 OID string. */
849
+ function curveToOid(curve) {
850
+ for (const [name, oid] of EC_CURVE_OIDS) if (name === curve) return oid;
851
+ throw new Error(`Unsupported EC curve: ${curve}`);
852
+ }
853
+ /** Map an ASN.1 curve OID string back to its curve name, or `undefined` if unrecognized. */
854
+ function oidToCurve(oid) {
855
+ for (const [name, curveOid] of EC_CURVE_OIDS) if (curveOid === oid) return name;
856
+ }
857
+ /** Map an {@linkcode RsaScheme} to the WebCrypto algorithm name string. */
858
+ function rsaSchemeToWebCryptoAlgorithmName(scheme) {
859
+ if (scheme === "pss") return "RSA-PSS";
860
+ return "RSASSA-PKCS1-v1_5";
861
+ }
862
+ /** Encrypt DER key material as an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block. */
863
+ async function encryptTraditionalPem(label, der, options) {
864
+ const iv = options.iv ?? getCrypto().getRandomValues(/* @__PURE__ */ new Uint8Array(16));
865
+ if (iv.length !== 16) throw new Error("Traditional PEM encryption requires a 16-byte IV");
866
+ const cipher = options.cipher ?? "AES-256-CBC";
867
+ const key = await importTraditionalPemAesKey(options.password, iv.slice(0, 8), cipher, ["encrypt"]);
868
+ const body = base64Encode(new Uint8Array(await getCrypto().subtle.encrypt({
869
+ name: "AES-CBC",
870
+ iv: toArrayBuffer(iv)
871
+ }, key, toArrayBuffer(der)))).match(/.{1,64}/g)?.join("\n") ?? "";
872
+ return [
873
+ `-----BEGIN ${label}-----`,
874
+ "Proc-Type: 4,ENCRYPTED",
875
+ `DEK-Info: ${cipher},${toHex(iv).toUpperCase()}`,
876
+ "",
877
+ body,
878
+ `-----END ${label}-----`
879
+ ].join("\n");
880
+ }
881
+ /** Decrypt an OpenSSL-style `Proc-Type: 4,ENCRYPTED` PEM block back to plaintext DER. */
882
+ async function decryptTraditionalPem(expectedLabel, pem, password) {
883
+ const parsed = parseTraditionalPem(pem);
884
+ if (parsed.label !== expectedLabel) throw new Error(`Expected ${expectedLabel} PEM block`);
885
+ const dekInfo = parsed.headers.get("DEK-Info");
886
+ if (parsed.headers.get("Proc-Type") !== "4,ENCRYPTED" || dekInfo === void 0) throw new Error("Traditional PEM encryption headers missing");
887
+ const [cipher, ivHex] = dekInfo.split(",");
888
+ if (!isTraditionalPemCipher(cipher) || ivHex === void 0) throw new Error("Only AES-128-CBC, AES-192-CBC, and AES-256-CBC traditional PEM encryption is supported");
889
+ if (!isTraditionalPemIvHex(ivHex)) throw new Error("Traditional PEM encryption requires a 16-byte IV encoded as 32 hex characters");
890
+ const iv = hexToBytes(ivHex);
891
+ const key = await importTraditionalPemAesKey(password, iv.slice(0, 8), cipher, ["decrypt"]);
892
+ try {
893
+ return new Uint8Array(await getCrypto().subtle.decrypt({
894
+ name: "AES-CBC",
895
+ iv: toArrayBuffer(iv)
896
+ }, key, toArrayBuffer(base64Decode(parsed.base64Body))));
897
+ } catch {
898
+ throw wrongPasswordError("Invalid password or encrypted PEM content");
899
+ }
900
+ }
901
+ /** Derive and import an AES-CBC key for legacy PEM encryption using OpenSSL `EVP_BytesToKey`. */
902
+ function importTraditionalPemAesKey(password, salt, cipher, usages) {
903
+ const keyLength = traditionalPemCipherKeyLength(cipher);
904
+ const keyBytes = opensslBytesToKey(password, salt, keyLength / 8);
905
+ return getCrypto().subtle.importKey("raw", toArrayBuffer(keyBytes), {
906
+ name: "AES-CBC",
907
+ length: keyLength
908
+ }, false, usages);
909
+ }
910
+ /** Type guard for the three AES-CBC ciphers supported by legacy PEM encryption. */
911
+ function isTraditionalPemCipher(cipher) {
912
+ return cipher === "AES-128-CBC" || cipher === "AES-192-CBC" || cipher === "AES-256-CBC";
913
+ }
914
+ function isTraditionalPemIvHex(value) {
915
+ return value.length === 32 && /^[0-9A-Fa-f]+$/.test(value);
916
+ }
917
+ /** Return the AES key size in bits for a given cipher name. */
918
+ function traditionalPemCipherKeyLength(cipher) {
919
+ switch (cipher) {
920
+ case "AES-128-CBC": return 128;
921
+ case "AES-192-CBC": return 192;
922
+ case "AES-256-CBC": return 256;
923
+ }
924
+ }
925
+ /** OpenSSL `EVP_BytesToKey` with MD5 — derives a fixed-length key from password + salt. */
926
+ function opensslBytesToKey(password, salt, length) {
927
+ const passwordBytes = new TextEncoder().encode(password);
928
+ const chunks = [];
929
+ let previous = /* @__PURE__ */ new Uint8Array();
930
+ let total = 0;
931
+ while (total < length) {
932
+ const input = new Uint8Array(previous.length + passwordBytes.length + salt.length);
933
+ input.set(previous, 0);
934
+ input.set(passwordBytes, previous.length);
935
+ input.set(salt, previous.length + passwordBytes.length);
936
+ previous = md5(input);
937
+ chunks.push(previous);
938
+ total += previous.length;
939
+ }
940
+ const out = new Uint8Array(length);
941
+ let offset = 0;
942
+ for (const chunk of chunks) {
943
+ const slice = chunk.slice(0, Math.min(chunk.length, length - offset));
944
+ out.set(slice, offset);
945
+ offset += slice.length;
946
+ if (offset >= length) break;
947
+ }
948
+ return out;
949
+ }
950
+ /** Parse a PEM block into its label, RFC 1421 headers, and base64 body. */
951
+ function parseTraditionalPem(pem) {
952
+ const lines = pem.replace(/\r/g, "").trim().split("\n");
953
+ const begin = lines[0];
954
+ const end = lines[lines.length - 1];
955
+ if (begin === void 0 || end === void 0 || !begin.startsWith("-----BEGIN ") || !end.startsWith("-----END ")) throw new Error("Invalid PEM block");
956
+ const label = begin.slice(11, -5);
957
+ if (end !== `-----END ${label}-----`) throw new Error("PEM boundaries do not match");
958
+ const headers = /* @__PURE__ */ new Map();
959
+ let index = 1;
960
+ while (index < lines.length - 1) {
961
+ const line = lines[index];
962
+ if (line === void 0) break;
963
+ if (line.length === 0) {
964
+ index += 1;
965
+ break;
966
+ }
967
+ const delimiter = line.indexOf(": ");
968
+ if (delimiter === -1) break;
969
+ const headerName = line.slice(0, delimiter);
970
+ if (headers.has(headerName)) throw new Error(`Duplicate PEM header: ${headerName}`);
971
+ headers.set(headerName, line.slice(delimiter + 2));
972
+ index += 1;
973
+ }
974
+ return {
975
+ label,
976
+ headers,
977
+ base64Body: lines.slice(index, lines.length - 1).join("")
978
+ };
979
+ }
980
+ function parseSpkiDer(der) {
981
+ try {
982
+ const children = readSequenceChildren(der);
983
+ if (children.length !== 2) throw new Error("Malformed SubjectPublicKeyInfo");
984
+ const algorithm = children[0];
985
+ const subjectPublicKey = children[1];
986
+ if (algorithm === void 0 || algorithm.tag !== 48 || subjectPublicKey === void 0 || subjectPublicKey.tag !== 3) throw new Error("Malformed SubjectPublicKeyInfo");
987
+ extractBitStringValue(subjectPublicKey);
988
+ const algorithmChildren = readSequenceChildren(der.slice(algorithm.start - algorithm.headerLength, algorithm.end));
989
+ const algorithmOid = algorithmChildren[0];
990
+ if (algorithmOid === void 0 || algorithmOid.tag !== 6 || algorithmChildren.length < 1 || algorithmChildren.length > 2) throw new Error("Malformed SubjectPublicKeyInfo");
991
+ const parameters = algorithmChildren[1];
992
+ return {
993
+ algorithmOid: decodeObjectIdentifier(algorithmOid.value),
994
+ ...parameters === void 0 ? {} : { parametersTag: parameters.tag },
995
+ ...parameters?.tag === 6 ? { parametersOid: decodeObjectIdentifier(parameters.value) } : {}
996
+ };
997
+ } catch {
998
+ throw new Error("Malformed SubjectPublicKeyInfo");
999
+ }
1000
+ }
1001
+ /**
1002
+ * Derive the import algorithm from a parsed SPKI's own AlgorithmIdentifier.
1003
+ *
1004
+ * RSA keys default to the `pkcs1-v1_5`/`SHA-256` import parameters (a plain
1005
+ * `rsaEncryption` SPKI does not encode padding scheme or hash); EC keys carry
1006
+ * their curve in the DER; Ed25519 is fully determined by its OID.
1007
+ */
1008
+ function inferPublicKeyImportInput(parsedSpki) {
1009
+ switch (parsedSpki.algorithmOid) {
1010
+ case OIDS.rsaEncryption:
1011
+ if (parsedSpki.parametersTag === void 0 || parsedSpki.parametersTag === 5) return { kind: "rsa" };
1012
+ break;
1013
+ case OIDS.ecPublicKey: {
1014
+ const curve = parsedSpki.parametersTag === 6 && parsedSpki.parametersOid !== void 0 ? oidToCurve(parsedSpki.parametersOid) : void 0;
1015
+ if (curve !== void 0) return {
1016
+ kind: "ecdsa",
1017
+ curve
1018
+ };
1019
+ break;
1020
+ }
1021
+ case OIDS.ed25519:
1022
+ if (parsedSpki.parametersTag === void 0) return { kind: "ed25519" };
1023
+ break;
1024
+ }
1025
+ throw new Error("Unsupported SubjectPublicKeyInfo algorithm");
1026
+ }
1027
+ function assertSpkiMatchesRequestedAlgorithm(parsedSpki, algorithm) {
1028
+ switch (algorithm.kind) {
1029
+ case "rsa":
1030
+ if (parsedSpki.algorithmOid !== OIDS.rsaEncryption || parsedSpki.parametersTag !== void 0 && parsedSpki.parametersTag !== 5) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1031
+ return;
1032
+ case "ecdsa":
1033
+ if (parsedSpki.algorithmOid !== OIDS.ecPublicKey || parsedSpki.parametersTag !== 6 || parsedSpki.parametersOid !== curveToOid(algorithm.curve)) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1034
+ return;
1035
+ case "ed25519":
1036
+ if (parsedSpki.algorithmOid !== OIDS.ed25519 || parsedSpki.parametersTag !== void 0) throw new Error("SubjectPublicKeyInfo algorithm does not match requested import algorithm");
1037
+ return;
1038
+ }
1039
+ }
1040
+ function assertPkcs8MatchesRequestedAlgorithm(parsedPrivateKey, algorithm) {
1041
+ switch (algorithm.kind) {
1042
+ case "rsa":
1043
+ if (parsedPrivateKey.algorithmOid !== OIDS.rsaEncryption || parsedPrivateKey.parametersTag !== void 0 && parsedPrivateKey.parametersTag !== 5) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1044
+ return;
1045
+ case "ecdsa":
1046
+ if (parsedPrivateKey.algorithmOid !== OIDS.ecPublicKey || parsedPrivateKey.parametersTag !== 6 || parsedPrivateKey.parametersOid !== curveToOid(algorithm.curve)) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1047
+ return;
1048
+ case "ed25519":
1049
+ if (parsedPrivateKey.algorithmOid !== OIDS.ed25519 || parsedPrivateKey.parametersTag !== void 0) throw new Error("PKCS#8 private key algorithm does not match requested import algorithm");
1050
+ return;
1051
+ }
1052
+ }
1053
+ function assertSec1MatchesRequestedAlgorithm(parsedSec1, algorithm) {
1054
+ if (parsedSec1.parametersTag === void 0) return;
1055
+ if (parsedSec1.parametersTag !== 6 || parsedSec1.parametersOid !== curveToOid(algorithm.curve)) throw new Error("SEC 1 private key curve does not match requested import algorithm");
1056
+ }
1057
+ function assertPublicJwkMatchesRequestedAlgorithm(jwk, algorithm) {
1058
+ if (jwk.k !== void 0 || jwk.d !== void 0 || jwk.p !== void 0 || jwk.q !== void 0 || jwk.dp !== void 0 || jwk.dq !== void 0 || jwk.qi !== void 0 || jwk.oth !== void 0) throw new Error("Public JWK must not contain private key material");
1059
+ switch (algorithm.kind) {
1060
+ case "rsa":
1061
+ if (jwk.kty !== "RSA" || typeof jwk.n !== "string" || typeof jwk.e !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1062
+ return;
1063
+ case "ecdsa":
1064
+ if (jwk.kty !== "EC" || jwk.crv !== algorithm.curve || typeof jwk.x !== "string" || typeof jwk.y !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1065
+ return;
1066
+ case "ed25519":
1067
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") throw new Error("Public JWK algorithm does not match requested import algorithm");
1068
+ return;
1069
+ }
1070
+ }
1071
+ function assertPrivateJwkMatchesRequestedAlgorithm(jwk, algorithm) {
1072
+ if (jwk.k !== void 0 || jwk.oth !== void 0) throw new Error("Private JWK must not contain symmetric or multi-prime key material");
1073
+ if (typeof jwk.d !== "string") throw new Error("Private JWK must contain private key material");
1074
+ switch (algorithm.kind) {
1075
+ case "rsa":
1076
+ if (jwk.kty !== "RSA" || typeof jwk.n !== "string" || typeof jwk.e !== "string" || typeof jwk.p !== "string" || typeof jwk.q !== "string" || typeof jwk.dp !== "string" || typeof jwk.dq !== "string" || typeof jwk.qi !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1077
+ return;
1078
+ case "ecdsa":
1079
+ if (jwk.kty !== "EC" || jwk.crv !== algorithm.curve || typeof jwk.x !== "string" || typeof jwk.y !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1080
+ return;
1081
+ case "ed25519":
1082
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.x !== "string") throw new Error("Private JWK algorithm does not match requested import algorithm");
1083
+ return;
1084
+ }
1085
+ }
1086
+ //#endregion
1087
+ export { derivePublicKey, exportBinaryBase64, exportEncryptedPkcs1Pem, exportEncryptedPkcs8Der, exportEncryptedPkcs8Pem, exportEncryptedSec1Pem, exportPkcs1Der, exportPkcs1Pem, exportPkcs8Der, exportPkcs8Pem, exportPrivateJwk, exportPublicJwk, exportSec1Der, exportSec1Pem, exportSpkiDer, exportSpkiPem, generateKeyPair, importEncryptedPkcs1Pem, importEncryptedPkcs1PemOrThrow, importEncryptedPkcs8Der, importEncryptedPkcs8DerOrThrow, importEncryptedPkcs8Pem, importEncryptedPkcs8PemOrThrow, importEncryptedSec1Pem, importEncryptedSec1PemOrThrow, importPkcs1Der, importPkcs1DerOrThrow, importPkcs1Pem, importPkcs1PemOrThrow, importPkcs8Base64, importPkcs8Base64OrThrow, importPkcs8Der, importPkcs8DerOrThrow, importPkcs8Pem, importPkcs8PemOrThrow, importPrivateJwk, importPrivateJwkOrThrow, importPublicJwk, importPublicJwkOrThrow, importSec1Der, importSec1DerOrThrow, importSec1Pem, importSec1PemOrThrow, importSpkiBase64, importSpkiBase64OrThrow, importSpkiDer, importSpkiDerOrThrow, importSpkiPem, importSpkiPemOrThrow };