x509.es.js 132 KB

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