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