1187b660ae6f6e9ebe4f2d4747815d42cfe5a784e81de21732ce6a2c2f2fd11f4e99dd84c3d971641086b0d6806a0c1bbacac76bd7c381708dab26bbcd0470 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509
  1. /**
  2. * The `node:crypto` module provides cryptographic functionality that includes a
  3. * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
  4. * functions.
  5. *
  6. * ```js
  7. * const { createHmac } = await import('node:crypto');
  8. *
  9. * const secret = 'abcdefg';
  10. * const hash = createHmac('sha256', secret)
  11. * .update('I love cupcakes')
  12. * .digest('hex');
  13. * console.log(hash);
  14. * // Prints:
  15. * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
  16. * ```
  17. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/crypto.js)
  18. */
  19. declare module "crypto" {
  20. import * as stream from "node:stream";
  21. import { PeerCertificate } from "node:tls";
  22. /**
  23. * SPKAC is a Certificate Signing Request mechanism originally implemented by
  24. * Netscape and was specified formally as part of HTML5's `keygen` element.
  25. *
  26. * `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
  27. * should not use this element anymore.
  28. *
  29. * The `node:crypto` module provides the `Certificate` class for working with SPKAC
  30. * data. The most common usage is handling output generated by the HTML5 `<keygen>` element. Node.js uses [OpenSSL's SPKAC
  31. * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally.
  32. * @since v0.11.8
  33. */
  34. class Certificate {
  35. /**
  36. * ```js
  37. * const { Certificate } = await import('node:crypto');
  38. * const spkac = getSpkacSomehow();
  39. * const challenge = Certificate.exportChallenge(spkac);
  40. * console.log(challenge.toString('utf8'));
  41. * // Prints: the challenge as a UTF8 string
  42. * ```
  43. * @since v9.0.0
  44. * @param encoding The `encoding` of the `spkac` string.
  45. * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge.
  46. */
  47. static exportChallenge(spkac: BinaryLike): Buffer;
  48. /**
  49. * ```js
  50. * const { Certificate } = await import('node:crypto');
  51. * const spkac = getSpkacSomehow();
  52. * const publicKey = Certificate.exportPublicKey(spkac);
  53. * console.log(publicKey);
  54. * // Prints: the public key as <Buffer ...>
  55. * ```
  56. * @since v9.0.0
  57. * @param encoding The `encoding` of the `spkac` string.
  58. * @return The public key component of the `spkac` data structure, which includes a public key and a challenge.
  59. */
  60. static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
  61. /**
  62. * ```js
  63. * import { Buffer } from 'node:buffer';
  64. * const { Certificate } = await import('node:crypto');
  65. *
  66. * const spkac = getSpkacSomehow();
  67. * console.log(Certificate.verifySpkac(Buffer.from(spkac)));
  68. * // Prints: true or false
  69. * ```
  70. * @since v9.0.0
  71. * @param encoding The `encoding` of the `spkac` string.
  72. * @return `true` if the given `spkac` data structure is valid, `false` otherwise.
  73. */
  74. static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
  75. /**
  76. * @deprecated
  77. * @param spkac
  78. * @returns The challenge component of the `spkac` data structure,
  79. * which includes a public key and a challenge.
  80. */
  81. exportChallenge(spkac: BinaryLike): Buffer;
  82. /**
  83. * @deprecated
  84. * @param spkac
  85. * @param encoding The encoding of the spkac string.
  86. * @returns The public key component of the `spkac` data structure,
  87. * which includes a public key and a challenge.
  88. */
  89. exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
  90. /**
  91. * @deprecated
  92. * @param spkac
  93. * @returns `true` if the given `spkac` data structure is valid,
  94. * `false` otherwise.
  95. */
  96. verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
  97. }
  98. namespace constants {
  99. // https://nodejs.org/dist/latest-v22.x/docs/api/crypto.html#crypto-constants
  100. const OPENSSL_VERSION_NUMBER: number;
  101. /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
  102. const SSL_OP_ALL: number;
  103. /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */
  104. const SSL_OP_ALLOW_NO_DHE_KEX: number;
  105. /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
  106. const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
  107. /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
  108. const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
  109. /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */
  110. const SSL_OP_CISCO_ANYCONNECT: number;
  111. /** Instructs OpenSSL to turn on cookie exchange. */
  112. const SSL_OP_COOKIE_EXCHANGE: number;
  113. /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
  114. const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
  115. /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
  116. const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
  117. /** Allows initial connection to servers that do not support RI. */
  118. const SSL_OP_LEGACY_SERVER_CONNECT: number;
  119. /** Instructs OpenSSL to disable support for SSL/TLS compression. */
  120. const SSL_OP_NO_COMPRESSION: number;
  121. /** Instructs OpenSSL to disable encrypt-then-MAC. */
  122. const SSL_OP_NO_ENCRYPT_THEN_MAC: number;
  123. const SSL_OP_NO_QUERY_MTU: number;
  124. /** Instructs OpenSSL to disable renegotiation. */
  125. const SSL_OP_NO_RENEGOTIATION: number;
  126. /** Instructs OpenSSL to always start a new session when performing renegotiation. */
  127. const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
  128. /** Instructs OpenSSL to turn off SSL v2 */
  129. const SSL_OP_NO_SSLv2: number;
  130. /** Instructs OpenSSL to turn off SSL v3 */
  131. const SSL_OP_NO_SSLv3: number;
  132. /** Instructs OpenSSL to disable use of RFC4507bis tickets. */
  133. const SSL_OP_NO_TICKET: number;
  134. /** Instructs OpenSSL to turn off TLS v1 */
  135. const SSL_OP_NO_TLSv1: number;
  136. /** Instructs OpenSSL to turn off TLS v1.1 */
  137. const SSL_OP_NO_TLSv1_1: number;
  138. /** Instructs OpenSSL to turn off TLS v1.2 */
  139. const SSL_OP_NO_TLSv1_2: number;
  140. /** Instructs OpenSSL to turn off TLS v1.3 */
  141. const SSL_OP_NO_TLSv1_3: number;
  142. /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */
  143. const SSL_OP_PRIORITIZE_CHACHA: number;
  144. /** Instructs OpenSSL to disable version rollback attack detection. */
  145. const SSL_OP_TLS_ROLLBACK_BUG: number;
  146. const ENGINE_METHOD_RSA: number;
  147. const ENGINE_METHOD_DSA: number;
  148. const ENGINE_METHOD_DH: number;
  149. const ENGINE_METHOD_RAND: number;
  150. const ENGINE_METHOD_EC: number;
  151. const ENGINE_METHOD_CIPHERS: number;
  152. const ENGINE_METHOD_DIGESTS: number;
  153. const ENGINE_METHOD_PKEY_METHS: number;
  154. const ENGINE_METHOD_PKEY_ASN1_METHS: number;
  155. const ENGINE_METHOD_ALL: number;
  156. const ENGINE_METHOD_NONE: number;
  157. const DH_CHECK_P_NOT_SAFE_PRIME: number;
  158. const DH_CHECK_P_NOT_PRIME: number;
  159. const DH_UNABLE_TO_CHECK_GENERATOR: number;
  160. const DH_NOT_SUITABLE_GENERATOR: number;
  161. const RSA_PKCS1_PADDING: number;
  162. const RSA_SSLV23_PADDING: number;
  163. const RSA_NO_PADDING: number;
  164. const RSA_PKCS1_OAEP_PADDING: number;
  165. const RSA_X931_PADDING: number;
  166. const RSA_PKCS1_PSS_PADDING: number;
  167. /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
  168. const RSA_PSS_SALTLEN_DIGEST: number;
  169. /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
  170. const RSA_PSS_SALTLEN_MAX_SIGN: number;
  171. /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
  172. const RSA_PSS_SALTLEN_AUTO: number;
  173. const POINT_CONVERSION_COMPRESSED: number;
  174. const POINT_CONVERSION_UNCOMPRESSED: number;
  175. const POINT_CONVERSION_HYBRID: number;
  176. /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
  177. const defaultCoreCipherList: string;
  178. /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
  179. const defaultCipherList: string;
  180. }
  181. interface HashOptions extends stream.TransformOptions {
  182. /**
  183. * For XOF hash functions such as `shake256`, the
  184. * outputLength option can be used to specify the desired output length in bytes.
  185. */
  186. outputLength?: number | undefined;
  187. }
  188. /** @deprecated since v10.0.0 */
  189. const fips: boolean;
  190. /**
  191. * Creates and returns a `Hash` object that can be used to generate hash digests
  192. * using the given `algorithm`. Optional `options` argument controls stream
  193. * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
  194. * can be used to specify the desired output length in bytes.
  195. *
  196. * The `algorithm` is dependent on the available algorithms supported by the
  197. * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
  198. * On recent releases of OpenSSL, `openssl list -digest-algorithms` will
  199. * display the available digest algorithms.
  200. *
  201. * Example: generating the sha256 sum of a file
  202. *
  203. * ```js
  204. * import {
  205. * createReadStream,
  206. * } from 'node:fs';
  207. * import { argv } from 'node:process';
  208. * const {
  209. * createHash,
  210. * } = await import('node:crypto');
  211. *
  212. * const filename = argv[2];
  213. *
  214. * const hash = createHash('sha256');
  215. *
  216. * const input = createReadStream(filename);
  217. * input.on('readable', () => {
  218. * // Only one element is going to be produced by the
  219. * // hash stream.
  220. * const data = input.read();
  221. * if (data)
  222. * hash.update(data);
  223. * else {
  224. * console.log(`${hash.digest('hex')} ${filename}`);
  225. * }
  226. * });
  227. * ```
  228. * @since v0.1.92
  229. * @param options `stream.transform` options
  230. */
  231. function createHash(algorithm: string, options?: HashOptions): Hash;
  232. /**
  233. * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
  234. * Optional `options` argument controls stream behavior.
  235. *
  236. * The `algorithm` is dependent on the available algorithms supported by the
  237. * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
  238. * On recent releases of OpenSSL, `openssl list -digest-algorithms` will
  239. * display the available digest algorithms.
  240. *
  241. * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
  242. * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was
  243. * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not
  244. * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256).
  245. *
  246. * Example: generating the sha256 HMAC of a file
  247. *
  248. * ```js
  249. * import {
  250. * createReadStream,
  251. * } from 'node:fs';
  252. * import { argv } from 'node:process';
  253. * const {
  254. * createHmac,
  255. * } = await import('node:crypto');
  256. *
  257. * const filename = argv[2];
  258. *
  259. * const hmac = createHmac('sha256', 'a secret');
  260. *
  261. * const input = createReadStream(filename);
  262. * input.on('readable', () => {
  263. * // Only one element is going to be produced by the
  264. * // hash stream.
  265. * const data = input.read();
  266. * if (data)
  267. * hmac.update(data);
  268. * else {
  269. * console.log(`${hmac.digest('hex')} ${filename}`);
  270. * }
  271. * });
  272. * ```
  273. * @since v0.1.94
  274. * @param options `stream.transform` options
  275. */
  276. function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
  277. // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
  278. type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary";
  279. type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1";
  280. type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2";
  281. type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding;
  282. type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid";
  283. /**
  284. * The `Hash` class is a utility for creating hash digests of data. It can be
  285. * used in one of two ways:
  286. *
  287. * * As a `stream` that is both readable and writable, where data is written
  288. * to produce a computed hash digest on the readable side, or
  289. * * Using the `hash.update()` and `hash.digest()` methods to produce the
  290. * computed hash.
  291. *
  292. * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
  293. *
  294. * Example: Using `Hash` objects as streams:
  295. *
  296. * ```js
  297. * const {
  298. * createHash,
  299. * } = await import('node:crypto');
  300. *
  301. * const hash = createHash('sha256');
  302. *
  303. * hash.on('readable', () => {
  304. * // Only one element is going to be produced by the
  305. * // hash stream.
  306. * const data = hash.read();
  307. * if (data) {
  308. * console.log(data.toString('hex'));
  309. * // Prints:
  310. * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
  311. * }
  312. * });
  313. *
  314. * hash.write('some data to hash');
  315. * hash.end();
  316. * ```
  317. *
  318. * Example: Using `Hash` and piped streams:
  319. *
  320. * ```js
  321. * import { createReadStream } from 'node:fs';
  322. * import { stdout } from 'node:process';
  323. * const { createHash } = await import('node:crypto');
  324. *
  325. * const hash = createHash('sha256');
  326. *
  327. * const input = createReadStream('test.js');
  328. * input.pipe(hash).setEncoding('hex').pipe(stdout);
  329. * ```
  330. *
  331. * Example: Using the `hash.update()` and `hash.digest()` methods:
  332. *
  333. * ```js
  334. * const {
  335. * createHash,
  336. * } = await import('node:crypto');
  337. *
  338. * const hash = createHash('sha256');
  339. *
  340. * hash.update('some data to hash');
  341. * console.log(hash.digest('hex'));
  342. * // Prints:
  343. * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
  344. * ```
  345. * @since v0.1.92
  346. */
  347. class Hash extends stream.Transform {
  348. private constructor();
  349. /**
  350. * Creates a new `Hash` object that contains a deep copy of the internal state
  351. * of the current `Hash` object.
  352. *
  353. * The optional `options` argument controls stream behavior. For XOF hash
  354. * functions such as `'shake256'`, the `outputLength` option can be used to
  355. * specify the desired output length in bytes.
  356. *
  357. * An error is thrown when an attempt is made to copy the `Hash` object after
  358. * its `hash.digest()` method has been called.
  359. *
  360. * ```js
  361. * // Calculate a rolling hash.
  362. * const {
  363. * createHash,
  364. * } = await import('node:crypto');
  365. *
  366. * const hash = createHash('sha256');
  367. *
  368. * hash.update('one');
  369. * console.log(hash.copy().digest('hex'));
  370. *
  371. * hash.update('two');
  372. * console.log(hash.copy().digest('hex'));
  373. *
  374. * hash.update('three');
  375. * console.log(hash.copy().digest('hex'));
  376. *
  377. * // Etc.
  378. * ```
  379. * @since v13.1.0
  380. * @param options `stream.transform` options
  381. */
  382. copy(options?: HashOptions): Hash;
  383. /**
  384. * Updates the hash content with the given `data`, the encoding of which
  385. * is given in `inputEncoding`.
  386. * If `encoding` is not provided, and the `data` is a string, an
  387. * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
  388. *
  389. * This can be called many times with new data as it is streamed.
  390. * @since v0.1.92
  391. * @param inputEncoding The `encoding` of the `data` string.
  392. */
  393. update(data: BinaryLike): Hash;
  394. update(data: string, inputEncoding: Encoding): Hash;
  395. /**
  396. * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
  397. * If `encoding` is provided a string will be returned; otherwise
  398. * a `Buffer` is returned.
  399. *
  400. * The `Hash` object can not be used again after `hash.digest()` method has been
  401. * called. Multiple calls will cause an error to be thrown.
  402. * @since v0.1.92
  403. * @param encoding The `encoding` of the return value.
  404. */
  405. digest(): Buffer;
  406. digest(encoding: BinaryToTextEncoding): string;
  407. }
  408. /**
  409. * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
  410. * be used in one of two ways:
  411. *
  412. * * As a `stream` that is both readable and writable, where data is written
  413. * to produce a computed HMAC digest on the readable side, or
  414. * * Using the `hmac.update()` and `hmac.digest()` methods to produce the
  415. * computed HMAC digest.
  416. *
  417. * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
  418. *
  419. * Example: Using `Hmac` objects as streams:
  420. *
  421. * ```js
  422. * const {
  423. * createHmac,
  424. * } = await import('node:crypto');
  425. *
  426. * const hmac = createHmac('sha256', 'a secret');
  427. *
  428. * hmac.on('readable', () => {
  429. * // Only one element is going to be produced by the
  430. * // hash stream.
  431. * const data = hmac.read();
  432. * if (data) {
  433. * console.log(data.toString('hex'));
  434. * // Prints:
  435. * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
  436. * }
  437. * });
  438. *
  439. * hmac.write('some data to hash');
  440. * hmac.end();
  441. * ```
  442. *
  443. * Example: Using `Hmac` and piped streams:
  444. *
  445. * ```js
  446. * import { createReadStream } from 'node:fs';
  447. * import { stdout } from 'node:process';
  448. * const {
  449. * createHmac,
  450. * } = await import('node:crypto');
  451. *
  452. * const hmac = createHmac('sha256', 'a secret');
  453. *
  454. * const input = createReadStream('test.js');
  455. * input.pipe(hmac).pipe(stdout);
  456. * ```
  457. *
  458. * Example: Using the `hmac.update()` and `hmac.digest()` methods:
  459. *
  460. * ```js
  461. * const {
  462. * createHmac,
  463. * } = await import('node:crypto');
  464. *
  465. * const hmac = createHmac('sha256', 'a secret');
  466. *
  467. * hmac.update('some data to hash');
  468. * console.log(hmac.digest('hex'));
  469. * // Prints:
  470. * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
  471. * ```
  472. * @since v0.1.94
  473. * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances.
  474. */
  475. class Hmac extends stream.Transform {
  476. private constructor();
  477. /**
  478. * Updates the `Hmac` content with the given `data`, the encoding of which
  479. * is given in `inputEncoding`.
  480. * If `encoding` is not provided, and the `data` is a string, an
  481. * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
  482. *
  483. * This can be called many times with new data as it is streamed.
  484. * @since v0.1.94
  485. * @param inputEncoding The `encoding` of the `data` string.
  486. */
  487. update(data: BinaryLike): Hmac;
  488. update(data: string, inputEncoding: Encoding): Hmac;
  489. /**
  490. * Calculates the HMAC digest of all of the data passed using `hmac.update()`.
  491. * If `encoding` is
  492. * provided a string is returned; otherwise a `Buffer` is returned;
  493. *
  494. * The `Hmac` object can not be used again after `hmac.digest()` has been
  495. * called. Multiple calls to `hmac.digest()` will result in an error being thrown.
  496. * @since v0.1.94
  497. * @param encoding The `encoding` of the return value.
  498. */
  499. digest(): Buffer;
  500. digest(encoding: BinaryToTextEncoding): string;
  501. }
  502. type KeyObjectType = "secret" | "public" | "private";
  503. interface KeyExportOptions<T extends KeyFormat> {
  504. type: "pkcs1" | "spki" | "pkcs8" | "sec1";
  505. format: T;
  506. cipher?: string | undefined;
  507. passphrase?: string | Buffer | undefined;
  508. }
  509. interface JwkKeyExportOptions {
  510. format: "jwk";
  511. }
  512. interface JsonWebKey {
  513. crv?: string | undefined;
  514. d?: string | undefined;
  515. dp?: string | undefined;
  516. dq?: string | undefined;
  517. e?: string | undefined;
  518. k?: string | undefined;
  519. kty?: string | undefined;
  520. n?: string | undefined;
  521. p?: string | undefined;
  522. q?: string | undefined;
  523. qi?: string | undefined;
  524. x?: string | undefined;
  525. y?: string | undefined;
  526. [key: string]: unknown;
  527. }
  528. interface AsymmetricKeyDetails {
  529. /**
  530. * Key size in bits (RSA, DSA).
  531. */
  532. modulusLength?: number | undefined;
  533. /**
  534. * Public exponent (RSA).
  535. */
  536. publicExponent?: bigint | undefined;
  537. /**
  538. * Name of the message digest (RSA-PSS).
  539. */
  540. hashAlgorithm?: string | undefined;
  541. /**
  542. * Name of the message digest used by MGF1 (RSA-PSS).
  543. */
  544. mgf1HashAlgorithm?: string | undefined;
  545. /**
  546. * Minimal salt length in bytes (RSA-PSS).
  547. */
  548. saltLength?: number | undefined;
  549. /**
  550. * Size of q in bits (DSA).
  551. */
  552. divisorLength?: number | undefined;
  553. /**
  554. * Name of the curve (EC).
  555. */
  556. namedCurve?: string | undefined;
  557. }
  558. /**
  559. * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
  560. * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
  561. * objects are not to be created directly using the `new`keyword.
  562. *
  563. * Most applications should consider using the new `KeyObject` API instead of
  564. * passing keys as strings or `Buffer`s due to improved security features.
  565. *
  566. * `KeyObject` instances can be passed to other threads via `postMessage()`.
  567. * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
  568. * be listed in the `transferList` argument.
  569. * @since v11.6.0
  570. */
  571. class KeyObject {
  572. private constructor();
  573. /**
  574. * Example: Converting a `CryptoKey` instance to a `KeyObject`:
  575. *
  576. * ```js
  577. * const { KeyObject } = await import('node:crypto');
  578. * const { subtle } = globalThis.crypto;
  579. *
  580. * const key = await subtle.generateKey({
  581. * name: 'HMAC',
  582. * hash: 'SHA-256',
  583. * length: 256,
  584. * }, true, ['sign', 'verify']);
  585. *
  586. * const keyObject = KeyObject.from(key);
  587. * console.log(keyObject.symmetricKeySize);
  588. * // Prints: 32 (symmetric key size in bytes)
  589. * ```
  590. * @since v15.0.0
  591. */
  592. static from(key: webcrypto.CryptoKey): KeyObject;
  593. /**
  594. * For asymmetric keys, this property represents the type of the key. Supported key
  595. * types are:
  596. *
  597. * * `'rsa'` (OID 1.2.840.113549.1.1.1)
  598. * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
  599. * * `'dsa'` (OID 1.2.840.10040.4.1)
  600. * * `'ec'` (OID 1.2.840.10045.2.1)
  601. * * `'x25519'` (OID 1.3.101.110)
  602. * * `'x448'` (OID 1.3.101.111)
  603. * * `'ed25519'` (OID 1.3.101.112)
  604. * * `'ed448'` (OID 1.3.101.113)
  605. * * `'dh'` (OID 1.2.840.113549.1.3.1)
  606. *
  607. * This property is `undefined` for unrecognized `KeyObject` types and symmetric
  608. * keys.
  609. * @since v11.6.0
  610. */
  611. asymmetricKeyType?: KeyType | undefined;
  612. /**
  613. * This property exists only on asymmetric keys. Depending on the type of the key,
  614. * this object contains information about the key. None of the information obtained
  615. * through this property can be used to uniquely identify a key or to compromise
  616. * the security of the key.
  617. *
  618. * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
  619. * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
  620. * set.
  621. *
  622. * Other key details might be exposed via this API using additional attributes.
  623. * @since v15.7.0
  624. */
  625. asymmetricKeyDetails?: AsymmetricKeyDetails | undefined;
  626. /**
  627. * For symmetric keys, the following encoding options can be used:
  628. *
  629. * For public keys, the following encoding options can be used:
  630. *
  631. * For private keys, the following encoding options can be used:
  632. *
  633. * The result type depends on the selected encoding format, when PEM the
  634. * result is a string, when DER it will be a buffer containing the data
  635. * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
  636. *
  637. * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
  638. * ignored.
  639. *
  640. * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
  641. * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be
  642. * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
  643. * encrypted private keys. Since PKCS#8 defines its own
  644. * encryption mechanism, PEM-level encryption is not supported when encrypting
  645. * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for
  646. * PKCS#1 and SEC1 encryption.
  647. * @since v11.6.0
  648. */
  649. export(options: KeyExportOptions<"pem">): string | Buffer;
  650. export(options?: KeyExportOptions<"der">): Buffer;
  651. export(options?: JwkKeyExportOptions): JsonWebKey;
  652. /**
  653. * Returns `true` or `false` depending on whether the keys have exactly the same
  654. * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack).
  655. * @since v17.7.0, v16.15.0
  656. * @param otherKeyObject A `KeyObject` with which to compare `keyObject`.
  657. */
  658. equals(otherKeyObject: KeyObject): boolean;
  659. /**
  660. * For secret keys, this property represents the size of the key in bytes. This
  661. * property is `undefined` for asymmetric keys.
  662. * @since v11.6.0
  663. */
  664. symmetricKeySize?: number | undefined;
  665. /**
  666. * Converts a `KeyObject` instance to a `CryptoKey`.
  667. * @since 22.10.0
  668. */
  669. toCryptoKey(
  670. algorithm:
  671. | webcrypto.AlgorithmIdentifier
  672. | webcrypto.RsaHashedImportParams
  673. | webcrypto.EcKeyImportParams
  674. | webcrypto.HmacImportParams,
  675. extractable: boolean,
  676. keyUsages: readonly webcrypto.KeyUsage[],
  677. ): webcrypto.CryptoKey;
  678. /**
  679. * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
  680. * or `'private'` for private (asymmetric) keys.
  681. * @since v11.6.0
  682. */
  683. type: KeyObjectType;
  684. }
  685. type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm";
  686. type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
  687. type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb";
  688. type CipherChaCha20Poly1305Types = "chacha20-poly1305";
  689. type BinaryLike = string | NodeJS.ArrayBufferView;
  690. type CipherKey = BinaryLike | KeyObject;
  691. interface CipherCCMOptions extends stream.TransformOptions {
  692. authTagLength: number;
  693. }
  694. interface CipherGCMOptions extends stream.TransformOptions {
  695. authTagLength?: number | undefined;
  696. }
  697. interface CipherOCBOptions extends stream.TransformOptions {
  698. authTagLength: number;
  699. }
  700. interface CipherChaCha20Poly1305Options extends stream.TransformOptions {
  701. /** @default 16 */
  702. authTagLength?: number | undefined;
  703. }
  704. /**
  705. * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
  706. * initialization vector (`iv`).
  707. *
  708. * The `options` argument controls stream behavior and is optional except when a
  709. * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
  710. * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
  711. * tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
  712. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
  713. *
  714. * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
  715. * recent OpenSSL releases, `openssl list -cipher-algorithms` will
  716. * display the available cipher algorithms.
  717. *
  718. * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
  719. * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
  720. * a `KeyObject` of type `secret`. If the cipher does not need
  721. * an initialization vector, `iv` may be `null`.
  722. *
  723. * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  724. *
  725. * Initialization vectors should be unpredictable and unique; ideally, they will be
  726. * cryptographically random. They do not have to be secret: IVs are typically just
  727. * added to ciphertext messages unencrypted. It may sound contradictory that
  728. * something has to be unpredictable and unique, but does not have to be secret;
  729. * remember that an attacker must not be able to predict ahead of time what a
  730. * given IV will be.
  731. * @since v0.1.94
  732. * @param options `stream.transform` options
  733. */
  734. function createCipheriv(
  735. algorithm: CipherCCMTypes,
  736. key: CipherKey,
  737. iv: BinaryLike,
  738. options: CipherCCMOptions,
  739. ): CipherCCM;
  740. function createCipheriv(
  741. algorithm: CipherOCBTypes,
  742. key: CipherKey,
  743. iv: BinaryLike,
  744. options: CipherOCBOptions,
  745. ): CipherOCB;
  746. function createCipheriv(
  747. algorithm: CipherGCMTypes,
  748. key: CipherKey,
  749. iv: BinaryLike,
  750. options?: CipherGCMOptions,
  751. ): CipherGCM;
  752. function createCipheriv(
  753. algorithm: CipherChaCha20Poly1305Types,
  754. key: CipherKey,
  755. iv: BinaryLike,
  756. options?: CipherChaCha20Poly1305Options,
  757. ): CipherChaCha20Poly1305;
  758. function createCipheriv(
  759. algorithm: string,
  760. key: CipherKey,
  761. iv: BinaryLike | null,
  762. options?: stream.TransformOptions,
  763. ): Cipher;
  764. /**
  765. * Instances of the `Cipher` class are used to encrypt data. The class can be
  766. * used in one of two ways:
  767. *
  768. * * As a `stream` that is both readable and writable, where plain unencrypted
  769. * data is written to produce encrypted data on the readable side, or
  770. * * Using the `cipher.update()` and `cipher.final()` methods to produce
  771. * the encrypted data.
  772. *
  773. * The {@link createCipheriv} method is
  774. * used to create `Cipher` instances. `Cipher` objects are not to be created
  775. * directly using the `new` keyword.
  776. *
  777. * Example: Using `Cipher` objects as streams:
  778. *
  779. * ```js
  780. * const {
  781. * scrypt,
  782. * randomFill,
  783. * createCipheriv,
  784. * } = await import('node:crypto');
  785. *
  786. * const algorithm = 'aes-192-cbc';
  787. * const password = 'Password used to generate key';
  788. *
  789. * // First, we'll generate the key. The key length is dependent on the algorithm.
  790. * // In this case for aes192, it is 24 bytes (192 bits).
  791. * scrypt(password, 'salt', 24, (err, key) => {
  792. * if (err) throw err;
  793. * // Then, we'll generate a random initialization vector
  794. * randomFill(new Uint8Array(16), (err, iv) => {
  795. * if (err) throw err;
  796. *
  797. * // Once we have the key and iv, we can create and use the cipher...
  798. * const cipher = createCipheriv(algorithm, key, iv);
  799. *
  800. * let encrypted = '';
  801. * cipher.setEncoding('hex');
  802. *
  803. * cipher.on('data', (chunk) => encrypted += chunk);
  804. * cipher.on('end', () => console.log(encrypted));
  805. *
  806. * cipher.write('some clear text data');
  807. * cipher.end();
  808. * });
  809. * });
  810. * ```
  811. *
  812. * Example: Using `Cipher` and piped streams:
  813. *
  814. * ```js
  815. * import {
  816. * createReadStream,
  817. * createWriteStream,
  818. * } from 'node:fs';
  819. *
  820. * import {
  821. * pipeline,
  822. * } from 'node:stream';
  823. *
  824. * const {
  825. * scrypt,
  826. * randomFill,
  827. * createCipheriv,
  828. * } = await import('node:crypto');
  829. *
  830. * const algorithm = 'aes-192-cbc';
  831. * const password = 'Password used to generate key';
  832. *
  833. * // First, we'll generate the key. The key length is dependent on the algorithm.
  834. * // In this case for aes192, it is 24 bytes (192 bits).
  835. * scrypt(password, 'salt', 24, (err, key) => {
  836. * if (err) throw err;
  837. * // Then, we'll generate a random initialization vector
  838. * randomFill(new Uint8Array(16), (err, iv) => {
  839. * if (err) throw err;
  840. *
  841. * const cipher = createCipheriv(algorithm, key, iv);
  842. *
  843. * const input = createReadStream('test.js');
  844. * const output = createWriteStream('test.enc');
  845. *
  846. * pipeline(input, cipher, output, (err) => {
  847. * if (err) throw err;
  848. * });
  849. * });
  850. * });
  851. * ```
  852. *
  853. * Example: Using the `cipher.update()` and `cipher.final()` methods:
  854. *
  855. * ```js
  856. * const {
  857. * scrypt,
  858. * randomFill,
  859. * createCipheriv,
  860. * } = await import('node:crypto');
  861. *
  862. * const algorithm = 'aes-192-cbc';
  863. * const password = 'Password used to generate key';
  864. *
  865. * // First, we'll generate the key. The key length is dependent on the algorithm.
  866. * // In this case for aes192, it is 24 bytes (192 bits).
  867. * scrypt(password, 'salt', 24, (err, key) => {
  868. * if (err) throw err;
  869. * // Then, we'll generate a random initialization vector
  870. * randomFill(new Uint8Array(16), (err, iv) => {
  871. * if (err) throw err;
  872. *
  873. * const cipher = createCipheriv(algorithm, key, iv);
  874. *
  875. * let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
  876. * encrypted += cipher.final('hex');
  877. * console.log(encrypted);
  878. * });
  879. * });
  880. * ```
  881. * @since v0.1.94
  882. */
  883. class Cipher extends stream.Transform {
  884. private constructor();
  885. /**
  886. * Updates the cipher with `data`. If the `inputEncoding` argument is given,
  887. * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`,
  888. * `TypedArray`, or `DataView`, then `inputEncoding` is ignored.
  889. *
  890. * The `outputEncoding` specifies the output format of the enciphered
  891. * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
  892. *
  893. * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being
  894. * thrown.
  895. * @since v0.1.94
  896. * @param inputEncoding The `encoding` of the data.
  897. * @param outputEncoding The `encoding` of the return value.
  898. */
  899. update(data: BinaryLike): Buffer;
  900. update(data: string, inputEncoding: Encoding): Buffer;
  901. update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
  902. update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
  903. /**
  904. * Once the `cipher.final()` method has been called, the `Cipher` object can no
  905. * longer be used to encrypt data. Attempts to call `cipher.final()` more than
  906. * once will result in an error being thrown.
  907. * @since v0.1.94
  908. * @param outputEncoding The `encoding` of the return value.
  909. * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
  910. */
  911. final(): Buffer;
  912. final(outputEncoding: BufferEncoding): string;
  913. /**
  914. * When using block encryption algorithms, the `Cipher` class will automatically
  915. * add padding to the input data to the appropriate block size. To disable the
  916. * default padding call `cipher.setAutoPadding(false)`.
  917. *
  918. * When `autoPadding` is `false`, the length of the entire input data must be a
  919. * multiple of the cipher's block size or `cipher.final()` will throw an error.
  920. * Disabling automatic padding is useful for non-standard padding, for instance
  921. * using `0x0` instead of PKCS padding.
  922. *
  923. * The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
  924. * @since v0.7.1
  925. * @param [autoPadding=true]
  926. * @return for method chaining.
  927. */
  928. setAutoPadding(autoPadding?: boolean): this;
  929. }
  930. interface CipherCCM extends Cipher {
  931. setAAD(
  932. buffer: NodeJS.ArrayBufferView,
  933. options: {
  934. plaintextLength: number;
  935. },
  936. ): this;
  937. getAuthTag(): Buffer;
  938. }
  939. interface CipherGCM extends Cipher {
  940. setAAD(
  941. buffer: NodeJS.ArrayBufferView,
  942. options?: {
  943. plaintextLength: number;
  944. },
  945. ): this;
  946. getAuthTag(): Buffer;
  947. }
  948. interface CipherOCB extends Cipher {
  949. setAAD(
  950. buffer: NodeJS.ArrayBufferView,
  951. options?: {
  952. plaintextLength: number;
  953. },
  954. ): this;
  955. getAuthTag(): Buffer;
  956. }
  957. interface CipherChaCha20Poly1305 extends Cipher {
  958. setAAD(
  959. buffer: NodeJS.ArrayBufferView,
  960. options: {
  961. plaintextLength: number;
  962. },
  963. ): this;
  964. getAuthTag(): Buffer;
  965. }
  966. /**
  967. * Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`).
  968. *
  969. * The `options` argument controls stream behavior and is optional except when a
  970. * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the
  971. * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags
  972. * to those with the specified length.
  973. * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
  974. *
  975. * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
  976. * recent OpenSSL releases, `openssl list -cipher-algorithms` will
  977. * display the available cipher algorithms.
  978. *
  979. * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
  980. * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
  981. * a `KeyObject` of type `secret`. If the cipher does not need
  982. * an initialization vector, `iv` may be `null`.
  983. *
  984. * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  985. *
  986. * Initialization vectors should be unpredictable and unique; ideally, they will be
  987. * cryptographically random. They do not have to be secret: IVs are typically just
  988. * added to ciphertext messages unencrypted. It may sound contradictory that
  989. * something has to be unpredictable and unique, but does not have to be secret;
  990. * remember that an attacker must not be able to predict ahead of time what a given
  991. * IV will be.
  992. * @since v0.1.94
  993. * @param options `stream.transform` options
  994. */
  995. function createDecipheriv(
  996. algorithm: CipherCCMTypes,
  997. key: CipherKey,
  998. iv: BinaryLike,
  999. options: CipherCCMOptions,
  1000. ): DecipherCCM;
  1001. function createDecipheriv(
  1002. algorithm: CipherOCBTypes,
  1003. key: CipherKey,
  1004. iv: BinaryLike,
  1005. options: CipherOCBOptions,
  1006. ): DecipherOCB;
  1007. function createDecipheriv(
  1008. algorithm: CipherGCMTypes,
  1009. key: CipherKey,
  1010. iv: BinaryLike,
  1011. options?: CipherGCMOptions,
  1012. ): DecipherGCM;
  1013. function createDecipheriv(
  1014. algorithm: CipherChaCha20Poly1305Types,
  1015. key: CipherKey,
  1016. iv: BinaryLike,
  1017. options?: CipherChaCha20Poly1305Options,
  1018. ): DecipherChaCha20Poly1305;
  1019. function createDecipheriv(
  1020. algorithm: string,
  1021. key: CipherKey,
  1022. iv: BinaryLike | null,
  1023. options?: stream.TransformOptions,
  1024. ): Decipher;
  1025. /**
  1026. * Instances of the `Decipher` class are used to decrypt data. The class can be
  1027. * used in one of two ways:
  1028. *
  1029. * * As a `stream` that is both readable and writable, where plain encrypted
  1030. * data is written to produce unencrypted data on the readable side, or
  1031. * * Using the `decipher.update()` and `decipher.final()` methods to
  1032. * produce the unencrypted data.
  1033. *
  1034. * The {@link createDecipheriv} method is
  1035. * used to create `Decipher` instances. `Decipher` objects are not to be created
  1036. * directly using the `new` keyword.
  1037. *
  1038. * Example: Using `Decipher` objects as streams:
  1039. *
  1040. * ```js
  1041. * import { Buffer } from 'node:buffer';
  1042. * const {
  1043. * scryptSync,
  1044. * createDecipheriv,
  1045. * } = await import('node:crypto');
  1046. *
  1047. * const algorithm = 'aes-192-cbc';
  1048. * const password = 'Password used to generate key';
  1049. * // Key length is dependent on the algorithm. In this case for aes192, it is
  1050. * // 24 bytes (192 bits).
  1051. * // Use the async `crypto.scrypt()` instead.
  1052. * const key = scryptSync(password, 'salt', 24);
  1053. * // The IV is usually passed along with the ciphertext.
  1054. * const iv = Buffer.alloc(16, 0); // Initialization vector.
  1055. *
  1056. * const decipher = createDecipheriv(algorithm, key, iv);
  1057. *
  1058. * let decrypted = '';
  1059. * decipher.on('readable', () => {
  1060. * let chunk;
  1061. * while (null !== (chunk = decipher.read())) {
  1062. * decrypted += chunk.toString('utf8');
  1063. * }
  1064. * });
  1065. * decipher.on('end', () => {
  1066. * console.log(decrypted);
  1067. * // Prints: some clear text data
  1068. * });
  1069. *
  1070. * // Encrypted with same algorithm, key and iv.
  1071. * const encrypted =
  1072. * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
  1073. * decipher.write(encrypted, 'hex');
  1074. * decipher.end();
  1075. * ```
  1076. *
  1077. * Example: Using `Decipher` and piped streams:
  1078. *
  1079. * ```js
  1080. * import {
  1081. * createReadStream,
  1082. * createWriteStream,
  1083. * } from 'node:fs';
  1084. * import { Buffer } from 'node:buffer';
  1085. * const {
  1086. * scryptSync,
  1087. * createDecipheriv,
  1088. * } = await import('node:crypto');
  1089. *
  1090. * const algorithm = 'aes-192-cbc';
  1091. * const password = 'Password used to generate key';
  1092. * // Use the async `crypto.scrypt()` instead.
  1093. * const key = scryptSync(password, 'salt', 24);
  1094. * // The IV is usually passed along with the ciphertext.
  1095. * const iv = Buffer.alloc(16, 0); // Initialization vector.
  1096. *
  1097. * const decipher = createDecipheriv(algorithm, key, iv);
  1098. *
  1099. * const input = createReadStream('test.enc');
  1100. * const output = createWriteStream('test.js');
  1101. *
  1102. * input.pipe(decipher).pipe(output);
  1103. * ```
  1104. *
  1105. * Example: Using the `decipher.update()` and `decipher.final()` methods:
  1106. *
  1107. * ```js
  1108. * import { Buffer } from 'node:buffer';
  1109. * const {
  1110. * scryptSync,
  1111. * createDecipheriv,
  1112. * } = await import('node:crypto');
  1113. *
  1114. * const algorithm = 'aes-192-cbc';
  1115. * const password = 'Password used to generate key';
  1116. * // Use the async `crypto.scrypt()` instead.
  1117. * const key = scryptSync(password, 'salt', 24);
  1118. * // The IV is usually passed along with the ciphertext.
  1119. * const iv = Buffer.alloc(16, 0); // Initialization vector.
  1120. *
  1121. * const decipher = createDecipheriv(algorithm, key, iv);
  1122. *
  1123. * // Encrypted using same algorithm, key and iv.
  1124. * const encrypted =
  1125. * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
  1126. * let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  1127. * decrypted += decipher.final('utf8');
  1128. * console.log(decrypted);
  1129. * // Prints: some clear text data
  1130. * ```
  1131. * @since v0.1.94
  1132. */
  1133. class Decipher extends stream.Transform {
  1134. private constructor();
  1135. /**
  1136. * Updates the decipher with `data`. If the `inputEncoding` argument is given,
  1137. * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is
  1138. * ignored.
  1139. *
  1140. * The `outputEncoding` specifies the output format of the enciphered
  1141. * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned.
  1142. *
  1143. * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error
  1144. * being thrown.
  1145. * @since v0.1.94
  1146. * @param inputEncoding The `encoding` of the `data` string.
  1147. * @param outputEncoding The `encoding` of the return value.
  1148. */
  1149. update(data: NodeJS.ArrayBufferView): Buffer;
  1150. update(data: string, inputEncoding: Encoding): Buffer;
  1151. update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
  1152. update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
  1153. /**
  1154. * Once the `decipher.final()` method has been called, the `Decipher` object can
  1155. * no longer be used to decrypt data. Attempts to call `decipher.final()` more
  1156. * than once will result in an error being thrown.
  1157. * @since v0.1.94
  1158. * @param outputEncoding The `encoding` of the return value.
  1159. * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
  1160. */
  1161. final(): Buffer;
  1162. final(outputEncoding: BufferEncoding): string;
  1163. /**
  1164. * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and
  1165. * removing padding.
  1166. *
  1167. * Turning auto padding off will only work if the input data's length is a
  1168. * multiple of the ciphers block size.
  1169. *
  1170. * The `decipher.setAutoPadding()` method must be called before `decipher.final()`.
  1171. * @since v0.7.1
  1172. * @param [autoPadding=true]
  1173. * @return for method chaining.
  1174. */
  1175. setAutoPadding(auto_padding?: boolean): this;
  1176. }
  1177. interface DecipherCCM extends Decipher {
  1178. setAuthTag(buffer: NodeJS.ArrayBufferView): this;
  1179. setAAD(
  1180. buffer: NodeJS.ArrayBufferView,
  1181. options: {
  1182. plaintextLength: number;
  1183. },
  1184. ): this;
  1185. }
  1186. interface DecipherGCM extends Decipher {
  1187. setAuthTag(buffer: NodeJS.ArrayBufferView): this;
  1188. setAAD(
  1189. buffer: NodeJS.ArrayBufferView,
  1190. options?: {
  1191. plaintextLength: number;
  1192. },
  1193. ): this;
  1194. }
  1195. interface DecipherOCB extends Decipher {
  1196. setAuthTag(buffer: NodeJS.ArrayBufferView): this;
  1197. setAAD(
  1198. buffer: NodeJS.ArrayBufferView,
  1199. options?: {
  1200. plaintextLength: number;
  1201. },
  1202. ): this;
  1203. }
  1204. interface DecipherChaCha20Poly1305 extends Decipher {
  1205. setAuthTag(buffer: NodeJS.ArrayBufferView): this;
  1206. setAAD(
  1207. buffer: NodeJS.ArrayBufferView,
  1208. options: {
  1209. plaintextLength: number;
  1210. },
  1211. ): this;
  1212. }
  1213. interface PrivateKeyInput {
  1214. key: string | Buffer;
  1215. format?: KeyFormat | undefined;
  1216. type?: "pkcs1" | "pkcs8" | "sec1" | undefined;
  1217. passphrase?: string | Buffer | undefined;
  1218. encoding?: string | undefined;
  1219. }
  1220. interface PublicKeyInput {
  1221. key: string | Buffer;
  1222. format?: KeyFormat | undefined;
  1223. type?: "pkcs1" | "spki" | undefined;
  1224. encoding?: string | undefined;
  1225. }
  1226. /**
  1227. * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
  1228. *
  1229. * ```js
  1230. * const {
  1231. * generateKey,
  1232. * } = await import('node:crypto');
  1233. *
  1234. * generateKey('hmac', { length: 512 }, (err, key) => {
  1235. * if (err) throw err;
  1236. * console.log(key.export().toString('hex')); // 46e..........620
  1237. * });
  1238. * ```
  1239. *
  1240. * The size of a generated HMAC key should not exceed the block size of the
  1241. * underlying hash function. See {@link createHmac} for more information.
  1242. * @since v15.0.0
  1243. * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
  1244. */
  1245. function generateKey(
  1246. type: "hmac" | "aes",
  1247. options: {
  1248. length: number;
  1249. },
  1250. callback: (err: Error | null, key: KeyObject) => void,
  1251. ): void;
  1252. /**
  1253. * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
  1254. *
  1255. * ```js
  1256. * const {
  1257. * generateKeySync,
  1258. * } = await import('node:crypto');
  1259. *
  1260. * const key = generateKeySync('hmac', { length: 512 });
  1261. * console.log(key.export().toString('hex')); // e89..........41e
  1262. * ```
  1263. *
  1264. * The size of a generated HMAC key should not exceed the block size of the
  1265. * underlying hash function. See {@link createHmac} for more information.
  1266. * @since v15.0.0
  1267. * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
  1268. */
  1269. function generateKeySync(
  1270. type: "hmac" | "aes",
  1271. options: {
  1272. length: number;
  1273. },
  1274. ): KeyObject;
  1275. interface JsonWebKeyInput {
  1276. key: JsonWebKey;
  1277. format: "jwk";
  1278. }
  1279. /**
  1280. * Creates and returns a new key object containing a private key. If `key` is a
  1281. * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above.
  1282. *
  1283. * If the private key is encrypted, a `passphrase` must be specified. The length
  1284. * of the passphrase is limited to 1024 bytes.
  1285. * @since v11.6.0
  1286. */
  1287. function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject;
  1288. /**
  1289. * Creates and returns a new key object containing a public key. If `key` is a
  1290. * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key;
  1291. * otherwise, `key` must be an object with the properties described above.
  1292. *
  1293. * If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
  1294. *
  1295. * Because public keys can be derived from private keys, a private key may be
  1296. * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the
  1297. * returned `KeyObject` will be `'public'` and that the private key cannot be
  1298. * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned
  1299. * and it will be impossible to extract the private key from the returned object.
  1300. * @since v11.6.0
  1301. */
  1302. function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject;
  1303. /**
  1304. * Creates and returns a new key object containing a secret key for symmetric
  1305. * encryption or `Hmac`.
  1306. * @since v11.6.0
  1307. * @param encoding The string encoding when `key` is a string.
  1308. */
  1309. function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject;
  1310. function createSecretKey(key: string, encoding: BufferEncoding): KeyObject;
  1311. /**
  1312. * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms.
  1313. * Optional `options` argument controls the `stream.Writable` behavior.
  1314. *
  1315. * In some cases, a `Sign` instance can be created using the name of a signature
  1316. * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
  1317. * the corresponding digest algorithm. This does not work for all signature
  1318. * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
  1319. * algorithm names.
  1320. * @since v0.1.92
  1321. * @param options `stream.Writable` options
  1322. */
  1323. function createSign(algorithm: string, options?: stream.WritableOptions): Sign;
  1324. type DSAEncoding = "der" | "ieee-p1363";
  1325. interface SigningOptions {
  1326. /**
  1327. * @see crypto.constants.RSA_PKCS1_PADDING
  1328. */
  1329. padding?: number | undefined;
  1330. saltLength?: number | undefined;
  1331. dsaEncoding?: DSAEncoding | undefined;
  1332. }
  1333. interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {}
  1334. interface SignKeyObjectInput extends SigningOptions {
  1335. key: KeyObject;
  1336. }
  1337. interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {}
  1338. interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {}
  1339. interface VerifyKeyObjectInput extends SigningOptions {
  1340. key: KeyObject;
  1341. }
  1342. interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {}
  1343. type KeyLike = string | Buffer | KeyObject;
  1344. /**
  1345. * The `Sign` class is a utility for generating signatures. It can be used in one
  1346. * of two ways:
  1347. *
  1348. * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or
  1349. * * Using the `sign.update()` and `sign.sign()` methods to produce the
  1350. * signature.
  1351. *
  1352. * The {@link createSign} method is used to create `Sign` instances. The
  1353. * argument is the string name of the hash function to use. `Sign` objects are not
  1354. * to be created directly using the `new` keyword.
  1355. *
  1356. * Example: Using `Sign` and `Verify` objects as streams:
  1357. *
  1358. * ```js
  1359. * const {
  1360. * generateKeyPairSync,
  1361. * createSign,
  1362. * createVerify,
  1363. * } = await import('node:crypto');
  1364. *
  1365. * const { privateKey, publicKey } = generateKeyPairSync('ec', {
  1366. * namedCurve: 'sect239k1',
  1367. * });
  1368. *
  1369. * const sign = createSign('SHA256');
  1370. * sign.write('some data to sign');
  1371. * sign.end();
  1372. * const signature = sign.sign(privateKey, 'hex');
  1373. *
  1374. * const verify = createVerify('SHA256');
  1375. * verify.write('some data to sign');
  1376. * verify.end();
  1377. * console.log(verify.verify(publicKey, signature, 'hex'));
  1378. * // Prints: true
  1379. * ```
  1380. *
  1381. * Example: Using the `sign.update()` and `verify.update()` methods:
  1382. *
  1383. * ```js
  1384. * const {
  1385. * generateKeyPairSync,
  1386. * createSign,
  1387. * createVerify,
  1388. * } = await import('node:crypto');
  1389. *
  1390. * const { privateKey, publicKey } = generateKeyPairSync('rsa', {
  1391. * modulusLength: 2048,
  1392. * });
  1393. *
  1394. * const sign = createSign('SHA256');
  1395. * sign.update('some data to sign');
  1396. * sign.end();
  1397. * const signature = sign.sign(privateKey);
  1398. *
  1399. * const verify = createVerify('SHA256');
  1400. * verify.update('some data to sign');
  1401. * verify.end();
  1402. * console.log(verify.verify(publicKey, signature));
  1403. * // Prints: true
  1404. * ```
  1405. * @since v0.1.92
  1406. */
  1407. class Sign extends stream.Writable {
  1408. private constructor();
  1409. /**
  1410. * Updates the `Sign` content with the given `data`, the encoding of which
  1411. * is given in `inputEncoding`.
  1412. * If `encoding` is not provided, and the `data` is a string, an
  1413. * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
  1414. *
  1415. * This can be called many times with new data as it is streamed.
  1416. * @since v0.1.92
  1417. * @param inputEncoding The `encoding` of the `data` string.
  1418. */
  1419. update(data: BinaryLike): this;
  1420. update(data: string, inputEncoding: Encoding): this;
  1421. /**
  1422. * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`.
  1423. *
  1424. * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an
  1425. * object, the following additional properties can be passed:
  1426. *
  1427. * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned.
  1428. *
  1429. * The `Sign` object can not be again used after `sign.sign()` method has been
  1430. * called. Multiple calls to `sign.sign()` will result in an error being thrown.
  1431. * @since v0.1.92
  1432. */
  1433. sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer;
  1434. sign(
  1435. privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput,
  1436. outputFormat: BinaryToTextEncoding,
  1437. ): string;
  1438. }
  1439. /**
  1440. * Creates and returns a `Verify` object that uses the given algorithm.
  1441. * Use {@link getHashes} to obtain an array of names of the available
  1442. * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior.
  1443. *
  1444. * In some cases, a `Verify` instance can be created using the name of a signature
  1445. * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
  1446. * the corresponding digest algorithm. This does not work for all signature
  1447. * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
  1448. * algorithm names.
  1449. * @since v0.1.92
  1450. * @param options `stream.Writable` options
  1451. */
  1452. function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
  1453. /**
  1454. * The `Verify` class is a utility for verifying signatures. It can be used in one
  1455. * of two ways:
  1456. *
  1457. * * As a writable `stream` where written data is used to validate against the
  1458. * supplied signature, or
  1459. * * Using the `verify.update()` and `verify.verify()` methods to verify
  1460. * the signature.
  1461. *
  1462. * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword.
  1463. *
  1464. * See `Sign` for examples.
  1465. * @since v0.1.92
  1466. */
  1467. class Verify extends stream.Writable {
  1468. private constructor();
  1469. /**
  1470. * Updates the `Verify` content with the given `data`, the encoding of which
  1471. * is given in `inputEncoding`.
  1472. * If `inputEncoding` is not provided, and the `data` is a string, an
  1473. * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored.
  1474. *
  1475. * This can be called many times with new data as it is streamed.
  1476. * @since v0.1.92
  1477. * @param inputEncoding The `encoding` of the `data` string.
  1478. */
  1479. update(data: BinaryLike): Verify;
  1480. update(data: string, inputEncoding: Encoding): Verify;
  1481. /**
  1482. * Verifies the provided data using the given `object` and `signature`.
  1483. *
  1484. * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an
  1485. * object, the following additional properties can be passed:
  1486. *
  1487. * The `signature` argument is the previously calculated signature for the data, in
  1488. * the `signatureEncoding`.
  1489. * If a `signatureEncoding` is specified, the `signature` is expected to be a
  1490. * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`.
  1491. *
  1492. * The `verify` object can not be used again after `verify.verify()` has been
  1493. * called. Multiple calls to `verify.verify()` will result in an error being
  1494. * thrown.
  1495. *
  1496. * Because public keys can be derived from private keys, a private key may
  1497. * be passed instead of a public key.
  1498. * @since v0.1.92
  1499. */
  1500. verify(
  1501. object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
  1502. signature: NodeJS.ArrayBufferView,
  1503. ): boolean;
  1504. verify(
  1505. object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
  1506. signature: string,
  1507. signature_format?: BinaryToTextEncoding,
  1508. ): boolean;
  1509. }
  1510. /**
  1511. * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
  1512. * optional specific `generator`.
  1513. *
  1514. * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used.
  1515. *
  1516. * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
  1517. * a `Buffer`, `TypedArray`, or `DataView` is expected.
  1518. *
  1519. * If `generatorEncoding` is specified, `generator` is expected to be a string;
  1520. * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected.
  1521. * @since v0.11.12
  1522. * @param primeEncoding The `encoding` of the `prime` string.
  1523. * @param [generator=2]
  1524. * @param generatorEncoding The `encoding` of the `generator` string.
  1525. */
  1526. function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman;
  1527. function createDiffieHellman(
  1528. prime: ArrayBuffer | NodeJS.ArrayBufferView,
  1529. generator?: number | ArrayBuffer | NodeJS.ArrayBufferView,
  1530. ): DiffieHellman;
  1531. function createDiffieHellman(
  1532. prime: ArrayBuffer | NodeJS.ArrayBufferView,
  1533. generator: string,
  1534. generatorEncoding: BinaryToTextEncoding,
  1535. ): DiffieHellman;
  1536. function createDiffieHellman(
  1537. prime: string,
  1538. primeEncoding: BinaryToTextEncoding,
  1539. generator?: number | ArrayBuffer | NodeJS.ArrayBufferView,
  1540. ): DiffieHellman;
  1541. function createDiffieHellman(
  1542. prime: string,
  1543. primeEncoding: BinaryToTextEncoding,
  1544. generator: string,
  1545. generatorEncoding: BinaryToTextEncoding,
  1546. ): DiffieHellman;
  1547. /**
  1548. * The `DiffieHellman` class is a utility for creating Diffie-Hellman key
  1549. * exchanges.
  1550. *
  1551. * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function.
  1552. *
  1553. * ```js
  1554. * import assert from 'node:assert';
  1555. *
  1556. * const {
  1557. * createDiffieHellman,
  1558. * } = await import('node:crypto');
  1559. *
  1560. * // Generate Alice's keys...
  1561. * const alice = createDiffieHellman(2048);
  1562. * const aliceKey = alice.generateKeys();
  1563. *
  1564. * // Generate Bob's keys...
  1565. * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
  1566. * const bobKey = bob.generateKeys();
  1567. *
  1568. * // Exchange and generate the secret...
  1569. * const aliceSecret = alice.computeSecret(bobKey);
  1570. * const bobSecret = bob.computeSecret(aliceKey);
  1571. *
  1572. * // OK
  1573. * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
  1574. * ```
  1575. * @since v0.5.0
  1576. */
  1577. class DiffieHellman {
  1578. private constructor();
  1579. /**
  1580. * Generates private and public Diffie-Hellman key values unless they have been
  1581. * generated or computed already, and returns
  1582. * the public key in the specified `encoding`. This key should be
  1583. * transferred to the other party.
  1584. * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
  1585. *
  1586. * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular,
  1587. * once a private key has been generated or set, calling this function only updates
  1588. * the public key but does not generate a new private key.
  1589. * @since v0.5.0
  1590. * @param encoding The `encoding` of the return value.
  1591. */
  1592. generateKeys(): Buffer;
  1593. generateKeys(encoding: BinaryToTextEncoding): string;
  1594. /**
  1595. * Computes the shared secret using `otherPublicKey` as the other
  1596. * party's public key and returns the computed shared secret. The supplied
  1597. * key is interpreted using the specified `inputEncoding`, and secret is
  1598. * encoded using specified `outputEncoding`.
  1599. * If the `inputEncoding` is not
  1600. * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`.
  1601. *
  1602. * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned.
  1603. * @since v0.5.0
  1604. * @param inputEncoding The `encoding` of an `otherPublicKey` string.
  1605. * @param outputEncoding The `encoding` of the return value.
  1606. */
  1607. computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer;
  1608. computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer;
  1609. computeSecret(
  1610. otherPublicKey: NodeJS.ArrayBufferView,
  1611. inputEncoding: null,
  1612. outputEncoding: BinaryToTextEncoding,
  1613. ): string;
  1614. computeSecret(
  1615. otherPublicKey: string,
  1616. inputEncoding: BinaryToTextEncoding,
  1617. outputEncoding: BinaryToTextEncoding,
  1618. ): string;
  1619. /**
  1620. * Returns the Diffie-Hellman prime in the specified `encoding`.
  1621. * If `encoding` is provided a string is
  1622. * returned; otherwise a `Buffer` is returned.
  1623. * @since v0.5.0
  1624. * @param encoding The `encoding` of the return value.
  1625. */
  1626. getPrime(): Buffer;
  1627. getPrime(encoding: BinaryToTextEncoding): string;
  1628. /**
  1629. * Returns the Diffie-Hellman generator in the specified `encoding`.
  1630. * If `encoding` is provided a string is
  1631. * returned; otherwise a `Buffer` is returned.
  1632. * @since v0.5.0
  1633. * @param encoding The `encoding` of the return value.
  1634. */
  1635. getGenerator(): Buffer;
  1636. getGenerator(encoding: BinaryToTextEncoding): string;
  1637. /**
  1638. * Returns the Diffie-Hellman public key in the specified `encoding`.
  1639. * If `encoding` is provided a
  1640. * string is returned; otherwise a `Buffer` is returned.
  1641. * @since v0.5.0
  1642. * @param encoding The `encoding` of the return value.
  1643. */
  1644. getPublicKey(): Buffer;
  1645. getPublicKey(encoding: BinaryToTextEncoding): string;
  1646. /**
  1647. * Returns the Diffie-Hellman private key in the specified `encoding`.
  1648. * If `encoding` is provided a
  1649. * string is returned; otherwise a `Buffer` is returned.
  1650. * @since v0.5.0
  1651. * @param encoding The `encoding` of the return value.
  1652. */
  1653. getPrivateKey(): Buffer;
  1654. getPrivateKey(encoding: BinaryToTextEncoding): string;
  1655. /**
  1656. * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected
  1657. * to be a string. If no `encoding` is provided, `publicKey` is expected
  1658. * to be a `Buffer`, `TypedArray`, or `DataView`.
  1659. * @since v0.5.0
  1660. * @param encoding The `encoding` of the `publicKey` string.
  1661. */
  1662. setPublicKey(publicKey: NodeJS.ArrayBufferView): void;
  1663. setPublicKey(publicKey: string, encoding: BufferEncoding): void;
  1664. /**
  1665. * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected
  1666. * to be a string. If no `encoding` is provided, `privateKey` is expected
  1667. * to be a `Buffer`, `TypedArray`, or `DataView`.
  1668. *
  1669. * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be
  1670. * used to manually provide the public key or to automatically derive it.
  1671. * @since v0.5.0
  1672. * @param encoding The `encoding` of the `privateKey` string.
  1673. */
  1674. setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
  1675. setPrivateKey(privateKey: string, encoding: BufferEncoding): void;
  1676. /**
  1677. * A bit field containing any warnings and/or errors resulting from a check
  1678. * performed during initialization of the `DiffieHellman` object.
  1679. *
  1680. * The following values are valid for this property (as defined in `node:constants` module):
  1681. *
  1682. * * `DH_CHECK_P_NOT_SAFE_PRIME`
  1683. * * `DH_CHECK_P_NOT_PRIME`
  1684. * * `DH_UNABLE_TO_CHECK_GENERATOR`
  1685. * * `DH_NOT_SUITABLE_GENERATOR`
  1686. * @since v0.11.12
  1687. */
  1688. verifyError: number;
  1689. }
  1690. /**
  1691. * The `DiffieHellmanGroup` class takes a well-known modp group as its argument.
  1692. * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation.
  1693. * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods.
  1694. *
  1695. * ```js
  1696. * const { createDiffieHellmanGroup } = await import('node:crypto');
  1697. * const dh = createDiffieHellmanGroup('modp1');
  1698. * ```
  1699. * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt):
  1700. * ```bash
  1701. * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
  1702. * modp1 # 768 bits
  1703. * modp2 # 1024 bits
  1704. * modp5 # 1536 bits
  1705. * modp14 # 2048 bits
  1706. * modp15 # etc.
  1707. * modp16
  1708. * modp17
  1709. * modp18
  1710. * ```
  1711. * @since v0.7.5
  1712. */
  1713. const DiffieHellmanGroup: DiffieHellmanGroupConstructor;
  1714. interface DiffieHellmanGroupConstructor {
  1715. new(name: string): DiffieHellmanGroup;
  1716. (name: string): DiffieHellmanGroup;
  1717. readonly prototype: DiffieHellmanGroup;
  1718. }
  1719. type DiffieHellmanGroup = Omit<DiffieHellman, "setPublicKey" | "setPrivateKey">;
  1720. /**
  1721. * Creates a predefined `DiffieHellmanGroup` key exchange object. The
  1722. * supported groups are listed in the documentation for `DiffieHellmanGroup`.
  1723. *
  1724. * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing
  1725. * the keys (with `diffieHellman.setPublicKey()`, for example). The
  1726. * advantage of using this method is that the parties do not have to
  1727. * generate nor exchange a group modulus beforehand, saving both processor
  1728. * and communication time.
  1729. *
  1730. * Example (obtaining a shared secret):
  1731. *
  1732. * ```js
  1733. * const {
  1734. * getDiffieHellman,
  1735. * } = await import('node:crypto');
  1736. * const alice = getDiffieHellman('modp14');
  1737. * const bob = getDiffieHellman('modp14');
  1738. *
  1739. * alice.generateKeys();
  1740. * bob.generateKeys();
  1741. *
  1742. * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
  1743. * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
  1744. *
  1745. * // aliceSecret and bobSecret should be the same
  1746. * console.log(aliceSecret === bobSecret);
  1747. * ```
  1748. * @since v0.7.5
  1749. */
  1750. function getDiffieHellman(groupName: string): DiffieHellmanGroup;
  1751. /**
  1752. * An alias for {@link getDiffieHellman}
  1753. * @since v0.9.3
  1754. */
  1755. function createDiffieHellmanGroup(name: string): DiffieHellmanGroup;
  1756. /**
  1757. * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
  1758. * implementation. A selected HMAC digest algorithm specified by `digest` is
  1759. * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`.
  1760. *
  1761. * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set;
  1762. * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be
  1763. * thrown if any of the input arguments specify invalid values or types.
  1764. *
  1765. * The `iterations` argument must be a number set as high as possible. The
  1766. * higher the number of iterations, the more secure the derived key will be,
  1767. * but will take a longer amount of time to complete.
  1768. *
  1769. * The `salt` should be as unique as possible. It is recommended that a salt is
  1770. * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
  1771. *
  1772. * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  1773. *
  1774. * ```js
  1775. * const {
  1776. * pbkdf2,
  1777. * } = await import('node:crypto');
  1778. *
  1779. * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  1780. * if (err) throw err;
  1781. * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
  1782. * });
  1783. * ```
  1784. *
  1785. * An array of supported digest functions can be retrieved using {@link getHashes}.
  1786. *
  1787. * This API uses libuv's threadpool, which can have surprising and
  1788. * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
  1789. * @since v0.5.5
  1790. */
  1791. function pbkdf2(
  1792. password: BinaryLike,
  1793. salt: BinaryLike,
  1794. iterations: number,
  1795. keylen: number,
  1796. digest: string,
  1797. callback: (err: Error | null, derivedKey: Buffer) => void,
  1798. ): void;
  1799. /**
  1800. * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
  1801. * implementation. A selected HMAC digest algorithm specified by `digest` is
  1802. * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`.
  1803. *
  1804. * If an error occurs an `Error` will be thrown, otherwise the derived key will be
  1805. * returned as a `Buffer`.
  1806. *
  1807. * The `iterations` argument must be a number set as high as possible. The
  1808. * higher the number of iterations, the more secure the derived key will be,
  1809. * but will take a longer amount of time to complete.
  1810. *
  1811. * The `salt` should be as unique as possible. It is recommended that a salt is
  1812. * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
  1813. *
  1814. * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  1815. *
  1816. * ```js
  1817. * const {
  1818. * pbkdf2Sync,
  1819. * } = await import('node:crypto');
  1820. *
  1821. * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
  1822. * console.log(key.toString('hex')); // '3745e48...08d59ae'
  1823. * ```
  1824. *
  1825. * An array of supported digest functions can be retrieved using {@link getHashes}.
  1826. * @since v0.9.3
  1827. */
  1828. function pbkdf2Sync(
  1829. password: BinaryLike,
  1830. salt: BinaryLike,
  1831. iterations: number,
  1832. keylen: number,
  1833. digest: string,
  1834. ): Buffer;
  1835. /**
  1836. * Generates cryptographically strong pseudorandom data. The `size` argument
  1837. * is a number indicating the number of bytes to generate.
  1838. *
  1839. * If a `callback` function is provided, the bytes are generated asynchronously
  1840. * and the `callback` function is invoked with two arguments: `err` and `buf`.
  1841. * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes.
  1842. *
  1843. * ```js
  1844. * // Asynchronous
  1845. * const {
  1846. * randomBytes,
  1847. * } = await import('node:crypto');
  1848. *
  1849. * randomBytes(256, (err, buf) => {
  1850. * if (err) throw err;
  1851. * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
  1852. * });
  1853. * ```
  1854. *
  1855. * If the `callback` function is not provided, the random bytes are generated
  1856. * synchronously and returned as a `Buffer`. An error will be thrown if
  1857. * there is a problem generating the bytes.
  1858. *
  1859. * ```js
  1860. * // Synchronous
  1861. * const {
  1862. * randomBytes,
  1863. * } = await import('node:crypto');
  1864. *
  1865. * const buf = randomBytes(256);
  1866. * console.log(
  1867. * `${buf.length} bytes of random data: ${buf.toString('hex')}`);
  1868. * ```
  1869. *
  1870. * The `crypto.randomBytes()` method will not complete until there is
  1871. * sufficient entropy available.
  1872. * This should normally never take longer than a few milliseconds. The only time
  1873. * when generating the random bytes may conceivably block for a longer period of
  1874. * time is right after boot, when the whole system is still low on entropy.
  1875. *
  1876. * This API uses libuv's threadpool, which can have surprising and
  1877. * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
  1878. *
  1879. * The asynchronous version of `crypto.randomBytes()` is carried out in a single
  1880. * threadpool request. To minimize threadpool task length variation, partition
  1881. * large `randomBytes` requests when doing so as part of fulfilling a client
  1882. * request.
  1883. * @since v0.5.8
  1884. * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.
  1885. * @return if the `callback` function is not provided.
  1886. */
  1887. function randomBytes(size: number): Buffer;
  1888. function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
  1889. function pseudoRandomBytes(size: number): Buffer;
  1890. function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
  1891. /**
  1892. * Return a random integer `n` such that `min <= n < max`. This
  1893. * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias).
  1894. *
  1895. * The range (`max - min`) must be less than 2**48. `min` and `max` must
  1896. * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
  1897. *
  1898. * If the `callback` function is not provided, the random integer is
  1899. * generated synchronously.
  1900. *
  1901. * ```js
  1902. * // Asynchronous
  1903. * const {
  1904. * randomInt,
  1905. * } = await import('node:crypto');
  1906. *
  1907. * randomInt(3, (err, n) => {
  1908. * if (err) throw err;
  1909. * console.log(`Random number chosen from (0, 1, 2): ${n}`);
  1910. * });
  1911. * ```
  1912. *
  1913. * ```js
  1914. * // Synchronous
  1915. * const {
  1916. * randomInt,
  1917. * } = await import('node:crypto');
  1918. *
  1919. * const n = randomInt(3);
  1920. * console.log(`Random number chosen from (0, 1, 2): ${n}`);
  1921. * ```
  1922. *
  1923. * ```js
  1924. * // With `min` argument
  1925. * const {
  1926. * randomInt,
  1927. * } = await import('node:crypto');
  1928. *
  1929. * const n = randomInt(1, 7);
  1930. * console.log(`The dice rolled: ${n}`);
  1931. * ```
  1932. * @since v14.10.0, v12.19.0
  1933. * @param [min=0] Start of random range (inclusive).
  1934. * @param max End of random range (exclusive).
  1935. * @param callback `function(err, n) {}`.
  1936. */
  1937. function randomInt(max: number): number;
  1938. function randomInt(min: number, max: number): number;
  1939. function randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
  1940. function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
  1941. /**
  1942. * Synchronous version of {@link randomFill}.
  1943. *
  1944. * ```js
  1945. * import { Buffer } from 'node:buffer';
  1946. * const { randomFillSync } = await import('node:crypto');
  1947. *
  1948. * const buf = Buffer.alloc(10);
  1949. * console.log(randomFillSync(buf).toString('hex'));
  1950. *
  1951. * randomFillSync(buf, 5);
  1952. * console.log(buf.toString('hex'));
  1953. *
  1954. * // The above is equivalent to the following:
  1955. * randomFillSync(buf, 5, 5);
  1956. * console.log(buf.toString('hex'));
  1957. * ```
  1958. *
  1959. * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`.
  1960. *
  1961. * ```js
  1962. * import { Buffer } from 'node:buffer';
  1963. * const { randomFillSync } = await import('node:crypto');
  1964. *
  1965. * const a = new Uint32Array(10);
  1966. * console.log(Buffer.from(randomFillSync(a).buffer,
  1967. * a.byteOffset, a.byteLength).toString('hex'));
  1968. *
  1969. * const b = new DataView(new ArrayBuffer(10));
  1970. * console.log(Buffer.from(randomFillSync(b).buffer,
  1971. * b.byteOffset, b.byteLength).toString('hex'));
  1972. *
  1973. * const c = new ArrayBuffer(10);
  1974. * console.log(Buffer.from(randomFillSync(c)).toString('hex'));
  1975. * ```
  1976. * @since v7.10.0, v6.13.0
  1977. * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
  1978. * @param [offset=0]
  1979. * @param [size=buffer.length - offset]
  1980. * @return The object passed as `buffer` argument.
  1981. */
  1982. function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
  1983. /**
  1984. * This function is similar to {@link randomBytes} but requires the first
  1985. * argument to be a `Buffer` that will be filled. It also
  1986. * requires that a callback is passed in.
  1987. *
  1988. * If the `callback` function is not provided, an error will be thrown.
  1989. *
  1990. * ```js
  1991. * import { Buffer } from 'node:buffer';
  1992. * const { randomFill } = await import('node:crypto');
  1993. *
  1994. * const buf = Buffer.alloc(10);
  1995. * randomFill(buf, (err, buf) => {
  1996. * if (err) throw err;
  1997. * console.log(buf.toString('hex'));
  1998. * });
  1999. *
  2000. * randomFill(buf, 5, (err, buf) => {
  2001. * if (err) throw err;
  2002. * console.log(buf.toString('hex'));
  2003. * });
  2004. *
  2005. * // The above is equivalent to the following:
  2006. * randomFill(buf, 5, 5, (err, buf) => {
  2007. * if (err) throw err;
  2008. * console.log(buf.toString('hex'));
  2009. * });
  2010. * ```
  2011. *
  2012. * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`.
  2013. *
  2014. * While this includes instances of `Float32Array` and `Float64Array`, this
  2015. * function should not be used to generate random floating-point numbers. The
  2016. * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
  2017. * contains finite numbers only, they are not drawn from a uniform random
  2018. * distribution and have no meaningful lower or upper bounds.
  2019. *
  2020. * ```js
  2021. * import { Buffer } from 'node:buffer';
  2022. * const { randomFill } = await import('node:crypto');
  2023. *
  2024. * const a = new Uint32Array(10);
  2025. * randomFill(a, (err, buf) => {
  2026. * if (err) throw err;
  2027. * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
  2028. * .toString('hex'));
  2029. * });
  2030. *
  2031. * const b = new DataView(new ArrayBuffer(10));
  2032. * randomFill(b, (err, buf) => {
  2033. * if (err) throw err;
  2034. * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
  2035. * .toString('hex'));
  2036. * });
  2037. *
  2038. * const c = new ArrayBuffer(10);
  2039. * randomFill(c, (err, buf) => {
  2040. * if (err) throw err;
  2041. * console.log(Buffer.from(buf).toString('hex'));
  2042. * });
  2043. * ```
  2044. *
  2045. * This API uses libuv's threadpool, which can have surprising and
  2046. * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
  2047. *
  2048. * The asynchronous version of `crypto.randomFill()` is carried out in a single
  2049. * threadpool request. To minimize threadpool task length variation, partition
  2050. * large `randomFill` requests when doing so as part of fulfilling a client
  2051. * request.
  2052. * @since v7.10.0, v6.13.0
  2053. * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
  2054. * @param [offset=0]
  2055. * @param [size=buffer.length - offset]
  2056. * @param callback `function(err, buf) {}`.
  2057. */
  2058. function randomFill<T extends NodeJS.ArrayBufferView>(
  2059. buffer: T,
  2060. callback: (err: Error | null, buf: T) => void,
  2061. ): void;
  2062. function randomFill<T extends NodeJS.ArrayBufferView>(
  2063. buffer: T,
  2064. offset: number,
  2065. callback: (err: Error | null, buf: T) => void,
  2066. ): void;
  2067. function randomFill<T extends NodeJS.ArrayBufferView>(
  2068. buffer: T,
  2069. offset: number,
  2070. size: number,
  2071. callback: (err: Error | null, buf: T) => void,
  2072. ): void;
  2073. interface ScryptOptions {
  2074. cost?: number | undefined;
  2075. blockSize?: number | undefined;
  2076. parallelization?: number | undefined;
  2077. N?: number | undefined;
  2078. r?: number | undefined;
  2079. p?: number | undefined;
  2080. maxmem?: number | undefined;
  2081. }
  2082. /**
  2083. * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
  2084. * key derivation function that is designed to be expensive computationally and
  2085. * memory-wise in order to make brute-force attacks unrewarding.
  2086. *
  2087. * The `salt` should be as unique as possible. It is recommended that a salt is
  2088. * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
  2089. *
  2090. * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  2091. *
  2092. * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the
  2093. * callback as a `Buffer`.
  2094. *
  2095. * An exception is thrown when any of the input arguments specify invalid values
  2096. * or types.
  2097. *
  2098. * ```js
  2099. * const {
  2100. * scrypt,
  2101. * } = await import('node:crypto');
  2102. *
  2103. * // Using the factory defaults.
  2104. * scrypt('password', 'salt', 64, (err, derivedKey) => {
  2105. * if (err) throw err;
  2106. * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
  2107. * });
  2108. * // Using a custom N parameter. Must be a power of two.
  2109. * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
  2110. * if (err) throw err;
  2111. * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
  2112. * });
  2113. * ```
  2114. * @since v10.5.0
  2115. */
  2116. function scrypt(
  2117. password: BinaryLike,
  2118. salt: BinaryLike,
  2119. keylen: number,
  2120. callback: (err: Error | null, derivedKey: Buffer) => void,
  2121. ): void;
  2122. function scrypt(
  2123. password: BinaryLike,
  2124. salt: BinaryLike,
  2125. keylen: number,
  2126. options: ScryptOptions,
  2127. callback: (err: Error | null, derivedKey: Buffer) => void,
  2128. ): void;
  2129. /**
  2130. * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
  2131. * key derivation function that is designed to be expensive computationally and
  2132. * memory-wise in order to make brute-force attacks unrewarding.
  2133. *
  2134. * The `salt` should be as unique as possible. It is recommended that a salt is
  2135. * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
  2136. *
  2137. * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
  2138. *
  2139. * An exception is thrown when key derivation fails, otherwise the derived key is
  2140. * returned as a `Buffer`.
  2141. *
  2142. * An exception is thrown when any of the input arguments specify invalid values
  2143. * or types.
  2144. *
  2145. * ```js
  2146. * const {
  2147. * scryptSync,
  2148. * } = await import('node:crypto');
  2149. * // Using the factory defaults.
  2150. *
  2151. * const key1 = scryptSync('password', 'salt', 64);
  2152. * console.log(key1.toString('hex')); // '3745e48...08d59ae'
  2153. * // Using a custom N parameter. Must be a power of two.
  2154. * const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
  2155. * console.log(key2.toString('hex')); // '3745e48...aa39b34'
  2156. * ```
  2157. * @since v10.5.0
  2158. */
  2159. function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
  2160. interface RsaPublicKey {
  2161. key: KeyLike;
  2162. padding?: number | undefined;
  2163. }
  2164. interface RsaPrivateKey {
  2165. key: KeyLike;
  2166. passphrase?: string | undefined;
  2167. /**
  2168. * @default 'sha1'
  2169. */
  2170. oaepHash?: string | undefined;
  2171. oaepLabel?: NodeJS.TypedArray | undefined;
  2172. padding?: number | undefined;
  2173. }
  2174. /**
  2175. * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using
  2176. * the corresponding private key, for example using {@link privateDecrypt}.
  2177. *
  2178. * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an
  2179. * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`.
  2180. *
  2181. * Because RSA public keys can be derived from private keys, a private key may
  2182. * be passed instead of a public key.
  2183. * @since v0.11.14
  2184. */
  2185. function publicEncrypt(
  2186. key: RsaPublicKey | RsaPrivateKey | KeyLike,
  2187. buffer: NodeJS.ArrayBufferView | string,
  2188. ): Buffer;
  2189. /**
  2190. * Decrypts `buffer` with `key`.`buffer` was previously encrypted using
  2191. * the corresponding private key, for example using {@link privateEncrypt}.
  2192. *
  2193. * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an
  2194. * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`.
  2195. *
  2196. * Because RSA public keys can be derived from private keys, a private key may
  2197. * be passed instead of a public key.
  2198. * @since v1.1.0
  2199. */
  2200. function publicDecrypt(
  2201. key: RsaPublicKey | RsaPrivateKey | KeyLike,
  2202. buffer: NodeJS.ArrayBufferView | string,
  2203. ): Buffer;
  2204. /**
  2205. * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
  2206. * the corresponding public key, for example using {@link publicEncrypt}.
  2207. *
  2208. * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an
  2209. * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`.
  2210. * @since v0.11.14
  2211. */
  2212. function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer;
  2213. /**
  2214. * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
  2215. * the corresponding public key, for example using {@link publicDecrypt}.
  2216. *
  2217. * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an
  2218. * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`.
  2219. * @since v1.1.0
  2220. */
  2221. function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer;
  2222. /**
  2223. * ```js
  2224. * const {
  2225. * getCiphers,
  2226. * } = await import('node:crypto');
  2227. *
  2228. * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
  2229. * ```
  2230. * @since v0.9.3
  2231. * @return An array with the names of the supported cipher algorithms.
  2232. */
  2233. function getCiphers(): string[];
  2234. /**
  2235. * ```js
  2236. * const {
  2237. * getCurves,
  2238. * } = await import('node:crypto');
  2239. *
  2240. * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
  2241. * ```
  2242. * @since v2.3.0
  2243. * @return An array with the names of the supported elliptic curves.
  2244. */
  2245. function getCurves(): string[];
  2246. /**
  2247. * @since v10.0.0
  2248. * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.
  2249. */
  2250. function getFips(): 1 | 0;
  2251. /**
  2252. * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
  2253. * Throws an error if FIPS mode is not available.
  2254. * @since v10.0.0
  2255. * @param bool `true` to enable FIPS mode.
  2256. */
  2257. function setFips(bool: boolean): void;
  2258. /**
  2259. * ```js
  2260. * const {
  2261. * getHashes,
  2262. * } = await import('node:crypto');
  2263. *
  2264. * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
  2265. * ```
  2266. * @since v0.9.3
  2267. * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
  2268. */
  2269. function getHashes(): string[];
  2270. /**
  2271. * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
  2272. * key exchanges.
  2273. *
  2274. * Instances of the `ECDH` class can be created using the {@link createECDH} function.
  2275. *
  2276. * ```js
  2277. * import assert from 'node:assert';
  2278. *
  2279. * const {
  2280. * createECDH,
  2281. * } = await import('node:crypto');
  2282. *
  2283. * // Generate Alice's keys...
  2284. * const alice = createECDH('secp521r1');
  2285. * const aliceKey = alice.generateKeys();
  2286. *
  2287. * // Generate Bob's keys...
  2288. * const bob = createECDH('secp521r1');
  2289. * const bobKey = bob.generateKeys();
  2290. *
  2291. * // Exchange and generate the secret...
  2292. * const aliceSecret = alice.computeSecret(bobKey);
  2293. * const bobSecret = bob.computeSecret(aliceKey);
  2294. *
  2295. * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
  2296. * // OK
  2297. * ```
  2298. * @since v0.11.14
  2299. */
  2300. class ECDH {
  2301. private constructor();
  2302. /**
  2303. * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
  2304. * format specified by `format`. The `format` argument specifies point encoding
  2305. * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
  2306. * interpreted using the specified `inputEncoding`, and the returned key is encoded
  2307. * using the specified `outputEncoding`.
  2308. *
  2309. * Use {@link getCurves} to obtain a list of available curve names.
  2310. * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
  2311. * the name and description of each available elliptic curve.
  2312. *
  2313. * If `format` is not specified the point will be returned in `'uncompressed'` format.
  2314. *
  2315. * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`.
  2316. *
  2317. * Example (uncompressing a key):
  2318. *
  2319. * ```js
  2320. * const {
  2321. * createECDH,
  2322. * ECDH,
  2323. * } = await import('node:crypto');
  2324. *
  2325. * const ecdh = createECDH('secp256k1');
  2326. * ecdh.generateKeys();
  2327. *
  2328. * const compressedKey = ecdh.getPublicKey('hex', 'compressed');
  2329. *
  2330. * const uncompressedKey = ECDH.convertKey(compressedKey,
  2331. * 'secp256k1',
  2332. * 'hex',
  2333. * 'hex',
  2334. * 'uncompressed');
  2335. *
  2336. * // The converted key and the uncompressed public key should be the same
  2337. * console.log(uncompressedKey === ecdh.getPublicKey('hex'));
  2338. * ```
  2339. * @since v10.0.0
  2340. * @param inputEncoding The `encoding` of the `key` string.
  2341. * @param outputEncoding The `encoding` of the return value.
  2342. * @param [format='uncompressed']
  2343. */
  2344. static convertKey(
  2345. key: BinaryLike,
  2346. curve: string,
  2347. inputEncoding?: BinaryToTextEncoding,
  2348. outputEncoding?: "latin1" | "hex" | "base64" | "base64url",
  2349. format?: "uncompressed" | "compressed" | "hybrid",
  2350. ): Buffer | string;
  2351. /**
  2352. * Generates private and public EC Diffie-Hellman key values, and returns
  2353. * the public key in the specified `format` and `encoding`. This key should be
  2354. * transferred to the other party.
  2355. *
  2356. * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format.
  2357. *
  2358. * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
  2359. * @since v0.11.14
  2360. * @param encoding The `encoding` of the return value.
  2361. * @param [format='uncompressed']
  2362. */
  2363. generateKeys(): Buffer;
  2364. generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
  2365. /**
  2366. * Computes the shared secret using `otherPublicKey` as the other
  2367. * party's public key and returns the computed shared secret. The supplied
  2368. * key is interpreted using specified `inputEncoding`, and the returned secret
  2369. * is encoded using the specified `outputEncoding`.
  2370. * If the `inputEncoding` is not
  2371. * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`.
  2372. *
  2373. * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned.
  2374. *
  2375. * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is
  2376. * usually supplied from a remote user over an insecure network,
  2377. * be sure to handle this exception accordingly.
  2378. * @since v0.11.14
  2379. * @param inputEncoding The `encoding` of the `otherPublicKey` string.
  2380. * @param outputEncoding The `encoding` of the return value.
  2381. */
  2382. computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer;
  2383. computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer;
  2384. computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string;
  2385. computeSecret(
  2386. otherPublicKey: string,
  2387. inputEncoding: BinaryToTextEncoding,
  2388. outputEncoding: BinaryToTextEncoding,
  2389. ): string;
  2390. /**
  2391. * If `encoding` is specified, a string is returned; otherwise a `Buffer` is
  2392. * returned.
  2393. * @since v0.11.14
  2394. * @param encoding The `encoding` of the return value.
  2395. * @return The EC Diffie-Hellman in the specified `encoding`.
  2396. */
  2397. getPrivateKey(): Buffer;
  2398. getPrivateKey(encoding: BinaryToTextEncoding): string;
  2399. /**
  2400. * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format.
  2401. *
  2402. * If `encoding` is specified, a string is returned; otherwise a `Buffer` is
  2403. * returned.
  2404. * @since v0.11.14
  2405. * @param encoding The `encoding` of the return value.
  2406. * @param [format='uncompressed']
  2407. * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`.
  2408. */
  2409. getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer;
  2410. getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
  2411. /**
  2412. * Sets the EC Diffie-Hellman private key.
  2413. * If `encoding` is provided, `privateKey` is expected
  2414. * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`.
  2415. *
  2416. * If `privateKey` is not valid for the curve specified when the `ECDH` object was
  2417. * created, an error is thrown. Upon setting the private key, the associated
  2418. * public point (key) is also generated and set in the `ECDH` object.
  2419. * @since v0.11.14
  2420. * @param encoding The `encoding` of the `privateKey` string.
  2421. */
  2422. setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
  2423. setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void;
  2424. }
  2425. /**
  2426. * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
  2427. * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent
  2428. * OpenSSL releases, `openssl ecparam -list_curves` will also display the name
  2429. * and description of each available elliptic curve.
  2430. * @since v0.11.14
  2431. */
  2432. function createECDH(curveName: string): ECDH;
  2433. /**
  2434. * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time
  2435. * algorithm.
  2436. *
  2437. * This function does not leak timing information that
  2438. * would allow an attacker to guess one of the values. This is suitable for
  2439. * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/).
  2440. *
  2441. * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
  2442. * must have the same byte length. An error is thrown if `a` and `b` have
  2443. * different byte lengths.
  2444. *
  2445. * If at least one of `a` and `b` is a `TypedArray` with more than one byte per
  2446. * entry, such as `Uint16Array`, the result will be computed using the platform
  2447. * byte order.
  2448. *
  2449. * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754**
  2450. * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point**
  2451. * **numbers `x` and `y` are equal.**
  2452. *
  2453. * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
  2454. * is timing-safe. Care should be taken to ensure that the surrounding code does
  2455. * not introduce timing vulnerabilities.
  2456. * @since v6.6.0
  2457. */
  2458. function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
  2459. type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448";
  2460. type KeyFormat = "pem" | "der" | "jwk";
  2461. interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
  2462. format: T;
  2463. cipher?: string | undefined;
  2464. passphrase?: string | undefined;
  2465. }
  2466. interface KeyPairKeyObjectResult {
  2467. publicKey: KeyObject;
  2468. privateKey: KeyObject;
  2469. }
  2470. interface ED25519KeyPairKeyObjectOptions {}
  2471. interface ED448KeyPairKeyObjectOptions {}
  2472. interface X25519KeyPairKeyObjectOptions {}
  2473. interface X448KeyPairKeyObjectOptions {}
  2474. interface ECKeyPairKeyObjectOptions {
  2475. /**
  2476. * Name of the curve to use
  2477. */
  2478. namedCurve: string;
  2479. /**
  2480. * Must be `'named'` or `'explicit'`. Default: `'named'`.
  2481. */
  2482. paramEncoding?: "explicit" | "named" | undefined;
  2483. }
  2484. interface RSAKeyPairKeyObjectOptions {
  2485. /**
  2486. * Key size in bits
  2487. */
  2488. modulusLength: number;
  2489. /**
  2490. * Public exponent
  2491. * @default 0x10001
  2492. */
  2493. publicExponent?: number | undefined;
  2494. }
  2495. interface RSAPSSKeyPairKeyObjectOptions {
  2496. /**
  2497. * Key size in bits
  2498. */
  2499. modulusLength: number;
  2500. /**
  2501. * Public exponent
  2502. * @default 0x10001
  2503. */
  2504. publicExponent?: number | undefined;
  2505. /**
  2506. * Name of the message digest
  2507. */
  2508. hashAlgorithm?: string;
  2509. /**
  2510. * Name of the message digest used by MGF1
  2511. */
  2512. mgf1HashAlgorithm?: string;
  2513. /**
  2514. * Minimal salt length in bytes
  2515. */
  2516. saltLength?: string;
  2517. }
  2518. interface DSAKeyPairKeyObjectOptions {
  2519. /**
  2520. * Key size in bits
  2521. */
  2522. modulusLength: number;
  2523. /**
  2524. * Size of q in bits
  2525. */
  2526. divisorLength: number;
  2527. }
  2528. interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2529. /**
  2530. * Key size in bits
  2531. */
  2532. modulusLength: number;
  2533. /**
  2534. * Public exponent
  2535. * @default 0x10001
  2536. */
  2537. publicExponent?: number | undefined;
  2538. publicKeyEncoding: {
  2539. type: "pkcs1" | "spki";
  2540. format: PubF;
  2541. };
  2542. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2543. type: "pkcs1" | "pkcs8";
  2544. };
  2545. }
  2546. interface RSAPSSKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2547. /**
  2548. * Key size in bits
  2549. */
  2550. modulusLength: number;
  2551. /**
  2552. * Public exponent
  2553. * @default 0x10001
  2554. */
  2555. publicExponent?: number | undefined;
  2556. /**
  2557. * Name of the message digest
  2558. */
  2559. hashAlgorithm?: string;
  2560. /**
  2561. * Name of the message digest used by MGF1
  2562. */
  2563. mgf1HashAlgorithm?: string;
  2564. /**
  2565. * Minimal salt length in bytes
  2566. */
  2567. saltLength?: string;
  2568. publicKeyEncoding: {
  2569. type: "spki";
  2570. format: PubF;
  2571. };
  2572. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2573. type: "pkcs8";
  2574. };
  2575. }
  2576. interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2577. /**
  2578. * Key size in bits
  2579. */
  2580. modulusLength: number;
  2581. /**
  2582. * Size of q in bits
  2583. */
  2584. divisorLength: number;
  2585. publicKeyEncoding: {
  2586. type: "spki";
  2587. format: PubF;
  2588. };
  2589. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2590. type: "pkcs8";
  2591. };
  2592. }
  2593. interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> extends ECKeyPairKeyObjectOptions {
  2594. publicKeyEncoding: {
  2595. type: "pkcs1" | "spki";
  2596. format: PubF;
  2597. };
  2598. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2599. type: "sec1" | "pkcs8";
  2600. };
  2601. }
  2602. interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2603. publicKeyEncoding: {
  2604. type: "spki";
  2605. format: PubF;
  2606. };
  2607. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2608. type: "pkcs8";
  2609. };
  2610. }
  2611. interface ED448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2612. publicKeyEncoding: {
  2613. type: "spki";
  2614. format: PubF;
  2615. };
  2616. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2617. type: "pkcs8";
  2618. };
  2619. }
  2620. interface X25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2621. publicKeyEncoding: {
  2622. type: "spki";
  2623. format: PubF;
  2624. };
  2625. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2626. type: "pkcs8";
  2627. };
  2628. }
  2629. interface X448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
  2630. publicKeyEncoding: {
  2631. type: "spki";
  2632. format: PubF;
  2633. };
  2634. privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
  2635. type: "pkcs8";
  2636. };
  2637. }
  2638. interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
  2639. publicKey: T1;
  2640. privateKey: T2;
  2641. }
  2642. /**
  2643. * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
  2644. * Ed25519, Ed448, X25519, X448, and DH are currently supported.
  2645. *
  2646. * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
  2647. * behaves as if `keyObject.export()` had been called on its result. Otherwise,
  2648. * the respective part of the key is returned as a `KeyObject`.
  2649. *
  2650. * When encoding public keys, it is recommended to use `'spki'`. When encoding
  2651. * private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
  2652. * and to keep the passphrase confidential.
  2653. *
  2654. * ```js
  2655. * const {
  2656. * generateKeyPairSync,
  2657. * } = await import('node:crypto');
  2658. *
  2659. * const {
  2660. * publicKey,
  2661. * privateKey,
  2662. * } = generateKeyPairSync('rsa', {
  2663. * modulusLength: 4096,
  2664. * publicKeyEncoding: {
  2665. * type: 'spki',
  2666. * format: 'pem',
  2667. * },
  2668. * privateKeyEncoding: {
  2669. * type: 'pkcs8',
  2670. * format: 'pem',
  2671. * cipher: 'aes-256-cbc',
  2672. * passphrase: 'top secret',
  2673. * },
  2674. * });
  2675. * ```
  2676. *
  2677. * The return value `{ publicKey, privateKey }` represents the generated key pair.
  2678. * When PEM encoding was selected, the respective key will be a string, otherwise
  2679. * it will be a buffer containing the data encoded as DER.
  2680. * @since v10.12.0
  2681. * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
  2682. */
  2683. function generateKeyPairSync(
  2684. type: "rsa",
  2685. options: RSAKeyPairOptions<"pem", "pem">,
  2686. ): KeyPairSyncResult<string, string>;
  2687. function generateKeyPairSync(
  2688. type: "rsa",
  2689. options: RSAKeyPairOptions<"pem", "der">,
  2690. ): KeyPairSyncResult<string, Buffer>;
  2691. function generateKeyPairSync(
  2692. type: "rsa",
  2693. options: RSAKeyPairOptions<"der", "pem">,
  2694. ): KeyPairSyncResult<Buffer, string>;
  2695. function generateKeyPairSync(
  2696. type: "rsa",
  2697. options: RSAKeyPairOptions<"der", "der">,
  2698. ): KeyPairSyncResult<Buffer, Buffer>;
  2699. function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2700. function generateKeyPairSync(
  2701. type: "rsa-pss",
  2702. options: RSAPSSKeyPairOptions<"pem", "pem">,
  2703. ): KeyPairSyncResult<string, string>;
  2704. function generateKeyPairSync(
  2705. type: "rsa-pss",
  2706. options: RSAPSSKeyPairOptions<"pem", "der">,
  2707. ): KeyPairSyncResult<string, Buffer>;
  2708. function generateKeyPairSync(
  2709. type: "rsa-pss",
  2710. options: RSAPSSKeyPairOptions<"der", "pem">,
  2711. ): KeyPairSyncResult<Buffer, string>;
  2712. function generateKeyPairSync(
  2713. type: "rsa-pss",
  2714. options: RSAPSSKeyPairOptions<"der", "der">,
  2715. ): KeyPairSyncResult<Buffer, Buffer>;
  2716. function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2717. function generateKeyPairSync(
  2718. type: "dsa",
  2719. options: DSAKeyPairOptions<"pem", "pem">,
  2720. ): KeyPairSyncResult<string, string>;
  2721. function generateKeyPairSync(
  2722. type: "dsa",
  2723. options: DSAKeyPairOptions<"pem", "der">,
  2724. ): KeyPairSyncResult<string, Buffer>;
  2725. function generateKeyPairSync(
  2726. type: "dsa",
  2727. options: DSAKeyPairOptions<"der", "pem">,
  2728. ): KeyPairSyncResult<Buffer, string>;
  2729. function generateKeyPairSync(
  2730. type: "dsa",
  2731. options: DSAKeyPairOptions<"der", "der">,
  2732. ): KeyPairSyncResult<Buffer, Buffer>;
  2733. function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2734. function generateKeyPairSync(
  2735. type: "ec",
  2736. options: ECKeyPairOptions<"pem", "pem">,
  2737. ): KeyPairSyncResult<string, string>;
  2738. function generateKeyPairSync(
  2739. type: "ec",
  2740. options: ECKeyPairOptions<"pem", "der">,
  2741. ): KeyPairSyncResult<string, Buffer>;
  2742. function generateKeyPairSync(
  2743. type: "ec",
  2744. options: ECKeyPairOptions<"der", "pem">,
  2745. ): KeyPairSyncResult<Buffer, string>;
  2746. function generateKeyPairSync(
  2747. type: "ec",
  2748. options: ECKeyPairOptions<"der", "der">,
  2749. ): KeyPairSyncResult<Buffer, Buffer>;
  2750. function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2751. function generateKeyPairSync(
  2752. type: "ed25519",
  2753. options: ED25519KeyPairOptions<"pem", "pem">,
  2754. ): KeyPairSyncResult<string, string>;
  2755. function generateKeyPairSync(
  2756. type: "ed25519",
  2757. options: ED25519KeyPairOptions<"pem", "der">,
  2758. ): KeyPairSyncResult<string, Buffer>;
  2759. function generateKeyPairSync(
  2760. type: "ed25519",
  2761. options: ED25519KeyPairOptions<"der", "pem">,
  2762. ): KeyPairSyncResult<Buffer, string>;
  2763. function generateKeyPairSync(
  2764. type: "ed25519",
  2765. options: ED25519KeyPairOptions<"der", "der">,
  2766. ): KeyPairSyncResult<Buffer, Buffer>;
  2767. function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2768. function generateKeyPairSync(
  2769. type: "ed448",
  2770. options: ED448KeyPairOptions<"pem", "pem">,
  2771. ): KeyPairSyncResult<string, string>;
  2772. function generateKeyPairSync(
  2773. type: "ed448",
  2774. options: ED448KeyPairOptions<"pem", "der">,
  2775. ): KeyPairSyncResult<string, Buffer>;
  2776. function generateKeyPairSync(
  2777. type: "ed448",
  2778. options: ED448KeyPairOptions<"der", "pem">,
  2779. ): KeyPairSyncResult<Buffer, string>;
  2780. function generateKeyPairSync(
  2781. type: "ed448",
  2782. options: ED448KeyPairOptions<"der", "der">,
  2783. ): KeyPairSyncResult<Buffer, Buffer>;
  2784. function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2785. function generateKeyPairSync(
  2786. type: "x25519",
  2787. options: X25519KeyPairOptions<"pem", "pem">,
  2788. ): KeyPairSyncResult<string, string>;
  2789. function generateKeyPairSync(
  2790. type: "x25519",
  2791. options: X25519KeyPairOptions<"pem", "der">,
  2792. ): KeyPairSyncResult<string, Buffer>;
  2793. function generateKeyPairSync(
  2794. type: "x25519",
  2795. options: X25519KeyPairOptions<"der", "pem">,
  2796. ): KeyPairSyncResult<Buffer, string>;
  2797. function generateKeyPairSync(
  2798. type: "x25519",
  2799. options: X25519KeyPairOptions<"der", "der">,
  2800. ): KeyPairSyncResult<Buffer, Buffer>;
  2801. function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2802. function generateKeyPairSync(
  2803. type: "x448",
  2804. options: X448KeyPairOptions<"pem", "pem">,
  2805. ): KeyPairSyncResult<string, string>;
  2806. function generateKeyPairSync(
  2807. type: "x448",
  2808. options: X448KeyPairOptions<"pem", "der">,
  2809. ): KeyPairSyncResult<string, Buffer>;
  2810. function generateKeyPairSync(
  2811. type: "x448",
  2812. options: X448KeyPairOptions<"der", "pem">,
  2813. ): KeyPairSyncResult<Buffer, string>;
  2814. function generateKeyPairSync(
  2815. type: "x448",
  2816. options: X448KeyPairOptions<"der", "der">,
  2817. ): KeyPairSyncResult<Buffer, Buffer>;
  2818. function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
  2819. /**
  2820. * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
  2821. * Ed25519, Ed448, X25519, X448, and DH are currently supported.
  2822. *
  2823. * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
  2824. * behaves as if `keyObject.export()` had been called on its result. Otherwise,
  2825. * the respective part of the key is returned as a `KeyObject`.
  2826. *
  2827. * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage:
  2828. *
  2829. * ```js
  2830. * const {
  2831. * generateKeyPair,
  2832. * } = await import('node:crypto');
  2833. *
  2834. * generateKeyPair('rsa', {
  2835. * modulusLength: 4096,
  2836. * publicKeyEncoding: {
  2837. * type: 'spki',
  2838. * format: 'pem',
  2839. * },
  2840. * privateKeyEncoding: {
  2841. * type: 'pkcs8',
  2842. * format: 'pem',
  2843. * cipher: 'aes-256-cbc',
  2844. * passphrase: 'top secret',
  2845. * },
  2846. * }, (err, publicKey, privateKey) => {
  2847. * // Handle errors and use the generated key pair.
  2848. * });
  2849. * ```
  2850. *
  2851. * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair.
  2852. *
  2853. * If this method is invoked as its `util.promisify()` ed version, it returns
  2854. * a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
  2855. * @since v10.12.0
  2856. * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
  2857. */
  2858. function generateKeyPair(
  2859. type: "rsa",
  2860. options: RSAKeyPairOptions<"pem", "pem">,
  2861. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2862. ): void;
  2863. function generateKeyPair(
  2864. type: "rsa",
  2865. options: RSAKeyPairOptions<"pem", "der">,
  2866. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2867. ): void;
  2868. function generateKeyPair(
  2869. type: "rsa",
  2870. options: RSAKeyPairOptions<"der", "pem">,
  2871. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2872. ): void;
  2873. function generateKeyPair(
  2874. type: "rsa",
  2875. options: RSAKeyPairOptions<"der", "der">,
  2876. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  2877. ): void;
  2878. function generateKeyPair(
  2879. type: "rsa",
  2880. options: RSAKeyPairKeyObjectOptions,
  2881. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  2882. ): void;
  2883. function generateKeyPair(
  2884. type: "rsa-pss",
  2885. options: RSAPSSKeyPairOptions<"pem", "pem">,
  2886. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2887. ): void;
  2888. function generateKeyPair(
  2889. type: "rsa-pss",
  2890. options: RSAPSSKeyPairOptions<"pem", "der">,
  2891. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2892. ): void;
  2893. function generateKeyPair(
  2894. type: "rsa-pss",
  2895. options: RSAPSSKeyPairOptions<"der", "pem">,
  2896. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2897. ): void;
  2898. function generateKeyPair(
  2899. type: "rsa-pss",
  2900. options: RSAPSSKeyPairOptions<"der", "der">,
  2901. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  2902. ): void;
  2903. function generateKeyPair(
  2904. type: "rsa-pss",
  2905. options: RSAPSSKeyPairKeyObjectOptions,
  2906. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  2907. ): void;
  2908. function generateKeyPair(
  2909. type: "dsa",
  2910. options: DSAKeyPairOptions<"pem", "pem">,
  2911. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2912. ): void;
  2913. function generateKeyPair(
  2914. type: "dsa",
  2915. options: DSAKeyPairOptions<"pem", "der">,
  2916. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2917. ): void;
  2918. function generateKeyPair(
  2919. type: "dsa",
  2920. options: DSAKeyPairOptions<"der", "pem">,
  2921. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2922. ): void;
  2923. function generateKeyPair(
  2924. type: "dsa",
  2925. options: DSAKeyPairOptions<"der", "der">,
  2926. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  2927. ): void;
  2928. function generateKeyPair(
  2929. type: "dsa",
  2930. options: DSAKeyPairKeyObjectOptions,
  2931. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  2932. ): void;
  2933. function generateKeyPair(
  2934. type: "ec",
  2935. options: ECKeyPairOptions<"pem", "pem">,
  2936. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2937. ): void;
  2938. function generateKeyPair(
  2939. type: "ec",
  2940. options: ECKeyPairOptions<"pem", "der">,
  2941. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2942. ): void;
  2943. function generateKeyPair(
  2944. type: "ec",
  2945. options: ECKeyPairOptions<"der", "pem">,
  2946. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2947. ): void;
  2948. function generateKeyPair(
  2949. type: "ec",
  2950. options: ECKeyPairOptions<"der", "der">,
  2951. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  2952. ): void;
  2953. function generateKeyPair(
  2954. type: "ec",
  2955. options: ECKeyPairKeyObjectOptions,
  2956. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  2957. ): void;
  2958. function generateKeyPair(
  2959. type: "ed25519",
  2960. options: ED25519KeyPairOptions<"pem", "pem">,
  2961. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2962. ): void;
  2963. function generateKeyPair(
  2964. type: "ed25519",
  2965. options: ED25519KeyPairOptions<"pem", "der">,
  2966. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2967. ): void;
  2968. function generateKeyPair(
  2969. type: "ed25519",
  2970. options: ED25519KeyPairOptions<"der", "pem">,
  2971. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2972. ): void;
  2973. function generateKeyPair(
  2974. type: "ed25519",
  2975. options: ED25519KeyPairOptions<"der", "der">,
  2976. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  2977. ): void;
  2978. function generateKeyPair(
  2979. type: "ed25519",
  2980. options: ED25519KeyPairKeyObjectOptions | undefined,
  2981. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  2982. ): void;
  2983. function generateKeyPair(
  2984. type: "ed448",
  2985. options: ED448KeyPairOptions<"pem", "pem">,
  2986. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  2987. ): void;
  2988. function generateKeyPair(
  2989. type: "ed448",
  2990. options: ED448KeyPairOptions<"pem", "der">,
  2991. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  2992. ): void;
  2993. function generateKeyPair(
  2994. type: "ed448",
  2995. options: ED448KeyPairOptions<"der", "pem">,
  2996. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  2997. ): void;
  2998. function generateKeyPair(
  2999. type: "ed448",
  3000. options: ED448KeyPairOptions<"der", "der">,
  3001. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  3002. ): void;
  3003. function generateKeyPair(
  3004. type: "ed448",
  3005. options: ED448KeyPairKeyObjectOptions | undefined,
  3006. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  3007. ): void;
  3008. function generateKeyPair(
  3009. type: "x25519",
  3010. options: X25519KeyPairOptions<"pem", "pem">,
  3011. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  3012. ): void;
  3013. function generateKeyPair(
  3014. type: "x25519",
  3015. options: X25519KeyPairOptions<"pem", "der">,
  3016. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  3017. ): void;
  3018. function generateKeyPair(
  3019. type: "x25519",
  3020. options: X25519KeyPairOptions<"der", "pem">,
  3021. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  3022. ): void;
  3023. function generateKeyPair(
  3024. type: "x25519",
  3025. options: X25519KeyPairOptions<"der", "der">,
  3026. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  3027. ): void;
  3028. function generateKeyPair(
  3029. type: "x25519",
  3030. options: X25519KeyPairKeyObjectOptions | undefined,
  3031. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  3032. ): void;
  3033. function generateKeyPair(
  3034. type: "x448",
  3035. options: X448KeyPairOptions<"pem", "pem">,
  3036. callback: (err: Error | null, publicKey: string, privateKey: string) => void,
  3037. ): void;
  3038. function generateKeyPair(
  3039. type: "x448",
  3040. options: X448KeyPairOptions<"pem", "der">,
  3041. callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
  3042. ): void;
  3043. function generateKeyPair(
  3044. type: "x448",
  3045. options: X448KeyPairOptions<"der", "pem">,
  3046. callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
  3047. ): void;
  3048. function generateKeyPair(
  3049. type: "x448",
  3050. options: X448KeyPairOptions<"der", "der">,
  3051. callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
  3052. ): void;
  3053. function generateKeyPair(
  3054. type: "x448",
  3055. options: X448KeyPairKeyObjectOptions | undefined,
  3056. callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
  3057. ): void;
  3058. namespace generateKeyPair {
  3059. function __promisify__(
  3060. type: "rsa",
  3061. options: RSAKeyPairOptions<"pem", "pem">,
  3062. ): Promise<{
  3063. publicKey: string;
  3064. privateKey: string;
  3065. }>;
  3066. function __promisify__(
  3067. type: "rsa",
  3068. options: RSAKeyPairOptions<"pem", "der">,
  3069. ): Promise<{
  3070. publicKey: string;
  3071. privateKey: Buffer;
  3072. }>;
  3073. function __promisify__(
  3074. type: "rsa",
  3075. options: RSAKeyPairOptions<"der", "pem">,
  3076. ): Promise<{
  3077. publicKey: Buffer;
  3078. privateKey: string;
  3079. }>;
  3080. function __promisify__(
  3081. type: "rsa",
  3082. options: RSAKeyPairOptions<"der", "der">,
  3083. ): Promise<{
  3084. publicKey: Buffer;
  3085. privateKey: Buffer;
  3086. }>;
  3087. function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
  3088. function __promisify__(
  3089. type: "rsa-pss",
  3090. options: RSAPSSKeyPairOptions<"pem", "pem">,
  3091. ): Promise<{
  3092. publicKey: string;
  3093. privateKey: string;
  3094. }>;
  3095. function __promisify__(
  3096. type: "rsa-pss",
  3097. options: RSAPSSKeyPairOptions<"pem", "der">,
  3098. ): Promise<{
  3099. publicKey: string;
  3100. privateKey: Buffer;
  3101. }>;
  3102. function __promisify__(
  3103. type: "rsa-pss",
  3104. options: RSAPSSKeyPairOptions<"der", "pem">,
  3105. ): Promise<{
  3106. publicKey: Buffer;
  3107. privateKey: string;
  3108. }>;
  3109. function __promisify__(
  3110. type: "rsa-pss",
  3111. options: RSAPSSKeyPairOptions<"der", "der">,
  3112. ): Promise<{
  3113. publicKey: Buffer;
  3114. privateKey: Buffer;
  3115. }>;
  3116. function __promisify__(
  3117. type: "rsa-pss",
  3118. options: RSAPSSKeyPairKeyObjectOptions,
  3119. ): Promise<KeyPairKeyObjectResult>;
  3120. function __promisify__(
  3121. type: "dsa",
  3122. options: DSAKeyPairOptions<"pem", "pem">,
  3123. ): Promise<{
  3124. publicKey: string;
  3125. privateKey: string;
  3126. }>;
  3127. function __promisify__(
  3128. type: "dsa",
  3129. options: DSAKeyPairOptions<"pem", "der">,
  3130. ): Promise<{
  3131. publicKey: string;
  3132. privateKey: Buffer;
  3133. }>;
  3134. function __promisify__(
  3135. type: "dsa",
  3136. options: DSAKeyPairOptions<"der", "pem">,
  3137. ): Promise<{
  3138. publicKey: Buffer;
  3139. privateKey: string;
  3140. }>;
  3141. function __promisify__(
  3142. type: "dsa",
  3143. options: DSAKeyPairOptions<"der", "der">,
  3144. ): Promise<{
  3145. publicKey: Buffer;
  3146. privateKey: Buffer;
  3147. }>;
  3148. function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
  3149. function __promisify__(
  3150. type: "ec",
  3151. options: ECKeyPairOptions<"pem", "pem">,
  3152. ): Promise<{
  3153. publicKey: string;
  3154. privateKey: string;
  3155. }>;
  3156. function __promisify__(
  3157. type: "ec",
  3158. options: ECKeyPairOptions<"pem", "der">,
  3159. ): Promise<{
  3160. publicKey: string;
  3161. privateKey: Buffer;
  3162. }>;
  3163. function __promisify__(
  3164. type: "ec",
  3165. options: ECKeyPairOptions<"der", "pem">,
  3166. ): Promise<{
  3167. publicKey: Buffer;
  3168. privateKey: string;
  3169. }>;
  3170. function __promisify__(
  3171. type: "ec",
  3172. options: ECKeyPairOptions<"der", "der">,
  3173. ): Promise<{
  3174. publicKey: Buffer;
  3175. privateKey: Buffer;
  3176. }>;
  3177. function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
  3178. function __promisify__(
  3179. type: "ed25519",
  3180. options: ED25519KeyPairOptions<"pem", "pem">,
  3181. ): Promise<{
  3182. publicKey: string;
  3183. privateKey: string;
  3184. }>;
  3185. function __promisify__(
  3186. type: "ed25519",
  3187. options: ED25519KeyPairOptions<"pem", "der">,
  3188. ): Promise<{
  3189. publicKey: string;
  3190. privateKey: Buffer;
  3191. }>;
  3192. function __promisify__(
  3193. type: "ed25519",
  3194. options: ED25519KeyPairOptions<"der", "pem">,
  3195. ): Promise<{
  3196. publicKey: Buffer;
  3197. privateKey: string;
  3198. }>;
  3199. function __promisify__(
  3200. type: "ed25519",
  3201. options: ED25519KeyPairOptions<"der", "der">,
  3202. ): Promise<{
  3203. publicKey: Buffer;
  3204. privateKey: Buffer;
  3205. }>;
  3206. function __promisify__(
  3207. type: "ed25519",
  3208. options?: ED25519KeyPairKeyObjectOptions,
  3209. ): Promise<KeyPairKeyObjectResult>;
  3210. function __promisify__(
  3211. type: "ed448",
  3212. options: ED448KeyPairOptions<"pem", "pem">,
  3213. ): Promise<{
  3214. publicKey: string;
  3215. privateKey: string;
  3216. }>;
  3217. function __promisify__(
  3218. type: "ed448",
  3219. options: ED448KeyPairOptions<"pem", "der">,
  3220. ): Promise<{
  3221. publicKey: string;
  3222. privateKey: Buffer;
  3223. }>;
  3224. function __promisify__(
  3225. type: "ed448",
  3226. options: ED448KeyPairOptions<"der", "pem">,
  3227. ): Promise<{
  3228. publicKey: Buffer;
  3229. privateKey: string;
  3230. }>;
  3231. function __promisify__(
  3232. type: "ed448",
  3233. options: ED448KeyPairOptions<"der", "der">,
  3234. ): Promise<{
  3235. publicKey: Buffer;
  3236. privateKey: Buffer;
  3237. }>;
  3238. function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
  3239. function __promisify__(
  3240. type: "x25519",
  3241. options: X25519KeyPairOptions<"pem", "pem">,
  3242. ): Promise<{
  3243. publicKey: string;
  3244. privateKey: string;
  3245. }>;
  3246. function __promisify__(
  3247. type: "x25519",
  3248. options: X25519KeyPairOptions<"pem", "der">,
  3249. ): Promise<{
  3250. publicKey: string;
  3251. privateKey: Buffer;
  3252. }>;
  3253. function __promisify__(
  3254. type: "x25519",
  3255. options: X25519KeyPairOptions<"der", "pem">,
  3256. ): Promise<{
  3257. publicKey: Buffer;
  3258. privateKey: string;
  3259. }>;
  3260. function __promisify__(
  3261. type: "x25519",
  3262. options: X25519KeyPairOptions<"der", "der">,
  3263. ): Promise<{
  3264. publicKey: Buffer;
  3265. privateKey: Buffer;
  3266. }>;
  3267. function __promisify__(
  3268. type: "x25519",
  3269. options?: X25519KeyPairKeyObjectOptions,
  3270. ): Promise<KeyPairKeyObjectResult>;
  3271. function __promisify__(
  3272. type: "x448",
  3273. options: X448KeyPairOptions<"pem", "pem">,
  3274. ): Promise<{
  3275. publicKey: string;
  3276. privateKey: string;
  3277. }>;
  3278. function __promisify__(
  3279. type: "x448",
  3280. options: X448KeyPairOptions<"pem", "der">,
  3281. ): Promise<{
  3282. publicKey: string;
  3283. privateKey: Buffer;
  3284. }>;
  3285. function __promisify__(
  3286. type: "x448",
  3287. options: X448KeyPairOptions<"der", "pem">,
  3288. ): Promise<{
  3289. publicKey: Buffer;
  3290. privateKey: string;
  3291. }>;
  3292. function __promisify__(
  3293. type: "x448",
  3294. options: X448KeyPairOptions<"der", "der">,
  3295. ): Promise<{
  3296. publicKey: Buffer;
  3297. privateKey: Buffer;
  3298. }>;
  3299. function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
  3300. }
  3301. /**
  3302. * Calculates and returns the signature for `data` using the given private key and
  3303. * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
  3304. * dependent upon the key type (especially Ed25519 and Ed448).
  3305. *
  3306. * If `key` is not a `KeyObject`, this function behaves as if `key` had been
  3307. * passed to {@link createPrivateKey}. If it is an object, the following
  3308. * additional properties can be passed:
  3309. *
  3310. * If the `callback` function is provided this function uses libuv's threadpool.
  3311. * @since v12.0.0
  3312. */
  3313. function sign(
  3314. algorithm: string | null | undefined,
  3315. data: NodeJS.ArrayBufferView,
  3316. key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput,
  3317. ): Buffer;
  3318. function sign(
  3319. algorithm: string | null | undefined,
  3320. data: NodeJS.ArrayBufferView,
  3321. key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput,
  3322. callback: (error: Error | null, data: Buffer) => void,
  3323. ): void;
  3324. /**
  3325. * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
  3326. * key type (especially Ed25519 and Ed448).
  3327. *
  3328. * If `key` is not a `KeyObject`, this function behaves as if `key` had been
  3329. * passed to {@link createPublicKey}. If it is an object, the following
  3330. * additional properties can be passed:
  3331. *
  3332. * The `signature` argument is the previously calculated signature for the `data`.
  3333. *
  3334. * Because public keys can be derived from private keys, a private key or a public
  3335. * key may be passed for `key`.
  3336. *
  3337. * If the `callback` function is provided this function uses libuv's threadpool.
  3338. * @since v12.0.0
  3339. */
  3340. function verify(
  3341. algorithm: string | null | undefined,
  3342. data: NodeJS.ArrayBufferView,
  3343. key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
  3344. signature: NodeJS.ArrayBufferView,
  3345. ): boolean;
  3346. function verify(
  3347. algorithm: string | null | undefined,
  3348. data: NodeJS.ArrayBufferView,
  3349. key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
  3350. signature: NodeJS.ArrayBufferView,
  3351. callback: (error: Error | null, result: boolean) => void,
  3352. ): void;
  3353. /**
  3354. * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
  3355. * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
  3356. * @since v13.9.0, v12.17.0
  3357. */
  3358. function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer;
  3359. /**
  3360. * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data
  3361. * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm`
  3362. * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases
  3363. * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms.
  3364. *
  3365. * Example:
  3366. *
  3367. * ```js
  3368. * import crypto from 'node:crypto';
  3369. * import { Buffer } from 'node:buffer';
  3370. *
  3371. * // Hashing a string and return the result as a hex-encoded string.
  3372. * const string = 'Node.js';
  3373. * // 10b3493287f831e81a438811a1ffba01f8cec4b7
  3374. * console.log(crypto.hash('sha1', string));
  3375. *
  3376. * // Encode a base64-encoded string into a Buffer, hash it and return
  3377. * // the result as a buffer.
  3378. * const base64 = 'Tm9kZS5qcw==';
  3379. * // <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
  3380. * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));
  3381. * ```
  3382. * @since v21.7.0, v20.12.0
  3383. * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user
  3384. * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead.
  3385. * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v22.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest.
  3386. */
  3387. function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string;
  3388. function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer;
  3389. function hash(
  3390. algorithm: string,
  3391. data: BinaryLike,
  3392. outputEncoding?: BinaryToTextEncoding | "buffer",
  3393. ): string | Buffer;
  3394. type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts";
  3395. interface CipherInfoOptions {
  3396. /**
  3397. * A test key length.
  3398. */
  3399. keyLength?: number | undefined;
  3400. /**
  3401. * A test IV length.
  3402. */
  3403. ivLength?: number | undefined;
  3404. }
  3405. interface CipherInfo {
  3406. /**
  3407. * The name of the cipher.
  3408. */
  3409. name: string;
  3410. /**
  3411. * The nid of the cipher.
  3412. */
  3413. nid: number;
  3414. /**
  3415. * The block size of the cipher in bytes.
  3416. * This property is omitted when mode is 'stream'.
  3417. */
  3418. blockSize?: number | undefined;
  3419. /**
  3420. * The expected or default initialization vector length in bytes.
  3421. * This property is omitted if the cipher does not use an initialization vector.
  3422. */
  3423. ivLength?: number | undefined;
  3424. /**
  3425. * The expected or default key length in bytes.
  3426. */
  3427. keyLength: number;
  3428. /**
  3429. * The cipher mode.
  3430. */
  3431. mode: CipherMode;
  3432. }
  3433. /**
  3434. * Returns information about a given cipher.
  3435. *
  3436. * Some ciphers accept variable length keys and initialization vectors. By default,
  3437. * the `crypto.getCipherInfo()` method will return the default values for these
  3438. * ciphers. To test if a given key length or iv length is acceptable for given
  3439. * cipher, use the `keyLength` and `ivLength` options. If the given values are
  3440. * unacceptable, `undefined` will be returned.
  3441. * @since v15.0.0
  3442. * @param nameOrNid The name or nid of the cipher to query.
  3443. */
  3444. function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined;
  3445. /**
  3446. * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
  3447. *
  3448. * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set;
  3449. * otherwise `err` will be `null`. The successfully generated `derivedKey` will
  3450. * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
  3451. * of the input arguments specify invalid values or types.
  3452. *
  3453. * ```js
  3454. * import { Buffer } from 'node:buffer';
  3455. * const {
  3456. * hkdf,
  3457. * } = await import('node:crypto');
  3458. *
  3459. * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
  3460. * if (err) throw err;
  3461. * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
  3462. * });
  3463. * ```
  3464. * @since v15.0.0
  3465. * @param digest The digest algorithm to use.
  3466. * @param ikm The input keying material. Must be provided but can be zero-length.
  3467. * @param salt The salt value. Must be provided but can be zero-length.
  3468. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
  3469. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
  3470. * generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
  3471. */
  3472. function hkdf(
  3473. digest: string,
  3474. irm: BinaryLike | KeyObject,
  3475. salt: BinaryLike,
  3476. info: BinaryLike,
  3477. keylen: number,
  3478. callback: (err: Error | null, derivedKey: ArrayBuffer) => void,
  3479. ): void;
  3480. /**
  3481. * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The
  3482. * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
  3483. *
  3484. * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
  3485. *
  3486. * An error will be thrown if any of the input arguments specify invalid values or
  3487. * types, or if the derived key cannot be generated.
  3488. *
  3489. * ```js
  3490. * import { Buffer } from 'node:buffer';
  3491. * const {
  3492. * hkdfSync,
  3493. * } = await import('node:crypto');
  3494. *
  3495. * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
  3496. * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
  3497. * ```
  3498. * @since v15.0.0
  3499. * @param digest The digest algorithm to use.
  3500. * @param ikm The input keying material. Must be provided but can be zero-length.
  3501. * @param salt The salt value. Must be provided but can be zero-length.
  3502. * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
  3503. * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
  3504. * generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
  3505. */
  3506. function hkdfSync(
  3507. digest: string,
  3508. ikm: BinaryLike | KeyObject,
  3509. salt: BinaryLike,
  3510. info: BinaryLike,
  3511. keylen: number,
  3512. ): ArrayBuffer;
  3513. interface SecureHeapUsage {
  3514. /**
  3515. * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
  3516. */
  3517. total: number;
  3518. /**
  3519. * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
  3520. */
  3521. min: number;
  3522. /**
  3523. * The total number of bytes currently allocated from the secure heap.
  3524. */
  3525. used: number;
  3526. /**
  3527. * The calculated ratio of `used` to `total` allocated bytes.
  3528. */
  3529. utilization: number;
  3530. }
  3531. /**
  3532. * @since v15.6.0
  3533. */
  3534. function secureHeapUsed(): SecureHeapUsage;
  3535. interface RandomUUIDOptions {
  3536. /**
  3537. * By default, to improve performance,
  3538. * Node.js will pre-emptively generate and persistently cache enough
  3539. * random data to generate up to 128 random UUIDs. To generate a UUID
  3540. * without using the cache, set `disableEntropyCache` to `true`.
  3541. *
  3542. * @default `false`
  3543. */
  3544. disableEntropyCache?: boolean | undefined;
  3545. }
  3546. type UUID = `${string}-${string}-${string}-${string}-${string}`;
  3547. /**
  3548. * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a
  3549. * cryptographic pseudorandom number generator.
  3550. * @since v15.6.0, v14.17.0
  3551. */
  3552. function randomUUID(options?: RandomUUIDOptions): UUID;
  3553. interface X509CheckOptions {
  3554. /**
  3555. * @default 'always'
  3556. */
  3557. subject?: "always" | "default" | "never";
  3558. /**
  3559. * @default true
  3560. */
  3561. wildcards?: boolean;
  3562. /**
  3563. * @default true
  3564. */
  3565. partialWildcards?: boolean;
  3566. /**
  3567. * @default false
  3568. */
  3569. multiLabelWildcards?: boolean;
  3570. /**
  3571. * @default false
  3572. */
  3573. singleLabelSubdomains?: boolean;
  3574. }
  3575. /**
  3576. * Encapsulates an X509 certificate and provides read-only access to
  3577. * its information.
  3578. *
  3579. * ```js
  3580. * const { X509Certificate } = await import('node:crypto');
  3581. *
  3582. * const x509 = new X509Certificate('{... pem encoded cert ...}');
  3583. *
  3584. * console.log(x509.subject);
  3585. * ```
  3586. * @since v15.6.0
  3587. */
  3588. class X509Certificate {
  3589. /**
  3590. * Will be \`true\` if this is a Certificate Authority (CA) certificate.
  3591. * @since v15.6.0
  3592. */
  3593. readonly ca: boolean;
  3594. /**
  3595. * The SHA-1 fingerprint of this certificate.
  3596. *
  3597. * Because SHA-1 is cryptographically broken and because the security of SHA-1 is
  3598. * significantly worse than that of algorithms that are commonly used to sign
  3599. * certificates, consider using `x509.fingerprint256` instead.
  3600. * @since v15.6.0
  3601. */
  3602. readonly fingerprint: string;
  3603. /**
  3604. * The SHA-256 fingerprint of this certificate.
  3605. * @since v15.6.0
  3606. */
  3607. readonly fingerprint256: string;
  3608. /**
  3609. * The SHA-512 fingerprint of this certificate.
  3610. *
  3611. * Because computing the SHA-256 fingerprint is usually faster and because it is
  3612. * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be
  3613. * a better choice. While SHA-512 presumably provides a higher level of security in
  3614. * general, the security of SHA-256 matches that of most algorithms that are
  3615. * commonly used to sign certificates.
  3616. * @since v17.2.0, v16.14.0
  3617. */
  3618. readonly fingerprint512: string;
  3619. /**
  3620. * The complete subject of this certificate.
  3621. * @since v15.6.0
  3622. */
  3623. readonly subject: string;
  3624. /**
  3625. * The subject alternative name specified for this certificate.
  3626. *
  3627. * This is a comma-separated list of subject alternative names. Each entry begins
  3628. * with a string identifying the kind of the subject alternative name followed by
  3629. * a colon and the value associated with the entry.
  3630. *
  3631. * Earlier versions of Node.js incorrectly assumed that it is safe to split this
  3632. * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However,
  3633. * both malicious and legitimate certificates can contain subject alternative names
  3634. * that include this sequence when represented as a string.
  3635. *
  3636. * After the prefix denoting the type of the entry, the remainder of each entry
  3637. * might be enclosed in quotes to indicate that the value is a JSON string literal.
  3638. * For backward compatibility, Node.js only uses JSON string literals within this
  3639. * property when necessary to avoid ambiguity. Third-party code should be prepared
  3640. * to handle both possible entry formats.
  3641. * @since v15.6.0
  3642. */
  3643. readonly subjectAltName: string | undefined;
  3644. /**
  3645. * A textual representation of the certificate's authority information access
  3646. * extension.
  3647. *
  3648. * This is a line feed separated list of access descriptions. Each line begins with
  3649. * the access method and the kind of the access location, followed by a colon and
  3650. * the value associated with the access location.
  3651. *
  3652. * After the prefix denoting the access method and the kind of the access location,
  3653. * the remainder of each line might be enclosed in quotes to indicate that the
  3654. * value is a JSON string literal. For backward compatibility, Node.js only uses
  3655. * JSON string literals within this property when necessary to avoid ambiguity.
  3656. * Third-party code should be prepared to handle both possible entry formats.
  3657. * @since v15.6.0
  3658. */
  3659. readonly infoAccess: string | undefined;
  3660. /**
  3661. * An array detailing the key usages for this certificate.
  3662. * @since v15.6.0
  3663. */
  3664. readonly keyUsage: string[];
  3665. /**
  3666. * The issuer identification included in this certificate.
  3667. * @since v15.6.0
  3668. */
  3669. readonly issuer: string;
  3670. /**
  3671. * The issuer certificate or `undefined` if the issuer certificate is not
  3672. * available.
  3673. * @since v15.9.0
  3674. */
  3675. readonly issuerCertificate?: X509Certificate | undefined;
  3676. /**
  3677. * The public key `KeyObject` for this certificate.
  3678. * @since v15.6.0
  3679. */
  3680. readonly publicKey: KeyObject;
  3681. /**
  3682. * A `Buffer` containing the DER encoding of this certificate.
  3683. * @since v15.6.0
  3684. */
  3685. readonly raw: Buffer;
  3686. /**
  3687. * The serial number of this certificate.
  3688. *
  3689. * Serial numbers are assigned by certificate authorities and do not uniquely
  3690. * identify certificates. Consider using `x509.fingerprint256` as a unique
  3691. * identifier instead.
  3692. * @since v15.6.0
  3693. */
  3694. readonly serialNumber: string;
  3695. /**
  3696. * The date/time from which this certificate is considered valid.
  3697. * @since v15.6.0
  3698. */
  3699. readonly validFrom: string;
  3700. /**
  3701. * The date/time from which this certificate is valid, encapsulated in a `Date` object.
  3702. * @since v22.10.0
  3703. */
  3704. readonly validFromDate: Date;
  3705. /**
  3706. * The date/time until which this certificate is considered valid.
  3707. * @since v15.6.0
  3708. */
  3709. readonly validTo: string;
  3710. /**
  3711. * The date/time until which this certificate is valid, encapsulated in a `Date` object.
  3712. * @since v22.10.0
  3713. */
  3714. readonly validToDate: Date;
  3715. constructor(buffer: BinaryLike);
  3716. /**
  3717. * Checks whether the certificate matches the given email address.
  3718. *
  3719. * If the `'subject'` option is undefined or set to `'default'`, the certificate
  3720. * subject is only considered if the subject alternative name extension either does
  3721. * not exist or does not contain any email addresses.
  3722. *
  3723. * If the `'subject'` option is set to `'always'` and if the subject alternative
  3724. * name extension either does not exist or does not contain a matching email
  3725. * address, the certificate subject is considered.
  3726. *
  3727. * If the `'subject'` option is set to `'never'`, the certificate subject is never
  3728. * considered, even if the certificate contains no subject alternative names.
  3729. * @since v15.6.0
  3730. * @return Returns `email` if the certificate matches, `undefined` if it does not.
  3731. */
  3732. checkEmail(email: string, options?: Pick<X509CheckOptions, "subject">): string | undefined;
  3733. /**
  3734. * Checks whether the certificate matches the given host name.
  3735. *
  3736. * If the certificate matches the given host name, the matching subject name is
  3737. * returned. The returned name might be an exact match (e.g., `foo.example.com`)
  3738. * or it might contain wildcards (e.g., `*.example.com`). Because host name
  3739. * comparisons are case-insensitive, the returned subject name might also differ
  3740. * from the given `name` in capitalization.
  3741. *
  3742. * If the `'subject'` option is undefined or set to `'default'`, the certificate
  3743. * subject is only considered if the subject alternative name extension either does
  3744. * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS").
  3745. *
  3746. * If the `'subject'` option is set to `'always'` and if the subject alternative
  3747. * name extension either does not exist or does not contain a matching DNS name,
  3748. * the certificate subject is considered.
  3749. *
  3750. * If the `'subject'` option is set to `'never'`, the certificate subject is never
  3751. * considered, even if the certificate contains no subject alternative names.
  3752. * @since v15.6.0
  3753. * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`.
  3754. */
  3755. checkHost(name: string, options?: X509CheckOptions): string | undefined;
  3756. /**
  3757. * Checks whether the certificate matches the given IP address (IPv4 or IPv6).
  3758. *
  3759. * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they
  3760. * must match the given `ip` address exactly. Other subject alternative names as
  3761. * well as the subject field of the certificate are ignored.
  3762. * @since v15.6.0
  3763. * @return Returns `ip` if the certificate matches, `undefined` if it does not.
  3764. */
  3765. checkIP(ip: string): string | undefined;
  3766. /**
  3767. * Checks whether this certificate was issued by the given `otherCert`.
  3768. * @since v15.6.0
  3769. */
  3770. checkIssued(otherCert: X509Certificate): boolean;
  3771. /**
  3772. * Checks whether the public key for this certificate is consistent with
  3773. * the given private key.
  3774. * @since v15.6.0
  3775. * @param privateKey A private key.
  3776. */
  3777. checkPrivateKey(privateKey: KeyObject): boolean;
  3778. /**
  3779. * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded
  3780. * certificate.
  3781. * @since v15.6.0
  3782. */
  3783. toJSON(): string;
  3784. /**
  3785. * Returns information about this certificate using the legacy `certificate object` encoding.
  3786. * @since v15.6.0
  3787. */
  3788. toLegacyObject(): PeerCertificate;
  3789. /**
  3790. * Returns the PEM-encoded certificate.
  3791. * @since v15.6.0
  3792. */
  3793. toString(): string;
  3794. /**
  3795. * Verifies that this certificate was signed by the given public key.
  3796. * Does not perform any other validation checks on the certificate.
  3797. * @since v15.6.0
  3798. * @param publicKey A public key.
  3799. */
  3800. verify(publicKey: KeyObject): boolean;
  3801. }
  3802. type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint;
  3803. interface GeneratePrimeOptions {
  3804. add?: LargeNumberLike | undefined;
  3805. rem?: LargeNumberLike | undefined;
  3806. /**
  3807. * @default false
  3808. */
  3809. safe?: boolean | undefined;
  3810. bigint?: boolean | undefined;
  3811. }
  3812. interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions {
  3813. bigint: true;
  3814. }
  3815. interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions {
  3816. bigint?: false | undefined;
  3817. }
  3818. /**
  3819. * Generates a pseudorandom prime of `size` bits.
  3820. *
  3821. * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime.
  3822. *
  3823. * The `options.add` and `options.rem` parameters can be used to enforce additional
  3824. * requirements, e.g., for Diffie-Hellman:
  3825. *
  3826. * * If `options.add` and `options.rem` are both set, the prime will satisfy the
  3827. * condition that `prime % add = rem`.
  3828. * * If only `options.add` is set and `options.safe` is not `true`, the prime will
  3829. * satisfy the condition that `prime % add = 1`.
  3830. * * If only `options.add` is set and `options.safe` is set to `true`, the prime
  3831. * will instead satisfy the condition that `prime % add = 3`. This is necessary
  3832. * because `prime % add = 1` for `options.add > 2` would contradict the condition
  3833. * enforced by `options.safe`.
  3834. * * `options.rem` is ignored if `options.add` is not given.
  3835. *
  3836. * Both `options.add` and `options.rem` must be encoded as big-endian sequences
  3837. * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`.
  3838. *
  3839. * By default, the prime is encoded as a big-endian sequence of octets
  3840. * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
  3841. * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
  3842. * @since v15.8.0
  3843. * @param size The size (in bits) of the prime to generate.
  3844. */
  3845. function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
  3846. function generatePrime(
  3847. size: number,
  3848. options: GeneratePrimeOptionsBigInt,
  3849. callback: (err: Error | null, prime: bigint) => void,
  3850. ): void;
  3851. function generatePrime(
  3852. size: number,
  3853. options: GeneratePrimeOptionsArrayBuffer,
  3854. callback: (err: Error | null, prime: ArrayBuffer) => void,
  3855. ): void;
  3856. function generatePrime(
  3857. size: number,
  3858. options: GeneratePrimeOptions,
  3859. callback: (err: Error | null, prime: ArrayBuffer | bigint) => void,
  3860. ): void;
  3861. /**
  3862. * Generates a pseudorandom prime of `size` bits.
  3863. *
  3864. * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime.
  3865. *
  3866. * The `options.add` and `options.rem` parameters can be used to enforce additional
  3867. * requirements, e.g., for Diffie-Hellman:
  3868. *
  3869. * * If `options.add` and `options.rem` are both set, the prime will satisfy the
  3870. * condition that `prime % add = rem`.
  3871. * * If only `options.add` is set and `options.safe` is not `true`, the prime will
  3872. * satisfy the condition that `prime % add = 1`.
  3873. * * If only `options.add` is set and `options.safe` is set to `true`, the prime
  3874. * will instead satisfy the condition that `prime % add = 3`. This is necessary
  3875. * because `prime % add = 1` for `options.add > 2` would contradict the condition
  3876. * enforced by `options.safe`.
  3877. * * `options.rem` is ignored if `options.add` is not given.
  3878. *
  3879. * Both `options.add` and `options.rem` must be encoded as big-endian sequences
  3880. * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`.
  3881. *
  3882. * By default, the prime is encoded as a big-endian sequence of octets
  3883. * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
  3884. * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
  3885. * @since v15.8.0
  3886. * @param size The size (in bits) of the prime to generate.
  3887. */
  3888. function generatePrimeSync(size: number): ArrayBuffer;
  3889. function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint;
  3890. function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer;
  3891. function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint;
  3892. interface CheckPrimeOptions {
  3893. /**
  3894. * The number of Miller-Rabin probabilistic primality iterations to perform.
  3895. * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input.
  3896. * Care must be used when selecting a number of checks.
  3897. * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details.
  3898. *
  3899. * @default 0
  3900. */
  3901. checks?: number | undefined;
  3902. }
  3903. /**
  3904. * Checks the primality of the `candidate`.
  3905. * @since v15.8.0
  3906. * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
  3907. */
  3908. function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void;
  3909. function checkPrime(
  3910. value: LargeNumberLike,
  3911. options: CheckPrimeOptions,
  3912. callback: (err: Error | null, result: boolean) => void,
  3913. ): void;
  3914. /**
  3915. * Checks the primality of the `candidate`.
  3916. * @since v15.8.0
  3917. * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
  3918. * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.
  3919. */
  3920. function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean;
  3921. /**
  3922. * Load and set the `engine` for some or all OpenSSL functions (selected by flags).
  3923. *
  3924. * `engine` could be either an id or a path to the engine's shared library.
  3925. *
  3926. * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`):
  3927. *
  3928. * * `crypto.constants.ENGINE_METHOD_RSA`
  3929. * * `crypto.constants.ENGINE_METHOD_DSA`
  3930. * * `crypto.constants.ENGINE_METHOD_DH`
  3931. * * `crypto.constants.ENGINE_METHOD_RAND`
  3932. * * `crypto.constants.ENGINE_METHOD_EC`
  3933. * * `crypto.constants.ENGINE_METHOD_CIPHERS`
  3934. * * `crypto.constants.ENGINE_METHOD_DIGESTS`
  3935. * * `crypto.constants.ENGINE_METHOD_PKEY_METHS`
  3936. * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
  3937. * * `crypto.constants.ENGINE_METHOD_ALL`
  3938. * * `crypto.constants.ENGINE_METHOD_NONE`
  3939. * @since v0.11.11
  3940. * @param flags
  3941. */
  3942. function setEngine(engine: string, flags?: number): void;
  3943. /**
  3944. * A convenient alias for {@link webcrypto.getRandomValues}. This
  3945. * implementation is not compliant with the Web Crypto spec, to write
  3946. * web-compatible code use {@link webcrypto.getRandomValues} instead.
  3947. * @since v17.4.0
  3948. * @return Returns `typedArray`.
  3949. */
  3950. function getRandomValues<T extends webcrypto.BufferSource>(typedArray: T): T;
  3951. /**
  3952. * A convenient alias for `crypto.webcrypto.subtle`.
  3953. * @since v17.4.0
  3954. */
  3955. const subtle: webcrypto.SubtleCrypto;
  3956. /**
  3957. * An implementation of the Web Crypto API standard.
  3958. *
  3959. * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details.
  3960. * @since v15.0.0
  3961. */
  3962. const webcrypto: webcrypto.Crypto;
  3963. namespace webcrypto {
  3964. type BufferSource = ArrayBufferView | ArrayBuffer;
  3965. type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
  3966. type KeyType = "private" | "public" | "secret";
  3967. type KeyUsage =
  3968. | "decrypt"
  3969. | "deriveBits"
  3970. | "deriveKey"
  3971. | "encrypt"
  3972. | "sign"
  3973. | "unwrapKey"
  3974. | "verify"
  3975. | "wrapKey";
  3976. type AlgorithmIdentifier = Algorithm | string;
  3977. type HashAlgorithmIdentifier = AlgorithmIdentifier;
  3978. type NamedCurve = string;
  3979. type BigInteger = Uint8Array;
  3980. interface AesCbcParams extends Algorithm {
  3981. iv: BufferSource;
  3982. }
  3983. interface AesCtrParams extends Algorithm {
  3984. counter: BufferSource;
  3985. length: number;
  3986. }
  3987. interface AesDerivedKeyParams extends Algorithm {
  3988. length: number;
  3989. }
  3990. interface AesGcmParams extends Algorithm {
  3991. additionalData?: BufferSource;
  3992. iv: BufferSource;
  3993. tagLength?: number;
  3994. }
  3995. interface AesKeyAlgorithm extends KeyAlgorithm {
  3996. length: number;
  3997. }
  3998. interface AesKeyGenParams extends Algorithm {
  3999. length: number;
  4000. }
  4001. interface Algorithm {
  4002. name: string;
  4003. }
  4004. interface EcKeyAlgorithm extends KeyAlgorithm {
  4005. namedCurve: NamedCurve;
  4006. }
  4007. interface EcKeyGenParams extends Algorithm {
  4008. namedCurve: NamedCurve;
  4009. }
  4010. interface EcKeyImportParams extends Algorithm {
  4011. namedCurve: NamedCurve;
  4012. }
  4013. interface EcdhKeyDeriveParams extends Algorithm {
  4014. public: CryptoKey;
  4015. }
  4016. interface EcdsaParams extends Algorithm {
  4017. hash: HashAlgorithmIdentifier;
  4018. }
  4019. interface Ed448Params extends Algorithm {
  4020. context?: BufferSource;
  4021. }
  4022. interface HkdfParams extends Algorithm {
  4023. hash: HashAlgorithmIdentifier;
  4024. info: BufferSource;
  4025. salt: BufferSource;
  4026. }
  4027. interface HmacImportParams extends Algorithm {
  4028. hash: HashAlgorithmIdentifier;
  4029. length?: number;
  4030. }
  4031. interface HmacKeyAlgorithm extends KeyAlgorithm {
  4032. hash: KeyAlgorithm;
  4033. length: number;
  4034. }
  4035. interface HmacKeyGenParams extends Algorithm {
  4036. hash: HashAlgorithmIdentifier;
  4037. length?: number;
  4038. }
  4039. interface JsonWebKey {
  4040. alg?: string;
  4041. crv?: string;
  4042. d?: string;
  4043. dp?: string;
  4044. dq?: string;
  4045. e?: string;
  4046. ext?: boolean;
  4047. k?: string;
  4048. key_ops?: string[];
  4049. kty?: string;
  4050. n?: string;
  4051. oth?: RsaOtherPrimesInfo[];
  4052. p?: string;
  4053. q?: string;
  4054. qi?: string;
  4055. use?: string;
  4056. x?: string;
  4057. y?: string;
  4058. }
  4059. interface KeyAlgorithm {
  4060. name: string;
  4061. }
  4062. interface Pbkdf2Params extends Algorithm {
  4063. hash: HashAlgorithmIdentifier;
  4064. iterations: number;
  4065. salt: BufferSource;
  4066. }
  4067. interface RsaHashedImportParams extends Algorithm {
  4068. hash: HashAlgorithmIdentifier;
  4069. }
  4070. interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
  4071. hash: KeyAlgorithm;
  4072. }
  4073. interface RsaHashedKeyGenParams extends RsaKeyGenParams {
  4074. hash: HashAlgorithmIdentifier;
  4075. }
  4076. interface RsaKeyAlgorithm extends KeyAlgorithm {
  4077. modulusLength: number;
  4078. publicExponent: BigInteger;
  4079. }
  4080. interface RsaKeyGenParams extends Algorithm {
  4081. modulusLength: number;
  4082. publicExponent: BigInteger;
  4083. }
  4084. interface RsaOaepParams extends Algorithm {
  4085. label?: BufferSource;
  4086. }
  4087. interface RsaOtherPrimesInfo {
  4088. d?: string;
  4089. r?: string;
  4090. t?: string;
  4091. }
  4092. interface RsaPssParams extends Algorithm {
  4093. saltLength: number;
  4094. }
  4095. /**
  4096. * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class.
  4097. * `Crypto` is a singleton that provides access to the remainder of the crypto API.
  4098. * @since v15.0.0
  4099. */
  4100. interface Crypto {
  4101. /**
  4102. * Provides access to the `SubtleCrypto` API.
  4103. * @since v15.0.0
  4104. */
  4105. readonly subtle: SubtleCrypto;
  4106. /**
  4107. * Generates cryptographically strong random values.
  4108. * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned.
  4109. *
  4110. * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted.
  4111. *
  4112. * An error will be thrown if the given `typedArray` is larger than 65,536 bytes.
  4113. * @since v15.0.0
  4114. */
  4115. getRandomValues<T extends Exclude<NodeJS.TypedArray, Float32Array | Float64Array>>(typedArray: T): T;
  4116. /**
  4117. * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID.
  4118. * The UUID is generated using a cryptographic pseudorandom number generator.
  4119. * @since v16.7.0
  4120. */
  4121. randomUUID(): UUID;
  4122. CryptoKey: CryptoKeyConstructor;
  4123. }
  4124. // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable.
  4125. interface CryptoKeyConstructor {
  4126. /** Illegal constructor */
  4127. (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user.
  4128. readonly length: 0;
  4129. readonly name: "CryptoKey";
  4130. readonly prototype: CryptoKey;
  4131. }
  4132. /**
  4133. * @since v15.0.0
  4134. */
  4135. interface CryptoKey {
  4136. /**
  4137. * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters.
  4138. * @since v15.0.0
  4139. */
  4140. readonly algorithm: KeyAlgorithm;
  4141. /**
  4142. * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`.
  4143. * @since v15.0.0
  4144. */
  4145. readonly extractable: boolean;
  4146. /**
  4147. * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key.
  4148. * @since v15.0.0
  4149. */
  4150. readonly type: KeyType;
  4151. /**
  4152. * An array of strings identifying the operations for which the key may be used.
  4153. *
  4154. * The possible usages are:
  4155. * - `'encrypt'` - The key may be used to encrypt data.
  4156. * - `'decrypt'` - The key may be used to decrypt data.
  4157. * - `'sign'` - The key may be used to generate digital signatures.
  4158. * - `'verify'` - The key may be used to verify digital signatures.
  4159. * - `'deriveKey'` - The key may be used to derive a new key.
  4160. * - `'deriveBits'` - The key may be used to derive bits.
  4161. * - `'wrapKey'` - The key may be used to wrap another key.
  4162. * - `'unwrapKey'` - The key may be used to unwrap another key.
  4163. *
  4164. * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`).
  4165. * @since v15.0.0
  4166. */
  4167. readonly usages: KeyUsage[];
  4168. }
  4169. /**
  4170. * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair.
  4171. * @since v15.0.0
  4172. */
  4173. interface CryptoKeyPair {
  4174. /**
  4175. * A {@link CryptoKey} whose type will be `'private'`.
  4176. * @since v15.0.0
  4177. */
  4178. privateKey: CryptoKey;
  4179. /**
  4180. * A {@link CryptoKey} whose type will be `'public'`.
  4181. * @since v15.0.0
  4182. */
  4183. publicKey: CryptoKey;
  4184. }
  4185. /**
  4186. * @since v15.0.0
  4187. */
  4188. interface SubtleCrypto {
  4189. /**
  4190. * Using the method and parameters specified in `algorithm` and the keying material provided by `key`,
  4191. * `subtle.decrypt()` attempts to decipher the provided `data`. If successful,
  4192. * the returned promise will be resolved with an `<ArrayBuffer>` containing the plaintext result.
  4193. *
  4194. * The algorithms currently supported include:
  4195. *
  4196. * - `'RSA-OAEP'`
  4197. * - `'AES-CTR'`
  4198. * - `'AES-CBC'`
  4199. * - `'AES-GCM'`
  4200. * @since v15.0.0
  4201. */
  4202. decrypt(
  4203. algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
  4204. key: CryptoKey,
  4205. data: BufferSource,
  4206. ): Promise<ArrayBuffer>;
  4207. /**
  4208. * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`,
  4209. * `subtle.deriveBits()` attempts to generate `length` bits.
  4210. * The Node.js implementation requires that when `length` is a number it must be multiple of `8`.
  4211. * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed
  4212. * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms.
  4213. * If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the generated data.
  4214. *
  4215. * The algorithms currently supported include:
  4216. *
  4217. * - `'ECDH'`
  4218. * - `'X25519'`
  4219. * - `'X448'`
  4220. * - `'HKDF'`
  4221. * - `'PBKDF2'`
  4222. * @since v15.0.0
  4223. */
  4224. deriveBits(
  4225. algorithm: EcdhKeyDeriveParams,
  4226. baseKey: CryptoKey,
  4227. length?: number | null,
  4228. ): Promise<ArrayBuffer>;
  4229. deriveBits(
  4230. algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
  4231. baseKey: CryptoKey,
  4232. length: number,
  4233. ): Promise<ArrayBuffer>;
  4234. /**
  4235. * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`,
  4236. * `subtle.deriveKey()` attempts to generate a new <CryptoKey>` based on the method and parameters in `derivedKeyAlgorithm`.
  4237. *
  4238. * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material,
  4239. * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input.
  4240. *
  4241. * The algorithms currently supported include:
  4242. *
  4243. * - `'ECDH'`
  4244. * - `'X25519'`
  4245. * - `'X448'`
  4246. * - `'HKDF'`
  4247. * - `'PBKDF2'`
  4248. * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
  4249. * @since v15.0.0
  4250. */
  4251. deriveKey(
  4252. algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
  4253. baseKey: CryptoKey,
  4254. derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams,
  4255. extractable: boolean,
  4256. keyUsages: readonly KeyUsage[],
  4257. ): Promise<CryptoKey>;
  4258. /**
  4259. * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`.
  4260. * If successful, the returned promise is resolved with an `<ArrayBuffer>` containing the computed digest.
  4261. *
  4262. * If `algorithm` is provided as a `<string>`, it must be one of:
  4263. *
  4264. * - `'SHA-1'`
  4265. * - `'SHA-256'`
  4266. * - `'SHA-384'`
  4267. * - `'SHA-512'`
  4268. *
  4269. * If `algorithm` is provided as an `<Object>`, it must have a `name` property whose value is one of the above.
  4270. * @since v15.0.0
  4271. */
  4272. digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;
  4273. /**
  4274. * Using the method and parameters specified by `algorithm` and the keying material provided by `key`,
  4275. * `subtle.encrypt()` attempts to encipher `data`. If successful,
  4276. * the returned promise is resolved with an `<ArrayBuffer>` containing the encrypted result.
  4277. *
  4278. * The algorithms currently supported include:
  4279. *
  4280. * - `'RSA-OAEP'`
  4281. * - `'AES-CTR'`
  4282. * - `'AES-CBC'`
  4283. * - `'AES-GCM'`
  4284. * @since v15.0.0
  4285. */
  4286. encrypt(
  4287. algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
  4288. key: CryptoKey,
  4289. data: BufferSource,
  4290. ): Promise<ArrayBuffer>;
  4291. /**
  4292. * Exports the given key into the specified format, if supported.
  4293. *
  4294. * If the `<CryptoKey>` is not extractable, the returned promise will reject.
  4295. *
  4296. * When `format` is either `'pkcs8'` or `'spki'` and the export is successful,
  4297. * the returned promise will be resolved with an `<ArrayBuffer>` containing the exported key data.
  4298. *
  4299. * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a
  4300. * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification.
  4301. * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
  4302. * @returns `<Promise>` containing `<ArrayBuffer>`.
  4303. * @since v15.0.0
  4304. */
  4305. exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
  4306. exportKey(format: Exclude<KeyFormat, "jwk">, key: CryptoKey): Promise<ArrayBuffer>;
  4307. /**
  4308. * Using the method and parameters provided in `algorithm`,
  4309. * `subtle.generateKey()` attempts to generate new keying material.
  4310. * Depending the method used, the method may generate either a single `<CryptoKey>` or a `<CryptoKeyPair>`.
  4311. *
  4312. * The `<CryptoKeyPair>` (public and private key) generating algorithms supported include:
  4313. *
  4314. * - `'RSASSA-PKCS1-v1_5'`
  4315. * - `'RSA-PSS'`
  4316. * - `'RSA-OAEP'`
  4317. * - `'ECDSA'`
  4318. * - `'Ed25519'`
  4319. * - `'Ed448'`
  4320. * - `'ECDH'`
  4321. * - `'X25519'`
  4322. * - `'X448'`
  4323. * The `<CryptoKey>` (secret key) generating algorithms supported include:
  4324. *
  4325. * - `'HMAC'`
  4326. * - `'AES-CTR'`
  4327. * - `'AES-CBC'`
  4328. * - `'AES-GCM'`
  4329. * - `'AES-KW'`
  4330. * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
  4331. * @since v15.0.0
  4332. */
  4333. generateKey(
  4334. algorithm: RsaHashedKeyGenParams | EcKeyGenParams,
  4335. extractable: boolean,
  4336. keyUsages: readonly KeyUsage[],
  4337. ): Promise<CryptoKeyPair>;
  4338. generateKey(
  4339. algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params,
  4340. extractable: boolean,
  4341. keyUsages: readonly KeyUsage[],
  4342. ): Promise<CryptoKey>;
  4343. generateKey(
  4344. algorithm: AlgorithmIdentifier,
  4345. extractable: boolean,
  4346. keyUsages: KeyUsage[],
  4347. ): Promise<CryptoKeyPair | CryptoKey>;
  4348. /**
  4349. * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format`
  4350. * to create a `<CryptoKey>` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments.
  4351. * If the import is successful, the returned promise will be resolved with the created `<CryptoKey>`.
  4352. *
  4353. * If importing a `'PBKDF2'` key, `extractable` must be `false`.
  4354. * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
  4355. * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
  4356. * @since v15.0.0
  4357. */
  4358. importKey(
  4359. format: "jwk",
  4360. keyData: JsonWebKey,
  4361. algorithm:
  4362. | AlgorithmIdentifier
  4363. | RsaHashedImportParams
  4364. | EcKeyImportParams
  4365. | HmacImportParams
  4366. | AesKeyAlgorithm,
  4367. extractable: boolean,
  4368. keyUsages: readonly KeyUsage[],
  4369. ): Promise<CryptoKey>;
  4370. importKey(
  4371. format: Exclude<KeyFormat, "jwk">,
  4372. keyData: BufferSource,
  4373. algorithm:
  4374. | AlgorithmIdentifier
  4375. | RsaHashedImportParams
  4376. | EcKeyImportParams
  4377. | HmacImportParams
  4378. | AesKeyAlgorithm,
  4379. extractable: boolean,
  4380. keyUsages: KeyUsage[],
  4381. ): Promise<CryptoKey>;
  4382. /**
  4383. * Using the method and parameters given by `algorithm` and the keying material provided by `key`,
  4384. * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful,
  4385. * the returned promise is resolved with an `<ArrayBuffer>` containing the generated signature.
  4386. *
  4387. * The algorithms currently supported include:
  4388. *
  4389. * - `'RSASSA-PKCS1-v1_5'`
  4390. * - `'RSA-PSS'`
  4391. * - `'ECDSA'`
  4392. * - `'Ed25519'`
  4393. * - `'Ed448'`
  4394. * - `'HMAC'`
  4395. * @since v15.0.0
  4396. */
  4397. sign(
  4398. algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params,
  4399. key: CryptoKey,
  4400. data: BufferSource,
  4401. ): Promise<ArrayBuffer>;
  4402. /**
  4403. * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
  4404. * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `<CryptoKey>` instance.
  4405. * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input)
  4406. * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs.
  4407. * If successful, the returned promise is resolved with a `<CryptoKey>` object.
  4408. *
  4409. * The wrapping algorithms currently supported include:
  4410. *
  4411. * - `'RSA-OAEP'`
  4412. * - `'AES-CTR'`
  4413. * - `'AES-CBC'`
  4414. * - `'AES-GCM'`
  4415. * - `'AES-KW'`
  4416. *
  4417. * The unwrapped key algorithms supported include:
  4418. *
  4419. * - `'RSASSA-PKCS1-v1_5'`
  4420. * - `'RSA-PSS'`
  4421. * - `'RSA-OAEP'`
  4422. * - `'ECDSA'`
  4423. * - `'Ed25519'`
  4424. * - `'Ed448'`
  4425. * - `'ECDH'`
  4426. * - `'X25519'`
  4427. * - `'X448'`
  4428. * - `'HMAC'`
  4429. * - `'AES-CTR'`
  4430. * - `'AES-CBC'`
  4431. * - `'AES-GCM'`
  4432. * - `'AES-KW'`
  4433. * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
  4434. * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
  4435. * @since v15.0.0
  4436. */
  4437. unwrapKey(
  4438. format: KeyFormat,
  4439. wrappedKey: BufferSource,
  4440. unwrappingKey: CryptoKey,
  4441. unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
  4442. unwrappedKeyAlgorithm:
  4443. | AlgorithmIdentifier
  4444. | RsaHashedImportParams
  4445. | EcKeyImportParams
  4446. | HmacImportParams
  4447. | AesKeyAlgorithm,
  4448. extractable: boolean,
  4449. keyUsages: KeyUsage[],
  4450. ): Promise<CryptoKey>;
  4451. /**
  4452. * Using the method and parameters given in `algorithm` and the keying material provided by `key`,
  4453. * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`.
  4454. * The returned promise is resolved with either `true` or `false`.
  4455. *
  4456. * The algorithms currently supported include:
  4457. *
  4458. * - `'RSASSA-PKCS1-v1_5'`
  4459. * - `'RSA-PSS'`
  4460. * - `'ECDSA'`
  4461. * - `'Ed25519'`
  4462. * - `'Ed448'`
  4463. * - `'HMAC'`
  4464. * @since v15.0.0
  4465. */
  4466. verify(
  4467. algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params,
  4468. key: CryptoKey,
  4469. signature: BufferSource,
  4470. data: BufferSource,
  4471. ): Promise<boolean>;
  4472. /**
  4473. * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
  4474. * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`,
  4475. * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`.
  4476. * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments,
  4477. * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs.
  4478. * If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the encrypted key data.
  4479. *
  4480. * The wrapping algorithms currently supported include:
  4481. *
  4482. * - `'RSA-OAEP'`
  4483. * - `'AES-CTR'`
  4484. * - `'AES-CBC'`
  4485. * - `'AES-GCM'`
  4486. * - `'AES-KW'`
  4487. * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
  4488. * @since v15.0.0
  4489. */
  4490. wrapKey(
  4491. format: KeyFormat,
  4492. key: CryptoKey,
  4493. wrappingKey: CryptoKey,
  4494. wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
  4495. ): Promise<ArrayBuffer>;
  4496. }
  4497. }
  4498. global {
  4499. var crypto: typeof globalThis extends {
  4500. crypto: infer T;
  4501. onmessage: any;
  4502. } ? T
  4503. : webcrypto.Crypto;
  4504. }
  4505. }
  4506. declare module "node:crypto" {
  4507. export * from "crypto";
  4508. }