| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368 |
- /*!
- * MIT License
- *
- * Copyright (c) Peculiar Ventures. All rights reserved.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- *
- */
- import 'reflect-metadata';
- import { AsnConvert, OctetString, AsnUtf8StringConverter } from '@peculiar/asn1-schema';
- import * as asn1X509 from '@peculiar/asn1-x509';
- 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';
- import { BufferSourceConverter, isEqual, Convert, combine } from 'pvtsutils';
- import { __decorate, __classPrivateFieldGet, __classPrivateFieldSet } from 'tslib';
- import * as asn1Cms from '@peculiar/asn1-cms';
- import * as asn1Ecc from '@peculiar/asn1-ecc';
- import { id_ecPublicKey, ECDSASigValue } from '@peculiar/asn1-ecc';
- import * as asn1Rsa from '@peculiar/asn1-rsa';
- import { id_RSASSA_PSS, id_rsaEncryption, RSAPublicKey, id_sha512, id_sha384, id_sha256, id_sha1 } from '@peculiar/asn1-rsa';
- import { container, injectable } from 'tsyringe';
- import * as asnPkcs9 from '@peculiar/asn1-pkcs9';
- import { id_pkcs9_at_extensionRequest } from '@peculiar/asn1-pkcs9';
- import { CertificationRequest, CertificationRequestInfo } from '@peculiar/asn1-csr';
- const diAlgorithm = "crypto.algorithm";
- class AlgorithmProvider {
- getAlgorithms() {
- return container.resolveAll(diAlgorithm);
- }
- toAsnAlgorithm(alg) {
- ({ ...alg });
- for (const algorithm of this.getAlgorithms()) {
- const res = algorithm.toAsnAlgorithm(alg);
- if (res) {
- return res;
- }
- }
- if (/^[0-9.]+$/.test(alg.name)) {
- const res = new AlgorithmIdentifier({ algorithm: alg.name });
- if ("parameters" in alg) {
- const unknown = alg;
- res.parameters = unknown.parameters;
- }
- return res;
- }
- throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm");
- }
- toWebAlgorithm(alg) {
- for (const algorithm of this.getAlgorithms()) {
- const res = algorithm.toWebAlgorithm(alg);
- if (res) {
- return res;
- }
- }
- const unknown = {
- name: alg.algorithm,
- parameters: alg.parameters,
- };
- return unknown;
- }
- }
- const diAlgorithmProvider = "crypto.algorithmProvider";
- container.registerSingleton(diAlgorithmProvider, AlgorithmProvider);
- var EcAlgorithm_1;
- const idVersionOne = "1.3.36.3.3.2.8.1.1";
- const idBrainpoolP160r1 = `${idVersionOne}.1`;
- const idBrainpoolP160t1 = `${idVersionOne}.2`;
- const idBrainpoolP192r1 = `${idVersionOne}.3`;
- const idBrainpoolP192t1 = `${idVersionOne}.4`;
- const idBrainpoolP224r1 = `${idVersionOne}.5`;
- const idBrainpoolP224t1 = `${idVersionOne}.6`;
- const idBrainpoolP256r1 = `${idVersionOne}.7`;
- const idBrainpoolP256t1 = `${idVersionOne}.8`;
- const idBrainpoolP320r1 = `${idVersionOne}.9`;
- const idBrainpoolP320t1 = `${idVersionOne}.10`;
- const idBrainpoolP384r1 = `${idVersionOne}.11`;
- const idBrainpoolP384t1 = `${idVersionOne}.12`;
- const idBrainpoolP512r1 = `${idVersionOne}.13`;
- const idBrainpoolP512t1 = `${idVersionOne}.14`;
- const brainpoolP160r1 = "brainpoolP160r1";
- const brainpoolP160t1 = "brainpoolP160t1";
- const brainpoolP192r1 = "brainpoolP192r1";
- const brainpoolP192t1 = "brainpoolP192t1";
- const brainpoolP224r1 = "brainpoolP224r1";
- const brainpoolP224t1 = "brainpoolP224t1";
- const brainpoolP256r1 = "brainpoolP256r1";
- const brainpoolP256t1 = "brainpoolP256t1";
- const brainpoolP320r1 = "brainpoolP320r1";
- const brainpoolP320t1 = "brainpoolP320t1";
- const brainpoolP384r1 = "brainpoolP384r1";
- const brainpoolP384t1 = "brainpoolP384t1";
- const brainpoolP512r1 = "brainpoolP512r1";
- const brainpoolP512t1 = "brainpoolP512t1";
- const ECDSA = "ECDSA";
- let EcAlgorithm = EcAlgorithm_1 = class EcAlgorithm {
- toAsnAlgorithm(alg) {
- switch (alg.name.toLowerCase()) {
- case ECDSA.toLowerCase():
- if ("hash" in alg) {
- const hash = typeof alg.hash === "string" ? alg.hash : alg.hash.name;
- switch (hash.toLowerCase()) {
- case "sha-1":
- return asn1Ecc.ecdsaWithSHA1;
- case "sha-256":
- return asn1Ecc.ecdsaWithSHA256;
- case "sha-384":
- return asn1Ecc.ecdsaWithSHA384;
- case "sha-512":
- return asn1Ecc.ecdsaWithSHA512;
- }
- }
- else if ("namedCurve" in alg) {
- let parameters = "";
- switch (alg.namedCurve) {
- case "P-256":
- parameters = asn1Ecc.id_secp256r1;
- break;
- case "K-256":
- parameters = EcAlgorithm_1.SECP256K1;
- break;
- case "P-384":
- parameters = asn1Ecc.id_secp384r1;
- break;
- case "P-521":
- parameters = asn1Ecc.id_secp521r1;
- break;
- case brainpoolP160r1:
- parameters = idBrainpoolP160r1;
- break;
- case brainpoolP160t1:
- parameters = idBrainpoolP160t1;
- break;
- case brainpoolP192r1:
- parameters = idBrainpoolP192r1;
- break;
- case brainpoolP192t1:
- parameters = idBrainpoolP192t1;
- break;
- case brainpoolP224r1:
- parameters = idBrainpoolP224r1;
- break;
- case brainpoolP224t1:
- parameters = idBrainpoolP224t1;
- break;
- case brainpoolP256r1:
- parameters = idBrainpoolP256r1;
- break;
- case brainpoolP256t1:
- parameters = idBrainpoolP256t1;
- break;
- case brainpoolP320r1:
- parameters = idBrainpoolP320r1;
- break;
- case brainpoolP320t1:
- parameters = idBrainpoolP320t1;
- break;
- case brainpoolP384r1:
- parameters = idBrainpoolP384r1;
- break;
- case brainpoolP384t1:
- parameters = idBrainpoolP384t1;
- break;
- case brainpoolP512r1:
- parameters = idBrainpoolP512r1;
- break;
- case brainpoolP512t1:
- parameters = idBrainpoolP512t1;
- break;
- }
- if (parameters) {
- return new AlgorithmIdentifier({
- algorithm: asn1Ecc.id_ecPublicKey,
- parameters: AsnConvert.serialize(new asn1Ecc.ECParameters({ namedCurve: parameters })),
- });
- }
- }
- }
- return null;
- }
- toWebAlgorithm(alg) {
- switch (alg.algorithm) {
- case asn1Ecc.id_ecdsaWithSHA1:
- return {
- name: ECDSA, hash: { name: "SHA-1" },
- };
- case asn1Ecc.id_ecdsaWithSHA256:
- return {
- name: ECDSA, hash: { name: "SHA-256" },
- };
- case asn1Ecc.id_ecdsaWithSHA384:
- return {
- name: ECDSA, hash: { name: "SHA-384" },
- };
- case asn1Ecc.id_ecdsaWithSHA512:
- return {
- name: ECDSA, hash: { name: "SHA-512" },
- };
- case asn1Ecc.id_ecPublicKey: {
- if (!alg.parameters) {
- throw new TypeError("Cannot get required parameters from EC algorithm");
- }
- const parameters = AsnConvert.parse(alg.parameters, asn1Ecc.ECParameters);
- switch (parameters.namedCurve) {
- case asn1Ecc.id_secp256r1:
- return {
- name: ECDSA, namedCurve: "P-256",
- };
- case EcAlgorithm_1.SECP256K1:
- return {
- name: ECDSA, namedCurve: "K-256",
- };
- case asn1Ecc.id_secp384r1:
- return {
- name: ECDSA, namedCurve: "P-384",
- };
- case asn1Ecc.id_secp521r1:
- return {
- name: ECDSA, namedCurve: "P-521",
- };
- case idBrainpoolP160r1:
- return {
- name: ECDSA, namedCurve: brainpoolP160r1,
- };
- case idBrainpoolP160t1:
- return {
- name: ECDSA, namedCurve: brainpoolP160t1,
- };
- case idBrainpoolP192r1:
- return {
- name: ECDSA, namedCurve: brainpoolP192r1,
- };
- case idBrainpoolP192t1:
- return {
- name: ECDSA, namedCurve: brainpoolP192t1,
- };
- case idBrainpoolP224r1:
- return {
- name: ECDSA, namedCurve: brainpoolP224r1,
- };
- case idBrainpoolP224t1:
- return {
- name: ECDSA, namedCurve: brainpoolP224t1,
- };
- case idBrainpoolP256r1:
- return {
- name: ECDSA, namedCurve: brainpoolP256r1,
- };
- case idBrainpoolP256t1:
- return {
- name: ECDSA, namedCurve: brainpoolP256t1,
- };
- case idBrainpoolP320r1:
- return {
- name: ECDSA, namedCurve: brainpoolP320r1,
- };
- case idBrainpoolP320t1:
- return {
- name: ECDSA, namedCurve: brainpoolP320t1,
- };
- case idBrainpoolP384r1:
- return {
- name: ECDSA, namedCurve: brainpoolP384r1,
- };
- case idBrainpoolP384t1:
- return {
- name: ECDSA, namedCurve: brainpoolP384t1,
- };
- case idBrainpoolP512r1:
- return {
- name: ECDSA, namedCurve: brainpoolP512r1,
- };
- case idBrainpoolP512t1:
- return {
- name: ECDSA, namedCurve: brainpoolP512t1,
- };
- }
- }
- }
- return null;
- }
- };
- EcAlgorithm.SECP256K1 = "1.3.132.0.10";
- EcAlgorithm = EcAlgorithm_1 = __decorate([
- injectable()
- ], EcAlgorithm);
- container.registerSingleton(diAlgorithm, EcAlgorithm);
- const NAME = Symbol("name");
- const VALUE = Symbol("value");
- class TextObject {
- constructor(name, items = {}, value = "") {
- this[NAME] = name;
- this[VALUE] = value;
- for (const key in items) {
- this[key] = items[key];
- }
- }
- }
- TextObject.NAME = NAME;
- TextObject.VALUE = VALUE;
- class DefaultAlgorithmSerializer {
- static toTextObject(alg) {
- const obj = new TextObject("Algorithm Identifier", {}, OidSerializer.toString(alg.algorithm));
- if (alg.parameters) {
- switch (alg.algorithm) {
- case asn1Ecc.id_ecPublicKey: {
- const ecAlg = new EcAlgorithm().toWebAlgorithm(alg);
- if (ecAlg && "namedCurve" in ecAlg) {
- obj["Named Curve"] = ecAlg.namedCurve;
- }
- else {
- obj["Parameters"] = alg.parameters;
- }
- break;
- }
- default:
- obj["Parameters"] = alg.parameters;
- }
- }
- return obj;
- }
- }
- class OidSerializer {
- static toString(oid) {
- const name = this.items[oid];
- if (name) {
- return name;
- }
- return oid;
- }
- }
- OidSerializer.items = {
- [asn1Rsa.id_sha1]: "sha1",
- [asn1Rsa.id_sha224]: "sha224",
- [asn1Rsa.id_sha256]: "sha256",
- [asn1Rsa.id_sha384]: "sha384",
- [asn1Rsa.id_sha512]: "sha512",
- [asn1Rsa.id_rsaEncryption]: "rsaEncryption",
- [asn1Rsa.id_sha1WithRSAEncryption]: "sha1WithRSAEncryption",
- [asn1Rsa.id_sha224WithRSAEncryption]: "sha224WithRSAEncryption",
- [asn1Rsa.id_sha256WithRSAEncryption]: "sha256WithRSAEncryption",
- [asn1Rsa.id_sha384WithRSAEncryption]: "sha384WithRSAEncryption",
- [asn1Rsa.id_sha512WithRSAEncryption]: "sha512WithRSAEncryption",
- [asn1Ecc.id_ecPublicKey]: "ecPublicKey",
- [asn1Ecc.id_ecdsaWithSHA1]: "ecdsaWithSHA1",
- [asn1Ecc.id_ecdsaWithSHA224]: "ecdsaWithSHA224",
- [asn1Ecc.id_ecdsaWithSHA256]: "ecdsaWithSHA256",
- [asn1Ecc.id_ecdsaWithSHA384]: "ecdsaWithSHA384",
- [asn1Ecc.id_ecdsaWithSHA512]: "ecdsaWithSHA512",
- [asn1X509.id_kp_serverAuth]: "TLS WWW server authentication",
- [asn1X509.id_kp_clientAuth]: "TLS WWW client authentication",
- [asn1X509.id_kp_codeSigning]: "Code Signing",
- [asn1X509.id_kp_emailProtection]: "E-mail Protection",
- [asn1X509.id_kp_timeStamping]: "Time Stamping",
- [asn1X509.id_kp_OCSPSigning]: "OCSP Signing",
- [asn1Cms.id_signedData]: "Signed Data",
- };
- class TextConverter {
- static serialize(obj) {
- return this.serializeObj(obj).join("\n");
- }
- static pad(deep = 0) {
- return "".padStart(2 * deep, " ");
- }
- static serializeObj(obj, deep = 0) {
- const res = [];
- let pad = this.pad(deep++);
- let value = "";
- const objValue = obj[TextObject.VALUE];
- if (objValue) {
- value = ` ${objValue}`;
- }
- res.push(`${pad}${obj[TextObject.NAME]}:${value}`);
- pad = this.pad(deep);
- for (const key in obj) {
- if (typeof key === "symbol") {
- continue;
- }
- const value = obj[key];
- const keyValue = key ? `${key}: ` : "";
- if (typeof value === "string"
- || typeof value === "number"
- || typeof value === "boolean") {
- res.push(`${pad}${keyValue}${value}`);
- }
- else if (value instanceof Date) {
- res.push(`${pad}${keyValue}${value.toUTCString()}`);
- }
- else if (Array.isArray(value)) {
- for (const obj of value) {
- obj[TextObject.NAME] = key;
- res.push(...this.serializeObj(obj, deep));
- }
- }
- else if (value instanceof TextObject) {
- value[TextObject.NAME] = key;
- res.push(...this.serializeObj(value, deep));
- }
- else if (BufferSourceConverter.isBufferSource(value)) {
- if (key) {
- res.push(`${pad}${keyValue}`);
- res.push(...this.serializeBufferSource(value, deep + 1));
- }
- else {
- res.push(...this.serializeBufferSource(value, deep));
- }
- }
- else if ("toTextObject" in value) {
- const obj = value.toTextObject();
- obj[TextObject.NAME] = key;
- res.push(...this.serializeObj(obj, deep));
- }
- else {
- throw new TypeError("Cannot serialize data in text format. Unsupported type.");
- }
- }
- return res;
- }
- static serializeBufferSource(buffer, deep = 0) {
- const pad = this.pad(deep);
- const view = BufferSourceConverter.toUint8Array(buffer);
- const res = [];
- for (let i = 0; i < view.length;) {
- const row = [];
- for (let j = 0; j < 16 && i < view.length; j++) {
- if (j === 8) {
- row.push("");
- }
- const hex = view[i++].toString(16).padStart(2, "0");
- row.push(hex);
- }
- res.push(`${pad}${row.join(" ")}`);
- }
- return res;
- }
- static serializeAlgorithm(alg) {
- return this.algorithmSerializer.toTextObject(alg);
- }
- }
- TextConverter.oidSerializer = OidSerializer;
- TextConverter.algorithmSerializer = DefaultAlgorithmSerializer;
- var _AsnData_rawData;
- class AsnData {
- get rawData() {
- if (!__classPrivateFieldGet(this, _AsnData_rawData, "f")) {
- __classPrivateFieldSet(this, _AsnData_rawData, AsnConvert.serialize(this.asn), "f");
- }
- return __classPrivateFieldGet(this, _AsnData_rawData, "f");
- }
- constructor(...args) {
- _AsnData_rawData.set(this, void 0);
- if (BufferSourceConverter.isBufferSource(args[0])) {
- this.asn = AsnConvert.parse(args[0], args[1]);
- __classPrivateFieldSet(this, _AsnData_rawData, BufferSourceConverter.toArrayBuffer(args[0]), "f");
- this.onInit(this.asn);
- }
- else {
- this.asn = args[0];
- this.onInit(this.asn);
- }
- }
- equal(data) {
- if (data instanceof AsnData) {
- return isEqual(data.rawData, this.rawData);
- }
- return false;
- }
- toString(format = "text") {
- switch (format) {
- case "asn":
- return AsnConvert.toString(this.rawData);
- case "text":
- return TextConverter.serialize(this.toTextObject());
- case "hex":
- return Convert.ToHex(this.rawData);
- case "base64":
- return Convert.ToBase64(this.rawData);
- case "base64url":
- return Convert.ToBase64Url(this.rawData);
- default:
- throw TypeError("Argument 'format' is unsupported value");
- }
- }
- getTextName() {
- const constructor = this.constructor;
- return constructor.NAME;
- }
- toTextObject() {
- const obj = this.toTextObjectEmpty();
- obj[""] = this.rawData;
- return obj;
- }
- toTextObjectEmpty(value) {
- return new TextObject(this.getTextName(), {}, value);
- }
- }
- _AsnData_rawData = new WeakMap();
- AsnData.NAME = "ASN";
- class Extension extends AsnData {
- constructor(...args) {
- let raw;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- raw = BufferSourceConverter.toArrayBuffer(args[0]);
- }
- else {
- raw = AsnConvert.serialize(new Extension$1({
- extnID: args[0],
- critical: args[1],
- extnValue: new OctetString(BufferSourceConverter.toArrayBuffer(args[2])),
- }));
- }
- super(raw, Extension$1);
- }
- onInit(asn) {
- this.type = asn.extnID;
- this.critical = asn.critical;
- this.value = asn.extnValue.buffer;
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj[""] = this.value;
- return obj;
- }
- toTextObjectWithoutValue() {
- const obj = this.toTextObjectEmpty(this.critical ? "critical" : undefined);
- if (obj[TextObject.NAME] === Extension.NAME) {
- obj[TextObject.NAME] = OidSerializer.toString(this.type);
- }
- return obj;
- }
- }
- var _a;
- class CryptoProvider {
- static isCryptoKeyPair(data) {
- return data && data.privateKey && data.publicKey;
- }
- static isCryptoKey(data) {
- return data && data.usages && data.type && data.algorithm && data.extractable !== undefined;
- }
- constructor() {
- this.items = new Map();
- this[_a] = "CryptoProvider";
- if (typeof self !== "undefined" && typeof crypto !== "undefined") {
- this.set(CryptoProvider.DEFAULT, crypto);
- }
- else if (typeof global !== "undefined" && global.crypto && global.crypto.subtle) {
- this.set(CryptoProvider.DEFAULT, global.crypto);
- }
- }
- clear() {
- this.items.clear();
- }
- delete(key) {
- return this.items.delete(key);
- }
- forEach(callbackfn, thisArg) {
- return this.items.forEach(callbackfn, thisArg);
- }
- has(key) {
- return this.items.has(key);
- }
- get size() {
- return this.items.size;
- }
- entries() {
- return this.items.entries();
- }
- keys() {
- return this.items.keys();
- }
- values() {
- return this.items.values();
- }
- [Symbol.iterator]() {
- return this.items[Symbol.iterator]();
- }
- get(key = CryptoProvider.DEFAULT) {
- const crypto = this.items.get(key.toLowerCase());
- if (!crypto) {
- throw new Error(`Cannot get Crypto by name '${key}'`);
- }
- return crypto;
- }
- set(key, value) {
- if (typeof key === "string") {
- if (!value) {
- throw new TypeError("Argument 'value' is required");
- }
- this.items.set(key.toLowerCase(), value);
- }
- else {
- this.items.set(CryptoProvider.DEFAULT, key);
- }
- return this;
- }
- }
- _a = Symbol.toStringTag;
- CryptoProvider.DEFAULT = "default";
- const cryptoProvider = new CryptoProvider();
- const OID_REGEX = /^[0-2](?:\.[1-9][0-9]*)+$/;
- function isOID(id) {
- return new RegExp(OID_REGEX).test(id);
- }
- class NameIdentifier {
- constructor(names = {}) {
- this.items = {};
- for (const id in names) {
- this.register(id, names[id]);
- }
- }
- get(idOrName) {
- return this.items[idOrName] || null;
- }
- findId(idOrName) {
- if (!isOID(idOrName)) {
- return this.get(idOrName);
- }
- return idOrName;
- }
- register(id, name) {
- this.items[id] = name;
- this.items[name] = id;
- }
- }
- const names = new NameIdentifier();
- names.register("CN", "2.5.4.3");
- names.register("L", "2.5.4.7");
- names.register("ST", "2.5.4.8");
- names.register("O", "2.5.4.10");
- names.register("OU", "2.5.4.11");
- names.register("C", "2.5.4.6");
- names.register("DC", "0.9.2342.19200300.100.1.25");
- names.register("E", "1.2.840.113549.1.9.1");
- names.register("G", "2.5.4.42");
- names.register("I", "2.5.4.43");
- names.register("SN", "2.5.4.4");
- names.register("T", "2.5.4.12");
- function replaceUnknownCharacter(text, char) {
- return `\\${Convert.ToHex(Convert.FromUtf8String(char)).toUpperCase()}`;
- }
- function escape(data) {
- return data
- .replace(/([,+"\\<>;])/g, "\\$1")
- .replace(/^([ #])/, "\\$1")
- .replace(/([ ]$)/, "\\$1")
- .replace(/([\r\n\t])/, replaceUnknownCharacter);
- }
- class Name {
- static isASCII(text) {
- for (let i = 0; i < text.length; i++) {
- const code = text.charCodeAt(i);
- if (code > 0xFF) {
- return false;
- }
- }
- return true;
- }
- static isPrintableString(text) {
- return /^[A-Za-z0-9 '()+,-./:=?]*$/g.test(text);
- }
- constructor(data, extraNames = {}) {
- this.extraNames = new NameIdentifier();
- this.asn = new Name$1();
- for (const key in extraNames) {
- if (Object.prototype.hasOwnProperty.call(extraNames, key)) {
- const value = extraNames[key];
- this.extraNames.register(key, value);
- }
- }
- if (typeof data === "string") {
- this.asn = this.fromString(data);
- }
- else if (data instanceof Name$1) {
- this.asn = data;
- }
- else if (BufferSourceConverter.isBufferSource(data)) {
- this.asn = AsnConvert.parse(data, Name$1);
- }
- else {
- this.asn = this.fromJSON(data);
- }
- }
- getField(idOrName) {
- const id = this.extraNames.findId(idOrName) || names.findId(idOrName);
- const res = [];
- for (const name of this.asn) {
- for (const rdn of name) {
- if (rdn.type === id) {
- res.push(rdn.value.toString());
- }
- }
- }
- return res;
- }
- getName(idOrName) {
- return this.extraNames.get(idOrName) || names.get(idOrName);
- }
- toString() {
- return this.asn.map((rdn) => rdn.map((o) => {
- const type = this.getName(o.type) || o.type;
- const value = o.value.anyValue
- ? `#${Convert.ToHex(o.value.anyValue)}`
- : escape(o.value.toString());
- return `${type}=${value}`;
- })
- .join("+"))
- .join(", ");
- }
- toJSON() {
- var _a;
- const json = [];
- for (const rdn of this.asn) {
- const jsonItem = {};
- for (const attr of rdn) {
- const type = this.getName(attr.type) || attr.type;
- (_a = jsonItem[type]) !== null && _a !== void 0 ? _a : (jsonItem[type] = []);
- jsonItem[type].push(attr.value.anyValue ? `#${Convert.ToHex(attr.value.anyValue)}` : attr.value.toString());
- }
- json.push(jsonItem);
- }
- return json;
- }
- fromString(data) {
- const asn = new Name$1();
- const regex = /(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;
- let matches = null;
- let level = ",";
- while (matches = regex.exec(`${data},`)) {
- let [, type, value] = matches;
- const lastChar = value[value.length - 1];
- if (lastChar === "," || lastChar === "+") {
- value = value.slice(0, value.length - 1);
- matches[3] = lastChar;
- }
- const next = matches[3];
- type = this.getTypeOid(type);
- const attr = this.createAttribute(type, value);
- if (level === "+") {
- asn[asn.length - 1].push(attr);
- }
- else {
- asn.push(new RelativeDistinguishedName([attr]));
- }
- level = next;
- }
- return asn;
- }
- fromJSON(data) {
- const asn = new Name$1();
- for (const item of data) {
- const asnRdn = new RelativeDistinguishedName();
- for (const type in item) {
- const typeId = this.getTypeOid(type);
- const values = item[type];
- for (const value of values) {
- const asnAttr = this.createAttribute(typeId, value);
- asnRdn.push(asnAttr);
- }
- }
- asn.push(asnRdn);
- }
- return asn;
- }
- getTypeOid(type) {
- if (!/[\d.]+/.test(type)) {
- type = this.getName(type) || "";
- }
- if (!type) {
- throw new Error(`Cannot get OID for name type '${type}'`);
- }
- return type;
- }
- createAttribute(type, value) {
- const attr = new AttributeTypeAndValue({ type });
- if (typeof value === "object") {
- for (const key in value) {
- switch (key) {
- case "ia5String":
- attr.value.ia5String = value[key];
- break;
- case "utf8String":
- attr.value.utf8String = value[key];
- break;
- case "universalString":
- attr.value.universalString = value[key];
- break;
- case "bmpString":
- attr.value.bmpString = value[key];
- break;
- case "printableString":
- attr.value.printableString = value[key];
- break;
- }
- }
- }
- else if (value[0] === "#") {
- attr.value.anyValue = Convert.FromHex(value.slice(1));
- }
- else {
- const processedValue = this.processStringValue(value);
- if (type === this.getName("E") || type === this.getName("DC")) {
- attr.value.ia5String = processedValue;
- }
- else {
- if (Name.isPrintableString(processedValue)) {
- attr.value.printableString = processedValue;
- }
- else {
- attr.value.utf8String = processedValue;
- }
- }
- }
- return attr;
- }
- processStringValue(value) {
- const quotedMatches = /"(.*?[^\\])?"/.exec(value);
- if (quotedMatches) {
- value = quotedMatches[1];
- }
- return value
- .replace(/\\0a/ig, "\n")
- .replace(/\\0d/ig, "\r")
- .replace(/\\0g/ig, "\t")
- .replace(/\\(.)/g, "$1");
- }
- toArrayBuffer() {
- return AsnConvert.serialize(this.asn);
- }
- async getThumbprint(...args) {
- var _a;
- let crypto;
- let algorithm = "SHA-1";
- if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
- algorithm = args[0] || algorithm;
- crypto = args[1] || cryptoProvider.get();
- }
- else {
- crypto = args[0] || cryptoProvider.get();
- }
- return await crypto.subtle.digest(algorithm, this.toArrayBuffer());
- }
- }
- const ERR_GN_CONSTRUCTOR = "Cannot initialize GeneralName from ASN.1 data.";
- const ERR_GN_STRING_FORMAT = `${ERR_GN_CONSTRUCTOR} Unsupported string format in use.`;
- const ERR_GUID = `${ERR_GN_CONSTRUCTOR} Value doesn't match to GUID regular expression.`;
- const GUID_REGEX = /^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;
- const id_GUID = "1.3.6.1.4.1.311.25.1";
- const id_UPN = "1.3.6.1.4.1.311.20.2.3";
- const DNS = "dns";
- const DN = "dn";
- const EMAIL = "email";
- const IP = "ip";
- const URL = "url";
- const GUID = "guid";
- const UPN = "upn";
- const REGISTERED_ID = "id";
- class GeneralName extends AsnData {
- constructor(...args) {
- let name;
- if (args.length === 2) {
- switch (args[0]) {
- case DN: {
- const derName = new Name(args[1]).toArrayBuffer();
- const asnName = AsnConvert.parse(derName, asn1X509.Name);
- name = new asn1X509.GeneralName({ directoryName: asnName });
- break;
- }
- case DNS:
- name = new asn1X509.GeneralName({ dNSName: args[1] });
- break;
- case EMAIL:
- name = new asn1X509.GeneralName({ rfc822Name: args[1] });
- break;
- case GUID: {
- const matches = new RegExp(GUID_REGEX, "i").exec(args[1]);
- if (!matches) {
- throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");
- }
- const hex = matches
- .slice(1)
- .map((o, i) => {
- if (i < 3) {
- return Convert.ToHex(new Uint8Array(Convert.FromHex(o)).reverse());
- }
- return o;
- })
- .join("");
- name = new asn1X509.GeneralName({
- otherName: new asn1X509.OtherName({
- typeId: id_GUID,
- value: AsnConvert.serialize(new OctetString(Convert.FromHex(hex))),
- }),
- });
- break;
- }
- case IP:
- name = new asn1X509.GeneralName({ iPAddress: args[1] });
- break;
- case REGISTERED_ID:
- name = new asn1X509.GeneralName({ registeredID: args[1] });
- break;
- case UPN: {
- name = new asn1X509.GeneralName({
- otherName: new asn1X509.OtherName({
- typeId: id_UPN,
- value: AsnConvert.serialize(AsnUtf8StringConverter.toASN(args[1])),
- }),
- });
- break;
- }
- case URL:
- name = new asn1X509.GeneralName({ uniformResourceIdentifier: args[1] });
- break;
- default:
- throw new Error("Cannot create GeneralName. Unsupported type of the name");
- }
- }
- else if (BufferSourceConverter.isBufferSource(args[0])) {
- name = AsnConvert.parse(args[0], asn1X509.GeneralName);
- }
- else {
- name = args[0];
- }
- super(name);
- }
- onInit(asn) {
- if (asn.dNSName != undefined) {
- this.type = DNS;
- this.value = asn.dNSName;
- }
- else if (asn.rfc822Name != undefined) {
- this.type = EMAIL;
- this.value = asn.rfc822Name;
- }
- else if (asn.iPAddress != undefined) {
- this.type = IP;
- this.value = asn.iPAddress;
- }
- else if (asn.uniformResourceIdentifier != undefined) {
- this.type = URL;
- this.value = asn.uniformResourceIdentifier;
- }
- else if (asn.registeredID != undefined) {
- this.type = REGISTERED_ID;
- this.value = asn.registeredID;
- }
- else if (asn.directoryName != undefined) {
- this.type = DN;
- this.value = new Name(asn.directoryName).toString();
- }
- else if (asn.otherName != undefined) {
- if (asn.otherName.typeId === id_GUID) {
- this.type = GUID;
- const guid = AsnConvert.parse(asn.otherName.value, OctetString);
- const matches = new RegExp(GUID_REGEX, "i").exec(Convert.ToHex(guid));
- if (!matches) {
- throw new Error(ERR_GUID);
- }
- this.value = matches
- .slice(1)
- .map((o, i) => {
- if (i < 3) {
- return Convert.ToHex(new Uint8Array(Convert.FromHex(o)).reverse());
- }
- return o;
- })
- .join("-");
- }
- else if (asn.otherName.typeId === id_UPN) {
- this.type = UPN;
- this.value = AsnConvert.parse(asn.otherName.value, asn1X509.DirectoryString).toString();
- }
- else {
- throw new Error(ERR_GN_STRING_FORMAT);
- }
- }
- else {
- throw new Error(ERR_GN_STRING_FORMAT);
- }
- }
- toJSON() {
- return {
- type: this.type,
- value: this.value,
- };
- }
- toTextObject() {
- let type;
- switch (this.type) {
- case DN:
- case DNS:
- case GUID:
- case IP:
- case REGISTERED_ID:
- case UPN:
- case URL:
- type = this.type.toUpperCase();
- break;
- case EMAIL:
- type = "Email";
- break;
- default:
- throw new Error("Unsupported GeneralName type");
- }
- let value = this.value;
- if (this.type === REGISTERED_ID) {
- value = OidSerializer.toString(value);
- }
- return new TextObject(type, undefined, value);
- }
- }
- class GeneralNames extends AsnData {
- constructor(params) {
- let names;
- if (params instanceof asn1X509.GeneralNames) {
- names = params;
- }
- else if (Array.isArray(params)) {
- const items = [];
- for (const name of params) {
- if (name instanceof asn1X509.GeneralName) {
- items.push(name);
- }
- else {
- const asnName = AsnConvert.parse(new GeneralName(name.type, name.value).rawData, asn1X509.GeneralName);
- items.push(asnName);
- }
- }
- names = new asn1X509.GeneralNames(items);
- }
- else if (BufferSourceConverter.isBufferSource(params)) {
- names = AsnConvert.parse(params, asn1X509.GeneralNames);
- }
- else {
- throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");
- }
- super(names);
- }
- onInit(asn) {
- const items = [];
- for (const asnName of asn) {
- let name = null;
- try {
- name = new GeneralName(asnName);
- }
- catch {
- continue;
- }
- items.push(name);
- }
- this.items = items;
- }
- toJSON() {
- return this.items.map((o) => o.toJSON());
- }
- toTextObject() {
- const res = super.toTextObjectEmpty();
- for (const name of this.items) {
- const nameObj = name.toTextObject();
- let field = res[nameObj[TextObject.NAME]];
- if (!Array.isArray(field)) {
- field = [];
- res[nameObj[TextObject.NAME]] = field;
- }
- field.push(nameObj);
- }
- return res;
- }
- }
- GeneralNames.NAME = "GeneralNames";
- const rPaddingTag = "-{5}";
- const rEolChars = "\\n";
- const rNameTag = `[^${rEolChars}]+`;
- const rBeginTag = `${rPaddingTag}BEGIN (${rNameTag}(?=${rPaddingTag}))${rPaddingTag}`;
- const rEndTag = `${rPaddingTag}END \\1${rPaddingTag}`;
- const rEolGroup = "\\n";
- const rHeaderKey = `[^:${rEolChars}]+`;
- const rHeaderValue = `(?:[^${rEolChars}]+${rEolGroup}(?: +[^${rEolChars}]+${rEolGroup})*)`;
- const rBase64Chars = "[a-zA-Z0-9=+/]+";
- const rBase64 = `(?:${rBase64Chars}${rEolGroup})+`;
- const rPem = `${rBeginTag}${rEolGroup}(?:((?:${rHeaderKey}: ${rHeaderValue})+))?${rEolGroup}?(${rBase64})${rEndTag}`;
- class PemConverter {
- static isPem(data) {
- return typeof data === "string"
- && new RegExp(rPem, "g").test(data.replace(/\r/g, ""));
- }
- static decodeWithHeaders(pem) {
- pem = pem.replace(/\r/g, "");
- const pattern = new RegExp(rPem, "g");
- const res = [];
- let matches = null;
- while (matches = pattern.exec(pem)) {
- const base64 = matches[3]
- .replace(new RegExp(`[${rEolChars}]+`, "g"), "");
- const pemStruct = {
- type: matches[1],
- headers: [],
- rawData: Convert.FromBase64(base64),
- };
- const headersString = matches[2];
- if (headersString) {
- const headers = headersString.split(new RegExp(rEolGroup, "g"));
- let lastHeader = null;
- for (const header of headers) {
- const [key, value] = header.split(/:(.*)/);
- if (value === undefined) {
- if (!lastHeader) {
- throw new Error("Cannot parse PEM string. Incorrect header value");
- }
- lastHeader.value += key.trim();
- }
- else {
- if (lastHeader) {
- pemStruct.headers.push(lastHeader);
- }
- lastHeader = {
- key, value: value.trim(),
- };
- }
- }
- if (lastHeader) {
- pemStruct.headers.push(lastHeader);
- }
- }
- res.push(pemStruct);
- }
- return res;
- }
- static decode(pem) {
- const blocks = this.decodeWithHeaders(pem);
- return blocks.map((o) => o.rawData);
- }
- static decodeFirst(pem) {
- const items = this.decode(pem);
- if (!items.length) {
- throw new RangeError("PEM string doesn't contain any objects");
- }
- return items[0];
- }
- static encode(rawData, tag) {
- if (Array.isArray(rawData)) {
- const raws = new Array();
- if (tag) {
- rawData.forEach((element) => {
- if (!BufferSourceConverter.isBufferSource(element)) {
- throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");
- }
- raws.push(this.encodeStruct({
- type: tag,
- rawData: BufferSourceConverter.toArrayBuffer(element),
- }));
- });
- }
- else {
- rawData.forEach((element) => {
- if (!("type" in element)) {
- throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");
- }
- raws.push(this.encodeStruct(element));
- });
- }
- return raws.join("\n");
- }
- else {
- if (!tag) {
- throw new Error("Required argument 'tag' is missed");
- }
- return this.encodeStruct({
- type: tag,
- rawData: BufferSourceConverter.toArrayBuffer(rawData),
- });
- }
- }
- static encodeStruct(pem) {
- var _a;
- const upperCaseType = pem.type.toLocaleUpperCase();
- const res = [];
- res.push(`-----BEGIN ${upperCaseType}-----`);
- if ((_a = pem.headers) === null || _a === void 0 ? void 0 : _a.length) {
- for (const header of pem.headers) {
- res.push(`${header.key}: ${header.value}`);
- }
- res.push("");
- }
- const base64 = Convert.ToBase64(pem.rawData);
- let sliced;
- let offset = 0;
- const rows = Array();
- while (offset < base64.length) {
- if (base64.length - offset < 64) {
- sliced = base64.substring(offset);
- }
- else {
- sliced = base64.substring(offset, offset + 64);
- offset += 64;
- }
- if (sliced.length !== 0) {
- rows.push(sliced);
- if (sliced.length < 64) {
- break;
- }
- }
- else {
- break;
- }
- }
- res.push(...rows);
- res.push(`-----END ${upperCaseType}-----`);
- return res.join("\n");
- }
- }
- PemConverter.CertificateTag = "CERTIFICATE";
- PemConverter.CrlTag = "CRL";
- PemConverter.CertificateRequestTag = "CERTIFICATE REQUEST";
- PemConverter.PublicKeyTag = "PUBLIC KEY";
- PemConverter.PrivateKeyTag = "PRIVATE KEY";
- class PemData extends AsnData {
- static isAsnEncoded(data) {
- return BufferSourceConverter.isBufferSource(data) || typeof data === "string";
- }
- static toArrayBuffer(raw) {
- if (typeof raw === "string") {
- if (PemConverter.isPem(raw)) {
- return PemConverter.decode(raw)[0];
- }
- else if (Convert.isHex(raw)) {
- return Convert.FromHex(raw);
- }
- else if (Convert.isBase64(raw)) {
- return Convert.FromBase64(raw);
- }
- else if (Convert.isBase64Url(raw)) {
- return Convert.FromBase64Url(raw);
- }
- else {
- throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
- }
- }
- else {
- const buffer = BufferSourceConverter.toUint8Array(raw);
- if (buffer.length > 0 && buffer[0] === 0x30) {
- return BufferSourceConverter.toArrayBuffer(raw);
- }
- const stringRaw = Convert.ToBinary(raw);
- if (PemConverter.isPem(stringRaw)) {
- return PemConverter.decode(stringRaw)[0];
- }
- else if (Convert.isHex(stringRaw)) {
- return Convert.FromHex(stringRaw);
- }
- else if (Convert.isBase64(stringRaw)) {
- return Convert.FromBase64(stringRaw);
- }
- else if (Convert.isBase64Url(stringRaw)) {
- return Convert.FromBase64Url(stringRaw);
- }
- throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
- }
- }
- constructor(...args) {
- if (PemData.isAsnEncoded(args[0])) {
- super(PemData.toArrayBuffer(args[0]), args[1]);
- }
- else {
- super(args[0]);
- }
- }
- toString(format = "pem") {
- switch (format) {
- case "pem":
- return PemConverter.encode(this.rawData, this.tag);
- default:
- return super.toString(format);
- }
- }
- }
- class PublicKey extends PemData {
- static async create(data, crypto = cryptoProvider.get()) {
- if (data instanceof PublicKey) {
- return data;
- }
- else if (CryptoProvider.isCryptoKey(data)) {
- if (data.type !== "public") {
- throw new TypeError("Public key is required");
- }
- const spki = await crypto.subtle.exportKey("spki", data);
- return new PublicKey(spki);
- }
- else if (data.publicKey) {
- return data.publicKey;
- }
- else if (BufferSourceConverter.isBufferSource(data)) {
- return new PublicKey(data);
- }
- else {
- throw new TypeError("Unsupported PublicKeyType");
- }
- }
- constructor(param) {
- if (PemData.isAsnEncoded(param)) {
- super(param, SubjectPublicKeyInfo);
- }
- else {
- super(param);
- }
- this.tag = PemConverter.PublicKeyTag;
- }
- async export(...args) {
- let crypto;
- let keyUsages = ["verify"];
- let algorithm = {
- hash: "SHA-256", ...this.algorithm,
- };
- if (args.length > 1) {
- algorithm = args[0] || algorithm;
- keyUsages = args[1] || keyUsages;
- crypto = args[2] || cryptoProvider.get();
- }
- else {
- crypto = args[0] || cryptoProvider.get();
- }
- let raw = this.rawData;
- const asnSpki = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
- if (asnSpki.algorithm.algorithm === id_RSASSA_PSS) {
- raw = convertSpkiToRsaPkcs1(asnSpki, raw);
- }
- return crypto.subtle.importKey("spki", raw, algorithm, true, keyUsages);
- }
- onInit(asn) {
- const algProv = container.resolve(diAlgorithmProvider);
- const algorithm = this.algorithm = algProv.toWebAlgorithm(asn.algorithm);
- switch (asn.algorithm.algorithm) {
- case id_rsaEncryption:
- {
- const rsaPublicKey = AsnConvert.parse(asn.subjectPublicKey, RSAPublicKey);
- const modulus = BufferSourceConverter.toUint8Array(rsaPublicKey.modulus);
- algorithm.publicExponent = BufferSourceConverter.toUint8Array(rsaPublicKey.publicExponent);
- algorithm.modulusLength = (!modulus[0] ? modulus.slice(1) : modulus).byteLength << 3;
- break;
- }
- }
- }
- async getThumbprint(...args) {
- var _a;
- let crypto;
- let algorithm = "SHA-1";
- if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
- algorithm = args[0] || algorithm;
- crypto = args[1] || cryptoProvider.get();
- }
- else {
- crypto = args[0] || cryptoProvider.get();
- }
- return await crypto.subtle.digest(algorithm, this.rawData);
- }
- async getKeyIdentifier(...args) {
- let crypto;
- let algorithm = "SHA-1";
- if (args.length === 1) {
- if (typeof args[0] === "string") {
- algorithm = args[0];
- crypto = cryptoProvider.get();
- }
- else {
- crypto = args[0];
- }
- }
- else if (args.length === 2) {
- algorithm = args[0];
- crypto = args[1];
- }
- else {
- crypto = cryptoProvider.get();
- }
- const asn = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
- return await crypto.subtle.digest(algorithm, asn.subjectPublicKey);
- }
- toTextObject() {
- const obj = this.toTextObjectEmpty();
- const asn = AsnConvert.parse(this.rawData, SubjectPublicKeyInfo);
- obj["Algorithm"] = TextConverter.serializeAlgorithm(asn.algorithm);
- switch (asn.algorithm.algorithm) {
- case id_ecPublicKey:
- obj["EC Point"] = asn.subjectPublicKey;
- break;
- case id_rsaEncryption:
- default:
- obj["Raw Data"] = asn.subjectPublicKey;
- }
- return obj;
- }
- }
- function convertSpkiToRsaPkcs1(asnSpki, raw) {
- asnSpki.algorithm = new AlgorithmIdentifier({
- algorithm: id_rsaEncryption,
- parameters: null,
- });
- raw = AsnConvert.serialize(asnSpki);
- return raw;
- }
- class AuthorityKeyIdentifierExtension extends Extension {
- static async create(param, critical = false, crypto = cryptoProvider.get()) {
- if ("name" in param && "serialNumber" in param) {
- return new AuthorityKeyIdentifierExtension(param, critical);
- }
- const key = await PublicKey.create(param, crypto);
- const id = await key.getKeyIdentifier(crypto);
- return new AuthorityKeyIdentifierExtension(Convert.ToHex(id), critical);
- }
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else if (typeof args[0] === "string") {
- const value = new asn1X509.AuthorityKeyIdentifier({ keyIdentifier: new asn1X509.KeyIdentifier(Convert.FromHex(args[0])) });
- super(asn1X509.id_ce_authorityKeyIdentifier, args[1], AsnConvert.serialize(value));
- }
- else {
- const certId = args[0];
- const certIdName = certId.name instanceof GeneralNames
- ? AsnConvert.parse(certId.name.rawData, asn1X509.GeneralNames)
- : certId.name;
- const value = new asn1X509.AuthorityKeyIdentifier({
- authorityCertIssuer: certIdName,
- authorityCertSerialNumber: Convert.FromHex(certId.serialNumber),
- });
- super(asn1X509.id_ce_authorityKeyIdentifier, args[1], AsnConvert.serialize(value));
- }
- }
- onInit(asn) {
- super.onInit(asn);
- const aki = AsnConvert.parse(asn.extnValue, asn1X509.AuthorityKeyIdentifier);
- if (aki.keyIdentifier) {
- this.keyId = Convert.ToHex(aki.keyIdentifier);
- }
- if (aki.authorityCertIssuer || aki.authorityCertSerialNumber) {
- this.certId = {
- name: aki.authorityCertIssuer || [],
- serialNumber: aki.authorityCertSerialNumber ? Convert.ToHex(aki.authorityCertSerialNumber) : "",
- };
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const asn = AsnConvert.parse(this.value, asn1X509.AuthorityKeyIdentifier);
- if (asn.authorityCertIssuer) {
- obj["Authority Issuer"] = new GeneralNames(asn.authorityCertIssuer).toTextObject();
- }
- if (asn.authorityCertSerialNumber) {
- obj["Authority Serial Number"] = asn.authorityCertSerialNumber;
- }
- if (asn.keyIdentifier) {
- obj[""] = asn.keyIdentifier;
- }
- return obj;
- }
- }
- AuthorityKeyIdentifierExtension.NAME = "Authority Key Identifier";
- class BasicConstraintsExtension extends Extension {
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- const value = AsnConvert.parse(this.value, BasicConstraints);
- this.ca = value.cA;
- this.pathLength = value.pathLenConstraint;
- }
- else {
- const value = new BasicConstraints({
- cA: args[0],
- pathLenConstraint: args[1],
- });
- super(id_ce_basicConstraints, args[2], AsnConvert.serialize(value));
- this.ca = args[0];
- this.pathLength = args[1];
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- if (this.ca) {
- obj["CA"] = this.ca;
- }
- if (this.pathLength !== undefined) {
- obj["Path Length"] = this.pathLength;
- }
- return obj;
- }
- }
- BasicConstraintsExtension.NAME = "Basic Constraints";
- var ExtendedKeyUsage;
- (function (ExtendedKeyUsage) {
- ExtendedKeyUsage["serverAuth"] = "1.3.6.1.5.5.7.3.1";
- ExtendedKeyUsage["clientAuth"] = "1.3.6.1.5.5.7.3.2";
- ExtendedKeyUsage["codeSigning"] = "1.3.6.1.5.5.7.3.3";
- ExtendedKeyUsage["emailProtection"] = "1.3.6.1.5.5.7.3.4";
- ExtendedKeyUsage["timeStamping"] = "1.3.6.1.5.5.7.3.8";
- ExtendedKeyUsage["ocspSigning"] = "1.3.6.1.5.5.7.3.9";
- })(ExtendedKeyUsage || (ExtendedKeyUsage = {}));
- class ExtendedKeyUsageExtension extends Extension {
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- const value = AsnConvert.parse(this.value, asn1X509.ExtendedKeyUsage);
- this.usages = value.map((o) => o);
- }
- else {
- const value = new asn1X509.ExtendedKeyUsage(args[0]);
- super(asn1X509.id_ce_extKeyUsage, args[1], AsnConvert.serialize(value));
- this.usages = args[0];
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj[""] = this.usages.map((o) => OidSerializer.toString(o)).join(", ");
- return obj;
- }
- }
- ExtendedKeyUsageExtension.NAME = "Extended Key Usages";
- var KeyUsageFlags;
- (function (KeyUsageFlags) {
- KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
- KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
- KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
- KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
- KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
- KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
- KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
- KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
- KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
- })(KeyUsageFlags || (KeyUsageFlags = {}));
- class KeyUsagesExtension extends Extension {
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- const value = AsnConvert.parse(this.value, KeyUsage);
- this.usages = value.toNumber();
- }
- else {
- const value = new KeyUsage(args[0]);
- super(id_ce_keyUsage, args[1], AsnConvert.serialize(value));
- this.usages = args[0];
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const asn = AsnConvert.parse(this.value, KeyUsage);
- obj[""] = asn.toJSON().join(", ");
- return obj;
- }
- }
- KeyUsagesExtension.NAME = "Key Usages";
- class SubjectKeyIdentifierExtension extends Extension {
- static async create(publicKey, critical = false, crypto = cryptoProvider.get()) {
- const key = await PublicKey.create(publicKey, crypto);
- const id = await key.getKeyIdentifier(crypto);
- return new SubjectKeyIdentifierExtension(Convert.ToHex(id), critical);
- }
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- const value = AsnConvert.parse(this.value, asn1X509.SubjectKeyIdentifier);
- this.keyId = Convert.ToHex(value);
- }
- else {
- const identifier = typeof args[0] === "string"
- ? Convert.FromHex(args[0])
- : args[0];
- const value = new asn1X509.SubjectKeyIdentifier(identifier);
- super(asn1X509.id_ce_subjectKeyIdentifier, args[1], AsnConvert.serialize(value));
- this.keyId = Convert.ToHex(identifier);
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const asn = AsnConvert.parse(this.value, asn1X509.SubjectKeyIdentifier);
- obj[""] = asn;
- return obj;
- }
- }
- SubjectKeyIdentifierExtension.NAME = "Subject Key Identifier";
- class SubjectAlternativeNameExtension extends Extension {
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else {
- super(asn1X509.id_ce_subjectAltName, args[1], new GeneralNames(args[0] || []).rawData);
- }
- }
- onInit(asn) {
- super.onInit(asn);
- const value = AsnConvert.parse(asn.extnValue, asn1X509.SubjectAlternativeName);
- this.names = new GeneralNames(value);
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const namesObj = this.names.toTextObject();
- for (const key in namesObj) {
- obj[key] = namesObj[key];
- }
- return obj;
- }
- }
- SubjectAlternativeNameExtension.NAME = "Subject Alternative Name";
- class ExtensionFactory {
- static register(id, type) {
- this.items.set(id, type);
- }
- static create(data) {
- const extension = new Extension(data);
- const Type = this.items.get(extension.type);
- if (Type) {
- return new Type(data);
- }
- return extension;
- }
- }
- ExtensionFactory.items = new Map();
- class CertificatePolicyExtension extends Extension {
- constructor(...args) {
- var _a;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- const asnPolicies = AsnConvert.parse(this.value, asn1X509.CertificatePolicies);
- this.policies = asnPolicies.map((o) => o.policyIdentifier);
- }
- else {
- const policies = args[0];
- const critical = (_a = args[1]) !== null && _a !== void 0 ? _a : false;
- const value = new asn1X509.CertificatePolicies(policies.map((o) => (new asn1X509.PolicyInformation({ policyIdentifier: o }))));
- super(asn1X509.id_ce_certificatePolicies, critical, AsnConvert.serialize(value));
- this.policies = policies;
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj["Policy"] = this.policies.map((o) => new TextObject("", {}, OidSerializer.toString(o)));
- return obj;
- }
- }
- CertificatePolicyExtension.NAME = "Certificate Policies";
- ExtensionFactory.register(asn1X509.id_ce_certificatePolicies, CertificatePolicyExtension);
- class CRLDistributionPointsExtension extends Extension {
- constructor(...args) {
- var _a;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else if (Array.isArray(args[0]) && typeof args[0][0] === "string") {
- const urls = args[0];
- const dps = urls.map((url) => {
- return new asn1X509.DistributionPoint({
- distributionPoint: new asn1X509.DistributionPointName({ fullName: [new asn1X509.GeneralName({ uniformResourceIdentifier: url })] }),
- });
- });
- const value = new asn1X509.CRLDistributionPoints(dps);
- super(asn1X509.id_ce_cRLDistributionPoints, args[1], AsnConvert.serialize(value));
- }
- else {
- const value = new asn1X509.CRLDistributionPoints(args[0]);
- super(asn1X509.id_ce_cRLDistributionPoints, args[1], AsnConvert.serialize(value));
- }
- (_a = this.distributionPoints) !== null && _a !== void 0 ? _a : (this.distributionPoints = []);
- }
- onInit(asn) {
- super.onInit(asn);
- const crlExt = AsnConvert.parse(asn.extnValue, asn1X509.CRLDistributionPoints);
- this.distributionPoints = crlExt;
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj["Distribution Point"] = this.distributionPoints.map((dp) => {
- var _a;
- const dpObj = {};
- if (dp.distributionPoint) {
- dpObj[""] = (_a = dp.distributionPoint.fullName) === null || _a === void 0 ? void 0 : _a.map((name) => new GeneralName(name).toString()).join(", ");
- }
- if (dp.reasons) {
- dpObj["Reasons"] = dp.reasons.toString();
- }
- if (dp.cRLIssuer) {
- dpObj["CRL Issuer"] = dp.cRLIssuer.map((issuer) => issuer.toString()).join(", ");
- }
- return dpObj;
- });
- return obj;
- }
- }
- CRLDistributionPointsExtension.NAME = "CRL Distribution Points";
- class AuthorityInfoAccessExtension extends Extension {
- constructor(...args) {
- var _a, _b, _c, _d;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else if (args[0] instanceof asn1X509.AuthorityInfoAccessSyntax) {
- const value = new asn1X509.AuthorityInfoAccessSyntax(args[0]);
- super(asn1X509.id_pe_authorityInfoAccess, args[1], AsnConvert.serialize(value));
- }
- else {
- const params = args[0];
- const value = new asn1X509.AuthorityInfoAccessSyntax();
- addAccessDescriptions(value, params, asn1X509.id_ad_ocsp, "ocsp");
- addAccessDescriptions(value, params, asn1X509.id_ad_caIssuers, "caIssuers");
- addAccessDescriptions(value, params, asn1X509.id_ad_timeStamping, "timeStamping");
- addAccessDescriptions(value, params, asn1X509.id_ad_caRepository, "caRepository");
- super(asn1X509.id_pe_authorityInfoAccess, args[1], AsnConvert.serialize(value));
- }
- (_a = this.ocsp) !== null && _a !== void 0 ? _a : (this.ocsp = []);
- (_b = this.caIssuers) !== null && _b !== void 0 ? _b : (this.caIssuers = []);
- (_c = this.timeStamping) !== null && _c !== void 0 ? _c : (this.timeStamping = []);
- (_d = this.caRepository) !== null && _d !== void 0 ? _d : (this.caRepository = []);
- }
- onInit(asn) {
- super.onInit(asn);
- this.ocsp = [];
- this.caIssuers = [];
- this.timeStamping = [];
- this.caRepository = [];
- const aia = AsnConvert.parse(asn.extnValue, asn1X509.AuthorityInfoAccessSyntax);
- aia.forEach((accessDescription) => {
- switch (accessDescription.accessMethod) {
- case asn1X509.id_ad_ocsp:
- this.ocsp.push(new GeneralName(accessDescription.accessLocation));
- break;
- case asn1X509.id_ad_caIssuers:
- this.caIssuers.push(new GeneralName(accessDescription.accessLocation));
- break;
- case asn1X509.id_ad_timeStamping:
- this.timeStamping.push(new GeneralName(accessDescription.accessLocation));
- break;
- case asn1X509.id_ad_caRepository:
- this.caRepository.push(new GeneralName(accessDescription.accessLocation));
- break;
- }
- });
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- if (this.ocsp.length) {
- addUrlsToObject(obj, "OCSP", this.ocsp);
- }
- if (this.caIssuers.length) {
- addUrlsToObject(obj, "CA Issuers", this.caIssuers);
- }
- if (this.timeStamping.length) {
- addUrlsToObject(obj, "Time Stamping", this.timeStamping);
- }
- if (this.caRepository.length) {
- addUrlsToObject(obj, "CA Repository", this.caRepository);
- }
- return obj;
- }
- }
- AuthorityInfoAccessExtension.NAME = "Authority Info Access";
- function addUrlsToObject(obj, key, urls) {
- if (urls.length === 1) {
- obj[key] = urls[0].toTextObject();
- }
- else {
- const names = new TextObject("");
- urls.forEach((name, index) => {
- const nameObj = name.toTextObject();
- const indexedKey = `${nameObj[TextObject.NAME]} ${index + 1}`;
- let field = names[indexedKey];
- if (!Array.isArray(field)) {
- field = [];
- names[indexedKey] = field;
- }
- field.push(nameObj);
- });
- obj[key] = names;
- }
- }
- function addAccessDescriptions(value, params, method, key) {
- const items = params[key];
- if (items) {
- const array = Array.isArray(items) ? items : [items];
- array.forEach((url) => {
- if (typeof url === "string") {
- url = new GeneralName("url", url);
- }
- value.push(new asn1X509.AccessDescription({
- accessMethod: method,
- accessLocation: AsnConvert.parse(url.rawData, asn1X509.GeneralName),
- }));
- });
- }
- }
- class IssuerAlternativeNameExtension extends Extension {
- constructor(...args) {
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else {
- super(asn1X509.id_ce_issuerAltName, args[1], new GeneralNames(args[0] || []).rawData);
- }
- }
- onInit(asn) {
- super.onInit(asn);
- const value = AsnConvert.parse(asn.extnValue, asn1X509.GeneralNames);
- this.names = new GeneralNames(value);
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const namesObj = this.names.toTextObject();
- for (const key in namesObj) {
- obj[key] = namesObj[key];
- }
- return obj;
- }
- }
- IssuerAlternativeNameExtension.NAME = "Issuer Alternative Name";
- class Attribute extends AsnData {
- constructor(...args) {
- let raw;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- raw = BufferSourceConverter.toArrayBuffer(args[0]);
- }
- else {
- const type = args[0];
- const values = Array.isArray(args[1])
- ? args[1].map((o) => BufferSourceConverter.toArrayBuffer(o))
- : [];
- raw = AsnConvert.serialize(new Attribute$1({
- type, values,
- }));
- }
- super(raw, Attribute$1);
- }
- onInit(asn) {
- this.type = asn.type;
- this.values = asn.values;
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj["Value"] = this.values.map((o) => new TextObject("", { "": o }));
- return obj;
- }
- toTextObjectWithoutValue() {
- const obj = this.toTextObjectEmpty();
- if (obj[TextObject.NAME] === Attribute.NAME) {
- obj[TextObject.NAME] = OidSerializer.toString(this.type);
- }
- return obj;
- }
- }
- Attribute.NAME = "Attribute";
- class ChallengePasswordAttribute extends Attribute {
- constructor(...args) {
- var _a;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else {
- const value = new asnPkcs9.ChallengePassword({ printableString: args[0] });
- super(asnPkcs9.id_pkcs9_at_challengePassword, [AsnConvert.serialize(value)]);
- }
- (_a = this.password) !== null && _a !== void 0 ? _a : (this.password = "");
- }
- onInit(asn) {
- super.onInit(asn);
- if (this.values[0]) {
- const value = AsnConvert.parse(this.values[0], asnPkcs9.ChallengePassword);
- this.password = value.toString();
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- obj[TextObject.VALUE] = this.password;
- return obj;
- }
- }
- ChallengePasswordAttribute.NAME = "Challenge Password";
- class ExtensionsAttribute extends Attribute {
- constructor(...args) {
- var _a;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- super(args[0]);
- }
- else {
- const extensions = args[0];
- const value = new asn1X509.Extensions();
- for (const extension of extensions) {
- value.push(AsnConvert.parse(extension.rawData, asn1X509.Extension));
- }
- super(asnPkcs9.id_pkcs9_at_extensionRequest, [AsnConvert.serialize(value)]);
- }
- (_a = this.items) !== null && _a !== void 0 ? _a : (this.items = []);
- }
- onInit(asn) {
- super.onInit(asn);
- if (this.values[0]) {
- const value = AsnConvert.parse(this.values[0], asn1X509.Extensions);
- this.items = value.map((o) => ExtensionFactory.create(AsnConvert.serialize(o)));
- }
- }
- toTextObject() {
- const obj = this.toTextObjectWithoutValue();
- const extensions = this.items.map((o) => o.toTextObject());
- for (const extension of extensions) {
- obj[extension[TextObject.NAME]] = extension;
- }
- return obj;
- }
- }
- ExtensionsAttribute.NAME = "Extensions";
- class AttributeFactory {
- static register(id, type) {
- this.items.set(id, type);
- }
- static create(data) {
- const attribute = new Attribute(data);
- const Type = this.items.get(attribute.type);
- if (Type) {
- return new Type(data);
- }
- return attribute;
- }
- }
- AttributeFactory.items = new Map();
- const diAsnSignatureFormatter = "crypto.signatureFormatter";
- class AsnDefaultSignatureFormatter {
- toAsnSignature(algorithm, signature) {
- return BufferSourceConverter.toArrayBuffer(signature);
- }
- toWebSignature(algorithm, signature) {
- return BufferSourceConverter.toArrayBuffer(signature);
- }
- }
- var RsaAlgorithm_1;
- let RsaAlgorithm = RsaAlgorithm_1 = class RsaAlgorithm {
- static createPssParams(hash, saltLength) {
- const hashAlgorithm = RsaAlgorithm_1.getHashAlgorithm(hash);
- if (!hashAlgorithm) {
- return null;
- }
- return new asn1Rsa.RsaSaPssParams({
- hashAlgorithm,
- maskGenAlgorithm: new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_mgf1,
- parameters: AsnConvert.serialize(hashAlgorithm),
- }),
- saltLength,
- });
- }
- static getHashAlgorithm(alg) {
- const algProv = container.resolve(diAlgorithmProvider);
- if (typeof alg === "string") {
- return algProv.toAsnAlgorithm({ name: alg });
- }
- if (typeof alg === "object" && alg && "name" in alg) {
- return algProv.toAsnAlgorithm(alg);
- }
- return null;
- }
- toAsnAlgorithm(alg) {
- switch (alg.name.toLowerCase()) {
- case "rsassa-pkcs1-v1_5":
- if ("hash" in alg) {
- let hash;
- if (typeof alg.hash === "string") {
- hash = alg.hash;
- }
- else if (alg.hash && typeof alg.hash === "object"
- && "name" in alg.hash && typeof alg.hash.name === "string") {
- hash = alg.hash.name.toUpperCase();
- }
- else {
- throw new Error("Cannot get hash algorithm name");
- }
- switch (hash.toLowerCase()) {
- case "sha-1":
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_sha1WithRSAEncryption, parameters: null,
- });
- case "sha-256":
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_sha256WithRSAEncryption, parameters: null,
- });
- case "sha-384":
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_sha384WithRSAEncryption, parameters: null,
- });
- case "sha-512":
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_sha512WithRSAEncryption, parameters: null,
- });
- }
- }
- else {
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_rsaEncryption, parameters: null,
- });
- }
- break;
- case "rsa-pss":
- if ("hash" in alg) {
- if (!("saltLength" in alg && typeof alg.saltLength === "number")) {
- throw new Error("Cannot get 'saltLength' from 'alg' argument");
- }
- const pssParams = RsaAlgorithm_1.createPssParams(alg.hash, alg.saltLength);
- if (!pssParams) {
- throw new Error("Cannot create PSS parameters");
- }
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_RSASSA_PSS, parameters: AsnConvert.serialize(pssParams),
- });
- }
- else {
- return new AlgorithmIdentifier({
- algorithm: asn1Rsa.id_RSASSA_PSS, parameters: null,
- });
- }
- }
- return null;
- }
- toWebAlgorithm(alg) {
- switch (alg.algorithm) {
- case asn1Rsa.id_rsaEncryption:
- return { name: "RSASSA-PKCS1-v1_5" };
- case asn1Rsa.id_sha1WithRSAEncryption:
- return {
- name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-1" },
- };
- case asn1Rsa.id_sha256WithRSAEncryption:
- return {
- name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" },
- };
- case asn1Rsa.id_sha384WithRSAEncryption:
- return {
- name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" },
- };
- case asn1Rsa.id_sha512WithRSAEncryption:
- return {
- name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" },
- };
- case asn1Rsa.id_RSASSA_PSS:
- if (alg.parameters) {
- const pssParams = AsnConvert.parse(alg.parameters, asn1Rsa.RsaSaPssParams);
- const algProv = container.resolve(diAlgorithmProvider);
- const hashAlg = algProv.toWebAlgorithm(pssParams.hashAlgorithm);
- return {
- name: "RSA-PSS",
- hash: hashAlg,
- saltLength: pssParams.saltLength,
- };
- }
- else {
- return { name: "RSA-PSS" };
- }
- }
- return null;
- }
- };
- RsaAlgorithm = RsaAlgorithm_1 = __decorate([
- injectable()
- ], RsaAlgorithm);
- container.registerSingleton(diAlgorithm, RsaAlgorithm);
- let ShaAlgorithm = class ShaAlgorithm {
- toAsnAlgorithm(alg) {
- switch (alg.name.toLowerCase()) {
- case "sha-1":
- return new AlgorithmIdentifier({ algorithm: id_sha1 });
- case "sha-256":
- return new AlgorithmIdentifier({ algorithm: id_sha256 });
- case "sha-384":
- return new AlgorithmIdentifier({ algorithm: id_sha384 });
- case "sha-512":
- return new AlgorithmIdentifier({ algorithm: id_sha512 });
- }
- return null;
- }
- toWebAlgorithm(alg) {
- switch (alg.algorithm) {
- case id_sha1:
- return { name: "SHA-1" };
- case id_sha256:
- return { name: "SHA-256" };
- case id_sha384:
- return { name: "SHA-384" };
- case id_sha512:
- return { name: "SHA-512" };
- }
- return null;
- }
- };
- ShaAlgorithm = __decorate([
- injectable()
- ], ShaAlgorithm);
- container.registerSingleton(diAlgorithm, ShaAlgorithm);
- class AsnEcSignatureFormatter {
- addPadding(pointSize, data) {
- const bytes = BufferSourceConverter.toUint8Array(data);
- const res = new Uint8Array(pointSize);
- res.set(bytes, pointSize - bytes.length);
- return res.buffer;
- }
- removePadding(data, positive = false) {
- let bytes = BufferSourceConverter.toUint8Array(data);
- for (let i = 0; i < bytes.length; i++) {
- if (!bytes[i]) {
- continue;
- }
- bytes = bytes.slice(i);
- break;
- }
- if (positive && bytes[0] > 127) {
- const result = new Uint8Array(bytes.length + 1);
- result.set(bytes, 1);
- return result.buffer;
- }
- return bytes.buffer;
- }
- toAsnSignature(algorithm, signature) {
- if (algorithm.name === "ECDSA") {
- const namedCurve = algorithm.namedCurve;
- const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
- || AsnEcSignatureFormatter.defaultNamedCurveSize;
- const ecSignature = new ECDSASigValue();
- const uint8Signature = BufferSourceConverter.toUint8Array(signature);
- ecSignature.r = this.removePadding(uint8Signature.slice(0, pointSize), true);
- ecSignature.s = this.removePadding(uint8Signature.slice(pointSize, pointSize + pointSize), true);
- return AsnConvert.serialize(ecSignature);
- }
- return null;
- }
- toWebSignature(algorithm, signature) {
- if (algorithm.name === "ECDSA") {
- const ecSigValue = AsnConvert.parse(signature, ECDSASigValue);
- const namedCurve = algorithm.namedCurve;
- const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve)
- || AsnEcSignatureFormatter.defaultNamedCurveSize;
- const r = this.addPadding(pointSize, this.removePadding(ecSigValue.r));
- const s = this.addPadding(pointSize, this.removePadding(ecSigValue.s));
- return combine(r, s);
- }
- return null;
- }
- }
- AsnEcSignatureFormatter.namedCurveSize = new Map();
- AsnEcSignatureFormatter.defaultNamedCurveSize = 32;
- const idX25519 = "1.3.101.110";
- const idX448 = "1.3.101.111";
- const idEd25519 = "1.3.101.112";
- const idEd448 = "1.3.101.113";
- let EdAlgorithm = class EdAlgorithm {
- toAsnAlgorithm(alg) {
- let algorithm = null;
- switch (alg.name.toLowerCase()) {
- case "ed25519":
- algorithm = idEd25519;
- break;
- case "x25519":
- algorithm = idX25519;
- break;
- case "eddsa":
- switch (alg.namedCurve.toLowerCase()) {
- case "ed25519":
- algorithm = idEd25519;
- break;
- case "ed448":
- algorithm = idEd448;
- break;
- }
- break;
- case "ecdh-es":
- switch (alg.namedCurve.toLowerCase()) {
- case "x25519":
- algorithm = idX25519;
- break;
- case "x448":
- algorithm = idX448;
- break;
- }
- }
- if (algorithm) {
- return new AlgorithmIdentifier({ algorithm });
- }
- return null;
- }
- toWebAlgorithm(alg) {
- switch (alg.algorithm) {
- case idEd25519:
- return { name: "Ed25519" };
- case idEd448:
- return {
- name: "EdDSA", namedCurve: "Ed448",
- };
- case idX25519:
- return { name: "X25519" };
- case idX448:
- return {
- name: "ECDH-ES", namedCurve: "X448",
- };
- }
- return null;
- }
- };
- EdAlgorithm = __decorate([
- injectable()
- ], EdAlgorithm);
- container.registerSingleton(diAlgorithm, EdAlgorithm);
- var _Pkcs10CertificateRequest_tbs, _Pkcs10CertificateRequest_subjectName, _Pkcs10CertificateRequest_subject, _Pkcs10CertificateRequest_signatureAlgorithm, _Pkcs10CertificateRequest_signature, _Pkcs10CertificateRequest_publicKey, _Pkcs10CertificateRequest_attributes, _Pkcs10CertificateRequest_extensions;
- class Pkcs10CertificateRequest extends PemData {
- get subjectName() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_subjectName, new Name(this.asn.certificationRequestInfo.subject), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f");
- }
- get subject() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_subject, this.subjectName.toString(), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f");
- }
- get signatureAlgorithm() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f")) {
- const algProv = container.resolve(diAlgorithmProvider);
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f");
- }
- get signature() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_signature, this.asn.signature, "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f");
- }
- get publicKey() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_publicKey, new PublicKey(this.asn.certificationRequestInfo.subjectPKInfo), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f");
- }
- get attributes() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_attributes, this.asn.certificationRequestInfo.attributes
- .map((o) => AttributeFactory.create(AsnConvert.serialize(o))), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f");
- }
- get extensions() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, [], "f");
- const extensions = this.getAttribute(id_pkcs9_at_extensionRequest);
- if (extensions instanceof ExtensionsAttribute) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, extensions.items, "f");
- }
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f");
- }
- get tbs() {
- if (!__classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f")) {
- __classPrivateFieldSet(this, _Pkcs10CertificateRequest_tbs, this.asn.certificationRequestInfoRaw
- || AsnConvert.serialize(this.asn.certificationRequestInfo), "f");
- }
- return __classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f");
- }
- constructor(param) {
- const args = PemData.isAsnEncoded(param) ? [param, CertificationRequest] : [param];
- super(args[0], args[1]);
- _Pkcs10CertificateRequest_tbs.set(this, void 0);
- _Pkcs10CertificateRequest_subjectName.set(this, void 0);
- _Pkcs10CertificateRequest_subject.set(this, void 0);
- _Pkcs10CertificateRequest_signatureAlgorithm.set(this, void 0);
- _Pkcs10CertificateRequest_signature.set(this, void 0);
- _Pkcs10CertificateRequest_publicKey.set(this, void 0);
- _Pkcs10CertificateRequest_attributes.set(this, void 0);
- _Pkcs10CertificateRequest_extensions.set(this, void 0);
- this.tag = PemConverter.CertificateRequestTag;
- }
- onInit(_asn) {
- }
- getAttribute(type) {
- for (const attr of this.attributes) {
- if (attr.type === type) {
- return attr;
- }
- }
- return null;
- }
- getAttributes(type) {
- return this.attributes.filter((o) => o.type === type);
- }
- getExtension(type) {
- for (const ext of this.extensions) {
- if (ext.type === type) {
- return ext;
- }
- }
- return null;
- }
- getExtensions(type) {
- return this.extensions.filter((o) => o.type === type);
- }
- async verify(crypto = cryptoProvider.get()) {
- const algorithm = {
- ...this.publicKey.algorithm, ...this.signatureAlgorithm,
- };
- const publicKey = await this.publicKey.export(algorithm, ["verify"], crypto);
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let signature = null;
- for (const signatureFormatter of signatureFormatters) {
- signature = signatureFormatter.toWebSignature(algorithm, this.signature);
- if (signature) {
- break;
- }
- }
- if (!signature) {
- throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
- }
- const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
- return ok;
- }
- toTextObject() {
- const obj = this.toTextObjectEmpty();
- const req = AsnConvert.parse(this.rawData, CertificationRequest);
- const tbs = req.certificationRequestInfo;
- const data = new TextObject("", {
- Version: `${Version[tbs.version]} (${tbs.version})`,
- Subject: this.subject,
- "Subject Public Key Info": this.publicKey,
- });
- if (this.attributes.length) {
- const attrs = new TextObject("");
- for (const ext of this.attributes) {
- const attrObj = ext.toTextObject();
- attrs[attrObj[TextObject.NAME]] = attrObj;
- }
- data["Attributes"] = attrs;
- }
- obj["Data"] = data;
- obj["Signature"] = new TextObject("", {
- Algorithm: TextConverter.serializeAlgorithm(req.signatureAlgorithm),
- "": req.signature,
- });
- return obj;
- }
- }
- _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();
- Pkcs10CertificateRequest.NAME = "PKCS#10 Certificate Request";
- class Pkcs10CertificateRequestGenerator {
- static async create(params, crypto = cryptoProvider.get()) {
- if (!params.keys.privateKey) {
- throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
- }
- if (!params.keys.publicKey) {
- throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
- }
- const spki = await crypto.subtle.exportKey("spki", params.keys.publicKey);
- const asnReq = new CertificationRequest({
- certificationRequestInfo: new CertificationRequestInfo({ subjectPKInfo: AsnConvert.parse(spki, SubjectPublicKeyInfo) }),
- });
- if (params.name) {
- const name = params.name instanceof Name
- ? params.name
- : new Name(params.name);
- asnReq.certificationRequestInfo.subject = AsnConvert.parse(name.toArrayBuffer(), Name$1);
- }
- if (params.attributes) {
- for (const o of params.attributes) {
- asnReq.certificationRequestInfo.attributes.push(AsnConvert.parse(o.rawData, Attribute$1));
- }
- }
- if (params.extensions && params.extensions.length) {
- const attr = new Attribute$1({ type: id_pkcs9_at_extensionRequest });
- const extensions = new Extensions();
- for (const o of params.extensions) {
- extensions.push(AsnConvert.parse(o.rawData, Extension$1));
- }
- attr.values.push(AsnConvert.serialize(extensions));
- asnReq.certificationRequestInfo.attributes.push(attr);
- }
- const signingAlgorithm = {
- ...params.signingAlgorithm, ...params.keys.privateKey.algorithm,
- };
- const algProv = container.resolve(diAlgorithmProvider);
- asnReq.signatureAlgorithm = algProv.toAsnAlgorithm(signingAlgorithm);
- const tbs = AsnConvert.serialize(asnReq.certificationRequestInfo);
- const signature = await crypto.subtle.sign(signingAlgorithm, params.keys.privateKey, tbs);
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let asnSignature = null;
- for (const signatureFormatter of signatureFormatters) {
- asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
- if (asnSignature) {
- break;
- }
- }
- if (!asnSignature) {
- throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
- }
- asnReq.signature = asnSignature;
- return new Pkcs10CertificateRequest(AsnConvert.serialize(asnReq));
- }
- }
- 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;
- class X509Certificate extends PemData {
- get publicKey() {
- if (!__classPrivateFieldGet(this, _X509Certificate_publicKey, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_publicKey, new PublicKey(this.asn.tbsCertificate.subjectPublicKeyInfo), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_publicKey, "f");
- }
- get serialNumber() {
- if (!__classPrivateFieldGet(this, _X509Certificate_serialNumber, "f")) {
- const tbs = this.asn.tbsCertificate;
- let serialNumberBytes = new Uint8Array(tbs.serialNumber);
- if (serialNumberBytes.length > 1
- && serialNumberBytes[0] === 0x00
- && serialNumberBytes[1] > 0x7F) {
- serialNumberBytes = serialNumberBytes.slice(1);
- }
- __classPrivateFieldSet(this, _X509Certificate_serialNumber, Convert.ToHex(serialNumberBytes), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_serialNumber, "f");
- }
- get subjectName() {
- if (!__classPrivateFieldGet(this, _X509Certificate_subjectName, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_subjectName, new Name(this.asn.tbsCertificate.subject), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_subjectName, "f");
- }
- get subject() {
- if (!__classPrivateFieldGet(this, _X509Certificate_subject, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_subject, this.subjectName.toString(), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_subject, "f");
- }
- get issuerName() {
- if (!__classPrivateFieldGet(this, _X509Certificate_issuerName, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_issuerName, new Name(this.asn.tbsCertificate.issuer), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_issuerName, "f");
- }
- get issuer() {
- if (!__classPrivateFieldGet(this, _X509Certificate_issuer, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_issuer, this.issuerName.toString(), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_issuer, "f");
- }
- get notBefore() {
- if (!__classPrivateFieldGet(this, _X509Certificate_notBefore, "f")) {
- const notBefore = this.asn.tbsCertificate.validity.notBefore.utcTime
- || this.asn.tbsCertificate.validity.notBefore.generalTime;
- if (!notBefore) {
- throw new Error("Cannot get 'notBefore' value");
- }
- __classPrivateFieldSet(this, _X509Certificate_notBefore, notBefore, "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_notBefore, "f");
- }
- get notAfter() {
- if (!__classPrivateFieldGet(this, _X509Certificate_notAfter, "f")) {
- const notAfter = this.asn.tbsCertificate.validity.notAfter.utcTime
- || this.asn.tbsCertificate.validity.notAfter.generalTime;
- if (!notAfter) {
- throw new Error("Cannot get 'notAfter' value");
- }
- __classPrivateFieldSet(this, _X509Certificate_notAfter, notAfter, "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_notAfter, "f");
- }
- get signatureAlgorithm() {
- if (!__classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f")) {
- const algProv = container.resolve(diAlgorithmProvider);
- __classPrivateFieldSet(this, _X509Certificate_signatureAlgorithm, algProv
- .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f");
- }
- get signature() {
- if (!__classPrivateFieldGet(this, _X509Certificate_signature, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_signature, this.asn.signatureValue, "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_signature, "f");
- }
- get extensions() {
- if (!__classPrivateFieldGet(this, _X509Certificate_extensions, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_extensions, [], "f");
- if (this.asn.tbsCertificate.extensions) {
- __classPrivateFieldSet(this, _X509Certificate_extensions, this.asn.tbsCertificate.extensions.map((o) => (ExtensionFactory.create(AsnConvert.serialize(o)))), "f");
- }
- }
- return __classPrivateFieldGet(this, _X509Certificate_extensions, "f");
- }
- get tbs() {
- if (!__classPrivateFieldGet(this, _X509Certificate_tbs, "f")) {
- __classPrivateFieldSet(this, _X509Certificate_tbs, this.asn.tbsCertificateRaw || AsnConvert.serialize(this.asn.tbsCertificate), "f");
- }
- return __classPrivateFieldGet(this, _X509Certificate_tbs, "f");
- }
- constructor(param) {
- const args = PemData.isAsnEncoded(param) ? [param, Certificate] : [param];
- super(args[0], args[1]);
- _X509Certificate_tbs.set(this, void 0);
- _X509Certificate_serialNumber.set(this, void 0);
- _X509Certificate_subjectName.set(this, void 0);
- _X509Certificate_subject.set(this, void 0);
- _X509Certificate_issuerName.set(this, void 0);
- _X509Certificate_issuer.set(this, void 0);
- _X509Certificate_notBefore.set(this, void 0);
- _X509Certificate_notAfter.set(this, void 0);
- _X509Certificate_signatureAlgorithm.set(this, void 0);
- _X509Certificate_signature.set(this, void 0);
- _X509Certificate_extensions.set(this, void 0);
- _X509Certificate_publicKey.set(this, void 0);
- this.tag = PemConverter.CertificateTag;
- }
- onInit(_asn) {
- }
- getExtension(type) {
- for (const ext of this.extensions) {
- if (typeof type === "string") {
- if (ext.type === type) {
- return ext;
- }
- }
- else {
- if (ext instanceof type) {
- return ext;
- }
- }
- }
- return null;
- }
- getExtensions(type) {
- return this.extensions.filter((o) => {
- if (typeof type === "string") {
- return o.type === type;
- }
- else {
- return o instanceof type;
- }
- });
- }
- async verify(params = {}, crypto = cryptoProvider.get()) {
- let keyAlgorithm;
- let publicKey;
- const paramsKey = params.publicKey;
- try {
- if (!paramsKey) {
- keyAlgorithm = {
- ...this.publicKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
- }
- else if ("publicKey" in paramsKey) {
- keyAlgorithm = {
- ...paramsKey.publicKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"], crypto);
- }
- else if (paramsKey instanceof PublicKey) {
- keyAlgorithm = {
- ...paramsKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = await paramsKey.export(keyAlgorithm, ["verify"], crypto);
- }
- else if (BufferSourceConverter.isBufferSource(paramsKey)) {
- const key = new PublicKey(paramsKey);
- keyAlgorithm = {
- ...key.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = await key.export(keyAlgorithm, ["verify"], crypto);
- }
- else {
- keyAlgorithm = {
- ...paramsKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = paramsKey;
- }
- }
- catch {
- return false;
- }
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let signature = null;
- for (const signatureFormatter of signatureFormatters) {
- signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
- if (signature) {
- break;
- }
- }
- if (!signature) {
- throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
- }
- const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
- if (params.signatureOnly) {
- return ok;
- }
- else {
- const date = params.date || new Date();
- const time = date.getTime();
- return ok && this.notBefore.getTime() < time && time < this.notAfter.getTime();
- }
- }
- async getThumbprint(...args) {
- let crypto;
- let algorithm = "SHA-1";
- if (args[0]) {
- if (!args[0].subtle) {
- algorithm = args[0] || algorithm;
- crypto = args[1];
- }
- else {
- crypto = args[0];
- }
- }
- crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
- return await crypto.subtle.digest(algorithm, this.rawData);
- }
- async isSelfSigned(crypto = cryptoProvider.get()) {
- return this.subject === this.issuer && await this.verify({ signatureOnly: true }, crypto);
- }
- toTextObject() {
- const obj = this.toTextObjectEmpty();
- const cert = AsnConvert.parse(this.rawData, Certificate);
- const tbs = cert.tbsCertificate;
- const data = new TextObject("", {
- Version: `${Version[tbs.version]} (${tbs.version})`,
- "Serial Number": tbs.serialNumber,
- "Signature Algorithm": TextConverter.serializeAlgorithm(tbs.signature),
- Issuer: this.issuer,
- Validity: new TextObject("", {
- "Not Before": tbs.validity.notBefore.getTime(),
- "Not After": tbs.validity.notAfter.getTime(),
- }),
- Subject: this.subject,
- "Subject Public Key Info": this.publicKey,
- });
- if (tbs.issuerUniqueID) {
- data["Issuer Unique ID"] = tbs.issuerUniqueID;
- }
- if (tbs.subjectUniqueID) {
- data["Subject Unique ID"] = tbs.subjectUniqueID;
- }
- if (this.extensions.length) {
- const extensions = new TextObject("");
- for (const ext of this.extensions) {
- const extObj = ext.toTextObject();
- extensions[extObj[TextObject.NAME]] = extObj;
- }
- data["Extensions"] = extensions;
- }
- obj["Data"] = data;
- obj["Signature"] = new TextObject("", {
- Algorithm: TextConverter.serializeAlgorithm(cert.signatureAlgorithm),
- "": cert.signatureValue,
- });
- return obj;
- }
- }
- _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();
- X509Certificate.NAME = "Certificate";
- class X509Certificates extends Array {
- constructor(param) {
- super();
- if (PemData.isAsnEncoded(param)) {
- this.import(param);
- }
- else if (param instanceof X509Certificate) {
- this.push(param);
- }
- else if (Array.isArray(param)) {
- for (const item of param) {
- this.push(item);
- }
- }
- }
- export(format) {
- const signedData = new asn1Cms.SignedData();
- signedData.version = 1;
- signedData.encapContentInfo.eContentType = asn1Cms.id_data;
- signedData.encapContentInfo.eContent = new asn1Cms.EncapsulatedContent({ single: new OctetString() });
- signedData.certificates = new asn1Cms.CertificateSet(this.map((o) => new asn1Cms.CertificateChoices({ certificate: AsnConvert.parse(o.rawData, Certificate) })));
- const cms = new asn1Cms.ContentInfo({
- contentType: asn1Cms.id_signedData,
- content: AsnConvert.serialize(signedData),
- });
- const raw = AsnConvert.serialize(cms);
- if (format === "raw") {
- return raw;
- }
- return this.toString(format);
- }
- import(data) {
- const raw = PemData.toArrayBuffer(data);
- const cms = AsnConvert.parse(raw, asn1Cms.ContentInfo);
- if (cms.contentType !== asn1Cms.id_signedData) {
- throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");
- }
- const signedData = AsnConvert.parse(cms.content, asn1Cms.SignedData);
- this.clear();
- for (const item of signedData.certificates || []) {
- if (item.certificate) {
- this.push(new X509Certificate(item.certificate));
- }
- }
- }
- clear() {
- while (this.pop()) {
- }
- }
- toString(format = "pem") {
- const raw = this.export("raw");
- switch (format) {
- case "pem":
- return PemConverter.encode(raw, "CMS");
- case "pem-chain":
- return this
- .map((o) => o.toString("pem"))
- .join("\n");
- case "asn":
- return AsnConvert.toString(raw);
- case "hex":
- return Convert.ToHex(raw);
- case "base64":
- return Convert.ToBase64(raw);
- case "base64url":
- return Convert.ToBase64Url(raw);
- case "text":
- return TextConverter.serialize(this.toTextObject());
- default:
- throw TypeError("Argument 'format' is unsupported value");
- }
- }
- toTextObject() {
- const contentInfo = AsnConvert.parse(this.export("raw"), asn1Cms.ContentInfo);
- const signedData = AsnConvert.parse(contentInfo.content, asn1Cms.SignedData);
- const obj = new TextObject("X509Certificates", {
- "Content Type": OidSerializer.toString(contentInfo.contentType),
- Content: new TextObject("", {
- Version: `${asn1Cms.CMSVersion[signedData.version]} (${signedData.version})`,
- Certificates: new TextObject("", { Certificate: this.map((o) => o.toTextObject()) }),
- }),
- });
- return obj;
- }
- }
- class X509ChainBuilder {
- constructor(params = {}) {
- this.certificates = [];
- if (params.certificates) {
- this.certificates = params.certificates;
- }
- }
- async build(cert, crypto = cryptoProvider.get()) {
- const chain = new X509Certificates(cert);
- let current = cert;
- while (current = await this.findIssuer(current, crypto)) {
- const thumbprint = await current.getThumbprint(crypto);
- for (const item of chain) {
- const thumbprint2 = await item.getThumbprint(crypto);
- if (isEqual(thumbprint, thumbprint2)) {
- throw new Error("Cannot build a certificate chain. Circular dependency.");
- }
- }
- chain.push(current);
- }
- return chain;
- }
- async findIssuer(cert, crypto = cryptoProvider.get()) {
- if (!await cert.isSelfSigned(crypto)) {
- const akiExt = cert.getExtension(asn1X509.id_ce_authorityKeyIdentifier);
- for (const item of this.certificates) {
- if (item.subject !== cert.issuer) {
- continue;
- }
- if (akiExt) {
- if (akiExt.keyId) {
- const skiExt = item.getExtension(asn1X509.id_ce_subjectKeyIdentifier);
- if (skiExt && skiExt.keyId !== akiExt.keyId) {
- continue;
- }
- }
- else if (akiExt.certId) {
- const sanExt = item.getExtension(asn1X509.id_ce_subjectAltName);
- if (sanExt
- && !(akiExt.certId.serialNumber === item.serialNumber && isEqual(AsnConvert.serialize(akiExt.certId.name), AsnConvert.serialize(sanExt)))) {
- continue;
- }
- }
- }
- try {
- const algorithm = {
- ...item.publicKey.algorithm, ...cert.signatureAlgorithm,
- };
- const publicKey = await item.publicKey.export(algorithm, ["verify"], crypto);
- const ok = await cert.verify({
- publicKey, signatureOnly: true,
- }, crypto);
- if (!ok) {
- continue;
- }
- }
- catch {
- continue;
- }
- return item;
- }
- }
- return null;
- }
- }
- function generateCertificateSerialNumber(input, crypto = cryptoProvider.get()) {
- const inputView = BufferSourceConverter.toUint8Array(Convert.FromHex(input || ""));
- let serialNumber = inputView && inputView.length && inputView.some((o) => o > 0)
- ? new Uint8Array(inputView)
- : undefined;
- if (!serialNumber) {
- serialNumber = crypto.getRandomValues(new Uint8Array(16));
- }
- let firstNonZero = 0;
- while (firstNonZero < serialNumber.length - 1 && serialNumber[firstNonZero] === 0) {
- firstNonZero++;
- }
- serialNumber = serialNumber.slice(firstNonZero);
- if (serialNumber[0] > 0x7F) {
- const newSerialNumber = new Uint8Array(serialNumber.length + 1);
- newSerialNumber[0] = 0x00;
- newSerialNumber.set(serialNumber, 1);
- serialNumber = newSerialNumber;
- }
- return serialNumber.buffer;
- }
- class X509CertificateGenerator {
- static async createSelfSigned(params, crypto = cryptoProvider.get()) {
- if (!params.keys.privateKey) {
- throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
- }
- if (!params.keys.publicKey) {
- throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
- }
- return this.create({
- serialNumber: params.serialNumber,
- subject: params.name,
- issuer: params.name,
- notBefore: params.notBefore,
- notAfter: params.notAfter,
- publicKey: params.keys.publicKey,
- signingKey: params.keys.privateKey,
- signingAlgorithm: params.signingAlgorithm,
- extensions: params.extensions,
- }, crypto);
- }
- static async create(params, crypto = cryptoProvider.get()) {
- var _a;
- let spki;
- if (params.publicKey instanceof PublicKey) {
- spki = params.publicKey.rawData;
- }
- else if ("publicKey" in params.publicKey) {
- spki = params.publicKey.publicKey.rawData;
- }
- else if (BufferSourceConverter.isBufferSource(params.publicKey)) {
- spki = params.publicKey;
- }
- else {
- spki = await crypto.subtle.exportKey("spki", params.publicKey);
- }
- const serialNumber = generateCertificateSerialNumber(params.serialNumber, crypto);
- const notBefore = params.notBefore || new Date();
- const notAfter = params.notAfter || new Date(notBefore.getTime() + 31536000000);
- const asnX509 = new asn1X509.Certificate({
- tbsCertificate: new asn1X509.TBSCertificate({
- version: asn1X509.Version.v3,
- serialNumber,
- validity: new asn1X509.Validity({
- notBefore,
- notAfter,
- }),
- extensions: new asn1X509.Extensions(((_a = params.extensions) === null || _a === void 0 ? void 0 : _a.map((o) => AsnConvert.parse(o.rawData, asn1X509.Extension))) || []),
- subjectPublicKeyInfo: AsnConvert.parse(spki, asn1X509.SubjectPublicKeyInfo),
- }),
- });
- if (params.subject) {
- const name = params.subject instanceof Name
- ? params.subject
- : new Name(params.subject);
- asnX509.tbsCertificate.subject = AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
- }
- if (params.issuer) {
- const name = params.issuer instanceof Name
- ? params.issuer
- : new Name(params.issuer);
- asnX509.tbsCertificate.issuer = AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
- }
- const defaultSigningAlgorithm = { hash: "SHA-256" };
- const signatureAlgorithm = ("signingKey" in params)
- ? {
- ...defaultSigningAlgorithm, ...params.signingAlgorithm, ...params.signingKey.algorithm,
- }
- : {
- ...defaultSigningAlgorithm, ...params.signingAlgorithm,
- };
- const algProv = container.resolve(diAlgorithmProvider);
- asnX509.tbsCertificate.signature = asnX509.signatureAlgorithm = algProv
- .toAsnAlgorithm(signatureAlgorithm);
- const tbs = AsnConvert.serialize(asnX509.tbsCertificate);
- const signatureValue = ("signingKey" in params)
- ? await crypto.subtle.sign(signatureAlgorithm, params.signingKey, tbs)
- : params.signature;
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let asnSignature = null;
- for (const signatureFormatter of signatureFormatters) {
- asnSignature = signatureFormatter.toAsnSignature(signatureAlgorithm, signatureValue);
- if (asnSignature) {
- break;
- }
- }
- if (!asnSignature) {
- throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
- }
- asnX509.signatureValue = asnSignature;
- return new X509Certificate(AsnConvert.serialize(asnX509));
- }
- }
- var _X509CrlEntry_serialNumber, _X509CrlEntry_revocationDate, _X509CrlEntry_reason, _X509CrlEntry_invalidity, _X509CrlEntry_extensions;
- var X509CrlReason;
- (function (X509CrlReason) {
- X509CrlReason[X509CrlReason["unspecified"] = 0] = "unspecified";
- X509CrlReason[X509CrlReason["keyCompromise"] = 1] = "keyCompromise";
- X509CrlReason[X509CrlReason["cACompromise"] = 2] = "cACompromise";
- X509CrlReason[X509CrlReason["affiliationChanged"] = 3] = "affiliationChanged";
- X509CrlReason[X509CrlReason["superseded"] = 4] = "superseded";
- X509CrlReason[X509CrlReason["cessationOfOperation"] = 5] = "cessationOfOperation";
- X509CrlReason[X509CrlReason["certificateHold"] = 6] = "certificateHold";
- X509CrlReason[X509CrlReason["removeFromCRL"] = 8] = "removeFromCRL";
- X509CrlReason[X509CrlReason["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
- X509CrlReason[X509CrlReason["aACompromise"] = 10] = "aACompromise";
- })(X509CrlReason || (X509CrlReason = {}));
- class X509CrlEntry extends AsnData {
- get serialNumber() {
- if (!__classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f")) {
- __classPrivateFieldSet(this, _X509CrlEntry_serialNumber, Convert.ToHex(this.asn.userCertificate), "f");
- }
- return __classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f");
- }
- get revocationDate() {
- if (!__classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f")) {
- __classPrivateFieldSet(this, _X509CrlEntry_revocationDate, this.asn.revocationDate.getTime(), "f");
- }
- return __classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f");
- }
- get reason() {
- if (__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === undefined) {
- void this.extensions;
- }
- return __classPrivateFieldGet(this, _X509CrlEntry_reason, "f");
- }
- get invalidity() {
- if (__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === undefined) {
- void this.extensions;
- }
- return __classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f");
- }
- get extensions() {
- if (!__classPrivateFieldGet(this, _X509CrlEntry_extensions, "f")) {
- __classPrivateFieldSet(this, _X509CrlEntry_extensions, [], "f");
- if (this.asn.crlEntryExtensions) {
- __classPrivateFieldSet(this, _X509CrlEntry_extensions, this.asn.crlEntryExtensions.map((o) => {
- const extension = ExtensionFactory.create(AsnConvert.serialize(o));
- switch (extension.type) {
- case id_ce_cRLReasons:
- if (__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === undefined) {
- __classPrivateFieldSet(this, _X509CrlEntry_reason, AsnConvert
- .parse(extension.value, CRLReason).reason, "f");
- }
- break;
- case id_ce_invalidityDate:
- if (__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === undefined) {
- __classPrivateFieldSet(this, _X509CrlEntry_invalidity, AsnConvert.parse(extension.value, InvalidityDate).value, "f");
- }
- break;
- }
- return extension;
- }), "f");
- }
- }
- return __classPrivateFieldGet(this, _X509CrlEntry_extensions, "f");
- }
- constructor(...args) {
- let raw;
- if (BufferSourceConverter.isBufferSource(args[0])) {
- raw = BufferSourceConverter.toArrayBuffer(args[0]);
- }
- else if (typeof args[0] === "string") {
- raw = AsnConvert.serialize(new RevokedCertificate({
- userCertificate: generateCertificateSerialNumber(args[0]),
- revocationDate: new Time(args[1]),
- crlEntryExtensions: args[2],
- }));
- }
- else if (args[0] instanceof RevokedCertificate) {
- raw = args[0];
- }
- if (!raw) {
- throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");
- }
- super(raw, RevokedCertificate);
- _X509CrlEntry_serialNumber.set(this, void 0);
- _X509CrlEntry_revocationDate.set(this, void 0);
- _X509CrlEntry_reason.set(this, void 0);
- _X509CrlEntry_invalidity.set(this, void 0);
- _X509CrlEntry_extensions.set(this, void 0);
- }
- onInit(_asn) {
- }
- }
- _X509CrlEntry_serialNumber = new WeakMap(), _X509CrlEntry_revocationDate = new WeakMap(), _X509CrlEntry_reason = new WeakMap(), _X509CrlEntry_invalidity = new WeakMap(), _X509CrlEntry_extensions = new WeakMap();
- var _X509Crl_tbs, _X509Crl_signatureAlgorithm, _X509Crl_issuerName, _X509Crl_thisUpdate, _X509Crl_nextUpdate, _X509Crl_entries, _X509Crl_extensions;
- class X509Crl extends PemData {
- get version() {
- return this.asn.tbsCertList.version;
- }
- get signatureAlgorithm() {
- if (!__classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f")) {
- const algProv = container.resolve(diAlgorithmProvider);
- __classPrivateFieldSet(this, _X509Crl_signatureAlgorithm, algProv
- .toWebAlgorithm(this.asn.signatureAlgorithm), "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f");
- }
- get signature() {
- return this.asn.signature;
- }
- get issuer() {
- return this.issuerName.toString();
- }
- get issuerName() {
- if (!__classPrivateFieldGet(this, _X509Crl_issuerName, "f")) {
- __classPrivateFieldSet(this, _X509Crl_issuerName, new Name(this.asn.tbsCertList.issuer), "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_issuerName, "f");
- }
- get thisUpdate() {
- if (!__classPrivateFieldGet(this, _X509Crl_thisUpdate, "f")) {
- const thisUpdate = this.asn.tbsCertList.thisUpdate.getTime();
- if (!thisUpdate) {
- throw new Error("Cannot get 'thisUpdate' value");
- }
- __classPrivateFieldSet(this, _X509Crl_thisUpdate, thisUpdate, "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_thisUpdate, "f");
- }
- get nextUpdate() {
- var _a;
- if (__classPrivateFieldGet(this, _X509Crl_nextUpdate, "f") === undefined) {
- __classPrivateFieldSet(this, _X509Crl_nextUpdate, ((_a = this.asn.tbsCertList.nextUpdate) === null || _a === void 0 ? void 0 : _a.getTime()) || undefined, "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_nextUpdate, "f");
- }
- get entries() {
- var _a;
- if (!__classPrivateFieldGet(this, _X509Crl_entries, "f")) {
- __classPrivateFieldSet(this, _X509Crl_entries, ((_a = this.asn.tbsCertList
- .revokedCertificates) === null || _a === void 0 ? void 0 : _a.map((o) => new X509CrlEntry(o))) || [], "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_entries, "f");
- }
- get extensions() {
- if (!__classPrivateFieldGet(this, _X509Crl_extensions, "f")) {
- __classPrivateFieldSet(this, _X509Crl_extensions, [], "f");
- if (this.asn.tbsCertList.crlExtensions) {
- __classPrivateFieldSet(this, _X509Crl_extensions, this.asn.tbsCertList.crlExtensions.map((o) => ExtensionFactory.create(AsnConvert.serialize(o))), "f");
- }
- }
- return __classPrivateFieldGet(this, _X509Crl_extensions, "f");
- }
- get tbs() {
- if (!__classPrivateFieldGet(this, _X509Crl_tbs, "f")) {
- __classPrivateFieldSet(this, _X509Crl_tbs, this.asn.tbsCertListRaw || AsnConvert.serialize(this.asn.tbsCertList), "f");
- }
- return __classPrivateFieldGet(this, _X509Crl_tbs, "f");
- }
- get tbsCertListSignatureAlgorithm() {
- return this.asn.tbsCertList.signature;
- }
- get certListSignatureAlgorithm() {
- return this.asn.signatureAlgorithm;
- }
- constructor(param) {
- super(param, PemData.isAsnEncoded(param) ? CertificateList : undefined);
- this.tag = PemConverter.CrlTag;
- _X509Crl_tbs.set(this, void 0);
- _X509Crl_signatureAlgorithm.set(this, void 0);
- _X509Crl_issuerName.set(this, void 0);
- _X509Crl_thisUpdate.set(this, void 0);
- _X509Crl_nextUpdate.set(this, void 0);
- _X509Crl_entries.set(this, void 0);
- _X509Crl_extensions.set(this, void 0);
- }
- onInit(_asn) {
- }
- getExtension(type) {
- for (const ext of this.extensions) {
- if (typeof type === "string") {
- if (ext.type === type) {
- return ext;
- }
- }
- else {
- if (ext instanceof type) {
- return ext;
- }
- }
- }
- return null;
- }
- getExtensions(type) {
- return this.extensions.filter((o) => {
- if (typeof type === "string") {
- return o.type === type;
- }
- else {
- return o instanceof type;
- }
- });
- }
- async verify(params, crypto = cryptoProvider.get()) {
- if (!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm)) {
- throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");
- }
- let keyAlgorithm;
- let publicKey;
- const paramsKey = params.publicKey;
- try {
- if (paramsKey instanceof X509Certificate) {
- keyAlgorithm = {
- ...paramsKey.publicKey.algorithm,
- ...paramsKey.signatureAlgorithm,
- };
- publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]);
- }
- else if (paramsKey instanceof PublicKey) {
- keyAlgorithm = {
- ...paramsKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = await paramsKey.export(keyAlgorithm, ["verify"]);
- }
- else {
- keyAlgorithm = {
- ...paramsKey.algorithm, ...this.signatureAlgorithm,
- };
- publicKey = paramsKey;
- }
- }
- catch {
- return false;
- }
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let signature = null;
- for (const signatureFormatter of signatureFormatters) {
- signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
- if (signature) {
- break;
- }
- }
- if (!signature) {
- throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
- }
- return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
- }
- async getThumbprint(...args) {
- let crypto;
- let algorithm = "SHA-1";
- if (args[0]) {
- if (!args[0].subtle) {
- algorithm = args[0] || algorithm;
- crypto = args[1];
- }
- else {
- crypto = args[0];
- }
- }
- crypto !== null && crypto !== void 0 ? crypto : (crypto = cryptoProvider.get());
- return await crypto.subtle.digest(algorithm, this.rawData);
- }
- findRevoked(certOrSerialNumber) {
- const serialNumber = typeof certOrSerialNumber === "string" ? certOrSerialNumber : certOrSerialNumber.serialNumber;
- const serialBuffer = generateCertificateSerialNumber(serialNumber);
- for (const revoked of this.asn.tbsCertList.revokedCertificates || []) {
- if (BufferSourceConverter.isEqual(revoked.userCertificate, serialBuffer)) {
- return new X509CrlEntry(AsnConvert.serialize(revoked));
- }
- }
- return null;
- }
- }
- _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();
- class X509CrlGenerator {
- static async create(params, crypto = cryptoProvider.get()) {
- var _a;
- const name = params.issuer instanceof Name
- ? params.issuer
- : new Name(params.issuer);
- const asnX509Crl = new asn1X509.CertificateList({
- tbsCertList: new asn1X509.TBSCertList({
- version: asn1X509.Version.v2,
- issuer: AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name),
- thisUpdate: new Time(params.thisUpdate || new Date()),
- }),
- });
- if (params.nextUpdate) {
- asnX509Crl.tbsCertList.nextUpdate = new Time(params.nextUpdate);
- }
- if (params.extensions && params.extensions.length) {
- asnX509Crl.tbsCertList.crlExtensions = new asn1X509.Extensions(params.extensions.map((o) => AsnConvert.parse(o.rawData, asn1X509.Extension)) || []);
- }
- if (params.entries && params.entries.length) {
- asnX509Crl.tbsCertList.revokedCertificates = [];
- for (const entry of params.entries) {
- const userCertificate = PemData.toArrayBuffer(entry.serialNumber);
- const index = asnX509Crl.tbsCertList.revokedCertificates
- .findIndex((cert) => isEqual(cert.userCertificate, userCertificate));
- if (index > -1) {
- throw new Error(`Certificate serial number ${entry.serialNumber} already exists in tbsCertList`);
- }
- const revokedCert = new RevokedCertificate({
- userCertificate: userCertificate,
- revocationDate: new Time(entry.revocationDate || new Date()),
- });
- if ("extensions" in entry && ((_a = entry.extensions) === null || _a === void 0 ? void 0 : _a.length)) {
- revokedCert.crlEntryExtensions = entry.extensions.map((o) => (AsnConvert.parse(o.rawData, asn1X509.Extension)));
- }
- else {
- revokedCert.crlEntryExtensions = [];
- }
- if (!(entry instanceof X509CrlEntry)) {
- if (entry.reason) {
- revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
- extnID: asn1X509.id_ce_cRLReasons,
- critical: false,
- extnValue: new OctetString(AsnConvert.serialize(new asn1X509.CRLReason(entry.reason))),
- }));
- }
- if (entry.invalidity) {
- revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
- extnID: asn1X509.id_ce_invalidityDate,
- critical: false,
- extnValue: new OctetString(AsnConvert.serialize(new asn1X509.InvalidityDate(entry.invalidity))),
- }));
- }
- if (entry.issuer) {
- const name = params.issuer instanceof Name
- ? params.issuer
- : new Name(params.issuer);
- revokedCert.crlEntryExtensions.push(new asn1X509.Extension({
- extnID: asn1X509.id_ce_certificateIssuer,
- critical: false,
- extnValue: new OctetString(AsnConvert.serialize(AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name))),
- }));
- }
- }
- asnX509Crl.tbsCertList.revokedCertificates.push(revokedCert);
- }
- }
- const signingAlgorithm = {
- ...params.signingAlgorithm, ...params.signingKey.algorithm,
- };
- const algProv = container.resolve(diAlgorithmProvider);
- asnX509Crl.tbsCertList.signature = asnX509Crl.signatureAlgorithm = algProv
- .toAsnAlgorithm(signingAlgorithm);
- const tbs = AsnConvert.serialize(asnX509Crl.tbsCertList);
- const signature = await crypto.subtle.sign(signingAlgorithm, params.signingKey, tbs);
- const signatureFormatters = container
- .resolveAll(diAsnSignatureFormatter)
- .reverse();
- let asnSignature = null;
- for (const signatureFormatter of signatureFormatters) {
- asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
- if (asnSignature) {
- break;
- }
- }
- if (!asnSignature) {
- throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
- }
- asnX509Crl.signature = asnSignature;
- return new X509Crl(AsnConvert.serialize(asnX509Crl));
- }
- }
- ExtensionFactory.register(asn1X509.id_ce_basicConstraints, BasicConstraintsExtension);
- ExtensionFactory.register(asn1X509.id_ce_extKeyUsage, ExtendedKeyUsageExtension);
- ExtensionFactory.register(asn1X509.id_ce_keyUsage, KeyUsagesExtension);
- ExtensionFactory.register(asn1X509.id_ce_subjectKeyIdentifier, SubjectKeyIdentifierExtension);
- ExtensionFactory.register(asn1X509.id_ce_authorityKeyIdentifier, AuthorityKeyIdentifierExtension);
- ExtensionFactory.register(asn1X509.id_ce_subjectAltName, SubjectAlternativeNameExtension);
- ExtensionFactory.register(asn1X509.id_ce_cRLDistributionPoints, CRLDistributionPointsExtension);
- ExtensionFactory.register(asn1X509.id_pe_authorityInfoAccess, AuthorityInfoAccessExtension);
- ExtensionFactory.register(asn1X509.id_ce_issuerAltName, IssuerAlternativeNameExtension);
- AttributeFactory.register(asnPkcs9.id_pkcs9_at_challengePassword, ChallengePasswordAttribute);
- AttributeFactory.register(asnPkcs9.id_pkcs9_at_extensionRequest, ExtensionsAttribute);
- container.registerSingleton(diAsnSignatureFormatter, AsnDefaultSignatureFormatter);
- container.registerSingleton(diAsnSignatureFormatter, AsnEcSignatureFormatter);
- AsnEcSignatureFormatter.namedCurveSize.set("P-256", 32);
- AsnEcSignatureFormatter.namedCurveSize.set("K-256", 32);
- AsnEcSignatureFormatter.namedCurveSize.set("P-384", 48);
- AsnEcSignatureFormatter.namedCurveSize.set("P-521", 66);
- 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 };
|