x509.cjs.js 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445
  1. /*!
  2. * MIT License
  3. *
  4. * Copyright (c) Peculiar Ventures. All rights reserved.
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. *
  24. */
  25. 'use strict';
  26. require('reflect-metadata');
  27. var asn1Schema = require('@peculiar/asn1-schema');
  28. var asn1X509 = require('@peculiar/asn1-x509');
  29. var pvtsutils = require('pvtsutils');
  30. var tslib = require('tslib');
  31. var asn1Cms = require('@peculiar/asn1-cms');
  32. var asn1Ecc = require('@peculiar/asn1-ecc');
  33. var asn1Rsa = require('@peculiar/asn1-rsa');
  34. var tsyringe = require('tsyringe');
  35. var asnPkcs9 = require('@peculiar/asn1-pkcs9');
  36. var asn1Csr = require('@peculiar/asn1-csr');
  37. function _interopNamespaceDefault(e) {
  38. var n = Object.create(null);
  39. if (e) {
  40. Object.keys(e).forEach(function (k) {
  41. if (k !== 'default') {
  42. var d = Object.getOwnPropertyDescriptor(e, k);
  43. Object.defineProperty(n, k, d.get ? d : {
  44. enumerable: true,
  45. get: function () { return e[k]; }
  46. });
  47. }
  48. });
  49. }
  50. n.default = e;
  51. return Object.freeze(n);
  52. }
  53. var asn1X509__namespace = /*#__PURE__*/_interopNamespaceDefault(asn1X509);
  54. var asn1Cms__namespace = /*#__PURE__*/_interopNamespaceDefault(asn1Cms);
  55. var asn1Ecc__namespace = /*#__PURE__*/_interopNamespaceDefault(asn1Ecc);
  56. var asn1Rsa__namespace = /*#__PURE__*/_interopNamespaceDefault(asn1Rsa);
  57. var asnPkcs9__namespace = /*#__PURE__*/_interopNamespaceDefault(asnPkcs9);
  58. const diAlgorithm = "crypto.algorithm";
  59. class AlgorithmProvider {
  60. getAlgorithms() {
  61. return tsyringe.container.resolveAll(diAlgorithm);
  62. }
  63. toAsnAlgorithm(alg) {
  64. ({ ...alg });
  65. for (const algorithm of this.getAlgorithms()) {
  66. const res = algorithm.toAsnAlgorithm(alg);
  67. if (res) {
  68. return res;
  69. }
  70. }
  71. if (/^[0-9.]+$/.test(alg.name)) {
  72. const res = new asn1X509.AlgorithmIdentifier({ algorithm: alg.name });
  73. if ("parameters" in alg) {
  74. const unknown = alg;
  75. res.parameters = unknown.parameters;
  76. }
  77. return res;
  78. }
  79. throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm");
  80. }
  81. toWebAlgorithm(alg) {
  82. for (const algorithm of this.getAlgorithms()) {
  83. const res = algorithm.toWebAlgorithm(alg);
  84. if (res) {
  85. return res;
  86. }
  87. }
  88. const unknown = {
  89. name: alg.algorithm,
  90. parameters: alg.parameters,
  91. };
  92. return unknown;
  93. }
  94. }
  95. const diAlgorithmProvider = "crypto.algorithmProvider";
  96. tsyringe.container.registerSingleton(diAlgorithmProvider, AlgorithmProvider);
  97. var EcAlgorithm_1;
  98. const idVersionOne = "1.3.36.3.3.2.8.1.1";
  99. const idBrainpoolP160r1 = `${idVersionOne}.1`;
  100. const idBrainpoolP160t1 = `${idVersionOne}.2`;
  101. const idBrainpoolP192r1 = `${idVersionOne}.3`;
  102. const idBrainpoolP192t1 = `${idVersionOne}.4`;
  103. const idBrainpoolP224r1 = `${idVersionOne}.5`;
  104. const idBrainpoolP224t1 = `${idVersionOne}.6`;
  105. const idBrainpoolP256r1 = `${idVersionOne}.7`;
  106. const idBrainpoolP256t1 = `${idVersionOne}.8`;
  107. const idBrainpoolP320r1 = `${idVersionOne}.9`;
  108. const idBrainpoolP320t1 = `${idVersionOne}.10`;
  109. const idBrainpoolP384r1 = `${idVersionOne}.11`;
  110. const idBrainpoolP384t1 = `${idVersionOne}.12`;
  111. const idBrainpoolP512r1 = `${idVersionOne}.13`;
  112. const idBrainpoolP512t1 = `${idVersionOne}.14`;
  113. const brainpoolP160r1 = "brainpoolP160r1";
  114. const brainpoolP160t1 = "brainpoolP160t1";
  115. const brainpoolP192r1 = "brainpoolP192r1";
  116. const brainpoolP192t1 = "brainpoolP192t1";
  117. const brainpoolP224r1 = "brainpoolP224r1";
  118. const brainpoolP224t1 = "brainpoolP224t1";
  119. const brainpoolP256r1 = "brainpoolP256r1";
  120. const brainpoolP256t1 = "brainpoolP256t1";
  121. const brainpoolP320r1 = "brainpoolP320r1";
  122. const brainpoolP320t1 = "brainpoolP320t1";
  123. const brainpoolP384r1 = "brainpoolP384r1";
  124. const brainpoolP384t1 = "brainpoolP384t1";
  125. const brainpoolP512r1 = "brainpoolP512r1";
  126. const brainpoolP512t1 = "brainpoolP512t1";
  127. const ECDSA = "ECDSA";
  128. exports.EcAlgorithm = EcAlgorithm_1 = class EcAlgorithm {
  129. toAsnAlgorithm(alg) {
  130. switch (alg.name.toLowerCase()) {
  131. case ECDSA.toLowerCase():
  132. if ("hash" in alg) {
  133. const hash = typeof alg.hash === "string" ? alg.hash : alg.hash.name;
  134. switch (hash.toLowerCase()) {
  135. case "sha-1":
  136. return asn1Ecc__namespace.ecdsaWithSHA1;
  137. case "sha-256":
  138. return asn1Ecc__namespace.ecdsaWithSHA256;
  139. case "sha-384":
  140. return asn1Ecc__namespace.ecdsaWithSHA384;
  141. case "sha-512":
  142. return asn1Ecc__namespace.ecdsaWithSHA512;
  143. }
  144. }
  145. else if ("namedCurve" in alg) {
  146. let parameters = "";
  147. switch (alg.namedCurve) {
  148. case "P-256":
  149. parameters = asn1Ecc__namespace.id_secp256r1;
  150. break;
  151. case "K-256":
  152. parameters = EcAlgorithm_1.SECP256K1;
  153. break;
  154. case "P-384":
  155. parameters = asn1Ecc__namespace.id_secp384r1;
  156. break;
  157. case "P-521":
  158. parameters = asn1Ecc__namespace.id_secp521r1;
  159. break;
  160. case brainpoolP160r1:
  161. parameters = idBrainpoolP160r1;
  162. break;
  163. case brainpoolP160t1:
  164. parameters = idBrainpoolP160t1;
  165. break;
  166. case brainpoolP192r1:
  167. parameters = idBrainpoolP192r1;
  168. break;
  169. case brainpoolP192t1:
  170. parameters = idBrainpoolP192t1;
  171. break;
  172. case brainpoolP224r1:
  173. parameters = idBrainpoolP224r1;
  174. break;
  175. case brainpoolP224t1:
  176. parameters = idBrainpoolP224t1;
  177. break;
  178. case brainpoolP256r1:
  179. parameters = idBrainpoolP256r1;
  180. break;
  181. case brainpoolP256t1:
  182. parameters = idBrainpoolP256t1;
  183. break;
  184. case brainpoolP320r1:
  185. parameters = idBrainpoolP320r1;
  186. break;
  187. case brainpoolP320t1:
  188. parameters = idBrainpoolP320t1;
  189. break;
  190. case brainpoolP384r1:
  191. parameters = idBrainpoolP384r1;
  192. break;
  193. case brainpoolP384t1:
  194. parameters = idBrainpoolP384t1;
  195. break;
  196. case brainpoolP512r1:
  197. parameters = idBrainpoolP512r1;
  198. break;
  199. case brainpoolP512t1:
  200. parameters = idBrainpoolP512t1;
  201. break;
  202. }
  203. if (parameters) {
  204. return new asn1X509.AlgorithmIdentifier({
  205. algorithm: asn1Ecc__namespace.id_ecPublicKey,
  206. parameters: asn1Schema.AsnConvert.serialize(new asn1Ecc__namespace.ECParameters({ namedCurve: parameters })),
  207. });
  208. }
  209. }
  210. }
  211. return null;
  212. }
  213. toWebAlgorithm(alg) {
  214. switch (alg.algorithm) {
  215. case asn1Ecc__namespace.id_ecdsaWithSHA1:
  216. return {
  217. name: ECDSA, hash: { name: "SHA-1" },
  218. };
  219. case asn1Ecc__namespace.id_ecdsaWithSHA256:
  220. return {
  221. name: ECDSA, hash: { name: "SHA-256" },
  222. };
  223. case asn1Ecc__namespace.id_ecdsaWithSHA384:
  224. return {
  225. name: ECDSA, hash: { name: "SHA-384" },
  226. };
  227. case asn1Ecc__namespace.id_ecdsaWithSHA512:
  228. return {
  229. name: ECDSA, hash: { name: "SHA-512" },
  230. };
  231. case asn1Ecc__namespace.id_ecPublicKey: {
  232. if (!alg.parameters) {
  233. throw new TypeError("Cannot get required parameters from EC algorithm");
  234. }
  235. const parameters = asn1Schema.AsnConvert.parse(alg.parameters, asn1Ecc__namespace.ECParameters);
  236. switch (parameters.namedCurve) {
  237. case asn1Ecc__namespace.id_secp256r1:
  238. return {
  239. name: ECDSA, namedCurve: "P-256",
  240. };
  241. case EcAlgorithm_1.SECP256K1:
  242. return {
  243. name: ECDSA, namedCurve: "K-256",
  244. };
  245. case asn1Ecc__namespace.id_secp384r1:
  246. return {
  247. name: ECDSA, namedCurve: "P-384",
  248. };
  249. case asn1Ecc__namespace.id_secp521r1:
  250. return {
  251. name: ECDSA, namedCurve: "P-521",
  252. };
  253. case idBrainpoolP160r1:
  254. return {
  255. name: ECDSA, namedCurve: brainpoolP160r1,
  256. };
  257. case idBrainpoolP160t1:
  258. return {
  259. name: ECDSA, namedCurve: brainpoolP160t1,
  260. };
  261. case idBrainpoolP192r1:
  262. return {
  263. name: ECDSA, namedCurve: brainpoolP192r1,
  264. };
  265. case idBrainpoolP192t1:
  266. return {
  267. name: ECDSA, namedCurve: brainpoolP192t1,
  268. };
  269. case idBrainpoolP224r1:
  270. return {
  271. name: ECDSA, namedCurve: brainpoolP224r1,
  272. };
  273. case idBrainpoolP224t1:
  274. return {
  275. name: ECDSA, namedCurve: brainpoolP224t1,
  276. };
  277. case idBrainpoolP256r1:
  278. return {
  279. name: ECDSA, namedCurve: brainpoolP256r1,
  280. };
  281. case idBrainpoolP256t1:
  282. return {
  283. name: ECDSA, namedCurve: brainpoolP256t1,
  284. };
  285. case idBrainpoolP320r1:
  286. return {
  287. name: ECDSA, namedCurve: brainpoolP320r1,
  288. };
  289. case idBrainpoolP320t1:
  290. return {
  291. name: ECDSA, namedCurve: brainpoolP320t1,
  292. };
  293. case idBrainpoolP384r1:
  294. return {
  295. name: ECDSA, namedCurve: brainpoolP384r1,
  296. };
  297. case idBrainpoolP384t1:
  298. return {
  299. name: ECDSA, namedCurve: brainpoolP384t1,
  300. };
  301. case idBrainpoolP512r1:
  302. return {
  303. name: ECDSA, namedCurve: brainpoolP512r1,
  304. };
  305. case idBrainpoolP512t1:
  306. return {
  307. name: ECDSA, namedCurve: brainpoolP512t1,
  308. };
  309. }
  310. }
  311. }
  312. return null;
  313. }
  314. };
  315. exports.EcAlgorithm.SECP256K1 = "1.3.132.0.10";
  316. exports.EcAlgorithm = EcAlgorithm_1 = tslib.__decorate([
  317. tsyringe.injectable()
  318. ], exports.EcAlgorithm);
  319. tsyringe.container.registerSingleton(diAlgorithm, exports.EcAlgorithm);
  320. const NAME = Symbol("name");
  321. const VALUE = Symbol("value");
  322. class TextObject {
  323. constructor(name, items = {}, value = "") {
  324. this[NAME] = name;
  325. this[VALUE] = value;
  326. for (const key in items) {
  327. this[key] = items[key];
  328. }
  329. }
  330. }
  331. TextObject.NAME = NAME;
  332. TextObject.VALUE = VALUE;
  333. class DefaultAlgorithmSerializer {
  334. static toTextObject(alg) {
  335. const obj = new TextObject("Algorithm Identifier", {}, OidSerializer.toString(alg.algorithm));
  336. if (alg.parameters) {
  337. switch (alg.algorithm) {
  338. case asn1Ecc__namespace.id_ecPublicKey: {
  339. const ecAlg = new exports.EcAlgorithm().toWebAlgorithm(alg);
  340. if (ecAlg && "namedCurve" in ecAlg) {
  341. obj["Named Curve"] = ecAlg.namedCurve;
  342. }
  343. else {
  344. obj["Parameters"] = alg.parameters;
  345. }
  346. break;
  347. }
  348. default:
  349. obj["Parameters"] = alg.parameters;
  350. }
  351. }
  352. return obj;
  353. }
  354. }
  355. class OidSerializer {
  356. static toString(oid) {
  357. const name = this.items[oid];
  358. if (name) {
  359. return name;
  360. }
  361. return oid;
  362. }
  363. }
  364. OidSerializer.items = {
  365. [asn1Rsa__namespace.id_sha1]: "sha1",
  366. [asn1Rsa__namespace.id_sha224]: "sha224",
  367. [asn1Rsa__namespace.id_sha256]: "sha256",
  368. [asn1Rsa__namespace.id_sha384]: "sha384",
  369. [asn1Rsa__namespace.id_sha512]: "sha512",
  370. [asn1Rsa__namespace.id_rsaEncryption]: "rsaEncryption",
  371. [asn1Rsa__namespace.id_sha1WithRSAEncryption]: "sha1WithRSAEncryption",
  372. [asn1Rsa__namespace.id_sha224WithRSAEncryption]: "sha224WithRSAEncryption",
  373. [asn1Rsa__namespace.id_sha256WithRSAEncryption]: "sha256WithRSAEncryption",
  374. [asn1Rsa__namespace.id_sha384WithRSAEncryption]: "sha384WithRSAEncryption",
  375. [asn1Rsa__namespace.id_sha512WithRSAEncryption]: "sha512WithRSAEncryption",
  376. [asn1Ecc__namespace.id_ecPublicKey]: "ecPublicKey",
  377. [asn1Ecc__namespace.id_ecdsaWithSHA1]: "ecdsaWithSHA1",
  378. [asn1Ecc__namespace.id_ecdsaWithSHA224]: "ecdsaWithSHA224",
  379. [asn1Ecc__namespace.id_ecdsaWithSHA256]: "ecdsaWithSHA256",
  380. [asn1Ecc__namespace.id_ecdsaWithSHA384]: "ecdsaWithSHA384",
  381. [asn1Ecc__namespace.id_ecdsaWithSHA512]: "ecdsaWithSHA512",
  382. [asn1X509__namespace.id_kp_serverAuth]: "TLS WWW server authentication",
  383. [asn1X509__namespace.id_kp_clientAuth]: "TLS WWW client authentication",
  384. [asn1X509__namespace.id_kp_codeSigning]: "Code Signing",
  385. [asn1X509__namespace.id_kp_emailProtection]: "E-mail Protection",
  386. [asn1X509__namespace.id_kp_timeStamping]: "Time Stamping",
  387. [asn1X509__namespace.id_kp_OCSPSigning]: "OCSP Signing",
  388. [asn1Cms__namespace.id_signedData]: "Signed Data",
  389. };
  390. class TextConverter {
  391. static serialize(obj) {
  392. return this.serializeObj(obj).join("\n");
  393. }
  394. static pad(deep = 0) {
  395. return "".padStart(2 * deep, " ");
  396. }
  397. static serializeObj(obj, deep = 0) {
  398. const res = [];
  399. let pad = this.pad(deep++);
  400. let value = "";
  401. const objValue = obj[TextObject.VALUE];
  402. if (objValue) {
  403. value = ` ${objValue}`;
  404. }
  405. res.push(`${pad}${obj[TextObject.NAME]}:${value}`);
  406. pad = this.pad(deep);
  407. for (const key in obj) {
  408. if (typeof key === "symbol") {
  409. continue;
  410. }
  411. const value = obj[key];
  412. const keyValue = key ? `${key}: ` : "";
  413. if (typeof value === "string"
  414. || typeof value === "number"
  415. || typeof value === "boolean") {
  416. res.push(`${pad}${keyValue}${value}`);
  417. }
  418. else if (value instanceof Date) {
  419. res.push(`${pad}${keyValue}${value.toUTCString()}`);
  420. }
  421. else if (Array.isArray(value)) {
  422. for (const obj of value) {
  423. obj[TextObject.NAME] = key;
  424. res.push(...this.serializeObj(obj, deep));
  425. }
  426. }
  427. else if (value instanceof TextObject) {
  428. value[TextObject.NAME] = key;
  429. res.push(...this.serializeObj(value, deep));
  430. }
  431. else if (pvtsutils.BufferSourceConverter.isBufferSource(value)) {
  432. if (key) {
  433. res.push(`${pad}${keyValue}`);
  434. res.push(...this.serializeBufferSource(value, deep + 1));
  435. }
  436. else {
  437. res.push(...this.serializeBufferSource(value, deep));
  438. }
  439. }
  440. else if ("toTextObject" in value) {
  441. const obj = value.toTextObject();
  442. obj[TextObject.NAME] = key;
  443. res.push(...this.serializeObj(obj, deep));
  444. }
  445. else {
  446. throw new TypeError("Cannot serialize data in text format. Unsupported type.");
  447. }
  448. }
  449. return res;
  450. }
  451. static serializeBufferSource(buffer, deep = 0) {
  452. const pad = this.pad(deep);
  453. const view = pvtsutils.BufferSourceConverter.toUint8Array(buffer);
  454. const res = [];
  455. for (let i = 0; i < view.length;) {
  456. const row = [];
  457. for (let j = 0; j < 16 && i < view.length; j++) {
  458. if (j === 8) {
  459. row.push("");
  460. }
  461. const hex = view[i++].toString(16).padStart(2, "0");
  462. row.push(hex);
  463. }
  464. res.push(`${pad}${row.join(" ")}`);
  465. }
  466. return res;
  467. }
  468. static serializeAlgorithm(alg) {
  469. return this.algorithmSerializer.toTextObject(alg);
  470. }
  471. }
  472. TextConverter.oidSerializer = OidSerializer;
  473. TextConverter.algorithmSerializer = DefaultAlgorithmSerializer;
  474. var _AsnData_rawData;
  475. class AsnData {
  476. get rawData() {
  477. if (!tslib.__classPrivateFieldGet(this, _AsnData_rawData, "f")) {
  478. tslib.__classPrivateFieldSet(this, _AsnData_rawData, asn1Schema.AsnConvert.serialize(this.asn), "f");
  479. }
  480. return tslib.__classPrivateFieldGet(this, _AsnData_rawData, "f");
  481. }
  482. constructor(...args) {
  483. _AsnData_rawData.set(this, void 0);
  484. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  485. this.asn = asn1Schema.AsnConvert.parse(args[0], args[1]);
  486. tslib.__classPrivateFieldSet(this, _AsnData_rawData, pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]), "f");
  487. this.onInit(this.asn);
  488. }
  489. else {
  490. this.asn = args[0];
  491. this.onInit(this.asn);
  492. }
  493. }
  494. equal(data) {
  495. if (data instanceof AsnData) {
  496. return pvtsutils.isEqual(data.rawData, this.rawData);
  497. }
  498. return false;
  499. }
  500. toString(format = "text") {
  501. switch (format) {
  502. case "asn":
  503. return asn1Schema.AsnConvert.toString(this.rawData);
  504. case "text":
  505. return TextConverter.serialize(this.toTextObject());
  506. case "hex":
  507. return pvtsutils.Convert.ToHex(this.rawData);
  508. case "base64":
  509. return pvtsutils.Convert.ToBase64(this.rawData);
  510. case "base64url":
  511. return pvtsutils.Convert.ToBase64Url(this.rawData);
  512. default:
  513. throw TypeError("Argument 'format' is unsupported value");
  514. }
  515. }
  516. getTextName() {
  517. const constructor = this.constructor;
  518. return constructor.NAME;
  519. }
  520. toTextObject() {
  521. const obj = this.toTextObjectEmpty();
  522. obj[""] = this.rawData;
  523. return obj;
  524. }
  525. toTextObjectEmpty(value) {
  526. return new TextObject(this.getTextName(), {}, value);
  527. }
  528. }
  529. _AsnData_rawData = new WeakMap();
  530. AsnData.NAME = "ASN";
  531. class Extension extends AsnData {
  532. constructor(...args) {
  533. let raw;
  534. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  535. raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
  536. }
  537. else {
  538. raw = asn1Schema.AsnConvert.serialize(new asn1X509.Extension({
  539. extnID: args[0],
  540. critical: args[1],
  541. extnValue: new asn1Schema.OctetString(pvtsutils.BufferSourceConverter.toArrayBuffer(args[2])),
  542. }));
  543. }
  544. super(raw, asn1X509.Extension);
  545. }
  546. onInit(asn) {
  547. this.type = asn.extnID;
  548. this.critical = asn.critical;
  549. this.value = asn.extnValue.buffer;
  550. }
  551. toTextObject() {
  552. const obj = this.toTextObjectWithoutValue();
  553. obj[""] = this.value;
  554. return obj;
  555. }
  556. toTextObjectWithoutValue() {
  557. const obj = this.toTextObjectEmpty(this.critical ? "critical" : undefined);
  558. if (obj[TextObject.NAME] === Extension.NAME) {
  559. obj[TextObject.NAME] = OidSerializer.toString(this.type);
  560. }
  561. return obj;
  562. }
  563. }
  564. var _a;
  565. class CryptoProvider {
  566. static isCryptoKeyPair(data) {
  567. return data && data.privateKey && data.publicKey;
  568. }
  569. static isCryptoKey(data) {
  570. return data && data.usages && data.type && data.algorithm && data.extractable !== undefined;
  571. }
  572. constructor() {
  573. this.items = new Map();
  574. this[_a] = "CryptoProvider";
  575. if (typeof self !== "undefined" && typeof crypto !== "undefined") {
  576. this.set(CryptoProvider.DEFAULT, crypto);
  577. }
  578. else if (typeof global !== "undefined" && global.crypto && global.crypto.subtle) {
  579. this.set(CryptoProvider.DEFAULT, global.crypto);
  580. }
  581. }
  582. clear() {
  583. this.items.clear();
  584. }
  585. delete(key) {
  586. return this.items.delete(key);
  587. }
  588. forEach(callbackfn, thisArg) {
  589. return this.items.forEach(callbackfn, thisArg);
  590. }
  591. has(key) {
  592. return this.items.has(key);
  593. }
  594. get size() {
  595. return this.items.size;
  596. }
  597. entries() {
  598. return this.items.entries();
  599. }
  600. keys() {
  601. return this.items.keys();
  602. }
  603. values() {
  604. return this.items.values();
  605. }
  606. [Symbol.iterator]() {
  607. return this.items[Symbol.iterator]();
  608. }
  609. get(key = CryptoProvider.DEFAULT) {
  610. const crypto = this.items.get(key.toLowerCase());
  611. if (!crypto) {
  612. throw new Error(`Cannot get Crypto by name '${key}'`);
  613. }
  614. return crypto;
  615. }
  616. set(key, value) {
  617. if (typeof key === "string") {
  618. if (!value) {
  619. throw new TypeError("Argument 'value' is required");
  620. }
  621. this.items.set(key.toLowerCase(), value);
  622. }
  623. else {
  624. this.items.set(CryptoProvider.DEFAULT, key);
  625. }
  626. return this;
  627. }
  628. }
  629. _a = Symbol.toStringTag;
  630. CryptoProvider.DEFAULT = "default";
  631. const cryptoProvider = new CryptoProvider();
  632. const OID_REGEX = /^[0-2](?:\.[1-9][0-9]*)+$/;
  633. function isOID(id) {
  634. return new RegExp(OID_REGEX).test(id);
  635. }
  636. class NameIdentifier {
  637. constructor(names = {}) {
  638. this.items = {};
  639. for (const id in names) {
  640. this.register(id, names[id]);
  641. }
  642. }
  643. get(idOrName) {
  644. return this.items[idOrName] || null;
  645. }
  646. findId(idOrName) {
  647. if (!isOID(idOrName)) {
  648. return this.get(idOrName);
  649. }
  650. return idOrName;
  651. }
  652. register(id, name) {
  653. this.items[id] = name;
  654. this.items[name] = id;
  655. }
  656. }
  657. const names = new NameIdentifier();
  658. names.register("CN", "2.5.4.3");
  659. names.register("L", "2.5.4.7");
  660. names.register("ST", "2.5.4.8");
  661. names.register("O", "2.5.4.10");
  662. names.register("OU", "2.5.4.11");
  663. names.register("C", "2.5.4.6");
  664. names.register("DC", "0.9.2342.19200300.100.1.25");
  665. names.register("E", "1.2.840.113549.1.9.1");
  666. names.register("G", "2.5.4.42");
  667. names.register("I", "2.5.4.43");
  668. names.register("SN", "2.5.4.4");
  669. names.register("T", "2.5.4.12");
  670. function replaceUnknownCharacter(text, char) {
  671. return `\\${pvtsutils.Convert.ToHex(pvtsutils.Convert.FromUtf8String(char)).toUpperCase()}`;
  672. }
  673. function escape(data) {
  674. return data
  675. .replace(/([,+"\\<>;])/g, "\\$1")
  676. .replace(/^([ #])/, "\\$1")
  677. .replace(/([ ]$)/, "\\$1")
  678. .replace(/([\r\n\t])/, replaceUnknownCharacter);
  679. }
  680. class Name {
  681. static isASCII(text) {
  682. for (let i = 0; i < text.length; i++) {
  683. const code = text.charCodeAt(i);
  684. if (code > 0xFF) {
  685. return false;
  686. }
  687. }
  688. return true;
  689. }
  690. static isPrintableString(text) {
  691. return /^[A-Za-z0-9 '()+,-./:=?]*$/g.test(text);
  692. }
  693. constructor(data, extraNames = {}) {
  694. this.extraNames = new NameIdentifier();
  695. this.asn = new asn1X509.Name();
  696. for (const key in extraNames) {
  697. if (Object.prototype.hasOwnProperty.call(extraNames, key)) {
  698. const value = extraNames[key];
  699. this.extraNames.register(key, value);
  700. }
  701. }
  702. if (typeof data === "string") {
  703. this.asn = this.fromString(data);
  704. }
  705. else if (data instanceof asn1X509.Name) {
  706. this.asn = data;
  707. }
  708. else if (pvtsutils.BufferSourceConverter.isBufferSource(data)) {
  709. this.asn = asn1Schema.AsnConvert.parse(data, asn1X509.Name);
  710. }
  711. else {
  712. this.asn = this.fromJSON(data);
  713. }
  714. }
  715. getField(idOrName) {
  716. const id = this.extraNames.findId(idOrName) || names.findId(idOrName);
  717. const res = [];
  718. for (const name of this.asn) {
  719. for (const rdn of name) {
  720. if (rdn.type === id) {
  721. res.push(rdn.value.toString());
  722. }
  723. }
  724. }
  725. return res;
  726. }
  727. getName(idOrName) {
  728. return this.extraNames.get(idOrName) || names.get(idOrName);
  729. }
  730. toString() {
  731. return this.asn.map((rdn) => rdn.map((o) => {
  732. const type = this.getName(o.type) || o.type;
  733. const value = o.value.anyValue
  734. ? `#${pvtsutils.Convert.ToHex(o.value.anyValue)}`
  735. : escape(o.value.toString());
  736. return `${type}=${value}`;
  737. })
  738. .join("+"))
  739. .join(", ");
  740. }
  741. toJSON() {
  742. var _a;
  743. const json = [];
  744. for (const rdn of this.asn) {
  745. const jsonItem = {};
  746. for (const attr of rdn) {
  747. const type = this.getName(attr.type) || attr.type;
  748. (_a = jsonItem[type]) !== null && _a !== void 0 ? _a : (jsonItem[type] = []);
  749. jsonItem[type].push(attr.value.anyValue ? `#${pvtsutils.Convert.ToHex(attr.value.anyValue)}` : attr.value.toString());
  750. }
  751. json.push(jsonItem);
  752. }
  753. return json;
  754. }
  755. fromString(data) {
  756. const asn = new asn1X509.Name();
  757. const regex = /(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;
  758. let matches = null;
  759. let level = ",";
  760. while (matches = regex.exec(`${data},`)) {
  761. let [, type, value] = matches;
  762. const lastChar = value[value.length - 1];
  763. if (lastChar === "," || lastChar === "+") {
  764. value = value.slice(0, value.length - 1);
  765. matches[3] = lastChar;
  766. }
  767. const next = matches[3];
  768. type = this.getTypeOid(type);
  769. const attr = this.createAttribute(type, value);
  770. if (level === "+") {
  771. asn[asn.length - 1].push(attr);
  772. }
  773. else {
  774. asn.push(new asn1X509.RelativeDistinguishedName([attr]));
  775. }
  776. level = next;
  777. }
  778. return asn;
  779. }
  780. fromJSON(data) {
  781. const asn = new asn1X509.Name();
  782. for (const item of data) {
  783. const asnRdn = new asn1X509.RelativeDistinguishedName();
  784. for (const type in item) {
  785. const typeId = this.getTypeOid(type);
  786. const values = item[type];
  787. for (const value of values) {
  788. const asnAttr = this.createAttribute(typeId, value);
  789. asnRdn.push(asnAttr);
  790. }
  791. }
  792. asn.push(asnRdn);
  793. }
  794. return asn;
  795. }
  796. getTypeOid(type) {
  797. if (!/[\d.]+/.test(type)) {
  798. type = this.getName(type) || "";
  799. }
  800. if (!type) {
  801. throw new Error(`Cannot get OID for name type '${type}'`);
  802. }
  803. return type;
  804. }
  805. createAttribute(type, value) {
  806. const attr = new asn1X509.AttributeTypeAndValue({ type });
  807. if (typeof value === "object") {
  808. for (const key in value) {
  809. switch (key) {
  810. case "ia5String":
  811. attr.value.ia5String = value[key];
  812. break;
  813. case "utf8String":
  814. attr.value.utf8String = value[key];
  815. break;
  816. case "universalString":
  817. attr.value.universalString = value[key];
  818. break;
  819. case "bmpString":
  820. attr.value.bmpString = value[key];
  821. break;
  822. case "printableString":
  823. attr.value.printableString = value[key];
  824. break;
  825. }
  826. }
  827. }
  828. else if (value[0] === "#") {
  829. attr.value.anyValue = pvtsutils.Convert.FromHex(value.slice(1));
  830. }
  831. else {
  832. const processedValue = this.processStringValue(value);
  833. if (type === this.getName("E") || type === this.getName("DC")) {
  834. attr.value.ia5String = processedValue;
  835. }
  836. else {
  837. if (Name.isPrintableString(processedValue)) {
  838. attr.value.printableString = processedValue;
  839. }
  840. else {
  841. attr.value.utf8String = processedValue;
  842. }
  843. }
  844. }
  845. return attr;
  846. }
  847. processStringValue(value) {
  848. const quotedMatches = /"(.*?[^\\])?"/.exec(value);
  849. if (quotedMatches) {
  850. value = quotedMatches[1];
  851. }
  852. return value
  853. .replace(/\\0a/ig, "\n")
  854. .replace(/\\0d/ig, "\r")
  855. .replace(/\\0g/ig, "\t")
  856. .replace(/\\(.)/g, "$1");
  857. }
  858. toArrayBuffer() {
  859. return asn1Schema.AsnConvert.serialize(this.asn);
  860. }
  861. async getThumbprint(...args) {
  862. var _a;
  863. let crypto;
  864. let algorithm = "SHA-1";
  865. if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
  866. algorithm = args[0] || algorithm;
  867. crypto = args[1] || cryptoProvider.get();
  868. }
  869. else {
  870. crypto = args[0] || cryptoProvider.get();
  871. }
  872. return await crypto.subtle.digest(algorithm, this.toArrayBuffer());
  873. }
  874. }
  875. const ERR_GN_CONSTRUCTOR = "Cannot initialize GeneralName from ASN.1 data.";
  876. const ERR_GN_STRING_FORMAT = `${ERR_GN_CONSTRUCTOR} Unsupported string format in use.`;
  877. const ERR_GUID = `${ERR_GN_CONSTRUCTOR} Value doesn't match to GUID regular expression.`;
  878. const GUID_REGEX = /^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;
  879. const id_GUID = "1.3.6.1.4.1.311.25.1";
  880. const id_UPN = "1.3.6.1.4.1.311.20.2.3";
  881. const DNS = "dns";
  882. const DN = "dn";
  883. const EMAIL = "email";
  884. const IP = "ip";
  885. const URL = "url";
  886. const GUID = "guid";
  887. const UPN = "upn";
  888. const REGISTERED_ID = "id";
  889. class GeneralName extends AsnData {
  890. constructor(...args) {
  891. let name;
  892. if (args.length === 2) {
  893. switch (args[0]) {
  894. case DN: {
  895. const derName = new Name(args[1]).toArrayBuffer();
  896. const asnName = asn1Schema.AsnConvert.parse(derName, asn1X509__namespace.Name);
  897. name = new asn1X509__namespace.GeneralName({ directoryName: asnName });
  898. break;
  899. }
  900. case DNS:
  901. name = new asn1X509__namespace.GeneralName({ dNSName: args[1] });
  902. break;
  903. case EMAIL:
  904. name = new asn1X509__namespace.GeneralName({ rfc822Name: args[1] });
  905. break;
  906. case GUID: {
  907. const matches = new RegExp(GUID_REGEX, "i").exec(args[1]);
  908. if (!matches) {
  909. throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");
  910. }
  911. const hex = matches
  912. .slice(1)
  913. .map((o, i) => {
  914. if (i < 3) {
  915. return pvtsutils.Convert.ToHex(new Uint8Array(pvtsutils.Convert.FromHex(o)).reverse());
  916. }
  917. return o;
  918. })
  919. .join("");
  920. name = new asn1X509__namespace.GeneralName({
  921. otherName: new asn1X509__namespace.OtherName({
  922. typeId: id_GUID,
  923. value: asn1Schema.AsnConvert.serialize(new asn1Schema.OctetString(pvtsutils.Convert.FromHex(hex))),
  924. }),
  925. });
  926. break;
  927. }
  928. case IP:
  929. name = new asn1X509__namespace.GeneralName({ iPAddress: args[1] });
  930. break;
  931. case REGISTERED_ID:
  932. name = new asn1X509__namespace.GeneralName({ registeredID: args[1] });
  933. break;
  934. case UPN: {
  935. name = new asn1X509__namespace.GeneralName({
  936. otherName: new asn1X509__namespace.OtherName({
  937. typeId: id_UPN,
  938. value: asn1Schema.AsnConvert.serialize(asn1Schema.AsnUtf8StringConverter.toASN(args[1])),
  939. }),
  940. });
  941. break;
  942. }
  943. case URL:
  944. name = new asn1X509__namespace.GeneralName({ uniformResourceIdentifier: args[1] });
  945. break;
  946. default:
  947. throw new Error("Cannot create GeneralName. Unsupported type of the name");
  948. }
  949. }
  950. else if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  951. name = asn1Schema.AsnConvert.parse(args[0], asn1X509__namespace.GeneralName);
  952. }
  953. else {
  954. name = args[0];
  955. }
  956. super(name);
  957. }
  958. onInit(asn) {
  959. if (asn.dNSName != undefined) {
  960. this.type = DNS;
  961. this.value = asn.dNSName;
  962. }
  963. else if (asn.rfc822Name != undefined) {
  964. this.type = EMAIL;
  965. this.value = asn.rfc822Name;
  966. }
  967. else if (asn.iPAddress != undefined) {
  968. this.type = IP;
  969. this.value = asn.iPAddress;
  970. }
  971. else if (asn.uniformResourceIdentifier != undefined) {
  972. this.type = URL;
  973. this.value = asn.uniformResourceIdentifier;
  974. }
  975. else if (asn.registeredID != undefined) {
  976. this.type = REGISTERED_ID;
  977. this.value = asn.registeredID;
  978. }
  979. else if (asn.directoryName != undefined) {
  980. this.type = DN;
  981. this.value = new Name(asn.directoryName).toString();
  982. }
  983. else if (asn.otherName != undefined) {
  984. if (asn.otherName.typeId === id_GUID) {
  985. this.type = GUID;
  986. const guid = asn1Schema.AsnConvert.parse(asn.otherName.value, asn1Schema.OctetString);
  987. const matches = new RegExp(GUID_REGEX, "i").exec(pvtsutils.Convert.ToHex(guid));
  988. if (!matches) {
  989. throw new Error(ERR_GUID);
  990. }
  991. this.value = matches
  992. .slice(1)
  993. .map((o, i) => {
  994. if (i < 3) {
  995. return pvtsutils.Convert.ToHex(new Uint8Array(pvtsutils.Convert.FromHex(o)).reverse());
  996. }
  997. return o;
  998. })
  999. .join("-");
  1000. }
  1001. else if (asn.otherName.typeId === id_UPN) {
  1002. this.type = UPN;
  1003. this.value = asn1Schema.AsnConvert.parse(asn.otherName.value, asn1X509__namespace.DirectoryString).toString();
  1004. }
  1005. else {
  1006. throw new Error(ERR_GN_STRING_FORMAT);
  1007. }
  1008. }
  1009. else {
  1010. throw new Error(ERR_GN_STRING_FORMAT);
  1011. }
  1012. }
  1013. toJSON() {
  1014. return {
  1015. type: this.type,
  1016. value: this.value,
  1017. };
  1018. }
  1019. toTextObject() {
  1020. let type;
  1021. switch (this.type) {
  1022. case DN:
  1023. case DNS:
  1024. case GUID:
  1025. case IP:
  1026. case REGISTERED_ID:
  1027. case UPN:
  1028. case URL:
  1029. type = this.type.toUpperCase();
  1030. break;
  1031. case EMAIL:
  1032. type = "Email";
  1033. break;
  1034. default:
  1035. throw new Error("Unsupported GeneralName type");
  1036. }
  1037. let value = this.value;
  1038. if (this.type === REGISTERED_ID) {
  1039. value = OidSerializer.toString(value);
  1040. }
  1041. return new TextObject(type, undefined, value);
  1042. }
  1043. }
  1044. class GeneralNames extends AsnData {
  1045. constructor(params) {
  1046. let names;
  1047. if (params instanceof asn1X509__namespace.GeneralNames) {
  1048. names = params;
  1049. }
  1050. else if (Array.isArray(params)) {
  1051. const items = [];
  1052. for (const name of params) {
  1053. if (name instanceof asn1X509__namespace.GeneralName) {
  1054. items.push(name);
  1055. }
  1056. else {
  1057. const asnName = asn1Schema.AsnConvert.parse(new GeneralName(name.type, name.value).rawData, asn1X509__namespace.GeneralName);
  1058. items.push(asnName);
  1059. }
  1060. }
  1061. names = new asn1X509__namespace.GeneralNames(items);
  1062. }
  1063. else if (pvtsutils.BufferSourceConverter.isBufferSource(params)) {
  1064. names = asn1Schema.AsnConvert.parse(params, asn1X509__namespace.GeneralNames);
  1065. }
  1066. else {
  1067. throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");
  1068. }
  1069. super(names);
  1070. }
  1071. onInit(asn) {
  1072. const items = [];
  1073. for (const asnName of asn) {
  1074. let name = null;
  1075. try {
  1076. name = new GeneralName(asnName);
  1077. }
  1078. catch {
  1079. continue;
  1080. }
  1081. items.push(name);
  1082. }
  1083. this.items = items;
  1084. }
  1085. toJSON() {
  1086. return this.items.map((o) => o.toJSON());
  1087. }
  1088. toTextObject() {
  1089. const res = super.toTextObjectEmpty();
  1090. for (const name of this.items) {
  1091. const nameObj = name.toTextObject();
  1092. let field = res[nameObj[TextObject.NAME]];
  1093. if (!Array.isArray(field)) {
  1094. field = [];
  1095. res[nameObj[TextObject.NAME]] = field;
  1096. }
  1097. field.push(nameObj);
  1098. }
  1099. return res;
  1100. }
  1101. }
  1102. GeneralNames.NAME = "GeneralNames";
  1103. const rPaddingTag = "-{5}";
  1104. const rEolChars = "\\n";
  1105. const rNameTag = `[^${rEolChars}]+`;
  1106. const rBeginTag = `${rPaddingTag}BEGIN (${rNameTag}(?=${rPaddingTag}))${rPaddingTag}`;
  1107. const rEndTag = `${rPaddingTag}END \\1${rPaddingTag}`;
  1108. const rEolGroup = "\\n";
  1109. const rHeaderKey = `[^:${rEolChars}]+`;
  1110. const rHeaderValue = `(?:[^${rEolChars}]+${rEolGroup}(?: +[^${rEolChars}]+${rEolGroup})*)`;
  1111. const rBase64Chars = "[a-zA-Z0-9=+/]+";
  1112. const rBase64 = `(?:${rBase64Chars}${rEolGroup})+`;
  1113. const rPem = `${rBeginTag}${rEolGroup}(?:((?:${rHeaderKey}: ${rHeaderValue})+))?${rEolGroup}?(${rBase64})${rEndTag}`;
  1114. class PemConverter {
  1115. static isPem(data) {
  1116. return typeof data === "string"
  1117. && new RegExp(rPem, "g").test(data.replace(/\r/g, ""));
  1118. }
  1119. static decodeWithHeaders(pem) {
  1120. pem = pem.replace(/\r/g, "");
  1121. const pattern = new RegExp(rPem, "g");
  1122. const res = [];
  1123. let matches = null;
  1124. while (matches = pattern.exec(pem)) {
  1125. const base64 = matches[3]
  1126. .replace(new RegExp(`[${rEolChars}]+`, "g"), "");
  1127. const pemStruct = {
  1128. type: matches[1],
  1129. headers: [],
  1130. rawData: pvtsutils.Convert.FromBase64(base64),
  1131. };
  1132. const headersString = matches[2];
  1133. if (headersString) {
  1134. const headers = headersString.split(new RegExp(rEolGroup, "g"));
  1135. let lastHeader = null;
  1136. for (const header of headers) {
  1137. const [key, value] = header.split(/:(.*)/);
  1138. if (value === undefined) {
  1139. if (!lastHeader) {
  1140. throw new Error("Cannot parse PEM string. Incorrect header value");
  1141. }
  1142. lastHeader.value += key.trim();
  1143. }
  1144. else {
  1145. if (lastHeader) {
  1146. pemStruct.headers.push(lastHeader);
  1147. }
  1148. lastHeader = {
  1149. key, value: value.trim(),
  1150. };
  1151. }
  1152. }
  1153. if (lastHeader) {
  1154. pemStruct.headers.push(lastHeader);
  1155. }
  1156. }
  1157. res.push(pemStruct);
  1158. }
  1159. return res;
  1160. }
  1161. static decode(pem) {
  1162. const blocks = this.decodeWithHeaders(pem);
  1163. return blocks.map((o) => o.rawData);
  1164. }
  1165. static decodeFirst(pem) {
  1166. const items = this.decode(pem);
  1167. if (!items.length) {
  1168. throw new RangeError("PEM string doesn't contain any objects");
  1169. }
  1170. return items[0];
  1171. }
  1172. static encode(rawData, tag) {
  1173. if (Array.isArray(rawData)) {
  1174. const raws = new Array();
  1175. if (tag) {
  1176. rawData.forEach((element) => {
  1177. if (!pvtsutils.BufferSourceConverter.isBufferSource(element)) {
  1178. throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");
  1179. }
  1180. raws.push(this.encodeStruct({
  1181. type: tag,
  1182. rawData: pvtsutils.BufferSourceConverter.toArrayBuffer(element),
  1183. }));
  1184. });
  1185. }
  1186. else {
  1187. rawData.forEach((element) => {
  1188. if (!("type" in element)) {
  1189. throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");
  1190. }
  1191. raws.push(this.encodeStruct(element));
  1192. });
  1193. }
  1194. return raws.join("\n");
  1195. }
  1196. else {
  1197. if (!tag) {
  1198. throw new Error("Required argument 'tag' is missed");
  1199. }
  1200. return this.encodeStruct({
  1201. type: tag,
  1202. rawData: pvtsutils.BufferSourceConverter.toArrayBuffer(rawData),
  1203. });
  1204. }
  1205. }
  1206. static encodeStruct(pem) {
  1207. var _a;
  1208. const upperCaseType = pem.type.toLocaleUpperCase();
  1209. const res = [];
  1210. res.push(`-----BEGIN ${upperCaseType}-----`);
  1211. if ((_a = pem.headers) === null || _a === void 0 ? void 0 : _a.length) {
  1212. for (const header of pem.headers) {
  1213. res.push(`${header.key}: ${header.value}`);
  1214. }
  1215. res.push("");
  1216. }
  1217. const base64 = pvtsutils.Convert.ToBase64(pem.rawData);
  1218. let sliced;
  1219. let offset = 0;
  1220. const rows = Array();
  1221. while (offset < base64.length) {
  1222. if (base64.length - offset < 64) {
  1223. sliced = base64.substring(offset);
  1224. }
  1225. else {
  1226. sliced = base64.substring(offset, offset + 64);
  1227. offset += 64;
  1228. }
  1229. if (sliced.length !== 0) {
  1230. rows.push(sliced);
  1231. if (sliced.length < 64) {
  1232. break;
  1233. }
  1234. }
  1235. else {
  1236. break;
  1237. }
  1238. }
  1239. res.push(...rows);
  1240. res.push(`-----END ${upperCaseType}-----`);
  1241. return res.join("\n");
  1242. }
  1243. }
  1244. PemConverter.CertificateTag = "CERTIFICATE";
  1245. PemConverter.CrlTag = "CRL";
  1246. PemConverter.CertificateRequestTag = "CERTIFICATE REQUEST";
  1247. PemConverter.PublicKeyTag = "PUBLIC KEY";
  1248. PemConverter.PrivateKeyTag = "PRIVATE KEY";
  1249. class PemData extends AsnData {
  1250. static isAsnEncoded(data) {
  1251. return pvtsutils.BufferSourceConverter.isBufferSource(data) || typeof data === "string";
  1252. }
  1253. static toArrayBuffer(raw) {
  1254. if (typeof raw === "string") {
  1255. if (PemConverter.isPem(raw)) {
  1256. return PemConverter.decode(raw)[0];
  1257. }
  1258. else if (pvtsutils.Convert.isHex(raw)) {
  1259. return pvtsutils.Convert.FromHex(raw);
  1260. }
  1261. else if (pvtsutils.Convert.isBase64(raw)) {
  1262. return pvtsutils.Convert.FromBase64(raw);
  1263. }
  1264. else if (pvtsutils.Convert.isBase64Url(raw)) {
  1265. return pvtsutils.Convert.FromBase64Url(raw);
  1266. }
  1267. else {
  1268. throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
  1269. }
  1270. }
  1271. else {
  1272. const buffer = pvtsutils.BufferSourceConverter.toUint8Array(raw);
  1273. if (buffer.length > 0 && buffer[0] === 0x30) {
  1274. return pvtsutils.BufferSourceConverter.toArrayBuffer(raw);
  1275. }
  1276. const stringRaw = pvtsutils.Convert.ToBinary(raw);
  1277. if (PemConverter.isPem(stringRaw)) {
  1278. return PemConverter.decode(stringRaw)[0];
  1279. }
  1280. else if (pvtsutils.Convert.isHex(stringRaw)) {
  1281. return pvtsutils.Convert.FromHex(stringRaw);
  1282. }
  1283. else if (pvtsutils.Convert.isBase64(stringRaw)) {
  1284. return pvtsutils.Convert.FromBase64(stringRaw);
  1285. }
  1286. else if (pvtsutils.Convert.isBase64Url(stringRaw)) {
  1287. return pvtsutils.Convert.FromBase64Url(stringRaw);
  1288. }
  1289. throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
  1290. }
  1291. }
  1292. constructor(...args) {
  1293. if (PemData.isAsnEncoded(args[0])) {
  1294. super(PemData.toArrayBuffer(args[0]), args[1]);
  1295. }
  1296. else {
  1297. super(args[0]);
  1298. }
  1299. }
  1300. toString(format = "pem") {
  1301. switch (format) {
  1302. case "pem":
  1303. return PemConverter.encode(this.rawData, this.tag);
  1304. default:
  1305. return super.toString(format);
  1306. }
  1307. }
  1308. }
  1309. class PublicKey extends PemData {
  1310. static async create(data, crypto = cryptoProvider.get()) {
  1311. if (data instanceof PublicKey) {
  1312. return data;
  1313. }
  1314. else if (CryptoProvider.isCryptoKey(data)) {
  1315. if (data.type !== "public") {
  1316. throw new TypeError("Public key is required");
  1317. }
  1318. const spki = await crypto.subtle.exportKey("spki", data);
  1319. return new PublicKey(spki);
  1320. }
  1321. else if (data.publicKey) {
  1322. return data.publicKey;
  1323. }
  1324. else if (pvtsutils.BufferSourceConverter.isBufferSource(data)) {
  1325. return new PublicKey(data);
  1326. }
  1327. else {
  1328. throw new TypeError("Unsupported PublicKeyType");
  1329. }
  1330. }
  1331. constructor(param) {
  1332. if (PemData.isAsnEncoded(param)) {
  1333. super(param, asn1X509.SubjectPublicKeyInfo);
  1334. }
  1335. else {
  1336. super(param);
  1337. }
  1338. this.tag = PemConverter.PublicKeyTag;
  1339. }
  1340. async export(...args) {
  1341. let crypto;
  1342. let keyUsages = ["verify"];
  1343. let algorithm = {
  1344. hash: "SHA-256", ...this.algorithm,
  1345. };
  1346. if (args.length > 1) {
  1347. algorithm = args[0] || algorithm;
  1348. keyUsages = args[1] || keyUsages;
  1349. crypto = args[2] || cryptoProvider.get();
  1350. }
  1351. else {
  1352. crypto = args[0] || cryptoProvider.get();
  1353. }
  1354. let raw = this.rawData;
  1355. const asnSpki = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
  1356. if (asnSpki.algorithm.algorithm === asn1Rsa.id_RSASSA_PSS) {
  1357. raw = convertSpkiToRsaPkcs1(asnSpki, raw);
  1358. }
  1359. return crypto.subtle.importKey("spki", raw, algorithm, true, keyUsages);
  1360. }
  1361. onInit(asn) {
  1362. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  1363. const algorithm = this.algorithm = algProv.toWebAlgorithm(asn.algorithm);
  1364. switch (asn.algorithm.algorithm) {
  1365. case asn1Rsa.id_rsaEncryption:
  1366. {
  1367. const rsaPublicKey = asn1Schema.AsnConvert.parse(asn.subjectPublicKey, asn1Rsa.RSAPublicKey);
  1368. const modulus = pvtsutils.BufferSourceConverter.toUint8Array(rsaPublicKey.modulus);
  1369. algorithm.publicExponent = pvtsutils.BufferSourceConverter.toUint8Array(rsaPublicKey.publicExponent);
  1370. algorithm.modulusLength = (!modulus[0] ? modulus.slice(1) : modulus).byteLength << 3;
  1371. break;
  1372. }
  1373. }
  1374. }
  1375. async getThumbprint(...args) {
  1376. var _a;
  1377. let crypto;
  1378. let algorithm = "SHA-1";
  1379. if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
  1380. algorithm = args[0] || algorithm;
  1381. crypto = args[1] || cryptoProvider.get();
  1382. }
  1383. else {
  1384. crypto = args[0] || cryptoProvider.get();
  1385. }
  1386. return await crypto.subtle.digest(algorithm, this.rawData);
  1387. }
  1388. async getKeyIdentifier(...args) {
  1389. let crypto;
  1390. let algorithm = "SHA-1";
  1391. if (args.length === 1) {
  1392. if (typeof args[0] === "string") {
  1393. algorithm = args[0];
  1394. crypto = cryptoProvider.get();
  1395. }
  1396. else {
  1397. crypto = args[0];
  1398. }
  1399. }
  1400. else if (args.length === 2) {
  1401. algorithm = args[0];
  1402. crypto = args[1];
  1403. }
  1404. else {
  1405. crypto = cryptoProvider.get();
  1406. }
  1407. const asn = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
  1408. return await crypto.subtle.digest(algorithm, asn.subjectPublicKey);
  1409. }
  1410. toTextObject() {
  1411. const obj = this.toTextObjectEmpty();
  1412. const asn = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
  1413. obj["Algorithm"] = TextConverter.serializeAlgorithm(asn.algorithm);
  1414. switch (asn.algorithm.algorithm) {
  1415. case asn1Ecc.id_ecPublicKey:
  1416. obj["EC Point"] = asn.subjectPublicKey;
  1417. break;
  1418. case asn1Rsa.id_rsaEncryption:
  1419. default:
  1420. obj["Raw Data"] = asn.subjectPublicKey;
  1421. }
  1422. return obj;
  1423. }
  1424. }
  1425. function convertSpkiToRsaPkcs1(asnSpki, raw) {
  1426. asnSpki.algorithm = new asn1X509.AlgorithmIdentifier({
  1427. algorithm: asn1Rsa.id_rsaEncryption,
  1428. parameters: null,
  1429. });
  1430. raw = asn1Schema.AsnConvert.serialize(asnSpki);
  1431. return raw;
  1432. }
  1433. class AuthorityKeyIdentifierExtension extends Extension {
  1434. static async create(param, critical = false, crypto = cryptoProvider.get()) {
  1435. if ("name" in param && "serialNumber" in param) {
  1436. return new AuthorityKeyIdentifierExtension(param, critical);
  1437. }
  1438. const key = await PublicKey.create(param, crypto);
  1439. const id = await key.getKeyIdentifier(crypto);
  1440. return new AuthorityKeyIdentifierExtension(pvtsutils.Convert.ToHex(id), critical);
  1441. }
  1442. constructor(...args) {
  1443. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1444. super(args[0]);
  1445. }
  1446. else if (typeof args[0] === "string") {
  1447. const value = new asn1X509__namespace.AuthorityKeyIdentifier({ keyIdentifier: new asn1X509__namespace.KeyIdentifier(pvtsutils.Convert.FromHex(args[0])) });
  1448. super(asn1X509__namespace.id_ce_authorityKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
  1449. }
  1450. else {
  1451. const certId = args[0];
  1452. const certIdName = certId.name instanceof GeneralNames
  1453. ? asn1Schema.AsnConvert.parse(certId.name.rawData, asn1X509__namespace.GeneralNames)
  1454. : certId.name;
  1455. const value = new asn1X509__namespace.AuthorityKeyIdentifier({
  1456. authorityCertIssuer: certIdName,
  1457. authorityCertSerialNumber: pvtsutils.Convert.FromHex(certId.serialNumber),
  1458. });
  1459. super(asn1X509__namespace.id_ce_authorityKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
  1460. }
  1461. }
  1462. onInit(asn) {
  1463. super.onInit(asn);
  1464. const aki = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.AuthorityKeyIdentifier);
  1465. if (aki.keyIdentifier) {
  1466. this.keyId = pvtsutils.Convert.ToHex(aki.keyIdentifier);
  1467. }
  1468. if (aki.authorityCertIssuer || aki.authorityCertSerialNumber) {
  1469. this.certId = {
  1470. name: aki.authorityCertIssuer || [],
  1471. serialNumber: aki.authorityCertSerialNumber ? pvtsutils.Convert.ToHex(aki.authorityCertSerialNumber) : "",
  1472. };
  1473. }
  1474. }
  1475. toTextObject() {
  1476. const obj = this.toTextObjectWithoutValue();
  1477. const asn = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.AuthorityKeyIdentifier);
  1478. if (asn.authorityCertIssuer) {
  1479. obj["Authority Issuer"] = new GeneralNames(asn.authorityCertIssuer).toTextObject();
  1480. }
  1481. if (asn.authorityCertSerialNumber) {
  1482. obj["Authority Serial Number"] = asn.authorityCertSerialNumber;
  1483. }
  1484. if (asn.keyIdentifier) {
  1485. obj[""] = asn.keyIdentifier;
  1486. }
  1487. return obj;
  1488. }
  1489. }
  1490. AuthorityKeyIdentifierExtension.NAME = "Authority Key Identifier";
  1491. class BasicConstraintsExtension extends Extension {
  1492. constructor(...args) {
  1493. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1494. super(args[0]);
  1495. const value = asn1Schema.AsnConvert.parse(this.value, asn1X509.BasicConstraints);
  1496. this.ca = value.cA;
  1497. this.pathLength = value.pathLenConstraint;
  1498. }
  1499. else {
  1500. const value = new asn1X509.BasicConstraints({
  1501. cA: args[0],
  1502. pathLenConstraint: args[1],
  1503. });
  1504. super(asn1X509.id_ce_basicConstraints, args[2], asn1Schema.AsnConvert.serialize(value));
  1505. this.ca = args[0];
  1506. this.pathLength = args[1];
  1507. }
  1508. }
  1509. toTextObject() {
  1510. const obj = this.toTextObjectWithoutValue();
  1511. if (this.ca) {
  1512. obj["CA"] = this.ca;
  1513. }
  1514. if (this.pathLength !== undefined) {
  1515. obj["Path Length"] = this.pathLength;
  1516. }
  1517. return obj;
  1518. }
  1519. }
  1520. BasicConstraintsExtension.NAME = "Basic Constraints";
  1521. exports.ExtendedKeyUsage = void 0;
  1522. (function (ExtendedKeyUsage) {
  1523. ExtendedKeyUsage["serverAuth"] = "1.3.6.1.5.5.7.3.1";
  1524. ExtendedKeyUsage["clientAuth"] = "1.3.6.1.5.5.7.3.2";
  1525. ExtendedKeyUsage["codeSigning"] = "1.3.6.1.5.5.7.3.3";
  1526. ExtendedKeyUsage["emailProtection"] = "1.3.6.1.5.5.7.3.4";
  1527. ExtendedKeyUsage["timeStamping"] = "1.3.6.1.5.5.7.3.8";
  1528. ExtendedKeyUsage["ocspSigning"] = "1.3.6.1.5.5.7.3.9";
  1529. })(exports.ExtendedKeyUsage || (exports.ExtendedKeyUsage = {}));
  1530. class ExtendedKeyUsageExtension extends Extension {
  1531. constructor(...args) {
  1532. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1533. super(args[0]);
  1534. const value = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.ExtendedKeyUsage);
  1535. this.usages = value.map((o) => o);
  1536. }
  1537. else {
  1538. const value = new asn1X509__namespace.ExtendedKeyUsage(args[0]);
  1539. super(asn1X509__namespace.id_ce_extKeyUsage, args[1], asn1Schema.AsnConvert.serialize(value));
  1540. this.usages = args[0];
  1541. }
  1542. }
  1543. toTextObject() {
  1544. const obj = this.toTextObjectWithoutValue();
  1545. obj[""] = this.usages.map((o) => OidSerializer.toString(o)).join(", ");
  1546. return obj;
  1547. }
  1548. }
  1549. ExtendedKeyUsageExtension.NAME = "Extended Key Usages";
  1550. exports.KeyUsageFlags = void 0;
  1551. (function (KeyUsageFlags) {
  1552. KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
  1553. KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
  1554. KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
  1555. KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
  1556. KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
  1557. KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
  1558. KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
  1559. KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
  1560. KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
  1561. })(exports.KeyUsageFlags || (exports.KeyUsageFlags = {}));
  1562. class KeyUsagesExtension extends Extension {
  1563. constructor(...args) {
  1564. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1565. super(args[0]);
  1566. const value = asn1Schema.AsnConvert.parse(this.value, asn1X509.KeyUsage);
  1567. this.usages = value.toNumber();
  1568. }
  1569. else {
  1570. const value = new asn1X509.KeyUsage(args[0]);
  1571. super(asn1X509.id_ce_keyUsage, args[1], asn1Schema.AsnConvert.serialize(value));
  1572. this.usages = args[0];
  1573. }
  1574. }
  1575. toTextObject() {
  1576. const obj = this.toTextObjectWithoutValue();
  1577. const asn = asn1Schema.AsnConvert.parse(this.value, asn1X509.KeyUsage);
  1578. obj[""] = asn.toJSON().join(", ");
  1579. return obj;
  1580. }
  1581. }
  1582. KeyUsagesExtension.NAME = "Key Usages";
  1583. class SubjectKeyIdentifierExtension extends Extension {
  1584. static async create(publicKey, critical = false, crypto = cryptoProvider.get()) {
  1585. const key = await PublicKey.create(publicKey, crypto);
  1586. const id = await key.getKeyIdentifier(crypto);
  1587. return new SubjectKeyIdentifierExtension(pvtsutils.Convert.ToHex(id), critical);
  1588. }
  1589. constructor(...args) {
  1590. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1591. super(args[0]);
  1592. const value = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.SubjectKeyIdentifier);
  1593. this.keyId = pvtsutils.Convert.ToHex(value);
  1594. }
  1595. else {
  1596. const identifier = typeof args[0] === "string"
  1597. ? pvtsutils.Convert.FromHex(args[0])
  1598. : args[0];
  1599. const value = new asn1X509__namespace.SubjectKeyIdentifier(identifier);
  1600. super(asn1X509__namespace.id_ce_subjectKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
  1601. this.keyId = pvtsutils.Convert.ToHex(identifier);
  1602. }
  1603. }
  1604. toTextObject() {
  1605. const obj = this.toTextObjectWithoutValue();
  1606. const asn = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.SubjectKeyIdentifier);
  1607. obj[""] = asn;
  1608. return obj;
  1609. }
  1610. }
  1611. SubjectKeyIdentifierExtension.NAME = "Subject Key Identifier";
  1612. class SubjectAlternativeNameExtension extends Extension {
  1613. constructor(...args) {
  1614. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1615. super(args[0]);
  1616. }
  1617. else {
  1618. super(asn1X509__namespace.id_ce_subjectAltName, args[1], new GeneralNames(args[0] || []).rawData);
  1619. }
  1620. }
  1621. onInit(asn) {
  1622. super.onInit(asn);
  1623. const value = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.SubjectAlternativeName);
  1624. this.names = new GeneralNames(value);
  1625. }
  1626. toTextObject() {
  1627. const obj = this.toTextObjectWithoutValue();
  1628. const namesObj = this.names.toTextObject();
  1629. for (const key in namesObj) {
  1630. obj[key] = namesObj[key];
  1631. }
  1632. return obj;
  1633. }
  1634. }
  1635. SubjectAlternativeNameExtension.NAME = "Subject Alternative Name";
  1636. class ExtensionFactory {
  1637. static register(id, type) {
  1638. this.items.set(id, type);
  1639. }
  1640. static create(data) {
  1641. const extension = new Extension(data);
  1642. const Type = this.items.get(extension.type);
  1643. if (Type) {
  1644. return new Type(data);
  1645. }
  1646. return extension;
  1647. }
  1648. }
  1649. ExtensionFactory.items = new Map();
  1650. class CertificatePolicyExtension extends Extension {
  1651. constructor(...args) {
  1652. var _a;
  1653. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1654. super(args[0]);
  1655. const asnPolicies = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.CertificatePolicies);
  1656. this.policies = asnPolicies.map((o) => o.policyIdentifier);
  1657. }
  1658. else {
  1659. const policies = args[0];
  1660. const critical = (_a = args[1]) !== null && _a !== void 0 ? _a : false;
  1661. const value = new asn1X509__namespace.CertificatePolicies(policies.map((o) => (new asn1X509__namespace.PolicyInformation({ policyIdentifier: o }))));
  1662. super(asn1X509__namespace.id_ce_certificatePolicies, critical, asn1Schema.AsnConvert.serialize(value));
  1663. this.policies = policies;
  1664. }
  1665. }
  1666. toTextObject() {
  1667. const obj = this.toTextObjectWithoutValue();
  1668. obj["Policy"] = this.policies.map((o) => new TextObject("", {}, OidSerializer.toString(o)));
  1669. return obj;
  1670. }
  1671. }
  1672. CertificatePolicyExtension.NAME = "Certificate Policies";
  1673. ExtensionFactory.register(asn1X509__namespace.id_ce_certificatePolicies, CertificatePolicyExtension);
  1674. class CRLDistributionPointsExtension extends Extension {
  1675. constructor(...args) {
  1676. var _a;
  1677. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1678. super(args[0]);
  1679. }
  1680. else if (Array.isArray(args[0]) && typeof args[0][0] === "string") {
  1681. const urls = args[0];
  1682. const dps = urls.map((url) => {
  1683. return new asn1X509__namespace.DistributionPoint({
  1684. distributionPoint: new asn1X509__namespace.DistributionPointName({ fullName: [new asn1X509__namespace.GeneralName({ uniformResourceIdentifier: url })] }),
  1685. });
  1686. });
  1687. const value = new asn1X509__namespace.CRLDistributionPoints(dps);
  1688. super(asn1X509__namespace.id_ce_cRLDistributionPoints, args[1], asn1Schema.AsnConvert.serialize(value));
  1689. }
  1690. else {
  1691. const value = new asn1X509__namespace.CRLDistributionPoints(args[0]);
  1692. super(asn1X509__namespace.id_ce_cRLDistributionPoints, args[1], asn1Schema.AsnConvert.serialize(value));
  1693. }
  1694. (_a = this.distributionPoints) !== null && _a !== void 0 ? _a : (this.distributionPoints = []);
  1695. }
  1696. onInit(asn) {
  1697. super.onInit(asn);
  1698. const crlExt = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.CRLDistributionPoints);
  1699. this.distributionPoints = crlExt;
  1700. }
  1701. toTextObject() {
  1702. const obj = this.toTextObjectWithoutValue();
  1703. obj["Distribution Point"] = this.distributionPoints.map((dp) => {
  1704. var _a;
  1705. const dpObj = {};
  1706. if (dp.distributionPoint) {
  1707. dpObj[""] = (_a = dp.distributionPoint.fullName) === null || _a === void 0 ? void 0 : _a.map((name) => new GeneralName(name).toString()).join(", ");
  1708. }
  1709. if (dp.reasons) {
  1710. dpObj["Reasons"] = dp.reasons.toString();
  1711. }
  1712. if (dp.cRLIssuer) {
  1713. dpObj["CRL Issuer"] = dp.cRLIssuer.map((issuer) => issuer.toString()).join(", ");
  1714. }
  1715. return dpObj;
  1716. });
  1717. return obj;
  1718. }
  1719. }
  1720. CRLDistributionPointsExtension.NAME = "CRL Distribution Points";
  1721. class AuthorityInfoAccessExtension extends Extension {
  1722. constructor(...args) {
  1723. var _a, _b, _c, _d;
  1724. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1725. super(args[0]);
  1726. }
  1727. else if (args[0] instanceof asn1X509__namespace.AuthorityInfoAccessSyntax) {
  1728. const value = new asn1X509__namespace.AuthorityInfoAccessSyntax(args[0]);
  1729. super(asn1X509__namespace.id_pe_authorityInfoAccess, args[1], asn1Schema.AsnConvert.serialize(value));
  1730. }
  1731. else {
  1732. const params = args[0];
  1733. const value = new asn1X509__namespace.AuthorityInfoAccessSyntax();
  1734. addAccessDescriptions(value, params, asn1X509__namespace.id_ad_ocsp, "ocsp");
  1735. addAccessDescriptions(value, params, asn1X509__namespace.id_ad_caIssuers, "caIssuers");
  1736. addAccessDescriptions(value, params, asn1X509__namespace.id_ad_timeStamping, "timeStamping");
  1737. addAccessDescriptions(value, params, asn1X509__namespace.id_ad_caRepository, "caRepository");
  1738. super(asn1X509__namespace.id_pe_authorityInfoAccess, args[1], asn1Schema.AsnConvert.serialize(value));
  1739. }
  1740. (_a = this.ocsp) !== null && _a !== void 0 ? _a : (this.ocsp = []);
  1741. (_b = this.caIssuers) !== null && _b !== void 0 ? _b : (this.caIssuers = []);
  1742. (_c = this.timeStamping) !== null && _c !== void 0 ? _c : (this.timeStamping = []);
  1743. (_d = this.caRepository) !== null && _d !== void 0 ? _d : (this.caRepository = []);
  1744. }
  1745. onInit(asn) {
  1746. super.onInit(asn);
  1747. this.ocsp = [];
  1748. this.caIssuers = [];
  1749. this.timeStamping = [];
  1750. this.caRepository = [];
  1751. const aia = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.AuthorityInfoAccessSyntax);
  1752. aia.forEach((accessDescription) => {
  1753. switch (accessDescription.accessMethod) {
  1754. case asn1X509__namespace.id_ad_ocsp:
  1755. this.ocsp.push(new GeneralName(accessDescription.accessLocation));
  1756. break;
  1757. case asn1X509__namespace.id_ad_caIssuers:
  1758. this.caIssuers.push(new GeneralName(accessDescription.accessLocation));
  1759. break;
  1760. case asn1X509__namespace.id_ad_timeStamping:
  1761. this.timeStamping.push(new GeneralName(accessDescription.accessLocation));
  1762. break;
  1763. case asn1X509__namespace.id_ad_caRepository:
  1764. this.caRepository.push(new GeneralName(accessDescription.accessLocation));
  1765. break;
  1766. }
  1767. });
  1768. }
  1769. toTextObject() {
  1770. const obj = this.toTextObjectWithoutValue();
  1771. if (this.ocsp.length) {
  1772. addUrlsToObject(obj, "OCSP", this.ocsp);
  1773. }
  1774. if (this.caIssuers.length) {
  1775. addUrlsToObject(obj, "CA Issuers", this.caIssuers);
  1776. }
  1777. if (this.timeStamping.length) {
  1778. addUrlsToObject(obj, "Time Stamping", this.timeStamping);
  1779. }
  1780. if (this.caRepository.length) {
  1781. addUrlsToObject(obj, "CA Repository", this.caRepository);
  1782. }
  1783. return obj;
  1784. }
  1785. }
  1786. AuthorityInfoAccessExtension.NAME = "Authority Info Access";
  1787. function addUrlsToObject(obj, key, urls) {
  1788. if (urls.length === 1) {
  1789. obj[key] = urls[0].toTextObject();
  1790. }
  1791. else {
  1792. const names = new TextObject("");
  1793. urls.forEach((name, index) => {
  1794. const nameObj = name.toTextObject();
  1795. const indexedKey = `${nameObj[TextObject.NAME]} ${index + 1}`;
  1796. let field = names[indexedKey];
  1797. if (!Array.isArray(field)) {
  1798. field = [];
  1799. names[indexedKey] = field;
  1800. }
  1801. field.push(nameObj);
  1802. });
  1803. obj[key] = names;
  1804. }
  1805. }
  1806. function addAccessDescriptions(value, params, method, key) {
  1807. const items = params[key];
  1808. if (items) {
  1809. const array = Array.isArray(items) ? items : [items];
  1810. array.forEach((url) => {
  1811. if (typeof url === "string") {
  1812. url = new GeneralName("url", url);
  1813. }
  1814. value.push(new asn1X509__namespace.AccessDescription({
  1815. accessMethod: method,
  1816. accessLocation: asn1Schema.AsnConvert.parse(url.rawData, asn1X509__namespace.GeneralName),
  1817. }));
  1818. });
  1819. }
  1820. }
  1821. class IssuerAlternativeNameExtension extends Extension {
  1822. constructor(...args) {
  1823. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1824. super(args[0]);
  1825. }
  1826. else {
  1827. super(asn1X509__namespace.id_ce_issuerAltName, args[1], new GeneralNames(args[0] || []).rawData);
  1828. }
  1829. }
  1830. onInit(asn) {
  1831. super.onInit(asn);
  1832. const value = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.GeneralNames);
  1833. this.names = new GeneralNames(value);
  1834. }
  1835. toTextObject() {
  1836. const obj = this.toTextObjectWithoutValue();
  1837. const namesObj = this.names.toTextObject();
  1838. for (const key in namesObj) {
  1839. obj[key] = namesObj[key];
  1840. }
  1841. return obj;
  1842. }
  1843. }
  1844. IssuerAlternativeNameExtension.NAME = "Issuer Alternative Name";
  1845. class Attribute extends AsnData {
  1846. constructor(...args) {
  1847. let raw;
  1848. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1849. raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
  1850. }
  1851. else {
  1852. const type = args[0];
  1853. const values = Array.isArray(args[1])
  1854. ? args[1].map((o) => pvtsutils.BufferSourceConverter.toArrayBuffer(o))
  1855. : [];
  1856. raw = asn1Schema.AsnConvert.serialize(new asn1X509.Attribute({
  1857. type, values,
  1858. }));
  1859. }
  1860. super(raw, asn1X509.Attribute);
  1861. }
  1862. onInit(asn) {
  1863. this.type = asn.type;
  1864. this.values = asn.values;
  1865. }
  1866. toTextObject() {
  1867. const obj = this.toTextObjectWithoutValue();
  1868. obj["Value"] = this.values.map((o) => new TextObject("", { "": o }));
  1869. return obj;
  1870. }
  1871. toTextObjectWithoutValue() {
  1872. const obj = this.toTextObjectEmpty();
  1873. if (obj[TextObject.NAME] === Attribute.NAME) {
  1874. obj[TextObject.NAME] = OidSerializer.toString(this.type);
  1875. }
  1876. return obj;
  1877. }
  1878. }
  1879. Attribute.NAME = "Attribute";
  1880. class ChallengePasswordAttribute extends Attribute {
  1881. constructor(...args) {
  1882. var _a;
  1883. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1884. super(args[0]);
  1885. }
  1886. else {
  1887. const value = new asnPkcs9__namespace.ChallengePassword({ printableString: args[0] });
  1888. super(asnPkcs9__namespace.id_pkcs9_at_challengePassword, [asn1Schema.AsnConvert.serialize(value)]);
  1889. }
  1890. (_a = this.password) !== null && _a !== void 0 ? _a : (this.password = "");
  1891. }
  1892. onInit(asn) {
  1893. super.onInit(asn);
  1894. if (this.values[0]) {
  1895. const value = asn1Schema.AsnConvert.parse(this.values[0], asnPkcs9__namespace.ChallengePassword);
  1896. this.password = value.toString();
  1897. }
  1898. }
  1899. toTextObject() {
  1900. const obj = this.toTextObjectWithoutValue();
  1901. obj[TextObject.VALUE] = this.password;
  1902. return obj;
  1903. }
  1904. }
  1905. ChallengePasswordAttribute.NAME = "Challenge Password";
  1906. class ExtensionsAttribute extends Attribute {
  1907. constructor(...args) {
  1908. var _a;
  1909. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  1910. super(args[0]);
  1911. }
  1912. else {
  1913. const extensions = args[0];
  1914. const value = new asn1X509__namespace.Extensions();
  1915. for (const extension of extensions) {
  1916. value.push(asn1Schema.AsnConvert.parse(extension.rawData, asn1X509__namespace.Extension));
  1917. }
  1918. super(asnPkcs9__namespace.id_pkcs9_at_extensionRequest, [asn1Schema.AsnConvert.serialize(value)]);
  1919. }
  1920. (_a = this.items) !== null && _a !== void 0 ? _a : (this.items = []);
  1921. }
  1922. onInit(asn) {
  1923. super.onInit(asn);
  1924. if (this.values[0]) {
  1925. const value = asn1Schema.AsnConvert.parse(this.values[0], asn1X509__namespace.Extensions);
  1926. this.items = value.map((o) => ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o)));
  1927. }
  1928. }
  1929. toTextObject() {
  1930. const obj = this.toTextObjectWithoutValue();
  1931. const extensions = this.items.map((o) => o.toTextObject());
  1932. for (const extension of extensions) {
  1933. obj[extension[TextObject.NAME]] = extension;
  1934. }
  1935. return obj;
  1936. }
  1937. }
  1938. ExtensionsAttribute.NAME = "Extensions";
  1939. class AttributeFactory {
  1940. static register(id, type) {
  1941. this.items.set(id, type);
  1942. }
  1943. static create(data) {
  1944. const attribute = new Attribute(data);
  1945. const Type = this.items.get(attribute.type);
  1946. if (Type) {
  1947. return new Type(data);
  1948. }
  1949. return attribute;
  1950. }
  1951. }
  1952. AttributeFactory.items = new Map();
  1953. const diAsnSignatureFormatter = "crypto.signatureFormatter";
  1954. class AsnDefaultSignatureFormatter {
  1955. toAsnSignature(algorithm, signature) {
  1956. return pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
  1957. }
  1958. toWebSignature(algorithm, signature) {
  1959. return pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
  1960. }
  1961. }
  1962. var RsaAlgorithm_1;
  1963. exports.RsaAlgorithm = RsaAlgorithm_1 = class RsaAlgorithm {
  1964. static createPssParams(hash, saltLength) {
  1965. const hashAlgorithm = RsaAlgorithm_1.getHashAlgorithm(hash);
  1966. if (!hashAlgorithm) {
  1967. return null;
  1968. }
  1969. return new asn1Rsa__namespace.RsaSaPssParams({
  1970. hashAlgorithm,
  1971. maskGenAlgorithm: new asn1X509.AlgorithmIdentifier({
  1972. algorithm: asn1Rsa__namespace.id_mgf1,
  1973. parameters: asn1Schema.AsnConvert.serialize(hashAlgorithm),
  1974. }),
  1975. saltLength,
  1976. });
  1977. }
  1978. static getHashAlgorithm(alg) {
  1979. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  1980. if (typeof alg === "string") {
  1981. return algProv.toAsnAlgorithm({ name: alg });
  1982. }
  1983. if (typeof alg === "object" && alg && "name" in alg) {
  1984. return algProv.toAsnAlgorithm(alg);
  1985. }
  1986. return null;
  1987. }
  1988. toAsnAlgorithm(alg) {
  1989. switch (alg.name.toLowerCase()) {
  1990. case "rsassa-pkcs1-v1_5":
  1991. if ("hash" in alg) {
  1992. let hash;
  1993. if (typeof alg.hash === "string") {
  1994. hash = alg.hash;
  1995. }
  1996. else if (alg.hash && typeof alg.hash === "object"
  1997. && "name" in alg.hash && typeof alg.hash.name === "string") {
  1998. hash = alg.hash.name.toUpperCase();
  1999. }
  2000. else {
  2001. throw new Error("Cannot get hash algorithm name");
  2002. }
  2003. switch (hash.toLowerCase()) {
  2004. case "sha-1":
  2005. return new asn1X509.AlgorithmIdentifier({
  2006. algorithm: asn1Rsa__namespace.id_sha1WithRSAEncryption, parameters: null,
  2007. });
  2008. case "sha-256":
  2009. return new asn1X509.AlgorithmIdentifier({
  2010. algorithm: asn1Rsa__namespace.id_sha256WithRSAEncryption, parameters: null,
  2011. });
  2012. case "sha-384":
  2013. return new asn1X509.AlgorithmIdentifier({
  2014. algorithm: asn1Rsa__namespace.id_sha384WithRSAEncryption, parameters: null,
  2015. });
  2016. case "sha-512":
  2017. return new asn1X509.AlgorithmIdentifier({
  2018. algorithm: asn1Rsa__namespace.id_sha512WithRSAEncryption, parameters: null,
  2019. });
  2020. }
  2021. }
  2022. else {
  2023. return new asn1X509.AlgorithmIdentifier({
  2024. algorithm: asn1Rsa__namespace.id_rsaEncryption, parameters: null,
  2025. });
  2026. }
  2027. break;
  2028. case "rsa-pss":
  2029. if ("hash" in alg) {
  2030. if (!("saltLength" in alg && typeof alg.saltLength === "number")) {
  2031. throw new Error("Cannot get 'saltLength' from 'alg' argument");
  2032. }
  2033. const pssParams = RsaAlgorithm_1.createPssParams(alg.hash, alg.saltLength);
  2034. if (!pssParams) {
  2035. throw new Error("Cannot create PSS parameters");
  2036. }
  2037. return new asn1X509.AlgorithmIdentifier({
  2038. algorithm: asn1Rsa__namespace.id_RSASSA_PSS, parameters: asn1Schema.AsnConvert.serialize(pssParams),
  2039. });
  2040. }
  2041. else {
  2042. return new asn1X509.AlgorithmIdentifier({
  2043. algorithm: asn1Rsa__namespace.id_RSASSA_PSS, parameters: null,
  2044. });
  2045. }
  2046. }
  2047. return null;
  2048. }
  2049. toWebAlgorithm(alg) {
  2050. switch (alg.algorithm) {
  2051. case asn1Rsa__namespace.id_rsaEncryption:
  2052. return { name: "RSASSA-PKCS1-v1_5" };
  2053. case asn1Rsa__namespace.id_sha1WithRSAEncryption:
  2054. return {
  2055. name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" },
  2056. };
  2057. case asn1Rsa__namespace.id_sha256WithRSAEncryption:
  2058. return {
  2059. name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" },
  2060. };
  2061. case asn1Rsa__namespace.id_sha384WithRSAEncryption:
  2062. return {
  2063. name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" },
  2064. };
  2065. case asn1Rsa__namespace.id_sha512WithRSAEncryption:
  2066. return {
  2067. name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" },
  2068. };
  2069. case asn1Rsa__namespace.id_RSASSA_PSS:
  2070. if (alg.parameters) {
  2071. const pssParams = asn1Schema.AsnConvert.parse(alg.parameters, asn1Rsa__namespace.RsaSaPssParams);
  2072. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  2073. const hashAlg = algProv.toWebAlgorithm(pssParams.hashAlgorithm);
  2074. return {
  2075. name: "RSA-PSS",
  2076. hash: hashAlg,
  2077. saltLength: pssParams.saltLength,
  2078. };
  2079. }
  2080. else {
  2081. return { name: "RSA-PSS" };
  2082. }
  2083. }
  2084. return null;
  2085. }
  2086. };
  2087. exports.RsaAlgorithm = RsaAlgorithm_1 = tslib.__decorate([
  2088. tsyringe.injectable()
  2089. ], exports.RsaAlgorithm);
  2090. tsyringe.container.registerSingleton(diAlgorithm, exports.RsaAlgorithm);
  2091. exports.ShaAlgorithm = class ShaAlgorithm {
  2092. toAsnAlgorithm(alg) {
  2093. switch (alg.name.toLowerCase()) {
  2094. case "sha-1":
  2095. return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha1 });
  2096. case "sha-256":
  2097. return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha256 });
  2098. case "sha-384":
  2099. return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha384 });
  2100. case "sha-512":
  2101. return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha512 });
  2102. }
  2103. return null;
  2104. }
  2105. toWebAlgorithm(alg) {
  2106. switch (alg.algorithm) {
  2107. case asn1Rsa.id_sha1:
  2108. return { name: "SHA-1" };
  2109. case asn1Rsa.id_sha256:
  2110. return { name: "SHA-256" };
  2111. case asn1Rsa.id_sha384:
  2112. return { name: "SHA-384" };
  2113. case asn1Rsa.id_sha512:
  2114. return { name: "SHA-512" };
  2115. }
  2116. return null;
  2117. }
  2118. };
  2119. exports.ShaAlgorithm = tslib.__decorate([
  2120. tsyringe.injectable()
  2121. ], exports.ShaAlgorithm);
  2122. tsyringe.container.registerSingleton(diAlgorithm, exports.ShaAlgorithm);
  2123. class AsnEcSignatureFormatter {
  2124. addPadding(pointSize, data) {
  2125. const bytes = pvtsutils.BufferSourceConverter.toUint8Array(data);
  2126. const res = new Uint8Array(pointSize);
  2127. res.set(bytes, pointSize - bytes.length);
  2128. return res.buffer;
  2129. }
  2130. removePadding(data, positive = false) {
  2131. let bytes = pvtsutils.BufferSourceConverter.toUint8Array(data);
  2132. for (let i = 0; i < bytes.length; i++) {
  2133. if (!bytes[i]) {
  2134. continue;
  2135. }
  2136. bytes = bytes.slice(i);
  2137. break;
  2138. }
  2139. if (positive && bytes[0] > 127) {
  2140. const result = new Uint8Array(bytes.length + 1);
  2141. result.set(bytes, 1);
  2142. return result.buffer;
  2143. }
  2144. return bytes.buffer;
  2145. }
  2146. toAsnSignature(algorithm, signature) {
  2147. if (algorithm.name === "ECDSA") {
  2148. const namedCurve = algorithm.namedCurve;
  2149. const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
  2150. || AsnEcSignatureFormatter.defaultNamedCurveSize;
  2151. const ecSignature = new asn1Ecc.ECDSASigValue();
  2152. const uint8Signature = pvtsutils.BufferSourceConverter.toUint8Array(signature);
  2153. ecSignature.r = this.removePadding(uint8Signature.slice(0, pointSize), true);
  2154. ecSignature.s = this.removePadding(uint8Signature.slice(pointSize, pointSize + pointSize), true);
  2155. return asn1Schema.AsnConvert.serialize(ecSignature);
  2156. }
  2157. return null;
  2158. }
  2159. toWebSignature(algorithm, signature) {
  2160. if (algorithm.name === "ECDSA") {
  2161. const ecSigValue = asn1Schema.AsnConvert.parse(signature, asn1Ecc.ECDSASigValue);
  2162. const namedCurve = algorithm.namedCurve;
  2163. const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
  2164. || AsnEcSignatureFormatter.defaultNamedCurveSize;
  2165. const r = this.addPadding(pointSize, this.removePadding(ecSigValue.r));
  2166. const s = this.addPadding(pointSize, this.removePadding(ecSigValue.s));
  2167. return pvtsutils.combine(r, s);
  2168. }
  2169. return null;
  2170. }
  2171. }
  2172. AsnEcSignatureFormatter.namedCurveSize = new Map();
  2173. AsnEcSignatureFormatter.defaultNamedCurveSize = 32;
  2174. const idX25519 = "1.3.101.110";
  2175. const idX448 = "1.3.101.111";
  2176. const idEd25519 = "1.3.101.112";
  2177. const idEd448 = "1.3.101.113";
  2178. exports.EdAlgorithm = class EdAlgorithm {
  2179. toAsnAlgorithm(alg) {
  2180. let algorithm = null;
  2181. switch (alg.name.toLowerCase()) {
  2182. case "ed25519":
  2183. algorithm = idEd25519;
  2184. break;
  2185. case "x25519":
  2186. algorithm = idX25519;
  2187. break;
  2188. case "eddsa":
  2189. switch (alg.namedCurve.toLowerCase()) {
  2190. case "ed25519":
  2191. algorithm = idEd25519;
  2192. break;
  2193. case "ed448":
  2194. algorithm = idEd448;
  2195. break;
  2196. }
  2197. break;
  2198. case "ecdh-es":
  2199. switch (alg.namedCurve.toLowerCase()) {
  2200. case "x25519":
  2201. algorithm = idX25519;
  2202. break;
  2203. case "x448":
  2204. algorithm = idX448;
  2205. break;
  2206. }
  2207. }
  2208. if (algorithm) {
  2209. return new asn1X509.AlgorithmIdentifier({ algorithm });
  2210. }
  2211. return null;
  2212. }
  2213. toWebAlgorithm(alg) {
  2214. switch (alg.algorithm) {
  2215. case idEd25519:
  2216. return { name: "Ed25519" };
  2217. case idEd448:
  2218. return {
  2219. name: "EdDSA", namedCurve: "Ed448",
  2220. };
  2221. case idX25519:
  2222. return { name: "X25519" };
  2223. case idX448:
  2224. return {
  2225. name: "ECDH-ES", namedCurve: "X448",
  2226. };
  2227. }
  2228. return null;
  2229. }
  2230. };
  2231. exports.EdAlgorithm = tslib.__decorate([
  2232. tsyringe.injectable()
  2233. ], exports.EdAlgorithm);
  2234. tsyringe.container.registerSingleton(diAlgorithm, exports.EdAlgorithm);
  2235. var _Pkcs10CertificateRequest_tbs, _Pkcs10CertificateRequest_subjectName, _Pkcs10CertificateRequest_subject, _Pkcs10CertificateRequest_signatureAlgorithm, _Pkcs10CertificateRequest_signature, _Pkcs10CertificateRequest_publicKey, _Pkcs10CertificateRequest_attributes, _Pkcs10CertificateRequest_extensions;
  2236. class Pkcs10CertificateRequest extends PemData {
  2237. get subjectName() {
  2238. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f")) {
  2239. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_subjectName, new Name(this.asn.certificationRequestInfo.subject), "f");
  2240. }
  2241. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f");
  2242. }
  2243. get subject() {
  2244. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f")) {
  2245. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_subject, this.subjectName.toString(), "f");
  2246. }
  2247. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f");
  2248. }
  2249. get signatureAlgorithm() {
  2250. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f")) {
  2251. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  2252. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
  2253. }
  2254. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f");
  2255. }
  2256. get signature() {
  2257. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f")) {
  2258. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_signature, this.asn.signature, "f");
  2259. }
  2260. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f");
  2261. }
  2262. get publicKey() {
  2263. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f")) {
  2264. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_publicKey, new PublicKey(this.asn.certificationRequestInfo.subjectPKInfo), "f");
  2265. }
  2266. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f");
  2267. }
  2268. get attributes() {
  2269. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f")) {
  2270. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_attributes, this.asn.certificationRequestInfo.attributes
  2271. .map((o) => AttributeFactory.create(asn1Schema.AsnConvert.serialize(o))), "f");
  2272. }
  2273. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f");
  2274. }
  2275. get extensions() {
  2276. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f")) {
  2277. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, [], "f");
  2278. const extensions = this.getAttribute(asnPkcs9.id_pkcs9_at_extensionRequest);
  2279. if (extensions instanceof ExtensionsAttribute) {
  2280. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, extensions.items, "f");
  2281. }
  2282. }
  2283. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f");
  2284. }
  2285. get tbs() {
  2286. if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f")) {
  2287. tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_tbs, this.asn.certificationRequestInfoRaw
  2288. || asn1Schema.AsnConvert.serialize(this.asn.certificationRequestInfo), "f");
  2289. }
  2290. return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f");
  2291. }
  2292. constructor(param) {
  2293. const args = PemData.isAsnEncoded(param) ? [param, asn1Csr.CertificationRequest] : [param];
  2294. super(args[0], args[1]);
  2295. _Pkcs10CertificateRequest_tbs.set(this, void 0);
  2296. _Pkcs10CertificateRequest_subjectName.set(this, void 0);
  2297. _Pkcs10CertificateRequest_subject.set(this, void 0);
  2298. _Pkcs10CertificateRequest_signatureAlgorithm.set(this, void 0);
  2299. _Pkcs10CertificateRequest_signature.set(this, void 0);
  2300. _Pkcs10CertificateRequest_publicKey.set(this, void 0);
  2301. _Pkcs10CertificateRequest_attributes.set(this, void 0);
  2302. _Pkcs10CertificateRequest_extensions.set(this, void 0);
  2303. this.tag = PemConverter.CertificateRequestTag;
  2304. }
  2305. onInit(_asn) {
  2306. }
  2307. getAttribute(type) {
  2308. for (const attr of this.attributes) {
  2309. if (attr.type === type) {
  2310. return attr;
  2311. }
  2312. }
  2313. return null;
  2314. }
  2315. getAttributes(type) {
  2316. return this.attributes.filter((o) => o.type === type);
  2317. }
  2318. getExtension(type) {
  2319. for (const ext of this.extensions) {
  2320. if (ext.type === type) {
  2321. return ext;
  2322. }
  2323. }
  2324. return null;
  2325. }
  2326. getExtensions(type) {
  2327. return this.extensions.filter((o) => o.type === type);
  2328. }
  2329. async verify(crypto = cryptoProvider.get()) {
  2330. const algorithm = {
  2331. ...this.publicKey.algorithm, ...this.signatureAlgorithm,
  2332. };
  2333. const publicKey = await this.publicKey.export(algorithm, ["verify"], crypto);
  2334. const signatureFormatters = tsyringe.container
  2335. .resolveAll(diAsnSignatureFormatter)
  2336. .reverse();
  2337. let signature = null;
  2338. for (const signatureFormatter of signatureFormatters) {
  2339. signature = signatureFormatter.toWebSignature(algorithm, this.signature);
  2340. if (signature) {
  2341. break;
  2342. }
  2343. }
  2344. if (!signature) {
  2345. throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
  2346. }
  2347. const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
  2348. return ok;
  2349. }
  2350. toTextObject() {
  2351. const obj = this.toTextObjectEmpty();
  2352. const req = asn1Schema.AsnConvert.parse(this.rawData, asn1Csr.CertificationRequest);
  2353. const tbs = req.certificationRequestInfo;
  2354. const data = new TextObject("", {
  2355. Version: `${asn1X509.Version[tbs.version]} (${tbs.version})`,
  2356. Subject: this.subject,
  2357. "Subject Public Key Info": this.publicKey,
  2358. });
  2359. if (this.attributes.length) {
  2360. const attrs = new TextObject("");
  2361. for (const ext of this.attributes) {
  2362. const attrObj = ext.toTextObject();
  2363. attrs[attrObj[TextObject.NAME]] = attrObj;
  2364. }
  2365. data["Attributes"] = attrs;
  2366. }
  2367. obj["Data"] = data;
  2368. obj["Signature"] = new TextObject("", {
  2369. Algorithm: TextConverter.serializeAlgorithm(req.signatureAlgorithm),
  2370. "": req.signature,
  2371. });
  2372. return obj;
  2373. }
  2374. }
  2375. _Pkcs10CertificateRequest_tbs = new WeakMap(), _Pkcs10CertificateRequest_subjectName = new WeakMap(), _Pkcs10CertificateRequest_subject = new WeakMap(), _Pkcs10CertificateRequest_signatureAlgorithm = new WeakMap(), _Pkcs10CertificateRequest_signature = new WeakMap(), _Pkcs10CertificateRequest_publicKey = new WeakMap(), _Pkcs10CertificateRequest_attributes = new WeakMap(), _Pkcs10CertificateRequest_extensions = new WeakMap();
  2376. Pkcs10CertificateRequest.NAME = "PKCS#10 Certificate Request";
  2377. class Pkcs10CertificateRequestGenerator {
  2378. static async create(params, crypto = cryptoProvider.get()) {
  2379. if (!params.keys.privateKey) {
  2380. throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
  2381. }
  2382. if (!params.keys.publicKey) {
  2383. throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
  2384. }
  2385. const spki = await crypto.subtle.exportKey("spki", params.keys.publicKey);
  2386. const asnReq = new asn1Csr.CertificationRequest({
  2387. certificationRequestInfo: new asn1Csr.CertificationRequestInfo({ subjectPKInfo: asn1Schema.AsnConvert.parse(spki, asn1X509.SubjectPublicKeyInfo) }),
  2388. });
  2389. if (params.name) {
  2390. const name = params.name instanceof Name
  2391. ? params.name
  2392. : new Name(params.name);
  2393. asnReq.certificationRequestInfo.subject = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
  2394. }
  2395. if (params.attributes) {
  2396. for (const o of params.attributes) {
  2397. asnReq.certificationRequestInfo.attributes.push(asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Attribute));
  2398. }
  2399. }
  2400. if (params.extensions && params.extensions.length) {
  2401. const attr = new asn1X509.Attribute({ type: asnPkcs9.id_pkcs9_at_extensionRequest });
  2402. const extensions = new asn1X509.Extensions();
  2403. for (const o of params.extensions) {
  2404. extensions.push(asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Extension));
  2405. }
  2406. attr.values.push(asn1Schema.AsnConvert.serialize(extensions));
  2407. asnReq.certificationRequestInfo.attributes.push(attr);
  2408. }
  2409. const signingAlgorithm = {
  2410. ...params.signingAlgorithm, ...params.keys.privateKey.algorithm,
  2411. };
  2412. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  2413. asnReq.signatureAlgorithm = algProv.toAsnAlgorithm(signingAlgorithm);
  2414. const tbs = asn1Schema.AsnConvert.serialize(asnReq.certificationRequestInfo);
  2415. const signature = await crypto.subtle.sign(signingAlgorithm, params.keys.privateKey, tbs);
  2416. const signatureFormatters = tsyringe.container
  2417. .resolveAll(diAsnSignatureFormatter)
  2418. .reverse();
  2419. let asnSignature = null;
  2420. for (const signatureFormatter of signatureFormatters) {
  2421. asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
  2422. if (asnSignature) {
  2423. break;
  2424. }
  2425. }
  2426. if (!asnSignature) {
  2427. throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
  2428. }
  2429. asnReq.signature = asnSignature;
  2430. return new Pkcs10CertificateRequest(asn1Schema.AsnConvert.serialize(asnReq));
  2431. }
  2432. }
  2433. var _X509Certificate_tbs, _X509Certificate_serialNumber, _X509Certificate_subjectName, _X509Certificate_subject, _X509Certificate_issuerName, _X509Certificate_issuer, _X509Certificate_notBefore, _X509Certificate_notAfter, _X509Certificate_signatureAlgorithm, _X509Certificate_signature, _X509Certificate_extensions, _X509Certificate_publicKey;
  2434. class X509Certificate extends PemData {
  2435. get publicKey() {
  2436. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_publicKey, "f")) {
  2437. tslib.__classPrivateFieldSet(this, _X509Certificate_publicKey, new PublicKey(this.asn.tbsCertificate.subjectPublicKeyInfo), "f");
  2438. }
  2439. return tslib.__classPrivateFieldGet(this, _X509Certificate_publicKey, "f");
  2440. }
  2441. get serialNumber() {
  2442. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_serialNumber, "f")) {
  2443. const tbs = this.asn.tbsCertificate;
  2444. let serialNumberBytes = new Uint8Array(tbs.serialNumber);
  2445. if (serialNumberBytes.length > 1
  2446. && serialNumberBytes[0] === 0x00
  2447. && serialNumberBytes[1] > 0x7F) {
  2448. serialNumberBytes = serialNumberBytes.slice(1);
  2449. }
  2450. tslib.__classPrivateFieldSet(this, _X509Certificate_serialNumber, pvtsutils.Convert.ToHex(serialNumberBytes), "f");
  2451. }
  2452. return tslib.__classPrivateFieldGet(this, _X509Certificate_serialNumber, "f");
  2453. }
  2454. get subjectName() {
  2455. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_subjectName, "f")) {
  2456. tslib.__classPrivateFieldSet(this, _X509Certificate_subjectName, new Name(this.asn.tbsCertificate.subject), "f");
  2457. }
  2458. return tslib.__classPrivateFieldGet(this, _X509Certificate_subjectName, "f");
  2459. }
  2460. get subject() {
  2461. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_subject, "f")) {
  2462. tslib.__classPrivateFieldSet(this, _X509Certificate_subject, this.subjectName.toString(), "f");
  2463. }
  2464. return tslib.__classPrivateFieldGet(this, _X509Certificate_subject, "f");
  2465. }
  2466. get issuerName() {
  2467. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_issuerName, "f")) {
  2468. tslib.__classPrivateFieldSet(this, _X509Certificate_issuerName, new Name(this.asn.tbsCertificate.issuer), "f");
  2469. }
  2470. return tslib.__classPrivateFieldGet(this, _X509Certificate_issuerName, "f");
  2471. }
  2472. get issuer() {
  2473. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_issuer, "f")) {
  2474. tslib.__classPrivateFieldSet(this, _X509Certificate_issuer, this.issuerName.toString(), "f");
  2475. }
  2476. return tslib.__classPrivateFieldGet(this, _X509Certificate_issuer, "f");
  2477. }
  2478. get notBefore() {
  2479. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_notBefore, "f")) {
  2480. const notBefore = this.asn.tbsCertificate.validity.notBefore.utcTime
  2481. || this.asn.tbsCertificate.validity.notBefore.generalTime;
  2482. if (!notBefore) {
  2483. throw new Error("Cannot get 'notBefore' value");
  2484. }
  2485. tslib.__classPrivateFieldSet(this, _X509Certificate_notBefore, notBefore, "f");
  2486. }
  2487. return tslib.__classPrivateFieldGet(this, _X509Certificate_notBefore, "f");
  2488. }
  2489. get notAfter() {
  2490. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_notAfter, "f")) {
  2491. const notAfter = this.asn.tbsCertificate.validity.notAfter.utcTime
  2492. || this.asn.tbsCertificate.validity.notAfter.generalTime;
  2493. if (!notAfter) {
  2494. throw new Error("Cannot get 'notAfter' value");
  2495. }
  2496. tslib.__classPrivateFieldSet(this, _X509Certificate_notAfter, notAfter, "f");
  2497. }
  2498. return tslib.__classPrivateFieldGet(this, _X509Certificate_notAfter, "f");
  2499. }
  2500. get signatureAlgorithm() {
  2501. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f")) {
  2502. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  2503. tslib.__classPrivateFieldSet(this, _X509Certificate_signatureAlgorithm, algProv
  2504. .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
  2505. }
  2506. return tslib.__classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f");
  2507. }
  2508. get signature() {
  2509. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_signature, "f")) {
  2510. tslib.__classPrivateFieldSet(this, _X509Certificate_signature, this.asn.signatureValue, "f");
  2511. }
  2512. return tslib.__classPrivateFieldGet(this, _X509Certificate_signature, "f");
  2513. }
  2514. get extensions() {
  2515. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_extensions, "f")) {
  2516. tslib.__classPrivateFieldSet(this, _X509Certificate_extensions, [], "f");
  2517. if (this.asn.tbsCertificate.extensions) {
  2518. tslib.__classPrivateFieldSet(this, _X509Certificate_extensions, this.asn.tbsCertificate.extensions.map((o) => (ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o)))), "f");
  2519. }
  2520. }
  2521. return tslib.__classPrivateFieldGet(this, _X509Certificate_extensions, "f");
  2522. }
  2523. get tbs() {
  2524. if (!tslib.__classPrivateFieldGet(this, _X509Certificate_tbs, "f")) {
  2525. tslib.__classPrivateFieldSet(this, _X509Certificate_tbs, this.asn.tbsCertificateRaw || asn1Schema.AsnConvert.serialize(this.asn.tbsCertificate), "f");
  2526. }
  2527. return tslib.__classPrivateFieldGet(this, _X509Certificate_tbs, "f");
  2528. }
  2529. constructor(param) {
  2530. const args = PemData.isAsnEncoded(param) ? [param, asn1X509.Certificate] : [param];
  2531. super(args[0], args[1]);
  2532. _X509Certificate_tbs.set(this, void 0);
  2533. _X509Certificate_serialNumber.set(this, void 0);
  2534. _X509Certificate_subjectName.set(this, void 0);
  2535. _X509Certificate_subject.set(this, void 0);
  2536. _X509Certificate_issuerName.set(this, void 0);
  2537. _X509Certificate_issuer.set(this, void 0);
  2538. _X509Certificate_notBefore.set(this, void 0);
  2539. _X509Certificate_notAfter.set(this, void 0);
  2540. _X509Certificate_signatureAlgorithm.set(this, void 0);
  2541. _X509Certificate_signature.set(this, void 0);
  2542. _X509Certificate_extensions.set(this, void 0);
  2543. _X509Certificate_publicKey.set(this, void 0);
  2544. this.tag = PemConverter.CertificateTag;
  2545. }
  2546. onInit(_asn) {
  2547. }
  2548. getExtension(type) {
  2549. for (const ext of this.extensions) {
  2550. if (typeof type === "string") {
  2551. if (ext.type === type) {
  2552. return ext;
  2553. }
  2554. }
  2555. else {
  2556. if (ext instanceof type) {
  2557. return ext;
  2558. }
  2559. }
  2560. }
  2561. return null;
  2562. }
  2563. getExtensions(type) {
  2564. return this.extensions.filter((o) => {
  2565. if (typeof type === "string") {
  2566. return o.type === type;
  2567. }
  2568. else {
  2569. return o instanceof type;
  2570. }
  2571. });
  2572. }
  2573. async verify(params = {}, crypto = cryptoProvider.get()) {
  2574. let keyAlgorithm;
  2575. let publicKey;
  2576. const paramsKey = params.publicKey;
  2577. try {
  2578. if (!paramsKey) {
  2579. keyAlgorithm = {
  2580. ...this.publicKey.algorithm, ...this.signatureAlgorithm,
  2581. };
  2582. publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
  2583. }
  2584. else if ("publicKey" in paramsKey) {
  2585. keyAlgorithm = {
  2586. ...paramsKey.publicKey.algorithm, ...this.signatureAlgorithm,
  2587. };
  2588. publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"], crypto);
  2589. }
  2590. else if (paramsKey instanceof PublicKey) {
  2591. keyAlgorithm = {
  2592. ...paramsKey.algorithm, ...this.signatureAlgorithm,
  2593. };
  2594. publicKey = await paramsKey.export(keyAlgorithm, ["verify"], crypto);
  2595. }
  2596. else if (pvtsutils.BufferSourceConverter.isBufferSource(paramsKey)) {
  2597. const key = new PublicKey(paramsKey);
  2598. keyAlgorithm = {
  2599. ...key.algorithm, ...this.signatureAlgorithm,
  2600. };
  2601. publicKey = await key.export(keyAlgorithm, ["verify"], crypto);
  2602. }
  2603. else {
  2604. keyAlgorithm = {
  2605. ...paramsKey.algorithm, ...this.signatureAlgorithm,
  2606. };
  2607. publicKey = paramsKey;
  2608. }
  2609. }
  2610. catch {
  2611. return false;
  2612. }
  2613. const signatureFormatters = tsyringe.container
  2614. .resolveAll(diAsnSignatureFormatter)
  2615. .reverse();
  2616. let signature = null;
  2617. for (const signatureFormatter of signatureFormatters) {
  2618. signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
  2619. if (signature) {
  2620. break;
  2621. }
  2622. }
  2623. if (!signature) {
  2624. throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
  2625. }
  2626. const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
  2627. if (params.signatureOnly) {
  2628. return ok;
  2629. }
  2630. else {
  2631. const date = params.date || new Date();
  2632. const time = date.getTime();
  2633. return ok && this.notBefore.getTime() < time && time < this.notAfter.getTime();
  2634. }
  2635. }
  2636. async getThumbprint(...args) {
  2637. let crypto;
  2638. let algorithm = "SHA-1";
  2639. if (args[0]) {
  2640. if (!args[0].subtle) {
  2641. algorithm = args[0] || algorithm;
  2642. crypto = args[1];
  2643. }
  2644. else {
  2645. crypto = args[0];
  2646. }
  2647. }
  2648. crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
  2649. return await crypto.subtle.digest(algorithm, this.rawData);
  2650. }
  2651. async isSelfSigned(crypto = cryptoProvider.get()) {
  2652. return this.subject === this.issuer && await this.verify({ signatureOnly: true }, crypto);
  2653. }
  2654. toTextObject() {
  2655. const obj = this.toTextObjectEmpty();
  2656. const cert = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.Certificate);
  2657. const tbs = cert.tbsCertificate;
  2658. const data = new TextObject("", {
  2659. Version: `${asn1X509.Version[tbs.version]} (${tbs.version})`,
  2660. "Serial Number": tbs.serialNumber,
  2661. "Signature Algorithm": TextConverter.serializeAlgorithm(tbs.signature),
  2662. Issuer: this.issuer,
  2663. Validity: new TextObject("", {
  2664. "Not Before": tbs.validity.notBefore.getTime(),
  2665. "Not After": tbs.validity.notAfter.getTime(),
  2666. }),
  2667. Subject: this.subject,
  2668. "Subject Public Key Info": this.publicKey,
  2669. });
  2670. if (tbs.issuerUniqueID) {
  2671. data["Issuer Unique ID"] = tbs.issuerUniqueID;
  2672. }
  2673. if (tbs.subjectUniqueID) {
  2674. data["Subject Unique ID"] = tbs.subjectUniqueID;
  2675. }
  2676. if (this.extensions.length) {
  2677. const extensions = new TextObject("");
  2678. for (const ext of this.extensions) {
  2679. const extObj = ext.toTextObject();
  2680. extensions[extObj[TextObject.NAME]] = extObj;
  2681. }
  2682. data["Extensions"] = extensions;
  2683. }
  2684. obj["Data"] = data;
  2685. obj["Signature"] = new TextObject("", {
  2686. Algorithm: TextConverter.serializeAlgorithm(cert.signatureAlgorithm),
  2687. "": cert.signatureValue,
  2688. });
  2689. return obj;
  2690. }
  2691. }
  2692. _X509Certificate_tbs = new WeakMap(), _X509Certificate_serialNumber = new WeakMap(), _X509Certificate_subjectName = new WeakMap(), _X509Certificate_subject = new WeakMap(), _X509Certificate_issuerName = new WeakMap(), _X509Certificate_issuer = new WeakMap(), _X509Certificate_notBefore = new WeakMap(), _X509Certificate_notAfter = new WeakMap(), _X509Certificate_signatureAlgorithm = new WeakMap(), _X509Certificate_signature = new WeakMap(), _X509Certificate_extensions = new WeakMap(), _X509Certificate_publicKey = new WeakMap();
  2693. X509Certificate.NAME = "Certificate";
  2694. class X509Certificates extends Array {
  2695. constructor(param) {
  2696. super();
  2697. if (PemData.isAsnEncoded(param)) {
  2698. this.import(param);
  2699. }
  2700. else if (param instanceof X509Certificate) {
  2701. this.push(param);
  2702. }
  2703. else if (Array.isArray(param)) {
  2704. for (const item of param) {
  2705. this.push(item);
  2706. }
  2707. }
  2708. }
  2709. export(format) {
  2710. const signedData = new asn1Cms__namespace.SignedData();
  2711. signedData.version = 1;
  2712. signedData.encapContentInfo.eContentType = asn1Cms__namespace.id_data;
  2713. signedData.encapContentInfo.eContent = new asn1Cms__namespace.EncapsulatedContent({ single: new asn1Schema.OctetString() });
  2714. signedData.certificates = new asn1Cms__namespace.CertificateSet(this.map((o) => new asn1Cms__namespace.CertificateChoices({ certificate: asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Certificate) })));
  2715. const cms = new asn1Cms__namespace.ContentInfo({
  2716. contentType: asn1Cms__namespace.id_signedData,
  2717. content: asn1Schema.AsnConvert.serialize(signedData),
  2718. });
  2719. const raw = asn1Schema.AsnConvert.serialize(cms);
  2720. if (format === "raw") {
  2721. return raw;
  2722. }
  2723. return this.toString(format);
  2724. }
  2725. import(data) {
  2726. const raw = PemData.toArrayBuffer(data);
  2727. const cms = asn1Schema.AsnConvert.parse(raw, asn1Cms__namespace.ContentInfo);
  2728. if (cms.contentType !== asn1Cms__namespace.id_signedData) {
  2729. throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");
  2730. }
  2731. const signedData = asn1Schema.AsnConvert.parse(cms.content, asn1Cms__namespace.SignedData);
  2732. this.clear();
  2733. for (const item of signedData.certificates || []) {
  2734. if (item.certificate) {
  2735. this.push(new X509Certificate(item.certificate));
  2736. }
  2737. }
  2738. }
  2739. clear() {
  2740. while (this.pop()) {
  2741. }
  2742. }
  2743. toString(format = "pem") {
  2744. const raw = this.export("raw");
  2745. switch (format) {
  2746. case "pem":
  2747. return PemConverter.encode(raw, "CMS");
  2748. case "pem-chain":
  2749. return this
  2750. .map((o) => o.toString("pem"))
  2751. .join("\n");
  2752. case "asn":
  2753. return asn1Schema.AsnConvert.toString(raw);
  2754. case "hex":
  2755. return pvtsutils.Convert.ToHex(raw);
  2756. case "base64":
  2757. return pvtsutils.Convert.ToBase64(raw);
  2758. case "base64url":
  2759. return pvtsutils.Convert.ToBase64Url(raw);
  2760. case "text":
  2761. return TextConverter.serialize(this.toTextObject());
  2762. default:
  2763. throw TypeError("Argument 'format' is unsupported value");
  2764. }
  2765. }
  2766. toTextObject() {
  2767. const contentInfo = asn1Schema.AsnConvert.parse(this.export("raw"), asn1Cms__namespace.ContentInfo);
  2768. const signedData = asn1Schema.AsnConvert.parse(contentInfo.content, asn1Cms__namespace.SignedData);
  2769. const obj = new TextObject("X509Certificates", {
  2770. "Content Type": OidSerializer.toString(contentInfo.contentType),
  2771. Content: new TextObject("", {
  2772. Version: `${asn1Cms__namespace.CMSVersion[signedData.version]} (${signedData.version})`,
  2773. Certificates: new TextObject("", { Certificate: this.map((o) => o.toTextObject()) }),
  2774. }),
  2775. });
  2776. return obj;
  2777. }
  2778. }
  2779. class X509ChainBuilder {
  2780. constructor(params = {}) {
  2781. this.certificates = [];
  2782. if (params.certificates) {
  2783. this.certificates = params.certificates;
  2784. }
  2785. }
  2786. async build(cert, crypto = cryptoProvider.get()) {
  2787. const chain = new X509Certificates(cert);
  2788. let current = cert;
  2789. while (current = await this.findIssuer(current, crypto)) {
  2790. const thumbprint = await current.getThumbprint(crypto);
  2791. for (const item of chain) {
  2792. const thumbprint2 = await item.getThumbprint(crypto);
  2793. if (pvtsutils.isEqual(thumbprint, thumbprint2)) {
  2794. throw new Error("Cannot build a certificate chain. Circular dependency.");
  2795. }
  2796. }
  2797. chain.push(current);
  2798. }
  2799. return chain;
  2800. }
  2801. async findIssuer(cert, crypto = cryptoProvider.get()) {
  2802. if (!await cert.isSelfSigned(crypto)) {
  2803. const akiExt = cert.getExtension(asn1X509__namespace.id_ce_authorityKeyIdentifier);
  2804. for (const item of this.certificates) {
  2805. if (item.subject !== cert.issuer) {
  2806. continue;
  2807. }
  2808. if (akiExt) {
  2809. if (akiExt.keyId) {
  2810. const skiExt = item.getExtension(asn1X509__namespace.id_ce_subjectKeyIdentifier);
  2811. if (skiExt && skiExt.keyId !== akiExt.keyId) {
  2812. continue;
  2813. }
  2814. }
  2815. else if (akiExt.certId) {
  2816. const sanExt = item.getExtension(asn1X509__namespace.id_ce_subjectAltName);
  2817. if (sanExt
  2818. && !(akiExt.certId.serialNumber === item.serialNumber && pvtsutils.isEqual(asn1Schema.AsnConvert.serialize(akiExt.certId.name), asn1Schema.AsnConvert.serialize(sanExt)))) {
  2819. continue;
  2820. }
  2821. }
  2822. }
  2823. try {
  2824. const algorithm = {
  2825. ...item.publicKey.algorithm, ...cert.signatureAlgorithm,
  2826. };
  2827. const publicKey = await item.publicKey.export(algorithm, ["verify"], crypto);
  2828. const ok = await cert.verify({
  2829. publicKey, signatureOnly: true,
  2830. }, crypto);
  2831. if (!ok) {
  2832. continue;
  2833. }
  2834. }
  2835. catch {
  2836. continue;
  2837. }
  2838. return item;
  2839. }
  2840. }
  2841. return null;
  2842. }
  2843. }
  2844. function generateCertificateSerialNumber(input, crypto = cryptoProvider.get()) {
  2845. const inputView = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(input || ""));
  2846. let serialNumber = inputView && inputView.length && inputView.some((o) => o > 0)
  2847. ? new Uint8Array(inputView)
  2848. : undefined;
  2849. if (!serialNumber) {
  2850. serialNumber = crypto.getRandomValues(new Uint8Array(16));
  2851. }
  2852. let firstNonZero = 0;
  2853. while (firstNonZero < serialNumber.length - 1 && serialNumber[firstNonZero] === 0) {
  2854. firstNonZero++;
  2855. }
  2856. serialNumber = serialNumber.slice(firstNonZero);
  2857. if (serialNumber[0] > 0x7F) {
  2858. const newSerialNumber = new Uint8Array(serialNumber.length + 1);
  2859. newSerialNumber[0] = 0x00;
  2860. newSerialNumber.set(serialNumber, 1);
  2861. serialNumber = newSerialNumber;
  2862. }
  2863. return serialNumber.buffer;
  2864. }
  2865. class X509CertificateGenerator {
  2866. static async createSelfSigned(params, crypto = cryptoProvider.get()) {
  2867. if (!params.keys.privateKey) {
  2868. throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
  2869. }
  2870. if (!params.keys.publicKey) {
  2871. throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
  2872. }
  2873. return this.create({
  2874. serialNumber: params.serialNumber,
  2875. subject: params.name,
  2876. issuer: params.name,
  2877. notBefore: params.notBefore,
  2878. notAfter: params.notAfter,
  2879. publicKey: params.keys.publicKey,
  2880. signingKey: params.keys.privateKey,
  2881. signingAlgorithm: params.signingAlgorithm,
  2882. extensions: params.extensions,
  2883. }, crypto);
  2884. }
  2885. static async create(params, crypto = cryptoProvider.get()) {
  2886. var _a;
  2887. let spki;
  2888. if (params.publicKey instanceof PublicKey) {
  2889. spki = params.publicKey.rawData;
  2890. }
  2891. else if ("publicKey" in params.publicKey) {
  2892. spki = params.publicKey.publicKey.rawData;
  2893. }
  2894. else if (pvtsutils.BufferSourceConverter.isBufferSource(params.publicKey)) {
  2895. spki = params.publicKey;
  2896. }
  2897. else {
  2898. spki = await crypto.subtle.exportKey("spki", params.publicKey);
  2899. }
  2900. const serialNumber = generateCertificateSerialNumber(params.serialNumber, crypto);
  2901. const notBefore = params.notBefore || new Date();
  2902. const notAfter = params.notAfter || new Date(notBefore.getTime() + 31536000000);
  2903. const asnX509 = new asn1X509__namespace.Certificate({
  2904. tbsCertificate: new asn1X509__namespace.TBSCertificate({
  2905. version: asn1X509__namespace.Version.v3,
  2906. serialNumber,
  2907. validity: new asn1X509__namespace.Validity({
  2908. notBefore,
  2909. notAfter,
  2910. }),
  2911. extensions: new asn1X509__namespace.Extensions(((_a = params.extensions) === null || _a === void 0 ? void 0 : _a.map((o) => asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension))) || []),
  2912. subjectPublicKeyInfo: asn1Schema.AsnConvert.parse(spki, asn1X509__namespace.SubjectPublicKeyInfo),
  2913. }),
  2914. });
  2915. if (params.subject) {
  2916. const name = params.subject instanceof Name
  2917. ? params.subject
  2918. : new Name(params.subject);
  2919. asnX509.tbsCertificate.subject = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name);
  2920. }
  2921. if (params.issuer) {
  2922. const name = params.issuer instanceof Name
  2923. ? params.issuer
  2924. : new Name(params.issuer);
  2925. asnX509.tbsCertificate.issuer = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name);
  2926. }
  2927. const defaultSigningAlgorithm = { hash: "SHA-256" };
  2928. const signatureAlgorithm = ("signingKey" in params)
  2929. ? {
  2930. ...defaultSigningAlgorithm, ...params.signingAlgorithm, ...params.signingKey.algorithm,
  2931. }
  2932. : {
  2933. ...defaultSigningAlgorithm, ...params.signingAlgorithm,
  2934. };
  2935. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  2936. asnX509.tbsCertificate.signature = asnX509.signatureAlgorithm = algProv
  2937. .toAsnAlgorithm(signatureAlgorithm);
  2938. const tbs = asn1Schema.AsnConvert.serialize(asnX509.tbsCertificate);
  2939. const signatureValue = ("signingKey" in params)
  2940. ? await crypto.subtle.sign(signatureAlgorithm, params.signingKey, tbs)
  2941. : params.signature;
  2942. const signatureFormatters = tsyringe.container
  2943. .resolveAll(diAsnSignatureFormatter)
  2944. .reverse();
  2945. let asnSignature = null;
  2946. for (const signatureFormatter of signatureFormatters) {
  2947. asnSignature = signatureFormatter.toAsnSignature(signatureAlgorithm, signatureValue);
  2948. if (asnSignature) {
  2949. break;
  2950. }
  2951. }
  2952. if (!asnSignature) {
  2953. throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
  2954. }
  2955. asnX509.signatureValue = asnSignature;
  2956. return new X509Certificate(asn1Schema.AsnConvert.serialize(asnX509));
  2957. }
  2958. }
  2959. var _X509CrlEntry_serialNumber, _X509CrlEntry_revocationDate, _X509CrlEntry_reason, _X509CrlEntry_invalidity, _X509CrlEntry_extensions;
  2960. exports.X509CrlReason = void 0;
  2961. (function (X509CrlReason) {
  2962. X509CrlReason[X509CrlReason["unspecified"] = 0] = "unspecified";
  2963. X509CrlReason[X509CrlReason["keyCompromise"] = 1] = "keyCompromise";
  2964. X509CrlReason[X509CrlReason["cACompromise"] = 2] = "cACompromise";
  2965. X509CrlReason[X509CrlReason["affiliationChanged"] = 3] = "affiliationChanged";
  2966. X509CrlReason[X509CrlReason["superseded"] = 4] = "superseded";
  2967. X509CrlReason[X509CrlReason["cessationOfOperation"] = 5] = "cessationOfOperation";
  2968. X509CrlReason[X509CrlReason["certificateHold"] = 6] = "certificateHold";
  2969. X509CrlReason[X509CrlReason["removeFromCRL"] = 8] = "removeFromCRL";
  2970. X509CrlReason[X509CrlReason["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
  2971. X509CrlReason[X509CrlReason["aACompromise"] = 10] = "aACompromise";
  2972. })(exports.X509CrlReason || (exports.X509CrlReason = {}));
  2973. class X509CrlEntry extends AsnData {
  2974. get serialNumber() {
  2975. if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f")) {
  2976. tslib.__classPrivateFieldSet(this, _X509CrlEntry_serialNumber, pvtsutils.Convert.ToHex(this.asn.userCertificate), "f");
  2977. }
  2978. return tslib.__classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f");
  2979. }
  2980. get revocationDate() {
  2981. if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f")) {
  2982. tslib.__classPrivateFieldSet(this, _X509CrlEntry_revocationDate, this.asn.revocationDate.getTime(), "f");
  2983. }
  2984. return tslib.__classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f");
  2985. }
  2986. get reason() {
  2987. if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === undefined) {
  2988. void this.extensions;
  2989. }
  2990. return tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f");
  2991. }
  2992. get invalidity() {
  2993. if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === undefined) {
  2994. void this.extensions;
  2995. }
  2996. return tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f");
  2997. }
  2998. get extensions() {
  2999. if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_extensions, "f")) {
  3000. tslib.__classPrivateFieldSet(this, _X509CrlEntry_extensions, [], "f");
  3001. if (this.asn.crlEntryExtensions) {
  3002. tslib.__classPrivateFieldSet(this, _X509CrlEntry_extensions, this.asn.crlEntryExtensions.map((o) => {
  3003. const extension = ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o));
  3004. switch (extension.type) {
  3005. case asn1X509.id_ce_cRLReasons:
  3006. if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === undefined) {
  3007. tslib.__classPrivateFieldSet(this, _X509CrlEntry_reason, asn1Schema.AsnConvert
  3008. .parse(extension.value, asn1X509.CRLReason).reason, "f");
  3009. }
  3010. break;
  3011. case asn1X509.id_ce_invalidityDate:
  3012. if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === undefined) {
  3013. tslib.__classPrivateFieldSet(this, _X509CrlEntry_invalidity, asn1Schema.AsnConvert.parse(extension.value, asn1X509.InvalidityDate).value, "f");
  3014. }
  3015. break;
  3016. }
  3017. return extension;
  3018. }), "f");
  3019. }
  3020. }
  3021. return tslib.__classPrivateFieldGet(this, _X509CrlEntry_extensions, "f");
  3022. }
  3023. constructor(...args) {
  3024. let raw;
  3025. if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
  3026. raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
  3027. }
  3028. else if (typeof args[0] === "string") {
  3029. raw = asn1Schema.AsnConvert.serialize(new asn1X509.RevokedCertificate({
  3030. userCertificate: generateCertificateSerialNumber(args[0]),
  3031. revocationDate: new asn1X509.Time(args[1]),
  3032. crlEntryExtensions: args[2],
  3033. }));
  3034. }
  3035. else if (args[0] instanceof asn1X509.RevokedCertificate) {
  3036. raw = args[0];
  3037. }
  3038. if (!raw) {
  3039. throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");
  3040. }
  3041. super(raw, asn1X509.RevokedCertificate);
  3042. _X509CrlEntry_serialNumber.set(this, void 0);
  3043. _X509CrlEntry_revocationDate.set(this, void 0);
  3044. _X509CrlEntry_reason.set(this, void 0);
  3045. _X509CrlEntry_invalidity.set(this, void 0);
  3046. _X509CrlEntry_extensions.set(this, void 0);
  3047. }
  3048. onInit(_asn) {
  3049. }
  3050. }
  3051. _X509CrlEntry_serialNumber = new WeakMap(), _X509CrlEntry_revocationDate = new WeakMap(), _X509CrlEntry_reason = new WeakMap(), _X509CrlEntry_invalidity = new WeakMap(), _X509CrlEntry_extensions = new WeakMap();
  3052. var _X509Crl_tbs, _X509Crl_signatureAlgorithm, _X509Crl_issuerName, _X509Crl_thisUpdate, _X509Crl_nextUpdate, _X509Crl_entries, _X509Crl_extensions;
  3053. class X509Crl extends PemData {
  3054. get version() {
  3055. return this.asn.tbsCertList.version;
  3056. }
  3057. get signatureAlgorithm() {
  3058. if (!tslib.__classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f")) {
  3059. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  3060. tslib.__classPrivateFieldSet(this, _X509Crl_signatureAlgorithm, algProv
  3061. .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
  3062. }
  3063. return tslib.__classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f");
  3064. }
  3065. get signature() {
  3066. return this.asn.signature;
  3067. }
  3068. get issuer() {
  3069. return this.issuerName.toString();
  3070. }
  3071. get issuerName() {
  3072. if (!tslib.__classPrivateFieldGet(this, _X509Crl_issuerName, "f")) {
  3073. tslib.__classPrivateFieldSet(this, _X509Crl_issuerName, new Name(this.asn.tbsCertList.issuer), "f");
  3074. }
  3075. return tslib.__classPrivateFieldGet(this, _X509Crl_issuerName, "f");
  3076. }
  3077. get thisUpdate() {
  3078. if (!tslib.__classPrivateFieldGet(this, _X509Crl_thisUpdate, "f")) {
  3079. const thisUpdate = this.asn.tbsCertList.thisUpdate.getTime();
  3080. if (!thisUpdate) {
  3081. throw new Error("Cannot get 'thisUpdate' value");
  3082. }
  3083. tslib.__classPrivateFieldSet(this, _X509Crl_thisUpdate, thisUpdate, "f");
  3084. }
  3085. return tslib.__classPrivateFieldGet(this, _X509Crl_thisUpdate, "f");
  3086. }
  3087. get nextUpdate() {
  3088. var _a;
  3089. if (tslib.__classPrivateFieldGet(this, _X509Crl_nextUpdate, "f") === undefined) {
  3090. tslib.__classPrivateFieldSet(this, _X509Crl_nextUpdate, ((_a = this.asn.tbsCertList.nextUpdate) === null || _a === void 0 ? void 0 : _a.getTime()) || undefined, "f");
  3091. }
  3092. return tslib.__classPrivateFieldGet(this, _X509Crl_nextUpdate, "f");
  3093. }
  3094. get entries() {
  3095. var _a;
  3096. if (!tslib.__classPrivateFieldGet(this, _X509Crl_entries, "f")) {
  3097. tslib.__classPrivateFieldSet(this, _X509Crl_entries, ((_a = this.asn.tbsCertList
  3098. .revokedCertificates) === null || _a === void 0 ? void 0 : _a.map((o) => new X509CrlEntry(o))) || [], "f");
  3099. }
  3100. return tslib.__classPrivateFieldGet(this, _X509Crl_entries, "f");
  3101. }
  3102. get extensions() {
  3103. if (!tslib.__classPrivateFieldGet(this, _X509Crl_extensions, "f")) {
  3104. tslib.__classPrivateFieldSet(this, _X509Crl_extensions, [], "f");
  3105. if (this.asn.tbsCertList.crlExtensions) {
  3106. tslib.__classPrivateFieldSet(this, _X509Crl_extensions, this.asn.tbsCertList.crlExtensions.map((o) => ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o))), "f");
  3107. }
  3108. }
  3109. return tslib.__classPrivateFieldGet(this, _X509Crl_extensions, "f");
  3110. }
  3111. get tbs() {
  3112. if (!tslib.__classPrivateFieldGet(this, _X509Crl_tbs, "f")) {
  3113. tslib.__classPrivateFieldSet(this, _X509Crl_tbs, this.asn.tbsCertListRaw || asn1Schema.AsnConvert.serialize(this.asn.tbsCertList), "f");
  3114. }
  3115. return tslib.__classPrivateFieldGet(this, _X509Crl_tbs, "f");
  3116. }
  3117. get tbsCertListSignatureAlgorithm() {
  3118. return this.asn.tbsCertList.signature;
  3119. }
  3120. get certListSignatureAlgorithm() {
  3121. return this.asn.signatureAlgorithm;
  3122. }
  3123. constructor(param) {
  3124. super(param, PemData.isAsnEncoded(param) ? asn1X509.CertificateList : undefined);
  3125. this.tag = PemConverter.CrlTag;
  3126. _X509Crl_tbs.set(this, void 0);
  3127. _X509Crl_signatureAlgorithm.set(this, void 0);
  3128. _X509Crl_issuerName.set(this, void 0);
  3129. _X509Crl_thisUpdate.set(this, void 0);
  3130. _X509Crl_nextUpdate.set(this, void 0);
  3131. _X509Crl_entries.set(this, void 0);
  3132. _X509Crl_extensions.set(this, void 0);
  3133. }
  3134. onInit(_asn) {
  3135. }
  3136. getExtension(type) {
  3137. for (const ext of this.extensions) {
  3138. if (typeof type === "string") {
  3139. if (ext.type === type) {
  3140. return ext;
  3141. }
  3142. }
  3143. else {
  3144. if (ext instanceof type) {
  3145. return ext;
  3146. }
  3147. }
  3148. }
  3149. return null;
  3150. }
  3151. getExtensions(type) {
  3152. return this.extensions.filter((o) => {
  3153. if (typeof type === "string") {
  3154. return o.type === type;
  3155. }
  3156. else {
  3157. return o instanceof type;
  3158. }
  3159. });
  3160. }
  3161. async verify(params, crypto = cryptoProvider.get()) {
  3162. if (!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm)) {
  3163. throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");
  3164. }
  3165. let keyAlgorithm;
  3166. let publicKey;
  3167. const paramsKey = params.publicKey;
  3168. try {
  3169. if (paramsKey instanceof X509Certificate) {
  3170. keyAlgorithm = {
  3171. ...paramsKey.publicKey.algorithm,
  3172. ...paramsKey.signatureAlgorithm,
  3173. };
  3174. publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]);
  3175. }
  3176. else if (paramsKey instanceof PublicKey) {
  3177. keyAlgorithm = {
  3178. ...paramsKey.algorithm, ...this.signatureAlgorithm,
  3179. };
  3180. publicKey = await paramsKey.export(keyAlgorithm, ["verify"]);
  3181. }
  3182. else {
  3183. keyAlgorithm = {
  3184. ...paramsKey.algorithm, ...this.signatureAlgorithm,
  3185. };
  3186. publicKey = paramsKey;
  3187. }
  3188. }
  3189. catch {
  3190. return false;
  3191. }
  3192. const signatureFormatters = tsyringe.container
  3193. .resolveAll(diAsnSignatureFormatter)
  3194. .reverse();
  3195. let signature = null;
  3196. for (const signatureFormatter of signatureFormatters) {
  3197. signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
  3198. if (signature) {
  3199. break;
  3200. }
  3201. }
  3202. if (!signature) {
  3203. throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
  3204. }
  3205. return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
  3206. }
  3207. async getThumbprint(...args) {
  3208. let crypto;
  3209. let algorithm = "SHA-1";
  3210. if (args[0]) {
  3211. if (!args[0].subtle) {
  3212. algorithm = args[0] || algorithm;
  3213. crypto = args[1];
  3214. }
  3215. else {
  3216. crypto = args[0];
  3217. }
  3218. }
  3219. crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
  3220. return await crypto.subtle.digest(algorithm, this.rawData);
  3221. }
  3222. findRevoked(certOrSerialNumber) {
  3223. const serialNumber = typeof certOrSerialNumber === "string" ? certOrSerialNumber : certOrSerialNumber.serialNumber;
  3224. const serialBuffer = generateCertificateSerialNumber(serialNumber);
  3225. for (const revoked of this.asn.tbsCertList.revokedCertificates || []) {
  3226. if (pvtsutils.BufferSourceConverter.isEqual(revoked.userCertificate, serialBuffer)) {
  3227. return new X509CrlEntry(asn1Schema.AsnConvert.serialize(revoked));
  3228. }
  3229. }
  3230. return null;
  3231. }
  3232. }
  3233. _X509Crl_tbs = new WeakMap(), _X509Crl_signatureAlgorithm = new WeakMap(), _X509Crl_issuerName = new WeakMap(), _X509Crl_thisUpdate = new WeakMap(), _X509Crl_nextUpdate = new WeakMap(), _X509Crl_entries = new WeakMap(), _X509Crl_extensions = new WeakMap();
  3234. class X509CrlGenerator {
  3235. static async create(params, crypto = cryptoProvider.get()) {
  3236. var _a;
  3237. const name = params.issuer instanceof Name
  3238. ? params.issuer
  3239. : new Name(params.issuer);
  3240. const asnX509Crl = new asn1X509__namespace.CertificateList({
  3241. tbsCertList: new asn1X509__namespace.TBSCertList({
  3242. version: asn1X509__namespace.Version.v2,
  3243. issuer: asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name),
  3244. thisUpdate: new asn1X509.Time(params.thisUpdate || new Date()),
  3245. }),
  3246. });
  3247. if (params.nextUpdate) {
  3248. asnX509Crl.tbsCertList.nextUpdate = new asn1X509.Time(params.nextUpdate);
  3249. }
  3250. if (params.extensions && params.extensions.length) {
  3251. asnX509Crl.tbsCertList.crlExtensions = new asn1X509__namespace.Extensions(params.extensions.map((o) => asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension)) || []);
  3252. }
  3253. if (params.entries && params.entries.length) {
  3254. asnX509Crl.tbsCertList.revokedCertificates = [];
  3255. for (const entry of params.entries) {
  3256. const userCertificate = PemData.toArrayBuffer(entry.serialNumber);
  3257. const index = asnX509Crl.tbsCertList.revokedCertificates
  3258. .findIndex((cert) => pvtsutils.isEqual(cert.userCertificate, userCertificate));
  3259. if (index > -1) {
  3260. throw new Error(`Certificate serial number ${entry.serialNumber} already exists in tbsCertList`);
  3261. }
  3262. const revokedCert = new asn1X509.RevokedCertificate({
  3263. userCertificate: userCertificate,
  3264. revocationDate: new asn1X509.Time(entry.revocationDate || new Date()),
  3265. });
  3266. if ("extensions" in entry && ((_a = entry.extensions) === null || _a === void 0 ? void 0 : _a.length)) {
  3267. revokedCert.crlEntryExtensions = entry.extensions.map((o) => (asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension)));
  3268. }
  3269. else {
  3270. revokedCert.crlEntryExtensions = [];
  3271. }
  3272. if (!(entry instanceof X509CrlEntry)) {
  3273. if (entry.reason) {
  3274. revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
  3275. extnID: asn1X509__namespace.id_ce_cRLReasons,
  3276. critical: false,
  3277. extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(new asn1X509__namespace.CRLReason(entry.reason))),
  3278. }));
  3279. }
  3280. if (entry.invalidity) {
  3281. revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
  3282. extnID: asn1X509__namespace.id_ce_invalidityDate,
  3283. critical: false,
  3284. extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(new asn1X509__namespace.InvalidityDate(entry.invalidity))),
  3285. }));
  3286. }
  3287. if (entry.issuer) {
  3288. const name = params.issuer instanceof Name
  3289. ? params.issuer
  3290. : new Name(params.issuer);
  3291. revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
  3292. extnID: asn1X509__namespace.id_ce_certificateIssuer,
  3293. critical: false,
  3294. extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name))),
  3295. }));
  3296. }
  3297. }
  3298. asnX509Crl.tbsCertList.revokedCertificates.push(revokedCert);
  3299. }
  3300. }
  3301. const signingAlgorithm = {
  3302. ...params.signingAlgorithm, ...params.signingKey.algorithm,
  3303. };
  3304. const algProv = tsyringe.container.resolve(diAlgorithmProvider);
  3305. asnX509Crl.tbsCertList.signature = asnX509Crl.signatureAlgorithm = algProv
  3306. .toAsnAlgorithm(signingAlgorithm);
  3307. const tbs = asn1Schema.AsnConvert.serialize(asnX509Crl.tbsCertList);
  3308. const signature = await crypto.subtle.sign(signingAlgorithm, params.signingKey, tbs);
  3309. const signatureFormatters = tsyringe.container
  3310. .resolveAll(diAsnSignatureFormatter)
  3311. .reverse();
  3312. let asnSignature = null;
  3313. for (const signatureFormatter of signatureFormatters) {
  3314. asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
  3315. if (asnSignature) {
  3316. break;
  3317. }
  3318. }
  3319. if (!asnSignature) {
  3320. throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
  3321. }
  3322. asnX509Crl.signature = asnSignature;
  3323. return new X509Crl(asn1Schema.AsnConvert.serialize(asnX509Crl));
  3324. }
  3325. }
  3326. ExtensionFactory.register(asn1X509__namespace.id_ce_basicConstraints, BasicConstraintsExtension);
  3327. ExtensionFactory.register(asn1X509__namespace.id_ce_extKeyUsage, ExtendedKeyUsageExtension);
  3328. ExtensionFactory.register(asn1X509__namespace.id_ce_keyUsage, KeyUsagesExtension);
  3329. ExtensionFactory.register(asn1X509__namespace.id_ce_subjectKeyIdentifier, SubjectKeyIdentifierExtension);
  3330. ExtensionFactory.register(asn1X509__namespace.id_ce_authorityKeyIdentifier, AuthorityKeyIdentifierExtension);
  3331. ExtensionFactory.register(asn1X509__namespace.id_ce_subjectAltName, SubjectAlternativeNameExtension);
  3332. ExtensionFactory.register(asn1X509__namespace.id_ce_cRLDistributionPoints, CRLDistributionPointsExtension);
  3333. ExtensionFactory.register(asn1X509__namespace.id_pe_authorityInfoAccess, AuthorityInfoAccessExtension);
  3334. ExtensionFactory.register(asn1X509__namespace.id_ce_issuerAltName, IssuerAlternativeNameExtension);
  3335. AttributeFactory.register(asnPkcs9__namespace.id_pkcs9_at_challengePassword, ChallengePasswordAttribute);
  3336. AttributeFactory.register(asnPkcs9__namespace.id_pkcs9_at_extensionRequest, ExtensionsAttribute);
  3337. tsyringe.container.registerSingleton(diAsnSignatureFormatter, AsnDefaultSignatureFormatter);
  3338. tsyringe.container.registerSingleton(diAsnSignatureFormatter, AsnEcSignatureFormatter);
  3339. AsnEcSignatureFormatter.namedCurveSize.set("P-256", 32);
  3340. AsnEcSignatureFormatter.namedCurveSize.set("K-256", 32);
  3341. AsnEcSignatureFormatter.namedCurveSize.set("P-384", 48);
  3342. AsnEcSignatureFormatter.namedCurveSize.set("P-521", 66);
  3343. exports.AlgorithmProvider = AlgorithmProvider;
  3344. exports.AsnData = AsnData;
  3345. exports.AsnDefaultSignatureFormatter = AsnDefaultSignatureFormatter;
  3346. exports.AsnEcSignatureFormatter = AsnEcSignatureFormatter;
  3347. exports.Attribute = Attribute;
  3348. exports.AttributeFactory = AttributeFactory;
  3349. exports.AuthorityInfoAccessExtension = AuthorityInfoAccessExtension;
  3350. exports.AuthorityKeyIdentifierExtension = AuthorityKeyIdentifierExtension;
  3351. exports.BasicConstraintsExtension = BasicConstraintsExtension;
  3352. exports.CRLDistributionPointsExtension = CRLDistributionPointsExtension;
  3353. exports.CertificatePolicyExtension = CertificatePolicyExtension;
  3354. exports.ChallengePasswordAttribute = ChallengePasswordAttribute;
  3355. exports.CryptoProvider = CryptoProvider;
  3356. exports.DN = DN;
  3357. exports.DNS = DNS;
  3358. exports.DefaultAlgorithmSerializer = DefaultAlgorithmSerializer;
  3359. exports.EMAIL = EMAIL;
  3360. exports.ExtendedKeyUsageExtension = ExtendedKeyUsageExtension;
  3361. exports.Extension = Extension;
  3362. exports.ExtensionFactory = ExtensionFactory;
  3363. exports.ExtensionsAttribute = ExtensionsAttribute;
  3364. exports.GUID = GUID;
  3365. exports.GeneralName = GeneralName;
  3366. exports.GeneralNames = GeneralNames;
  3367. exports.IP = IP;
  3368. exports.IssuerAlternativeNameExtension = IssuerAlternativeNameExtension;
  3369. exports.KeyUsagesExtension = KeyUsagesExtension;
  3370. exports.Name = Name;
  3371. exports.NameIdentifier = NameIdentifier;
  3372. exports.OidSerializer = OidSerializer;
  3373. exports.PemConverter = PemConverter;
  3374. exports.PemData = PemData;
  3375. exports.Pkcs10CertificateRequest = Pkcs10CertificateRequest;
  3376. exports.Pkcs10CertificateRequestGenerator = Pkcs10CertificateRequestGenerator;
  3377. exports.PublicKey = PublicKey;
  3378. exports.REGISTERED_ID = REGISTERED_ID;
  3379. exports.SubjectAlternativeNameExtension = SubjectAlternativeNameExtension;
  3380. exports.SubjectKeyIdentifierExtension = SubjectKeyIdentifierExtension;
  3381. exports.TextConverter = TextConverter;
  3382. exports.TextObject = TextObject;
  3383. exports.UPN = UPN;
  3384. exports.URL = URL;
  3385. exports.X509Certificate = X509Certificate;
  3386. exports.X509CertificateGenerator = X509CertificateGenerator;
  3387. exports.X509Certificates = X509Certificates;
  3388. exports.X509ChainBuilder = X509ChainBuilder;
  3389. exports.X509Crl = X509Crl;
  3390. exports.X509CrlEntry = X509CrlEntry;
  3391. exports.X509CrlGenerator = X509CrlGenerator;
  3392. exports.cryptoProvider = cryptoProvider;
  3393. exports.diAlgorithm = diAlgorithm;
  3394. exports.diAlgorithmProvider = diAlgorithmProvider;
  3395. exports.diAsnSignatureFormatter = diAsnSignatureFormatter;
  3396. exports.idEd25519 = idEd25519;
  3397. exports.idEd448 = idEd448;
  3398. exports.idX25519 = idX25519;
  3399. exports.idX448 = idX448;