jsencrypt.js 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351
  1. /*! JSEncrypt v2.3.1 | https://npmcdn.com/jsencrypt@2.3.1/LICENSE.txt */
  2. (function (root, factory) {
  3. if (typeof define === 'function' && define.amd) {
  4. // AMD
  5. define(['exports'], factory);
  6. } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
  7. // Node, CommonJS-like
  8. factory(module.exports);
  9. } else {
  10. factory(root);
  11. }
  12. })(this, function (exports) {
  13. // Copyright (c) 2005 Tom Wu
  14. // All Rights Reserved.
  15. // See "LICENSE" for details.
  16. // Basic JavaScript BN library - subset useful for RSA encryption.
  17. // Bits per digit
  18. var dbits;
  19. // JavaScript engine analysis
  20. var canary = 0xdeadbeefcafe;
  21. var j_lm = ((canary&0xffffff)==0xefcafe);
  22. // (public) Constructor
  23. function BigInteger(a,b,c) {
  24. if(a != null)
  25. if("number" == typeof a) this.fromNumber(a,b,c);
  26. else if(b == null && "string" != typeof a) this.fromString(a,256);
  27. else this.fromString(a,b);
  28. }
  29. // return new, unset BigInteger
  30. function nbi() { return new BigInteger(null); }
  31. // am: Compute w_j += (x*this_i), propagate carries,
  32. // c is initial carry, returns final carry.
  33. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  34. // We need to select the fastest one that works in this environment.
  35. // am1: use a single mult and divide to get the high bits,
  36. // max digit bits should be 26 because
  37. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  38. function am1(i,x,w,j,c,n) {
  39. while(--n >= 0) {
  40. var v = x*this[i++]+w[j]+c;
  41. c = Math.floor(v/0x4000000);
  42. w[j++] = v&0x3ffffff;
  43. }
  44. return c;
  45. }
  46. // am2 avoids a big mult-and-extract completely.
  47. // Max digit bits should be <= 30 because we do bitwise ops
  48. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  49. function am2(i,x,w,j,c,n) {
  50. var xl = x&0x7fff, xh = x>>15;
  51. while(--n >= 0) {
  52. var l = this[i]&0x7fff;
  53. var h = this[i++]>>15;
  54. var m = xh*l+h*xl;
  55. l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
  56. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  57. w[j++] = l&0x3fffffff;
  58. }
  59. return c;
  60. }
  61. // Alternately, set max digit bits to 28 since some
  62. // browsers slow down when dealing with 32-bit numbers.
  63. function am3(i,x,w,j,c,n) {
  64. var xl = x&0x3fff, xh = x>>14;
  65. while(--n >= 0) {
  66. var l = this[i]&0x3fff;
  67. var h = this[i++]>>14;
  68. var m = xh*l+h*xl;
  69. l = xl*l+((m&0x3fff)<<14)+w[j]+c;
  70. c = (l>>28)+(m>>14)+xh*h;
  71. w[j++] = l&0xfffffff;
  72. }
  73. return c;
  74. }
  75. if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
  76. BigInteger.prototype.am = am2;
  77. dbits = 30;
  78. }
  79. else if(j_lm && (navigator.appName != "Netscape")) {
  80. BigInteger.prototype.am = am1;
  81. dbits = 26;
  82. }
  83. else { // Mozilla/Netscape seems to prefer am3
  84. BigInteger.prototype.am = am3;
  85. dbits = 28;
  86. }
  87. BigInteger.prototype.DB = dbits;
  88. BigInteger.prototype.DM = ((1<<dbits)-1);
  89. BigInteger.prototype.DV = (1<<dbits);
  90. var BI_FP = 52;
  91. BigInteger.prototype.FV = Math.pow(2,BI_FP);
  92. BigInteger.prototype.F1 = BI_FP-dbits;
  93. BigInteger.prototype.F2 = 2*dbits-BI_FP;
  94. // Digit conversions
  95. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  96. var BI_RC = new Array();
  97. var rr,vv;
  98. rr = "0".charCodeAt(0);
  99. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  100. rr = "a".charCodeAt(0);
  101. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  102. rr = "A".charCodeAt(0);
  103. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  104. function int2char(n) { return BI_RM.charAt(n); }
  105. function intAt(s,i) {
  106. var c = BI_RC[s.charCodeAt(i)];
  107. return (c==null)?-1:c;
  108. }
  109. // (protected) copy this to r
  110. function bnpCopyTo(r) {
  111. for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
  112. r.t = this.t;
  113. r.s = this.s;
  114. }
  115. // (protected) set from integer value x, -DV <= x < DV
  116. function bnpFromInt(x) {
  117. this.t = 1;
  118. this.s = (x<0)?-1:0;
  119. if(x > 0) this[0] = x;
  120. else if(x < -1) this[0] = x+this.DV;
  121. else this.t = 0;
  122. }
  123. // return bigint initialized to value
  124. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  125. // (protected) set from string and radix
  126. function bnpFromString(s,b) {
  127. var k;
  128. if(b == 16) k = 4;
  129. else if(b == 8) k = 3;
  130. else if(b == 256) k = 8; // byte array
  131. else if(b == 2) k = 1;
  132. else if(b == 32) k = 5;
  133. else if(b == 4) k = 2;
  134. else { this.fromRadix(s,b); return; }
  135. this.t = 0;
  136. this.s = 0;
  137. var i = s.length, mi = false, sh = 0;
  138. while(--i >= 0) {
  139. var x = (k==8)?s[i]&0xff:intAt(s,i);
  140. if(x < 0) {
  141. if(s.charAt(i) == "-") mi = true;
  142. continue;
  143. }
  144. mi = false;
  145. if(sh == 0)
  146. this[this.t++] = x;
  147. else if(sh+k > this.DB) {
  148. this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
  149. this[this.t++] = (x>>(this.DB-sh));
  150. }
  151. else
  152. this[this.t-1] |= x<<sh;
  153. sh += k;
  154. if(sh >= this.DB) sh -= this.DB;
  155. }
  156. if(k == 8 && (s[0]&0x80) != 0) {
  157. this.s = -1;
  158. if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  159. }
  160. this.clamp();
  161. if(mi) BigInteger.ZERO.subTo(this,this);
  162. }
  163. // (protected) clamp off excess high words
  164. function bnpClamp() {
  165. var c = this.s&this.DM;
  166. while(this.t > 0 && this[this.t-1] == c) --this.t;
  167. }
  168. // (public) return string representation in given radix
  169. function bnToString(b) {
  170. if(this.s < 0) return "-"+this.negate().toString(b);
  171. var k;
  172. if(b == 16) k = 4;
  173. else if(b == 8) k = 3;
  174. else if(b == 2) k = 1;
  175. else if(b == 32) k = 5;
  176. else if(b == 4) k = 2;
  177. else return this.toRadix(b);
  178. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  179. var p = this.DB-(i*this.DB)%k;
  180. if(i-- > 0) {
  181. if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
  182. while(i >= 0) {
  183. if(p < k) {
  184. d = (this[i]&((1<<p)-1))<<(k-p);
  185. d |= this[--i]>>(p+=this.DB-k);
  186. }
  187. else {
  188. d = (this[i]>>(p-=k))&km;
  189. if(p <= 0) { p += this.DB; --i; }
  190. }
  191. if(d > 0) m = true;
  192. if(m) r += int2char(d);
  193. }
  194. }
  195. return m?r:"0";
  196. }
  197. // (public) -this
  198. function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
  199. // (public) |this|
  200. function bnAbs() { return (this.s<0)?this.negate():this; }
  201. // (public) return + if this > a, - if this < a, 0 if equal
  202. function bnCompareTo(a) {
  203. var r = this.s-a.s;
  204. if(r != 0) return r;
  205. var i = this.t;
  206. r = i-a.t;
  207. if(r != 0) return (this.s<0)?-r:r;
  208. while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
  209. return 0;
  210. }
  211. // returns bit length of the integer x
  212. function nbits(x) {
  213. var r = 1, t;
  214. if((t=x>>>16) != 0) { x = t; r += 16; }
  215. if((t=x>>8) != 0) { x = t; r += 8; }
  216. if((t=x>>4) != 0) { x = t; r += 4; }
  217. if((t=x>>2) != 0) { x = t; r += 2; }
  218. if((t=x>>1) != 0) { x = t; r += 1; }
  219. return r;
  220. }
  221. // (public) return the number of bits in "this"
  222. function bnBitLength() {
  223. if(this.t <= 0) return 0;
  224. return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
  225. }
  226. // (protected) r = this << n*DB
  227. function bnpDLShiftTo(n,r) {
  228. var i;
  229. for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
  230. for(i = n-1; i >= 0; --i) r[i] = 0;
  231. r.t = this.t+n;
  232. r.s = this.s;
  233. }
  234. // (protected) r = this >> n*DB
  235. function bnpDRShiftTo(n,r) {
  236. for(var i = n; i < this.t; ++i) r[i-n] = this[i];
  237. r.t = Math.max(this.t-n,0);
  238. r.s = this.s;
  239. }
  240. // (protected) r = this << n
  241. function bnpLShiftTo(n,r) {
  242. var bs = n%this.DB;
  243. var cbs = this.DB-bs;
  244. var bm = (1<<cbs)-1;
  245. var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  246. for(i = this.t-1; i >= 0; --i) {
  247. r[i+ds+1] = (this[i]>>cbs)|c;
  248. c = (this[i]&bm)<<bs;
  249. }
  250. for(i = ds-1; i >= 0; --i) r[i] = 0;
  251. r[ds] = c;
  252. r.t = this.t+ds+1;
  253. r.s = this.s;
  254. r.clamp();
  255. }
  256. // (protected) r = this >> n
  257. function bnpRShiftTo(n,r) {
  258. r.s = this.s;
  259. var ds = Math.floor(n/this.DB);
  260. if(ds >= this.t) { r.t = 0; return; }
  261. var bs = n%this.DB;
  262. var cbs = this.DB-bs;
  263. var bm = (1<<bs)-1;
  264. r[0] = this[ds]>>bs;
  265. for(var i = ds+1; i < this.t; ++i) {
  266. r[i-ds-1] |= (this[i]&bm)<<cbs;
  267. r[i-ds] = this[i]>>bs;
  268. }
  269. if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
  270. r.t = this.t-ds;
  271. r.clamp();
  272. }
  273. // (protected) r = this - a
  274. function bnpSubTo(a,r) {
  275. var i = 0, c = 0, m = Math.min(a.t,this.t);
  276. while(i < m) {
  277. c += this[i]-a[i];
  278. r[i++] = c&this.DM;
  279. c >>= this.DB;
  280. }
  281. if(a.t < this.t) {
  282. c -= a.s;
  283. while(i < this.t) {
  284. c += this[i];
  285. r[i++] = c&this.DM;
  286. c >>= this.DB;
  287. }
  288. c += this.s;
  289. }
  290. else {
  291. c += this.s;
  292. while(i < a.t) {
  293. c -= a[i];
  294. r[i++] = c&this.DM;
  295. c >>= this.DB;
  296. }
  297. c -= a.s;
  298. }
  299. r.s = (c<0)?-1:0;
  300. if(c < -1) r[i++] = this.DV+c;
  301. else if(c > 0) r[i++] = c;
  302. r.t = i;
  303. r.clamp();
  304. }
  305. // (protected) r = this * a, r != this,a (HAC 14.12)
  306. // "this" should be the larger one if appropriate.
  307. function bnpMultiplyTo(a,r) {
  308. var x = this.abs(), y = a.abs();
  309. var i = x.t;
  310. r.t = i+y.t;
  311. while(--i >= 0) r[i] = 0;
  312. for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
  313. r.s = 0;
  314. r.clamp();
  315. if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
  316. }
  317. // (protected) r = this^2, r != this (HAC 14.16)
  318. function bnpSquareTo(r) {
  319. var x = this.abs();
  320. var i = r.t = 2*x.t;
  321. while(--i >= 0) r[i] = 0;
  322. for(i = 0; i < x.t-1; ++i) {
  323. var c = x.am(i,x[i],r,2*i,0,1);
  324. if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
  325. r[i+x.t] -= x.DV;
  326. r[i+x.t+1] = 1;
  327. }
  328. }
  329. if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
  330. r.s = 0;
  331. r.clamp();
  332. }
  333. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  334. // r != q, this != m. q or r may be null.
  335. function bnpDivRemTo(m,q,r) {
  336. var pm = m.abs();
  337. if(pm.t <= 0) return;
  338. var pt = this.abs();
  339. if(pt.t < pm.t) {
  340. if(q != null) q.fromInt(0);
  341. if(r != null) this.copyTo(r);
  342. return;
  343. }
  344. if(r == null) r = nbi();
  345. var y = nbi(), ts = this.s, ms = m.s;
  346. var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
  347. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
  348. else { pm.copyTo(y); pt.copyTo(r); }
  349. var ys = y.t;
  350. var y0 = y[ys-1];
  351. if(y0 == 0) return;
  352. var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
  353. var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  354. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  355. y.dlShiftTo(j,t);
  356. if(r.compareTo(t) >= 0) {
  357. r[r.t++] = 1;
  358. r.subTo(t,r);
  359. }
  360. BigInteger.ONE.dlShiftTo(ys,t);
  361. t.subTo(y,y); // "negative" y so we can replace sub with am later
  362. while(y.t < ys) y[y.t++] = 0;
  363. while(--j >= 0) {
  364. // Estimate quotient digit
  365. var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
  366. if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  367. y.dlShiftTo(j,t);
  368. r.subTo(t,r);
  369. while(r[i] < --qd) r.subTo(t,r);
  370. }
  371. }
  372. if(q != null) {
  373. r.drShiftTo(ys,q);
  374. if(ts != ms) BigInteger.ZERO.subTo(q,q);
  375. }
  376. r.t = ys;
  377. r.clamp();
  378. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  379. if(ts < 0) BigInteger.ZERO.subTo(r,r);
  380. }
  381. // (public) this mod a
  382. function bnMod(a) {
  383. var r = nbi();
  384. this.abs().divRemTo(a,null,r);
  385. if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
  386. return r;
  387. }
  388. // Modular reduction using "classic" algorithm
  389. function Classic(m) { this.m = m; }
  390. function cConvert(x) {
  391. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  392. else return x;
  393. }
  394. function cRevert(x) { return x; }
  395. function cReduce(x) { x.divRemTo(this.m,null,x); }
  396. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  397. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  398. Classic.prototype.convert = cConvert;
  399. Classic.prototype.revert = cRevert;
  400. Classic.prototype.reduce = cReduce;
  401. Classic.prototype.mulTo = cMulTo;
  402. Classic.prototype.sqrTo = cSqrTo;
  403. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  404. // justification:
  405. // xy == 1 (mod m)
  406. // xy = 1+km
  407. // xy(2-xy) = (1+km)(1-km)
  408. // x[y(2-xy)] = 1-k^2m^2
  409. // x[y(2-xy)] == 1 (mod m^2)
  410. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  411. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  412. // JS multiply "overflows" differently from C/C++, so care is needed here.
  413. function bnpInvDigit() {
  414. if(this.t < 1) return 0;
  415. var x = this[0];
  416. if((x&1) == 0) return 0;
  417. var y = x&3; // y == 1/x mod 2^2
  418. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  419. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  420. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  421. // last step - calculate inverse mod DV directly;
  422. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  423. y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
  424. // we really want the negative inverse, and -DV < y < DV
  425. return (y>0)?this.DV-y:-y;
  426. }
  427. // Montgomery reduction
  428. function Montgomery(m) {
  429. this.m = m;
  430. this.mp = m.invDigit();
  431. this.mpl = this.mp&0x7fff;
  432. this.mph = this.mp>>15;
  433. this.um = (1<<(m.DB-15))-1;
  434. this.mt2 = 2*m.t;
  435. }
  436. // xR mod m
  437. function montConvert(x) {
  438. var r = nbi();
  439. x.abs().dlShiftTo(this.m.t,r);
  440. r.divRemTo(this.m,null,r);
  441. if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
  442. return r;
  443. }
  444. // x/R mod m
  445. function montRevert(x) {
  446. var r = nbi();
  447. x.copyTo(r);
  448. this.reduce(r);
  449. return r;
  450. }
  451. // x = x/R mod m (HAC 14.32)
  452. function montReduce(x) {
  453. while(x.t <= this.mt2) // pad x so am has enough room later
  454. x[x.t++] = 0;
  455. for(var i = 0; i < this.m.t; ++i) {
  456. // faster way of calculating u0 = x[i]*mp mod DV
  457. var j = x[i]&0x7fff;
  458. var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
  459. // use am to combine the multiply-shift-add into one call
  460. j = i+this.m.t;
  461. x[j] += this.m.am(0,u0,x,i,0,this.m.t);
  462. // propagate carry
  463. while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
  464. }
  465. x.clamp();
  466. x.drShiftTo(this.m.t,x);
  467. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  468. }
  469. // r = "x^2/R mod m"; x != r
  470. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  471. // r = "xy/R mod m"; x,y != r
  472. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  473. Montgomery.prototype.convert = montConvert;
  474. Montgomery.prototype.revert = montRevert;
  475. Montgomery.prototype.reduce = montReduce;
  476. Montgomery.prototype.mulTo = montMulTo;
  477. Montgomery.prototype.sqrTo = montSqrTo;
  478. // (protected) true iff this is even
  479. function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
  480. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  481. function bnpExp(e,z) {
  482. if(e > 0xffffffff || e < 1) return BigInteger.ONE;
  483. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  484. g.copyTo(r);
  485. while(--i >= 0) {
  486. z.sqrTo(r,r2);
  487. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  488. else { var t = r; r = r2; r2 = t; }
  489. }
  490. return z.revert(r);
  491. }
  492. // (public) this^e % m, 0 <= e < 2^32
  493. function bnModPowInt(e,m) {
  494. var z;
  495. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  496. return this.exp(e,z);
  497. }
  498. // protected
  499. BigInteger.prototype.copyTo = bnpCopyTo;
  500. BigInteger.prototype.fromInt = bnpFromInt;
  501. BigInteger.prototype.fromString = bnpFromString;
  502. BigInteger.prototype.clamp = bnpClamp;
  503. BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  504. BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  505. BigInteger.prototype.lShiftTo = bnpLShiftTo;
  506. BigInteger.prototype.rShiftTo = bnpRShiftTo;
  507. BigInteger.prototype.subTo = bnpSubTo;
  508. BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  509. BigInteger.prototype.squareTo = bnpSquareTo;
  510. BigInteger.prototype.divRemTo = bnpDivRemTo;
  511. BigInteger.prototype.invDigit = bnpInvDigit;
  512. BigInteger.prototype.isEven = bnpIsEven;
  513. BigInteger.prototype.exp = bnpExp;
  514. // public
  515. BigInteger.prototype.toString = bnToString;
  516. BigInteger.prototype.negate = bnNegate;
  517. BigInteger.prototype.abs = bnAbs;
  518. BigInteger.prototype.compareTo = bnCompareTo;
  519. BigInteger.prototype.bitLength = bnBitLength;
  520. BigInteger.prototype.mod = bnMod;
  521. BigInteger.prototype.modPowInt = bnModPowInt;
  522. // "constants"
  523. BigInteger.ZERO = nbv(0);
  524. BigInteger.ONE = nbv(1);
  525. // Copyright (c) 2005-2009 Tom Wu
  526. // All Rights Reserved.
  527. // See "LICENSE" for details.
  528. // Extended JavaScript BN functions, required for RSA private ops.
  529. // Version 1.1: new BigInteger("0", 10) returns "proper" zero
  530. // Version 1.2: square() API, isProbablePrime fix
  531. // (public)
  532. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  533. // (public) return value as integer
  534. function bnIntValue() {
  535. if(this.s < 0) {
  536. if(this.t == 1) return this[0]-this.DV;
  537. else if(this.t == 0) return -1;
  538. }
  539. else if(this.t == 1) return this[0];
  540. else if(this.t == 0) return 0;
  541. // assumes 16 < DB < 32
  542. return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
  543. }
  544. // (public) return value as byte
  545. function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
  546. // (public) return value as short (assumes DB>=16)
  547. function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
  548. // (protected) return x s.t. r^x < DV
  549. function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
  550. // (public) 0 if this == 0, 1 if this > 0
  551. function bnSigNum() {
  552. if(this.s < 0) return -1;
  553. else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
  554. else return 1;
  555. }
  556. // (protected) convert to radix string
  557. function bnpToRadix(b) {
  558. if(b == null) b = 10;
  559. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  560. var cs = this.chunkSize(b);
  561. var a = Math.pow(b,cs);
  562. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  563. this.divRemTo(d,y,z);
  564. while(y.signum() > 0) {
  565. r = (a+z.intValue()).toString(b).substr(1) + r;
  566. y.divRemTo(d,y,z);
  567. }
  568. return z.intValue().toString(b) + r;
  569. }
  570. // (protected) convert from radix string
  571. function bnpFromRadix(s,b) {
  572. this.fromInt(0);
  573. if(b == null) b = 10;
  574. var cs = this.chunkSize(b);
  575. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  576. for(var i = 0; i < s.length; ++i) {
  577. var x = intAt(s,i);
  578. if(x < 0) {
  579. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  580. continue;
  581. }
  582. w = b*w+x;
  583. if(++j >= cs) {
  584. this.dMultiply(d);
  585. this.dAddOffset(w,0);
  586. j = 0;
  587. w = 0;
  588. }
  589. }
  590. if(j > 0) {
  591. this.dMultiply(Math.pow(b,j));
  592. this.dAddOffset(w,0);
  593. }
  594. if(mi) BigInteger.ZERO.subTo(this,this);
  595. }
  596. // (protected) alternate constructor
  597. function bnpFromNumber(a,b,c) {
  598. if("number" == typeof b) {
  599. // new BigInteger(int,int,RNG)
  600. if(a < 2) this.fromInt(1);
  601. else {
  602. this.fromNumber(a,c);
  603. if(!this.testBit(a-1)) // force MSB set
  604. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  605. if(this.isEven()) this.dAddOffset(1,0); // force odd
  606. while(!this.isProbablePrime(b)) {
  607. this.dAddOffset(2,0);
  608. if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
  609. }
  610. }
  611. }
  612. else {
  613. // new BigInteger(int,RNG)
  614. var x = new Array(), t = a&7;
  615. x.length = (a>>3)+1;
  616. b.nextBytes(x);
  617. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  618. this.fromString(x,256);
  619. }
  620. }
  621. // (public) convert to bigendian byte array
  622. function bnToByteArray() {
  623. var i = this.t, r = new Array();
  624. r[0] = this.s;
  625. var p = this.DB-(i*this.DB)%8, d, k = 0;
  626. if(i-- > 0) {
  627. if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
  628. r[k++] = d|(this.s<<(this.DB-p));
  629. while(i >= 0) {
  630. if(p < 8) {
  631. d = (this[i]&((1<<p)-1))<<(8-p);
  632. d |= this[--i]>>(p+=this.DB-8);
  633. }
  634. else {
  635. d = (this[i]>>(p-=8))&0xff;
  636. if(p <= 0) { p += this.DB; --i; }
  637. }
  638. if((d&0x80) != 0) d |= -256;
  639. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  640. if(k > 0 || d != this.s) r[k++] = d;
  641. }
  642. }
  643. return r;
  644. }
  645. function bnEquals(a) { return(this.compareTo(a)==0); }
  646. function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
  647. function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
  648. // (protected) r = this op a (bitwise)
  649. function bnpBitwiseTo(a,op,r) {
  650. var i, f, m = Math.min(a.t,this.t);
  651. for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
  652. if(a.t < this.t) {
  653. f = a.s&this.DM;
  654. for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
  655. r.t = this.t;
  656. }
  657. else {
  658. f = this.s&this.DM;
  659. for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
  660. r.t = a.t;
  661. }
  662. r.s = op(this.s,a.s);
  663. r.clamp();
  664. }
  665. // (public) this & a
  666. function op_and(x,y) { return x&y; }
  667. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  668. // (public) this | a
  669. function op_or(x,y) { return x|y; }
  670. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  671. // (public) this ^ a
  672. function op_xor(x,y) { return x^y; }
  673. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  674. // (public) this & ~a
  675. function op_andnot(x,y) { return x&~y; }
  676. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  677. // (public) ~this
  678. function bnNot() {
  679. var r = nbi();
  680. for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
  681. r.t = this.t;
  682. r.s = ~this.s;
  683. return r;
  684. }
  685. // (public) this << n
  686. function bnShiftLeft(n) {
  687. var r = nbi();
  688. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  689. return r;
  690. }
  691. // (public) this >> n
  692. function bnShiftRight(n) {
  693. var r = nbi();
  694. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  695. return r;
  696. }
  697. // return index of lowest 1-bit in x, x < 2^31
  698. function lbit(x) {
  699. if(x == 0) return -1;
  700. var r = 0;
  701. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  702. if((x&0xff) == 0) { x >>= 8; r += 8; }
  703. if((x&0xf) == 0) { x >>= 4; r += 4; }
  704. if((x&3) == 0) { x >>= 2; r += 2; }
  705. if((x&1) == 0) ++r;
  706. return r;
  707. }
  708. // (public) returns index of lowest 1-bit (or -1 if none)
  709. function bnGetLowestSetBit() {
  710. for(var i = 0; i < this.t; ++i)
  711. if(this[i] != 0) return i*this.DB+lbit(this[i]);
  712. if(this.s < 0) return this.t*this.DB;
  713. return -1;
  714. }
  715. // return number of 1 bits in x
  716. function cbit(x) {
  717. var r = 0;
  718. while(x != 0) { x &= x-1; ++r; }
  719. return r;
  720. }
  721. // (public) return number of set bits
  722. function bnBitCount() {
  723. var r = 0, x = this.s&this.DM;
  724. for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
  725. return r;
  726. }
  727. // (public) true iff nth bit is set
  728. function bnTestBit(n) {
  729. var j = Math.floor(n/this.DB);
  730. if(j >= this.t) return(this.s!=0);
  731. return((this[j]&(1<<(n%this.DB)))!=0);
  732. }
  733. // (protected) this op (1<<n)
  734. function bnpChangeBit(n,op) {
  735. var r = BigInteger.ONE.shiftLeft(n);
  736. this.bitwiseTo(r,op,r);
  737. return r;
  738. }
  739. // (public) this | (1<<n)
  740. function bnSetBit(n) { return this.changeBit(n,op_or); }
  741. // (public) this & ~(1<<n)
  742. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  743. // (public) this ^ (1<<n)
  744. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  745. // (protected) r = this + a
  746. function bnpAddTo(a,r) {
  747. var i = 0, c = 0, m = Math.min(a.t,this.t);
  748. while(i < m) {
  749. c += this[i]+a[i];
  750. r[i++] = c&this.DM;
  751. c >>= this.DB;
  752. }
  753. if(a.t < this.t) {
  754. c += a.s;
  755. while(i < this.t) {
  756. c += this[i];
  757. r[i++] = c&this.DM;
  758. c >>= this.DB;
  759. }
  760. c += this.s;
  761. }
  762. else {
  763. c += this.s;
  764. while(i < a.t) {
  765. c += a[i];
  766. r[i++] = c&this.DM;
  767. c >>= this.DB;
  768. }
  769. c += a.s;
  770. }
  771. r.s = (c<0)?-1:0;
  772. if(c > 0) r[i++] = c;
  773. else if(c < -1) r[i++] = this.DV+c;
  774. r.t = i;
  775. r.clamp();
  776. }
  777. // (public) this + a
  778. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  779. // (public) this - a
  780. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  781. // (public) this * a
  782. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  783. // (public) this^2
  784. function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
  785. // (public) this / a
  786. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  787. // (public) this % a
  788. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  789. // (public) [this/a,this%a]
  790. function bnDivideAndRemainder(a) {
  791. var q = nbi(), r = nbi();
  792. this.divRemTo(a,q,r);
  793. return new Array(q,r);
  794. }
  795. // (protected) this *= n, this >= 0, 1 < n < DV
  796. function bnpDMultiply(n) {
  797. this[this.t] = this.am(0,n-1,this,0,0,this.t);
  798. ++this.t;
  799. this.clamp();
  800. }
  801. // (protected) this += n << w words, this >= 0
  802. function bnpDAddOffset(n,w) {
  803. if(n == 0) return;
  804. while(this.t <= w) this[this.t++] = 0;
  805. this[w] += n;
  806. while(this[w] >= this.DV) {
  807. this[w] -= this.DV;
  808. if(++w >= this.t) this[this.t++] = 0;
  809. ++this[w];
  810. }
  811. }
  812. // A "null" reducer
  813. function NullExp() {}
  814. function nNop(x) { return x; }
  815. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  816. function nSqrTo(x,r) { x.squareTo(r); }
  817. NullExp.prototype.convert = nNop;
  818. NullExp.prototype.revert = nNop;
  819. NullExp.prototype.mulTo = nMulTo;
  820. NullExp.prototype.sqrTo = nSqrTo;
  821. // (public) this^e
  822. function bnPow(e) { return this.exp(e,new NullExp()); }
  823. // (protected) r = lower n words of "this * a", a.t <= n
  824. // "this" should be the larger one if appropriate.
  825. function bnpMultiplyLowerTo(a,n,r) {
  826. var i = Math.min(this.t+a.t,n);
  827. r.s = 0; // assumes a,this >= 0
  828. r.t = i;
  829. while(i > 0) r[--i] = 0;
  830. var j;
  831. for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
  832. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
  833. r.clamp();
  834. }
  835. // (protected) r = "this * a" without lower n words, n > 0
  836. // "this" should be the larger one if appropriate.
  837. function bnpMultiplyUpperTo(a,n,r) {
  838. --n;
  839. var i = r.t = this.t+a.t-n;
  840. r.s = 0; // assumes a,this >= 0
  841. while(--i >= 0) r[i] = 0;
  842. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  843. r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
  844. r.clamp();
  845. r.drShiftTo(1,r);
  846. }
  847. // Barrett modular reduction
  848. function Barrett(m) {
  849. // setup Barrett
  850. this.r2 = nbi();
  851. this.q3 = nbi();
  852. BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
  853. this.mu = this.r2.divide(m);
  854. this.m = m;
  855. }
  856. function barrettConvert(x) {
  857. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  858. else if(x.compareTo(this.m) < 0) return x;
  859. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  860. }
  861. function barrettRevert(x) { return x; }
  862. // x = x mod m (HAC 14.42)
  863. function barrettReduce(x) {
  864. x.drShiftTo(this.m.t-1,this.r2);
  865. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  866. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  867. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  868. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  869. x.subTo(this.r2,x);
  870. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  871. }
  872. // r = x^2 mod m; x != r
  873. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  874. // r = x*y mod m; x,y != r
  875. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  876. Barrett.prototype.convert = barrettConvert;
  877. Barrett.prototype.revert = barrettRevert;
  878. Barrett.prototype.reduce = barrettReduce;
  879. Barrett.prototype.mulTo = barrettMulTo;
  880. Barrett.prototype.sqrTo = barrettSqrTo;
  881. // (public) this^e % m (HAC 14.85)
  882. function bnModPow(e,m) {
  883. var i = e.bitLength(), k, r = nbv(1), z;
  884. if(i <= 0) return r;
  885. else if(i < 18) k = 1;
  886. else if(i < 48) k = 3;
  887. else if(i < 144) k = 4;
  888. else if(i < 768) k = 5;
  889. else k = 6;
  890. if(i < 8)
  891. z = new Classic(m);
  892. else if(m.isEven())
  893. z = new Barrett(m);
  894. else
  895. z = new Montgomery(m);
  896. // precomputation
  897. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  898. g[1] = z.convert(this);
  899. if(k > 1) {
  900. var g2 = nbi();
  901. z.sqrTo(g[1],g2);
  902. while(n <= km) {
  903. g[n] = nbi();
  904. z.mulTo(g2,g[n-2],g[n]);
  905. n += 2;
  906. }
  907. }
  908. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  909. i = nbits(e[j])-1;
  910. while(j >= 0) {
  911. if(i >= k1) w = (e[j]>>(i-k1))&km;
  912. else {
  913. w = (e[j]&((1<<(i+1))-1))<<(k1-i);
  914. if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
  915. }
  916. n = k;
  917. while((w&1) == 0) { w >>= 1; --n; }
  918. if((i -= n) < 0) { i += this.DB; --j; }
  919. if(is1) { // ret == 1, don't bother squaring or multiplying it
  920. g[w].copyTo(r);
  921. is1 = false;
  922. }
  923. else {
  924. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  925. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  926. z.mulTo(r2,g[w],r);
  927. }
  928. while(j >= 0 && (e[j]&(1<<i)) == 0) {
  929. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  930. if(--i < 0) { i = this.DB-1; --j; }
  931. }
  932. }
  933. return z.revert(r);
  934. }
  935. // (public) gcd(this,a) (HAC 14.54)
  936. function bnGCD(a) {
  937. var x = (this.s<0)?this.negate():this.clone();
  938. var y = (a.s<0)?a.negate():a.clone();
  939. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  940. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  941. if(g < 0) return x;
  942. if(i < g) g = i;
  943. if(g > 0) {
  944. x.rShiftTo(g,x);
  945. y.rShiftTo(g,y);
  946. }
  947. while(x.signum() > 0) {
  948. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  949. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  950. if(x.compareTo(y) >= 0) {
  951. x.subTo(y,x);
  952. x.rShiftTo(1,x);
  953. }
  954. else {
  955. y.subTo(x,y);
  956. y.rShiftTo(1,y);
  957. }
  958. }
  959. if(g > 0) y.lShiftTo(g,y);
  960. return y;
  961. }
  962. // (protected) this % n, n < 2^26
  963. function bnpModInt(n) {
  964. if(n <= 0) return 0;
  965. var d = this.DV%n, r = (this.s<0)?n-1:0;
  966. if(this.t > 0)
  967. if(d == 0) r = this[0]%n;
  968. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
  969. return r;
  970. }
  971. // (public) 1/this % m (HAC 14.61)
  972. function bnModInverse(m) {
  973. var ac = m.isEven();
  974. if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
  975. var u = m.clone(), v = this.clone();
  976. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  977. while(u.signum() != 0) {
  978. while(u.isEven()) {
  979. u.rShiftTo(1,u);
  980. if(ac) {
  981. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  982. a.rShiftTo(1,a);
  983. }
  984. else if(!b.isEven()) b.subTo(m,b);
  985. b.rShiftTo(1,b);
  986. }
  987. while(v.isEven()) {
  988. v.rShiftTo(1,v);
  989. if(ac) {
  990. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  991. c.rShiftTo(1,c);
  992. }
  993. else if(!d.isEven()) d.subTo(m,d);
  994. d.rShiftTo(1,d);
  995. }
  996. if(u.compareTo(v) >= 0) {
  997. u.subTo(v,u);
  998. if(ac) a.subTo(c,a);
  999. b.subTo(d,b);
  1000. }
  1001. else {
  1002. v.subTo(u,v);
  1003. if(ac) c.subTo(a,c);
  1004. d.subTo(b,d);
  1005. }
  1006. }
  1007. if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
  1008. if(d.compareTo(m) >= 0) return d.subtract(m);
  1009. if(d.signum() < 0) d.addTo(m,d); else return d;
  1010. if(d.signum() < 0) return d.add(m); else return d;
  1011. }
  1012. var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
  1013. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  1014. // (public) test primality with certainty >= 1-.5^t
  1015. function bnIsProbablePrime(t) {
  1016. var i, x = this.abs();
  1017. if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
  1018. for(i = 0; i < lowprimes.length; ++i)
  1019. if(x[0] == lowprimes[i]) return true;
  1020. return false;
  1021. }
  1022. if(x.isEven()) return false;
  1023. i = 1;
  1024. while(i < lowprimes.length) {
  1025. var m = lowprimes[i], j = i+1;
  1026. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  1027. m = x.modInt(m);
  1028. while(i < j) if(m%lowprimes[i++] == 0) return false;
  1029. }
  1030. return x.millerRabin(t);
  1031. }
  1032. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  1033. function bnpMillerRabin(t) {
  1034. var n1 = this.subtract(BigInteger.ONE);
  1035. var k = n1.getLowestSetBit();
  1036. if(k <= 0) return false;
  1037. var r = n1.shiftRight(k);
  1038. t = (t+1)>>1;
  1039. if(t > lowprimes.length) t = lowprimes.length;
  1040. var a = nbi();
  1041. for(var i = 0; i < t; ++i) {
  1042. //Pick bases at random, instead of starting at 2
  1043. a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
  1044. var y = a.modPow(r,this);
  1045. if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  1046. var j = 1;
  1047. while(j++ < k && y.compareTo(n1) != 0) {
  1048. y = y.modPowInt(2,this);
  1049. if(y.compareTo(BigInteger.ONE) == 0) return false;
  1050. }
  1051. if(y.compareTo(n1) != 0) return false;
  1052. }
  1053. }
  1054. return true;
  1055. }
  1056. // protected
  1057. BigInteger.prototype.chunkSize = bnpChunkSize;
  1058. BigInteger.prototype.toRadix = bnpToRadix;
  1059. BigInteger.prototype.fromRadix = bnpFromRadix;
  1060. BigInteger.prototype.fromNumber = bnpFromNumber;
  1061. BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  1062. BigInteger.prototype.changeBit = bnpChangeBit;
  1063. BigInteger.prototype.addTo = bnpAddTo;
  1064. BigInteger.prototype.dMultiply = bnpDMultiply;
  1065. BigInteger.prototype.dAddOffset = bnpDAddOffset;
  1066. BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  1067. BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  1068. BigInteger.prototype.modInt = bnpModInt;
  1069. BigInteger.prototype.millerRabin = bnpMillerRabin;
  1070. // public
  1071. BigInteger.prototype.clone = bnClone;
  1072. BigInteger.prototype.intValue = bnIntValue;
  1073. BigInteger.prototype.byteValue = bnByteValue;
  1074. BigInteger.prototype.shortValue = bnShortValue;
  1075. BigInteger.prototype.signum = bnSigNum;
  1076. BigInteger.prototype.toByteArray = bnToByteArray;
  1077. BigInteger.prototype.equals = bnEquals;
  1078. BigInteger.prototype.min = bnMin;
  1079. BigInteger.prototype.max = bnMax;
  1080. BigInteger.prototype.and = bnAnd;
  1081. BigInteger.prototype.or = bnOr;
  1082. BigInteger.prototype.xor = bnXor;
  1083. BigInteger.prototype.andNot = bnAndNot;
  1084. BigInteger.prototype.not = bnNot;
  1085. BigInteger.prototype.shiftLeft = bnShiftLeft;
  1086. BigInteger.prototype.shiftRight = bnShiftRight;
  1087. BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  1088. BigInteger.prototype.bitCount = bnBitCount;
  1089. BigInteger.prototype.testBit = bnTestBit;
  1090. BigInteger.prototype.setBit = bnSetBit;
  1091. BigInteger.prototype.clearBit = bnClearBit;
  1092. BigInteger.prototype.flipBit = bnFlipBit;
  1093. BigInteger.prototype.add = bnAdd;
  1094. BigInteger.prototype.subtract = bnSubtract;
  1095. BigInteger.prototype.multiply = bnMultiply;
  1096. BigInteger.prototype.divide = bnDivide;
  1097. BigInteger.prototype.remainder = bnRemainder;
  1098. BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  1099. BigInteger.prototype.modPow = bnModPow;
  1100. BigInteger.prototype.modInverse = bnModInverse;
  1101. BigInteger.prototype.pow = bnPow;
  1102. BigInteger.prototype.gcd = bnGCD;
  1103. BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1104. // JSBN-specific extension
  1105. BigInteger.prototype.square = bnSquare;
  1106. // BigInteger interfaces not implemented in jsbn:
  1107. // BigInteger(int signum, byte[] magnitude)
  1108. // double doubleValue()
  1109. // float floatValue()
  1110. // int hashCode()
  1111. // long longValue()
  1112. // static BigInteger valueOf(long val)
  1113. // prng4.js - uses Arcfour as a PRNG
  1114. function Arcfour() {
  1115. this.i = 0;
  1116. this.j = 0;
  1117. this.S = new Array();
  1118. }
  1119. // Initialize arcfour context from key, an array of ints, each from [0..255]
  1120. function ARC4init(key) {
  1121. var i, j, t;
  1122. for(i = 0; i < 256; ++i)
  1123. this.S[i] = i;
  1124. j = 0;
  1125. for(i = 0; i < 256; ++i) {
  1126. j = (j + this.S[i] + key[i % key.length]) & 255;
  1127. t = this.S[i];
  1128. this.S[i] = this.S[j];
  1129. this.S[j] = t;
  1130. }
  1131. this.i = 0;
  1132. this.j = 0;
  1133. }
  1134. function ARC4next() {
  1135. var t;
  1136. this.i = (this.i + 1) & 255;
  1137. this.j = (this.j + this.S[this.i]) & 255;
  1138. t = this.S[this.i];
  1139. this.S[this.i] = this.S[this.j];
  1140. this.S[this.j] = t;
  1141. return this.S[(t + this.S[this.i]) & 255];
  1142. }
  1143. Arcfour.prototype.init = ARC4init;
  1144. Arcfour.prototype.next = ARC4next;
  1145. // Plug in your RNG constructor here
  1146. function prng_newstate() {
  1147. return new Arcfour();
  1148. }
  1149. // Pool size must be a multiple of 4 and greater than 32.
  1150. // An array of bytes the size of the pool will be passed to init()
  1151. var rng_psize = 256;
  1152. // Random number generator - requires a PRNG backend, e.g. prng4.js
  1153. var rng_state;
  1154. var rng_pool;
  1155. var rng_pptr;
  1156. // Initialize the pool with junk if needed.
  1157. if(rng_pool == null) {
  1158. rng_pool = new Array();
  1159. rng_pptr = 0;
  1160. var t;
  1161. if(window.crypto && window.crypto.getRandomValues) {
  1162. // Extract entropy (2048 bits) from RNG if available
  1163. var z = new Uint32Array(256);
  1164. window.crypto.getRandomValues(z);
  1165. for (t = 0; t < z.length; ++t)
  1166. rng_pool[rng_pptr++] = z[t] & 255;
  1167. }
  1168. // Use mouse events for entropy, if we do not have enough entropy by the time
  1169. // we need it, entropy will be generated by Math.random.
  1170. var onMouseMoveListener = function(ev) {
  1171. this.count = this.count || 0;
  1172. if (this.count >= 256 || rng_pptr >= rng_psize) {
  1173. if (window.removeEventListener)
  1174. window.removeEventListener("mousemove", onMouseMoveListener, false);
  1175. else if (window.detachEvent)
  1176. window.detachEvent("onmousemove", onMouseMoveListener);
  1177. return;
  1178. }
  1179. try {
  1180. var mouseCoordinates = ev.x + ev.y;
  1181. rng_pool[rng_pptr++] = mouseCoordinates & 255;
  1182. this.count += 1;
  1183. } catch (e) {
  1184. // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
  1185. }
  1186. };
  1187. if (window.addEventListener)
  1188. window.addEventListener("mousemove", onMouseMoveListener, false);
  1189. else if (window.attachEvent)
  1190. window.attachEvent("onmousemove", onMouseMoveListener);
  1191. }
  1192. function rng_get_byte() {
  1193. if(rng_state == null) {
  1194. rng_state = prng_newstate();
  1195. // At this point, we may not have collected enough entropy. If not, fall back to Math.random
  1196. while (rng_pptr < rng_psize) {
  1197. var random = Math.floor(65536 * Math.random());
  1198. rng_pool[rng_pptr++] = random & 255;
  1199. }
  1200. rng_state.init(rng_pool);
  1201. for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
  1202. rng_pool[rng_pptr] = 0;
  1203. rng_pptr = 0;
  1204. }
  1205. // TODO: allow reseeding after first request
  1206. return rng_state.next();
  1207. }
  1208. function rng_get_bytes(ba) {
  1209. var i;
  1210. for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  1211. }
  1212. function SecureRandom() {}
  1213. SecureRandom.prototype.nextBytes = rng_get_bytes;
  1214. // Depends on jsbn.js and rng.js
  1215. // Version 1.1: support utf-8 encoding in pkcs1pad2
  1216. // convert a (hex) string to a bignum object
  1217. function parseBigInt(str,r) {
  1218. return new BigInteger(str,r);
  1219. }
  1220. function linebrk(s,n) {
  1221. var ret = "";
  1222. var i = 0;
  1223. while(i + n < s.length) {
  1224. ret += s.substring(i,i+n) + "\n";
  1225. i += n;
  1226. }
  1227. return ret + s.substring(i,s.length);
  1228. }
  1229. function byte2Hex(b) {
  1230. if(b < 0x10)
  1231. return "0" + b.toString(16);
  1232. else
  1233. return b.toString(16);
  1234. }
  1235. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  1236. function pkcs1pad2(s,n) {
  1237. if(n < s.length + 11) { // TODO: fix for utf-8
  1238. console.error("Message too long for RSA");
  1239. return null;
  1240. }
  1241. var ba = new Array();
  1242. var i = s.length - 1;
  1243. while(i >= 0 && n > 0) {
  1244. var c = s.charCodeAt(i--);
  1245. if(c < 128) { // encode using utf-8
  1246. ba[--n] = c;
  1247. }
  1248. else if((c > 127) && (c < 2048)) {
  1249. ba[--n] = (c & 63) | 128;
  1250. ba[--n] = (c >> 6) | 192;
  1251. }
  1252. else {
  1253. ba[--n] = (c & 63) | 128;
  1254. ba[--n] = ((c >> 6) & 63) | 128;
  1255. ba[--n] = (c >> 12) | 224;
  1256. }
  1257. }
  1258. ba[--n] = 0;
  1259. var rng = new SecureRandom();
  1260. var x = new Array();
  1261. while(n > 2) { // random non-zero pad
  1262. x[0] = 0;
  1263. while(x[0] == 0) rng.nextBytes(x);
  1264. ba[--n] = x[0];
  1265. }
  1266. ba[--n] = 2;
  1267. ba[--n] = 0;
  1268. return new BigInteger(ba);
  1269. }
  1270. // "empty" RSA key constructor
  1271. function RSAKey() {
  1272. this.n = null;
  1273. this.e = 0;
  1274. this.d = null;
  1275. this.p = null;
  1276. this.q = null;
  1277. this.dmp1 = null;
  1278. this.dmq1 = null;
  1279. this.coeff = null;
  1280. }
  1281. // Set the public key fields N and e from hex strings
  1282. function RSASetPublic(N,E) {
  1283. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1284. this.n = parseBigInt(N,16);
  1285. this.e = parseInt(E,16);
  1286. }
  1287. else
  1288. console.error("Invalid RSA public key");
  1289. }
  1290. // Perform raw public operation on "x": return x^e (mod n)
  1291. function RSADoPublic(x) {
  1292. return x.modPowInt(this.e, this.n);
  1293. }
  1294. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  1295. function RSAEncrypt(text) {
  1296. var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
  1297. if(m == null) return null;
  1298. var c = this.doPublic(m);
  1299. if(c == null) return null;
  1300. var h = c.toString(16);
  1301. if((h.length & 1) == 0) return h; else return "0" + h;
  1302. }
  1303. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  1304. //function RSAEncryptB64(text) {
  1305. // var h = this.encrypt(text);
  1306. // if(h) return hex2b64(h); else return null;
  1307. //}
  1308. // protected
  1309. RSAKey.prototype.doPublic = RSADoPublic;
  1310. // public
  1311. RSAKey.prototype.setPublic = RSASetPublic;
  1312. RSAKey.prototype.encrypt = RSAEncrypt;
  1313. //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
  1314. // Depends on rsa.js and jsbn2.js
  1315. // Version 1.1: support utf-8 decoding in pkcs1unpad2
  1316. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  1317. function pkcs1unpad2(d,n) {
  1318. var b = d.toByteArray();
  1319. var i = 0;
  1320. while(i < b.length && b[i] == 0) ++i;
  1321. if(b.length-i != n-1 || b[i] != 2)
  1322. return null;
  1323. ++i;
  1324. while(b[i] != 0)
  1325. if(++i >= b.length) return null;
  1326. var ret = "";
  1327. while(++i < b.length) {
  1328. var c = b[i] & 255;
  1329. if(c < 128) { // utf-8 decode
  1330. ret += String.fromCharCode(c);
  1331. }
  1332. else if((c > 191) && (c < 224)) {
  1333. ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
  1334. ++i;
  1335. }
  1336. else {
  1337. ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63));
  1338. i += 2;
  1339. }
  1340. }
  1341. return ret;
  1342. }
  1343. // Set the private key fields N, e, and d from hex strings
  1344. function RSASetPrivate(N,E,D) {
  1345. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1346. this.n = parseBigInt(N,16);
  1347. this.e = parseInt(E,16);
  1348. this.d = parseBigInt(D,16);
  1349. }
  1350. else
  1351. console.error("Invalid RSA private key");
  1352. }
  1353. // Set the private key fields N, e, d and CRT params from hex strings
  1354. function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  1355. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1356. this.n = parseBigInt(N,16);
  1357. this.e = parseInt(E,16);
  1358. this.d = parseBigInt(D,16);
  1359. this.p = parseBigInt(P,16);
  1360. this.q = parseBigInt(Q,16);
  1361. this.dmp1 = parseBigInt(DP,16);
  1362. this.dmq1 = parseBigInt(DQ,16);
  1363. this.coeff = parseBigInt(C,16);
  1364. }
  1365. else
  1366. console.error("Invalid RSA private key");
  1367. }
  1368. // Generate a new random private key B bits long, using public expt E
  1369. function RSAGenerate(B,E) {
  1370. var rng = new SecureRandom();
  1371. var qs = B>>1;
  1372. this.e = parseInt(E,16);
  1373. var ee = new BigInteger(E,16);
  1374. for(;;) {
  1375. for(;;) {
  1376. this.p = new BigInteger(B-qs,1,rng);
  1377. if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
  1378. }
  1379. for(;;) {
  1380. this.q = new BigInteger(qs,1,rng);
  1381. if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
  1382. }
  1383. if(this.p.compareTo(this.q) <= 0) {
  1384. var t = this.p;
  1385. this.p = this.q;
  1386. this.q = t;
  1387. }
  1388. var p1 = this.p.subtract(BigInteger.ONE);
  1389. var q1 = this.q.subtract(BigInteger.ONE);
  1390. var phi = p1.multiply(q1);
  1391. if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  1392. this.n = this.p.multiply(this.q);
  1393. this.d = ee.modInverse(phi);
  1394. this.dmp1 = this.d.mod(p1);
  1395. this.dmq1 = this.d.mod(q1);
  1396. this.coeff = this.q.modInverse(this.p);
  1397. break;
  1398. }
  1399. }
  1400. }
  1401. // Perform raw private operation on "x": return x^d (mod n)
  1402. function RSADoPrivate(x) {
  1403. if(this.p == null || this.q == null)
  1404. return x.modPow(this.d, this.n);
  1405. // TODO: re-calculate any missing CRT params
  1406. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  1407. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  1408. while(xp.compareTo(xq) < 0)
  1409. xp = xp.add(this.p);
  1410. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  1411. }
  1412. // Return the PKCS#1 RSA decryption of "ctext".
  1413. // "ctext" is an even-length hex string and the output is a plain string.
  1414. function RSADecrypt(ctext) {
  1415. var c = parseBigInt(ctext, 16);
  1416. var m = this.doPrivate(c);
  1417. if(m == null) return null;
  1418. return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
  1419. }
  1420. // Return the PKCS#1 RSA decryption of "ctext".
  1421. // "ctext" is a Base64-encoded string and the output is a plain string.
  1422. //function RSAB64Decrypt(ctext) {
  1423. // var h = b64tohex(ctext);
  1424. // if(h) return this.decrypt(h); else return null;
  1425. //}
  1426. // protected
  1427. RSAKey.prototype.doPrivate = RSADoPrivate;
  1428. // public
  1429. RSAKey.prototype.setPrivate = RSASetPrivate;
  1430. RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  1431. RSAKey.prototype.generate = RSAGenerate;
  1432. RSAKey.prototype.decrypt = RSADecrypt;
  1433. //RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
  1434. // Copyright (c) 2011 Kevin M Burns Jr.
  1435. // All Rights Reserved.
  1436. // See "LICENSE" for details.
  1437. //
  1438. // Extension to jsbn which adds facilities for asynchronous RSA key generation
  1439. // Primarily created to avoid execution timeout on mobile devices
  1440. //
  1441. // http://www-cs-students.stanford.edu/~tjw/jsbn/
  1442. //
  1443. // ---
  1444. (function(){
  1445. // Generate a new random private key B bits long, using public expt E
  1446. var RSAGenerateAsync = function (B, E, callback) {
  1447. //var rng = new SeededRandom();
  1448. var rng = new SecureRandom();
  1449. var qs = B >> 1;
  1450. this.e = parseInt(E, 16);
  1451. var ee = new BigInteger(E, 16);
  1452. var rsa = this;
  1453. // These functions have non-descript names because they were originally for(;;) loops.
  1454. // I don't know about cryptography to give them better names than loop1-4.
  1455. var loop1 = function() {
  1456. var loop4 = function() {
  1457. if (rsa.p.compareTo(rsa.q) <= 0) {
  1458. var t = rsa.p;
  1459. rsa.p = rsa.q;
  1460. rsa.q = t;
  1461. }
  1462. var p1 = rsa.p.subtract(BigInteger.ONE);
  1463. var q1 = rsa.q.subtract(BigInteger.ONE);
  1464. var phi = p1.multiply(q1);
  1465. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  1466. rsa.n = rsa.p.multiply(rsa.q);
  1467. rsa.d = ee.modInverse(phi);
  1468. rsa.dmp1 = rsa.d.mod(p1);
  1469. rsa.dmq1 = rsa.d.mod(q1);
  1470. rsa.coeff = rsa.q.modInverse(rsa.p);
  1471. setTimeout(function(){callback()},0); // escape
  1472. } else {
  1473. setTimeout(loop1,0);
  1474. }
  1475. };
  1476. var loop3 = function() {
  1477. rsa.q = nbi();
  1478. rsa.q.fromNumberAsync(qs, 1, rng, function(){
  1479. rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r){
  1480. if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
  1481. setTimeout(loop4,0);
  1482. } else {
  1483. setTimeout(loop3,0);
  1484. }
  1485. });
  1486. });
  1487. };
  1488. var loop2 = function() {
  1489. rsa.p = nbi();
  1490. rsa.p.fromNumberAsync(B - qs, 1, rng, function(){
  1491. rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r){
  1492. if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
  1493. setTimeout(loop3,0);
  1494. } else {
  1495. setTimeout(loop2,0);
  1496. }
  1497. });
  1498. });
  1499. };
  1500. setTimeout(loop2,0);
  1501. };
  1502. setTimeout(loop1,0);
  1503. };
  1504. RSAKey.prototype.generateAsync = RSAGenerateAsync;
  1505. // Public API method
  1506. var bnGCDAsync = function (a, callback) {
  1507. var x = (this.s < 0) ? this.negate() : this.clone();
  1508. var y = (a.s < 0) ? a.negate() : a.clone();
  1509. if (x.compareTo(y) < 0) {
  1510. var t = x;
  1511. x = y;
  1512. y = t;
  1513. }
  1514. var i = x.getLowestSetBit(),
  1515. g = y.getLowestSetBit();
  1516. if (g < 0) {
  1517. callback(x);
  1518. return;
  1519. }
  1520. if (i < g) g = i;
  1521. if (g > 0) {
  1522. x.rShiftTo(g, x);
  1523. y.rShiftTo(g, y);
  1524. }
  1525. // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
  1526. var gcda1 = function() {
  1527. if ((i = x.getLowestSetBit()) > 0){ x.rShiftTo(i, x); }
  1528. if ((i = y.getLowestSetBit()) > 0){ y.rShiftTo(i, y); }
  1529. if (x.compareTo(y) >= 0) {
  1530. x.subTo(y, x);
  1531. x.rShiftTo(1, x);
  1532. } else {
  1533. y.subTo(x, y);
  1534. y.rShiftTo(1, y);
  1535. }
  1536. if(!(x.signum() > 0)) {
  1537. if (g > 0) y.lShiftTo(g, y);
  1538. setTimeout(function(){callback(y)},0); // escape
  1539. } else {
  1540. setTimeout(gcda1,0);
  1541. }
  1542. };
  1543. setTimeout(gcda1,10);
  1544. };
  1545. BigInteger.prototype.gcda = bnGCDAsync;
  1546. // (protected) alternate constructor
  1547. var bnpFromNumberAsync = function (a,b,c,callback) {
  1548. if("number" == typeof b) {
  1549. if(a < 2) {
  1550. this.fromInt(1);
  1551. } else {
  1552. this.fromNumber(a,c);
  1553. if(!this.testBit(a-1)){
  1554. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  1555. }
  1556. if(this.isEven()) {
  1557. this.dAddOffset(1,0);
  1558. }
  1559. var bnp = this;
  1560. var bnpfn1 = function(){
  1561. bnp.dAddOffset(2,0);
  1562. if(bnp.bitLength() > a) bnp.subTo(BigInteger.ONE.shiftLeft(a-1),bnp);
  1563. if(bnp.isProbablePrime(b)) {
  1564. setTimeout(function(){callback()},0); // escape
  1565. } else {
  1566. setTimeout(bnpfn1,0);
  1567. }
  1568. };
  1569. setTimeout(bnpfn1,0);
  1570. }
  1571. } else {
  1572. var x = new Array(), t = a&7;
  1573. x.length = (a>>3)+1;
  1574. b.nextBytes(x);
  1575. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  1576. this.fromString(x,256);
  1577. }
  1578. };
  1579. BigInteger.prototype.fromNumberAsync = bnpFromNumberAsync;
  1580. })();
  1581. var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1582. var b64pad="=";
  1583. function hex2b64(h) {
  1584. var i;
  1585. var c;
  1586. var ret = "";
  1587. for(i = 0; i+3 <= h.length; i+=3) {
  1588. c = parseInt(h.substring(i,i+3),16);
  1589. ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
  1590. }
  1591. if(i+1 == h.length) {
  1592. c = parseInt(h.substring(i,i+1),16);
  1593. ret += b64map.charAt(c << 2);
  1594. }
  1595. else if(i+2 == h.length) {
  1596. c = parseInt(h.substring(i,i+2),16);
  1597. ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
  1598. }
  1599. while((ret.length & 3) > 0) ret += b64pad;
  1600. return ret;
  1601. }
  1602. // convert a base64 string to hex
  1603. function b64tohex(s) {
  1604. var ret = ""
  1605. var i;
  1606. var k = 0; // b64 state, 0-3
  1607. var slop;
  1608. for(i = 0; i < s.length; ++i) {
  1609. if(s.charAt(i) == b64pad) break;
  1610. v = b64map.indexOf(s.charAt(i));
  1611. if(v < 0) continue;
  1612. if(k == 0) {
  1613. ret += int2char(v >> 2);
  1614. slop = v & 3;
  1615. k = 1;
  1616. }
  1617. else if(k == 1) {
  1618. ret += int2char((slop << 2) | (v >> 4));
  1619. slop = v & 0xf;
  1620. k = 2;
  1621. }
  1622. else if(k == 2) {
  1623. ret += int2char(slop);
  1624. ret += int2char(v >> 2);
  1625. slop = v & 3;
  1626. k = 3;
  1627. }
  1628. else {
  1629. ret += int2char((slop << 2) | (v >> 4));
  1630. ret += int2char(v & 0xf);
  1631. k = 0;
  1632. }
  1633. }
  1634. if(k == 1)
  1635. ret += int2char(slop << 2);
  1636. return ret;
  1637. }
  1638. // convert a base64 string to a byte/number array
  1639. function b64toBA(s) {
  1640. //piggyback on b64tohex for now, optimize later
  1641. var h = b64tohex(s);
  1642. var i;
  1643. var a = new Array();
  1644. for(i = 0; 2*i < h.length; ++i) {
  1645. a[i] = parseInt(h.substring(2*i,2*i+2),16);
  1646. }
  1647. return a;
  1648. }
  1649. /*! asn1-1.0.2.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license
  1650. */
  1651. var JSX = JSX || {};
  1652. JSX.env = JSX.env || {};
  1653. var L = JSX, OP = Object.prototype, FUNCTION_TOSTRING = '[object Function]',ADD = ["toString", "valueOf"];
  1654. JSX.env.parseUA = function(agent) {
  1655. var numberify = function(s) {
  1656. var c = 0;
  1657. return parseFloat(s.replace(/\./g, function() {
  1658. return (c++ == 1) ? '' : '.';
  1659. }));
  1660. },
  1661. nav = navigator,
  1662. o = {
  1663. ie: 0,
  1664. opera: 0,
  1665. gecko: 0,
  1666. webkit: 0,
  1667. chrome: 0,
  1668. mobile: null,
  1669. air: 0,
  1670. ipad: 0,
  1671. iphone: 0,
  1672. ipod: 0,
  1673. ios: null,
  1674. android: 0,
  1675. webos: 0,
  1676. caja: nav && nav.cajaVersion,
  1677. secure: false,
  1678. os: null
  1679. },
  1680. ua = agent || (navigator && navigator.userAgent),
  1681. loc = window && window.location,
  1682. href = loc && loc.href,
  1683. m;
  1684. o.secure = href && (href.toLowerCase().indexOf("https") === 0);
  1685. if (ua) {
  1686. if ((/windows|win32/i).test(ua)) {
  1687. o.os = 'windows';
  1688. } else if ((/macintosh/i).test(ua)) {
  1689. o.os = 'macintosh';
  1690. } else if ((/rhino/i).test(ua)) {
  1691. o.os = 'rhino';
  1692. }
  1693. if ((/KHTML/).test(ua)) {
  1694. o.webkit = 1;
  1695. }
  1696. m = ua.match(/AppleWebKit\/([^\s]*)/);
  1697. if (m && m[1]) {
  1698. o.webkit = numberify(m[1]);
  1699. if (/ Mobile\//.test(ua)) {
  1700. o.mobile = 'Apple'; // iPhone or iPod Touch
  1701. m = ua.match(/OS ([^\s]*)/);
  1702. if (m && m[1]) {
  1703. m = numberify(m[1].replace('_', '.'));
  1704. }
  1705. o.ios = m;
  1706. o.ipad = o.ipod = o.iphone = 0;
  1707. m = ua.match(/iPad|iPod|iPhone/);
  1708. if (m && m[0]) {
  1709. o[m[0].toLowerCase()] = o.ios;
  1710. }
  1711. } else {
  1712. m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);
  1713. if (m) {
  1714. o.mobile = m[0];
  1715. }
  1716. if (/webOS/.test(ua)) {
  1717. o.mobile = 'WebOS';
  1718. m = ua.match(/webOS\/([^\s]*);/);
  1719. if (m && m[1]) {
  1720. o.webos = numberify(m[1]);
  1721. }
  1722. }
  1723. if (/ Android/.test(ua)) {
  1724. o.mobile = 'Android';
  1725. m = ua.match(/Android ([^\s]*);/);
  1726. if (m && m[1]) {
  1727. o.android = numberify(m[1]);
  1728. }
  1729. }
  1730. }
  1731. m = ua.match(/Chrome\/([^\s]*)/);
  1732. if (m && m[1]) {
  1733. o.chrome = numberify(m[1]); // Chrome
  1734. } else {
  1735. m = ua.match(/AdobeAIR\/([^\s]*)/);
  1736. if (m) {
  1737. o.air = m[0]; // Adobe AIR 1.0 or better
  1738. }
  1739. }
  1740. }
  1741. if (!o.webkit) {
  1742. m = ua.match(/Opera[\s\/]([^\s]*)/);
  1743. if (m && m[1]) {
  1744. o.opera = numberify(m[1]);
  1745. m = ua.match(/Version\/([^\s]*)/);
  1746. if (m && m[1]) {
  1747. o.opera = numberify(m[1]); // opera 10+
  1748. }
  1749. m = ua.match(/Opera Mini[^;]*/);
  1750. if (m) {
  1751. o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
  1752. }
  1753. } else { // not opera or webkit
  1754. m = ua.match(/MSIE\s([^;]*)/);
  1755. if (m && m[1]) {
  1756. o.ie = numberify(m[1]);
  1757. } else { // not opera, webkit, or ie
  1758. m = ua.match(/Gecko\/([^\s]*)/);
  1759. if (m) {
  1760. o.gecko = 1; // Gecko detected, look for revision
  1761. m = ua.match(/rv:([^\s\)]*)/);
  1762. if (m && m[1]) {
  1763. o.gecko = numberify(m[1]);
  1764. }
  1765. }
  1766. }
  1767. }
  1768. }
  1769. }
  1770. return o;
  1771. };
  1772. JSX.env.ua = JSX.env.parseUA();
  1773. JSX.isFunction = function(o) {
  1774. return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING;
  1775. };
  1776. JSX._IEEnumFix = (JSX.env.ua.ie) ? function(r, s) {
  1777. var i, fname, f;
  1778. for (i=0;i<ADD.length;i=i+1) {
  1779. fname = ADD[i];
  1780. f = s[fname];
  1781. if (L.isFunction(f) && f!=OP[fname]) {
  1782. r[fname]=f;
  1783. }
  1784. }
  1785. } : function(){};
  1786. JSX.extend = function(subc, superc, overrides) {
  1787. if (!superc||!subc) {
  1788. throw new Error("extend failed, please check that " +
  1789. "all dependencies are included.");
  1790. }
  1791. var F = function() {}, i;
  1792. F.prototype=superc.prototype;
  1793. subc.prototype=new F();
  1794. subc.prototype.constructor=subc;
  1795. subc.superclass=superc.prototype;
  1796. if (superc.prototype.constructor == OP.constructor) {
  1797. superc.prototype.constructor=superc;
  1798. }
  1799. if (overrides) {
  1800. for (i in overrides) {
  1801. if (L.hasOwnProperty(overrides, i)) {
  1802. subc.prototype[i]=overrides[i];
  1803. }
  1804. }
  1805. L._IEEnumFix(subc.prototype, overrides);
  1806. }
  1807. };
  1808. /*
  1809. * asn1.js - ASN.1 DER encoder classes
  1810. *
  1811. * Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
  1812. *
  1813. * This software is licensed under the terms of the MIT License.
  1814. * http://kjur.github.com/jsrsasign/license
  1815. *
  1816. * The above copyright and license notice shall be
  1817. * included in all copies or substantial portions of the Software.
  1818. */
  1819. /**
  1820. * @fileOverview
  1821. * @name asn1-1.0.js
  1822. * @author Kenji Urushima kenji.urushima@gmail.com
  1823. * @version 1.0.2 (2013-May-30)
  1824. * @since 2.1
  1825. * @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
  1826. */
  1827. /**
  1828. * kjur's class library name space
  1829. * <p>
  1830. * This name space provides following name spaces:
  1831. * <ul>
  1832. * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
  1833. * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
  1834. * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  1835. * class and utilities</li>
  1836. * </ul>
  1837. * </p>
  1838. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  1839. * @name KJUR
  1840. * @namespace kjur's class library name space
  1841. */
  1842. if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
  1843. /**
  1844. * kjur's ASN.1 class library name space
  1845. * <p>
  1846. * This is ITU-T X.690 ASN.1 DER encoder class library and
  1847. * class structure and methods is very similar to
  1848. * org.bouncycastle.asn1 package of
  1849. * well known BouncyCaslte Cryptography Library.
  1850. *
  1851. * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
  1852. * Here are ASN.1 DER primitive classes.
  1853. * <ul>
  1854. * <li>{@link KJUR.asn1.DERBoolean}</li>
  1855. * <li>{@link KJUR.asn1.DERInteger}</li>
  1856. * <li>{@link KJUR.asn1.DERBitString}</li>
  1857. * <li>{@link KJUR.asn1.DEROctetString}</li>
  1858. * <li>{@link KJUR.asn1.DERNull}</li>
  1859. * <li>{@link KJUR.asn1.DERObjectIdentifier}</li>
  1860. * <li>{@link KJUR.asn1.DERUTF8String}</li>
  1861. * <li>{@link KJUR.asn1.DERNumericString}</li>
  1862. * <li>{@link KJUR.asn1.DERPrintableString}</li>
  1863. * <li>{@link KJUR.asn1.DERTeletexString}</li>
  1864. * <li>{@link KJUR.asn1.DERIA5String}</li>
  1865. * <li>{@link KJUR.asn1.DERUTCTime}</li>
  1866. * <li>{@link KJUR.asn1.DERGeneralizedTime}</li>
  1867. * <li>{@link KJUR.asn1.DERSequence}</li>
  1868. * <li>{@link KJUR.asn1.DERSet}</li>
  1869. * </ul>
  1870. *
  1871. * <h4>OTHER ASN.1 CLASSES</h4>
  1872. * <ul>
  1873. * <li>{@link KJUR.asn1.ASN1Object}</li>
  1874. * <li>{@link KJUR.asn1.DERAbstractString}</li>
  1875. * <li>{@link KJUR.asn1.DERAbstractTime}</li>
  1876. * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
  1877. * <li>{@link KJUR.asn1.DERTaggedObject}</li>
  1878. * </ul>
  1879. * </p>
  1880. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  1881. * @name KJUR.asn1
  1882. * @namespace
  1883. */
  1884. if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
  1885. /**
  1886. * ASN1 utilities class
  1887. * @name KJUR.asn1.ASN1Util
  1888. * @classs ASN1 utilities class
  1889. * @since asn1 1.0.2
  1890. */
  1891. KJUR.asn1.ASN1Util = new function() {
  1892. this.integerToByteHex = function(i) {
  1893. var h = i.toString(16);
  1894. if ((h.length % 2) == 1) h = '0' + h;
  1895. return h;
  1896. };
  1897. this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
  1898. var h = bigIntegerValue.toString(16);
  1899. if (h.substr(0, 1) != '-') {
  1900. if (h.length % 2 == 1) {
  1901. h = '0' + h;
  1902. } else {
  1903. if (! h.match(/^[0-7]/)) {
  1904. h = '00' + h;
  1905. }
  1906. }
  1907. } else {
  1908. var hPos = h.substr(1);
  1909. var xorLen = hPos.length;
  1910. if (xorLen % 2 == 1) {
  1911. xorLen += 1;
  1912. } else {
  1913. if (! h.match(/^[0-7]/)) {
  1914. xorLen += 2;
  1915. }
  1916. }
  1917. var hMask = '';
  1918. for (var i = 0; i < xorLen; i++) {
  1919. hMask += 'f';
  1920. }
  1921. var biMask = new BigInteger(hMask, 16);
  1922. var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
  1923. h = biNeg.toString(16).replace(/^-/, '');
  1924. }
  1925. return h;
  1926. };
  1927. /**
  1928. * get PEM string from hexadecimal data and header string
  1929. * @name getPEMStringFromHex
  1930. * @memberOf KJUR.asn1.ASN1Util
  1931. * @function
  1932. * @param {String} dataHex hexadecimal string of PEM body
  1933. * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
  1934. * @return {String} PEM formatted string of input data
  1935. * @description
  1936. * @example
  1937. * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
  1938. * // value of pem will be:
  1939. * -----BEGIN PRIVATE KEY-----
  1940. * YWFh
  1941. * -----END PRIVATE KEY-----
  1942. */
  1943. this.getPEMStringFromHex = function(dataHex, pemHeader) {
  1944. var dataWA = CryptoJS.enc.Hex.parse(dataHex);
  1945. var dataB64 = CryptoJS.enc.Base64.stringify(dataWA);
  1946. var pemBody = dataB64.replace(/(.{64})/g, "$1\r\n");
  1947. pemBody = pemBody.replace(/\r\n$/, '');
  1948. return "-----BEGIN " + pemHeader + "-----\r\n" +
  1949. pemBody +
  1950. "\r\n-----END " + pemHeader + "-----\r\n";
  1951. };
  1952. };
  1953. // ********************************************************************
  1954. // Abstract ASN.1 Classes
  1955. // ********************************************************************
  1956. // ********************************************************************
  1957. /**
  1958. * base class for ASN.1 DER encoder object
  1959. * @name KJUR.asn1.ASN1Object
  1960. * @class base class for ASN.1 DER encoder object
  1961. * @property {Boolean} isModified flag whether internal data was changed
  1962. * @property {String} hTLV hexadecimal string of ASN.1 TLV
  1963. * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
  1964. * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
  1965. * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
  1966. * @description
  1967. */
  1968. KJUR.asn1.ASN1Object = function() {
  1969. var isModified = true;
  1970. var hTLV = null;
  1971. var hT = '00'
  1972. var hL = '00';
  1973. var hV = '';
  1974. /**
  1975. * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
  1976. * @name getLengthHexFromValue
  1977. * @memberOf KJUR.asn1.ASN1Object
  1978. * @function
  1979. * @return {String} hexadecimal string of ASN.1 TLV length(L)
  1980. */
  1981. this.getLengthHexFromValue = function() {
  1982. if (typeof this.hV == "undefined" || this.hV == null) {
  1983. throw "this.hV is null or undefined.";
  1984. }
  1985. if (this.hV.length % 2 == 1) {
  1986. throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
  1987. }
  1988. var n = this.hV.length / 2;
  1989. var hN = n.toString(16);
  1990. if (hN.length % 2 == 1) {
  1991. hN = "0" + hN;
  1992. }
  1993. if (n < 128) {
  1994. return hN;
  1995. } else {
  1996. var hNlen = hN.length / 2;
  1997. if (hNlen > 15) {
  1998. throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
  1999. }
  2000. var head = 128 + hNlen;
  2001. return head.toString(16) + hN;
  2002. }
  2003. };
  2004. /**
  2005. * get hexadecimal string of ASN.1 TLV bytes
  2006. * @name getEncodedHex
  2007. * @memberOf KJUR.asn1.ASN1Object
  2008. * @function
  2009. * @return {String} hexadecimal string of ASN.1 TLV
  2010. */
  2011. this.getEncodedHex = function() {
  2012. if (this.hTLV == null || this.isModified) {
  2013. this.hV = this.getFreshValueHex();
  2014. this.hL = this.getLengthHexFromValue();
  2015. this.hTLV = this.hT + this.hL + this.hV;
  2016. this.isModified = false;
  2017. //console.error("first time: " + this.hTLV);
  2018. }
  2019. return this.hTLV;
  2020. };
  2021. /**
  2022. * get hexadecimal string of ASN.1 TLV value(V) bytes
  2023. * @name getValueHex
  2024. * @memberOf KJUR.asn1.ASN1Object
  2025. * @function
  2026. * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
  2027. */
  2028. this.getValueHex = function() {
  2029. this.getEncodedHex();
  2030. return this.hV;
  2031. }
  2032. this.getFreshValueHex = function() {
  2033. return '';
  2034. };
  2035. };
  2036. // == BEGIN DERAbstractString ================================================
  2037. /**
  2038. * base class for ASN.1 DER string classes
  2039. * @name KJUR.asn1.DERAbstractString
  2040. * @class base class for ASN.1 DER string classes
  2041. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2042. * @property {String} s internal string of value
  2043. * @extends KJUR.asn1.ASN1Object
  2044. * @description
  2045. * <br/>
  2046. * As for argument 'params' for constructor, you can specify one of
  2047. * following properties:
  2048. * <ul>
  2049. * <li>str - specify initial ASN.1 value(V) by a string</li>
  2050. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2051. * </ul>
  2052. * NOTE: 'params' can be omitted.
  2053. */
  2054. KJUR.asn1.DERAbstractString = function(params) {
  2055. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  2056. var s = null;
  2057. var hV = null;
  2058. /**
  2059. * get string value of this string object
  2060. * @name getString
  2061. * @memberOf KJUR.asn1.DERAbstractString
  2062. * @function
  2063. * @return {String} string value of this string object
  2064. */
  2065. this.getString = function() {
  2066. return this.s;
  2067. };
  2068. /**
  2069. * set value by a string
  2070. * @name setString
  2071. * @memberOf KJUR.asn1.DERAbstractString
  2072. * @function
  2073. * @param {String} newS value by a string to set
  2074. */
  2075. this.setString = function(newS) {
  2076. this.hTLV = null;
  2077. this.isModified = true;
  2078. this.s = newS;
  2079. this.hV = stohex(this.s);
  2080. };
  2081. /**
  2082. * set value by a hexadecimal string
  2083. * @name setStringHex
  2084. * @memberOf KJUR.asn1.DERAbstractString
  2085. * @function
  2086. * @param {String} newHexString value by a hexadecimal string to set
  2087. */
  2088. this.setStringHex = function(newHexString) {
  2089. this.hTLV = null;
  2090. this.isModified = true;
  2091. this.s = null;
  2092. this.hV = newHexString;
  2093. };
  2094. this.getFreshValueHex = function() {
  2095. return this.hV;
  2096. };
  2097. if (typeof params != "undefined") {
  2098. if (typeof params['str'] != "undefined") {
  2099. this.setString(params['str']);
  2100. } else if (typeof params['hex'] != "undefined") {
  2101. this.setStringHex(params['hex']);
  2102. }
  2103. }
  2104. };
  2105. JSX.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
  2106. // == END DERAbstractString ================================================
  2107. // == BEGIN DERAbstractTime ==================================================
  2108. /**
  2109. * base class for ASN.1 DER Generalized/UTCTime class
  2110. * @name KJUR.asn1.DERAbstractTime
  2111. * @class base class for ASN.1 DER Generalized/UTCTime class
  2112. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  2113. * @extends KJUR.asn1.ASN1Object
  2114. * @description
  2115. * @see KJUR.asn1.ASN1Object - superclass
  2116. */
  2117. KJUR.asn1.DERAbstractTime = function(params) {
  2118. KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  2119. var s = null;
  2120. var date = null;
  2121. // --- PRIVATE METHODS --------------------
  2122. this.localDateToUTC = function(d) {
  2123. utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  2124. var utcDate = new Date(utc);
  2125. return utcDate;
  2126. };
  2127. this.formatDate = function(dateObject, type) {
  2128. var pad = this.zeroPadding;
  2129. var d = this.localDateToUTC(dateObject);
  2130. var year = String(d.getFullYear());
  2131. if (type == 'utc') year = year.substr(2, 2);
  2132. var month = pad(String(d.getMonth() + 1), 2);
  2133. var day = pad(String(d.getDate()), 2);
  2134. var hour = pad(String(d.getHours()), 2);
  2135. var min = pad(String(d.getMinutes()), 2);
  2136. var sec = pad(String(d.getSeconds()), 2);
  2137. return year + month + day + hour + min + sec + 'Z';
  2138. };
  2139. this.zeroPadding = function(s, len) {
  2140. if (s.length >= len) return s;
  2141. return new Array(len - s.length + 1).join('0') + s;
  2142. };
  2143. // --- PUBLIC METHODS --------------------
  2144. /**
  2145. * get string value of this string object
  2146. * @name getString
  2147. * @memberOf KJUR.asn1.DERAbstractTime
  2148. * @function
  2149. * @return {String} string value of this time object
  2150. */
  2151. this.getString = function() {
  2152. return this.s;
  2153. };
  2154. /**
  2155. * set value by a string
  2156. * @name setString
  2157. * @memberOf KJUR.asn1.DERAbstractTime
  2158. * @function
  2159. * @param {String} newS value by a string to set such like "130430235959Z"
  2160. */
  2161. this.setString = function(newS) {
  2162. this.hTLV = null;
  2163. this.isModified = true;
  2164. this.s = newS;
  2165. this.hV = stohex(this.s);
  2166. };
  2167. /**
  2168. * set value by a Date object
  2169. * @name setByDateValue
  2170. * @memberOf KJUR.asn1.DERAbstractTime
  2171. * @function
  2172. * @param {Integer} year year of date (ex. 2013)
  2173. * @param {Integer} month month of date between 1 and 12 (ex. 12)
  2174. * @param {Integer} day day of month
  2175. * @param {Integer} hour hours of date
  2176. * @param {Integer} min minutes of date
  2177. * @param {Integer} sec seconds of date
  2178. */
  2179. this.setByDateValue = function(year, month, day, hour, min, sec) {
  2180. var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
  2181. this.setByDate(dateObject);
  2182. };
  2183. this.getFreshValueHex = function() {
  2184. return this.hV;
  2185. };
  2186. };
  2187. JSX.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
  2188. // == END DERAbstractTime ==================================================
  2189. // == BEGIN DERAbstractStructured ============================================
  2190. /**
  2191. * base class for ASN.1 DER structured class
  2192. * @name KJUR.asn1.DERAbstractStructured
  2193. * @class base class for ASN.1 DER structured class
  2194. * @property {Array} asn1Array internal array of ASN1Object
  2195. * @extends KJUR.asn1.ASN1Object
  2196. * @description
  2197. * @see KJUR.asn1.ASN1Object - superclass
  2198. */
  2199. KJUR.asn1.DERAbstractStructured = function(params) {
  2200. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  2201. var asn1Array = null;
  2202. /**
  2203. * set value by array of ASN1Object
  2204. * @name setByASN1ObjectArray
  2205. * @memberOf KJUR.asn1.DERAbstractStructured
  2206. * @function
  2207. * @param {array} asn1ObjectArray array of ASN1Object to set
  2208. */
  2209. this.setByASN1ObjectArray = function(asn1ObjectArray) {
  2210. this.hTLV = null;
  2211. this.isModified = true;
  2212. this.asn1Array = asn1ObjectArray;
  2213. };
  2214. /**
  2215. * append an ASN1Object to internal array
  2216. * @name appendASN1Object
  2217. * @memberOf KJUR.asn1.DERAbstractStructured
  2218. * @function
  2219. * @param {ASN1Object} asn1Object to add
  2220. */
  2221. this.appendASN1Object = function(asn1Object) {
  2222. this.hTLV = null;
  2223. this.isModified = true;
  2224. this.asn1Array.push(asn1Object);
  2225. };
  2226. this.asn1Array = new Array();
  2227. if (typeof params != "undefined") {
  2228. if (typeof params['array'] != "undefined") {
  2229. this.asn1Array = params['array'];
  2230. }
  2231. }
  2232. };
  2233. JSX.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
  2234. // ********************************************************************
  2235. // ASN.1 Object Classes
  2236. // ********************************************************************
  2237. // ********************************************************************
  2238. /**
  2239. * class for ASN.1 DER Boolean
  2240. * @name KJUR.asn1.DERBoolean
  2241. * @class class for ASN.1 DER Boolean
  2242. * @extends KJUR.asn1.ASN1Object
  2243. * @description
  2244. * @see KJUR.asn1.ASN1Object - superclass
  2245. */
  2246. KJUR.asn1.DERBoolean = function() {
  2247. KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  2248. this.hT = "01";
  2249. this.hTLV = "0101ff";
  2250. };
  2251. JSX.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
  2252. // ********************************************************************
  2253. /**
  2254. * class for ASN.1 DER Integer
  2255. * @name KJUR.asn1.DERInteger
  2256. * @class class for ASN.1 DER Integer
  2257. * @extends KJUR.asn1.ASN1Object
  2258. * @description
  2259. * <br/>
  2260. * As for argument 'params' for constructor, you can specify one of
  2261. * following properties:
  2262. * <ul>
  2263. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  2264. * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
  2265. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2266. * </ul>
  2267. * NOTE: 'params' can be omitted.
  2268. */
  2269. KJUR.asn1.DERInteger = function(params) {
  2270. KJUR.asn1.DERInteger.superclass.constructor.call(this);
  2271. this.hT = "02";
  2272. /**
  2273. * set value by Tom Wu's BigInteger object
  2274. * @name setByBigInteger
  2275. * @memberOf KJUR.asn1.DERInteger
  2276. * @function
  2277. * @param {BigInteger} bigIntegerValue to set
  2278. */
  2279. this.setByBigInteger = function(bigIntegerValue) {
  2280. this.hTLV = null;
  2281. this.isModified = true;
  2282. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  2283. };
  2284. /**
  2285. * set value by integer value
  2286. * @name setByInteger
  2287. * @memberOf KJUR.asn1.DERInteger
  2288. * @function
  2289. * @param {Integer} integer value to set
  2290. */
  2291. this.setByInteger = function(intValue) {
  2292. var bi = new BigInteger(String(intValue), 10);
  2293. this.setByBigInteger(bi);
  2294. };
  2295. /**
  2296. * set value by integer value
  2297. * @name setValueHex
  2298. * @memberOf KJUR.asn1.DERInteger
  2299. * @function
  2300. * @param {String} hexadecimal string of integer value
  2301. * @description
  2302. * <br/>
  2303. * NOTE: Value shall be represented by minimum octet length of
  2304. * two's complement representation.
  2305. */
  2306. this.setValueHex = function(newHexString) {
  2307. this.hV = newHexString;
  2308. };
  2309. this.getFreshValueHex = function() {
  2310. return this.hV;
  2311. };
  2312. if (typeof params != "undefined") {
  2313. if (typeof params['bigint'] != "undefined") {
  2314. this.setByBigInteger(params['bigint']);
  2315. } else if (typeof params['int'] != "undefined") {
  2316. this.setByInteger(params['int']);
  2317. } else if (typeof params['hex'] != "undefined") {
  2318. this.setValueHex(params['hex']);
  2319. }
  2320. }
  2321. };
  2322. JSX.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
  2323. // ********************************************************************
  2324. /**
  2325. * class for ASN.1 DER encoded BitString primitive
  2326. * @name KJUR.asn1.DERBitString
  2327. * @class class for ASN.1 DER encoded BitString primitive
  2328. * @extends KJUR.asn1.ASN1Object
  2329. * @description
  2330. * <br/>
  2331. * As for argument 'params' for constructor, you can specify one of
  2332. * following properties:
  2333. * <ul>
  2334. * <li>bin - specify binary string (ex. '10111')</li>
  2335. * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
  2336. * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
  2337. * </ul>
  2338. * NOTE: 'params' can be omitted.
  2339. */
  2340. KJUR.asn1.DERBitString = function(params) {
  2341. KJUR.asn1.DERBitString.superclass.constructor.call(this);
  2342. this.hT = "03";
  2343. /**
  2344. * set ASN.1 value(V) by a hexadecimal string including unused bits
  2345. * @name setHexValueIncludingUnusedBits
  2346. * @memberOf KJUR.asn1.DERBitString
  2347. * @function
  2348. * @param {String} newHexStringIncludingUnusedBits
  2349. */
  2350. this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
  2351. this.hTLV = null;
  2352. this.isModified = true;
  2353. this.hV = newHexStringIncludingUnusedBits;
  2354. };
  2355. /**
  2356. * set ASN.1 value(V) by unused bit and hexadecimal string of value
  2357. * @name setUnusedBitsAndHexValue
  2358. * @memberOf KJUR.asn1.DERBitString
  2359. * @function
  2360. * @param {Integer} unusedBits
  2361. * @param {String} hValue
  2362. */
  2363. this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
  2364. if (unusedBits < 0 || 7 < unusedBits) {
  2365. throw "unused bits shall be from 0 to 7: u = " + unusedBits;
  2366. }
  2367. var hUnusedBits = "0" + unusedBits;
  2368. this.hTLV = null;
  2369. this.isModified = true;
  2370. this.hV = hUnusedBits + hValue;
  2371. };
  2372. /**
  2373. * set ASN.1 DER BitString by binary string
  2374. * @name setByBinaryString
  2375. * @memberOf KJUR.asn1.DERBitString
  2376. * @function
  2377. * @param {String} binaryString binary value string (i.e. '10111')
  2378. * @description
  2379. * Its unused bits will be calculated automatically by length of
  2380. * 'binaryValue'. <br/>
  2381. * NOTE: Trailing zeros '0' will be ignored.
  2382. */
  2383. this.setByBinaryString = function(binaryString) {
  2384. binaryString = binaryString.replace(/0+$/, '');
  2385. var unusedBits = 8 - binaryString.length % 8;
  2386. if (unusedBits == 8) unusedBits = 0;
  2387. for (var i = 0; i <= unusedBits; i++) {
  2388. binaryString += '0';
  2389. }
  2390. var h = '';
  2391. for (var i = 0; i < binaryString.length - 1; i += 8) {
  2392. var b = binaryString.substr(i, 8);
  2393. var x = parseInt(b, 2).toString(16);
  2394. if (x.length == 1) x = '0' + x;
  2395. h += x;
  2396. }
  2397. this.hTLV = null;
  2398. this.isModified = true;
  2399. this.hV = '0' + unusedBits + h;
  2400. };
  2401. /**
  2402. * set ASN.1 TLV value(V) by an array of boolean
  2403. * @name setByBooleanArray
  2404. * @memberOf KJUR.asn1.DERBitString
  2405. * @function
  2406. * @param {array} booleanArray array of boolean (ex. [true, false, true])
  2407. * @description
  2408. * NOTE: Trailing falses will be ignored.
  2409. */
  2410. this.setByBooleanArray = function(booleanArray) {
  2411. var s = '';
  2412. for (var i = 0; i < booleanArray.length; i++) {
  2413. if (booleanArray[i] == true) {
  2414. s += '1';
  2415. } else {
  2416. s += '0';
  2417. }
  2418. }
  2419. this.setByBinaryString(s);
  2420. };
  2421. /**
  2422. * generate an array of false with specified length
  2423. * @name newFalseArray
  2424. * @memberOf KJUR.asn1.DERBitString
  2425. * @function
  2426. * @param {Integer} nLength length of array to generate
  2427. * @return {array} array of boolean faluse
  2428. * @description
  2429. * This static method may be useful to initialize boolean array.
  2430. */
  2431. this.newFalseArray = function(nLength) {
  2432. var a = new Array(nLength);
  2433. for (var i = 0; i < nLength; i++) {
  2434. a[i] = false;
  2435. }
  2436. return a;
  2437. };
  2438. this.getFreshValueHex = function() {
  2439. return this.hV;
  2440. };
  2441. if (typeof params != "undefined") {
  2442. if (typeof params['hex'] != "undefined") {
  2443. this.setHexValueIncludingUnusedBits(params['hex']);
  2444. } else if (typeof params['bin'] != "undefined") {
  2445. this.setByBinaryString(params['bin']);
  2446. } else if (typeof params['array'] != "undefined") {
  2447. this.setByBooleanArray(params['array']);
  2448. }
  2449. }
  2450. };
  2451. JSX.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
  2452. // ********************************************************************
  2453. /**
  2454. * class for ASN.1 DER OctetString
  2455. * @name KJUR.asn1.DEROctetString
  2456. * @class class for ASN.1 DER OctetString
  2457. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2458. * @extends KJUR.asn1.DERAbstractString
  2459. * @description
  2460. * @see KJUR.asn1.DERAbstractString - superclass
  2461. */
  2462. KJUR.asn1.DEROctetString = function(params) {
  2463. KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  2464. this.hT = "04";
  2465. };
  2466. JSX.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
  2467. // ********************************************************************
  2468. /**
  2469. * class for ASN.1 DER Null
  2470. * @name KJUR.asn1.DERNull
  2471. * @class class for ASN.1 DER Null
  2472. * @extends KJUR.asn1.ASN1Object
  2473. * @description
  2474. * @see KJUR.asn1.ASN1Object - superclass
  2475. */
  2476. KJUR.asn1.DERNull = function() {
  2477. KJUR.asn1.DERNull.superclass.constructor.call(this);
  2478. this.hT = "05";
  2479. this.hTLV = "0500";
  2480. };
  2481. JSX.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
  2482. // ********************************************************************
  2483. /**
  2484. * class for ASN.1 DER ObjectIdentifier
  2485. * @name KJUR.asn1.DERObjectIdentifier
  2486. * @class class for ASN.1 DER ObjectIdentifier
  2487. * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
  2488. * @extends KJUR.asn1.ASN1Object
  2489. * @description
  2490. * <br/>
  2491. * As for argument 'params' for constructor, you can specify one of
  2492. * following properties:
  2493. * <ul>
  2494. * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
  2495. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2496. * </ul>
  2497. * NOTE: 'params' can be omitted.
  2498. */
  2499. KJUR.asn1.DERObjectIdentifier = function(params) {
  2500. var itox = function(i) {
  2501. var h = i.toString(16);
  2502. if (h.length == 1) h = '0' + h;
  2503. return h;
  2504. };
  2505. var roidtox = function(roid) {
  2506. var h = '';
  2507. var bi = new BigInteger(roid, 10);
  2508. var b = bi.toString(2);
  2509. var padLen = 7 - b.length % 7;
  2510. if (padLen == 7) padLen = 0;
  2511. var bPad = '';
  2512. for (var i = 0; i < padLen; i++) bPad += '0';
  2513. b = bPad + b;
  2514. for (var i = 0; i < b.length - 1; i += 7) {
  2515. var b8 = b.substr(i, 7);
  2516. if (i != b.length - 7) b8 = '1' + b8;
  2517. h += itox(parseInt(b8, 2));
  2518. }
  2519. return h;
  2520. }
  2521. KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  2522. this.hT = "06";
  2523. /**
  2524. * set value by a hexadecimal string
  2525. * @name setValueHex
  2526. * @memberOf KJUR.asn1.DERObjectIdentifier
  2527. * @function
  2528. * @param {String} newHexString hexadecimal value of OID bytes
  2529. */
  2530. this.setValueHex = function(newHexString) {
  2531. this.hTLV = null;
  2532. this.isModified = true;
  2533. this.s = null;
  2534. this.hV = newHexString;
  2535. };
  2536. /**
  2537. * set value by a OID string
  2538. * @name setValueOidString
  2539. * @memberOf KJUR.asn1.DERObjectIdentifier
  2540. * @function
  2541. * @param {String} oidString OID string (ex. 2.5.4.13)
  2542. */
  2543. this.setValueOidString = function(oidString) {
  2544. if (! oidString.match(/^[0-9.]+$/)) {
  2545. throw "malformed oid string: " + oidString;
  2546. }
  2547. var h = '';
  2548. var a = oidString.split('.');
  2549. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  2550. h += itox(i0);
  2551. a.splice(0, 2);
  2552. for (var i = 0; i < a.length; i++) {
  2553. h += roidtox(a[i]);
  2554. }
  2555. this.hTLV = null;
  2556. this.isModified = true;
  2557. this.s = null;
  2558. this.hV = h;
  2559. };
  2560. /**
  2561. * set value by a OID name
  2562. * @name setValueName
  2563. * @memberOf KJUR.asn1.DERObjectIdentifier
  2564. * @function
  2565. * @param {String} oidName OID name (ex. 'serverAuth')
  2566. * @since 1.0.1
  2567. * @description
  2568. * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
  2569. * Otherwise raise error.
  2570. */
  2571. this.setValueName = function(oidName) {
  2572. if (typeof KJUR.asn1.x509.OID.name2oidList[oidName] != "undefined") {
  2573. var oid = KJUR.asn1.x509.OID.name2oidList[oidName];
  2574. this.setValueOidString(oid);
  2575. } else {
  2576. throw "DERObjectIdentifier oidName undefined: " + oidName;
  2577. }
  2578. };
  2579. this.getFreshValueHex = function() {
  2580. return this.hV;
  2581. };
  2582. if (typeof params != "undefined") {
  2583. if (typeof params['oid'] != "undefined") {
  2584. this.setValueOidString(params['oid']);
  2585. } else if (typeof params['hex'] != "undefined") {
  2586. this.setValueHex(params['hex']);
  2587. } else if (typeof params['name'] != "undefined") {
  2588. this.setValueName(params['name']);
  2589. }
  2590. }
  2591. };
  2592. JSX.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
  2593. // ********************************************************************
  2594. /**
  2595. * class for ASN.1 DER UTF8String
  2596. * @name KJUR.asn1.DERUTF8String
  2597. * @class class for ASN.1 DER UTF8String
  2598. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2599. * @extends KJUR.asn1.DERAbstractString
  2600. * @description
  2601. * @see KJUR.asn1.DERAbstractString - superclass
  2602. */
  2603. KJUR.asn1.DERUTF8String = function(params) {
  2604. KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  2605. this.hT = "0c";
  2606. };
  2607. JSX.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
  2608. // ********************************************************************
  2609. /**
  2610. * class for ASN.1 DER NumericString
  2611. * @name KJUR.asn1.DERNumericString
  2612. * @class class for ASN.1 DER NumericString
  2613. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2614. * @extends KJUR.asn1.DERAbstractString
  2615. * @description
  2616. * @see KJUR.asn1.DERAbstractString - superclass
  2617. */
  2618. KJUR.asn1.DERNumericString = function(params) {
  2619. KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  2620. this.hT = "12";
  2621. };
  2622. JSX.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
  2623. // ********************************************************************
  2624. /**
  2625. * class for ASN.1 DER PrintableString
  2626. * @name KJUR.asn1.DERPrintableString
  2627. * @class class for ASN.1 DER PrintableString
  2628. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2629. * @extends KJUR.asn1.DERAbstractString
  2630. * @description
  2631. * @see KJUR.asn1.DERAbstractString - superclass
  2632. */
  2633. KJUR.asn1.DERPrintableString = function(params) {
  2634. KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  2635. this.hT = "13";
  2636. };
  2637. JSX.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
  2638. // ********************************************************************
  2639. /**
  2640. * class for ASN.1 DER TeletexString
  2641. * @name KJUR.asn1.DERTeletexString
  2642. * @class class for ASN.1 DER TeletexString
  2643. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2644. * @extends KJUR.asn1.DERAbstractString
  2645. * @description
  2646. * @see KJUR.asn1.DERAbstractString - superclass
  2647. */
  2648. KJUR.asn1.DERTeletexString = function(params) {
  2649. KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  2650. this.hT = "14";
  2651. };
  2652. JSX.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
  2653. // ********************************************************************
  2654. /**
  2655. * class for ASN.1 DER IA5String
  2656. * @name KJUR.asn1.DERIA5String
  2657. * @class class for ASN.1 DER IA5String
  2658. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2659. * @extends KJUR.asn1.DERAbstractString
  2660. * @description
  2661. * @see KJUR.asn1.DERAbstractString - superclass
  2662. */
  2663. KJUR.asn1.DERIA5String = function(params) {
  2664. KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  2665. this.hT = "16";
  2666. };
  2667. JSX.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
  2668. // ********************************************************************
  2669. /**
  2670. * class for ASN.1 DER UTCTime
  2671. * @name KJUR.asn1.DERUTCTime
  2672. * @class class for ASN.1 DER UTCTime
  2673. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  2674. * @extends KJUR.asn1.DERAbstractTime
  2675. * @description
  2676. * <br/>
  2677. * As for argument 'params' for constructor, you can specify one of
  2678. * following properties:
  2679. * <ul>
  2680. * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
  2681. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2682. * <li>date - specify Date object.</li>
  2683. * </ul>
  2684. * NOTE: 'params' can be omitted.
  2685. * <h4>EXAMPLES</h4>
  2686. * @example
  2687. * var d1 = new KJUR.asn1.DERUTCTime();
  2688. * d1.setString('130430125959Z');
  2689. *
  2690. * var d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
  2691. *
  2692. * var d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
  2693. */
  2694. KJUR.asn1.DERUTCTime = function(params) {
  2695. KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  2696. this.hT = "17";
  2697. /**
  2698. * set value by a Date object
  2699. * @name setByDate
  2700. * @memberOf KJUR.asn1.DERUTCTime
  2701. * @function
  2702. * @param {Date} dateObject Date object to set ASN.1 value(V)
  2703. */
  2704. this.setByDate = function(dateObject) {
  2705. this.hTLV = null;
  2706. this.isModified = true;
  2707. this.date = dateObject;
  2708. this.s = this.formatDate(this.date, 'utc');
  2709. this.hV = stohex(this.s);
  2710. };
  2711. if (typeof params != "undefined") {
  2712. if (typeof params['str'] != "undefined") {
  2713. this.setString(params['str']);
  2714. } else if (typeof params['hex'] != "undefined") {
  2715. this.setStringHex(params['hex']);
  2716. } else if (typeof params['date'] != "undefined") {
  2717. this.setByDate(params['date']);
  2718. }
  2719. }
  2720. };
  2721. JSX.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
  2722. // ********************************************************************
  2723. /**
  2724. * class for ASN.1 DER GeneralizedTime
  2725. * @name KJUR.asn1.DERGeneralizedTime
  2726. * @class class for ASN.1 DER GeneralizedTime
  2727. * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
  2728. * @extends KJUR.asn1.DERAbstractTime
  2729. * @description
  2730. * <br/>
  2731. * As for argument 'params' for constructor, you can specify one of
  2732. * following properties:
  2733. * <ul>
  2734. * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
  2735. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2736. * <li>date - specify Date object.</li>
  2737. * </ul>
  2738. * NOTE: 'params' can be omitted.
  2739. */
  2740. KJUR.asn1.DERGeneralizedTime = function(params) {
  2741. KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  2742. this.hT = "18";
  2743. /**
  2744. * set value by a Date object
  2745. * @name setByDate
  2746. * @memberOf KJUR.asn1.DERGeneralizedTime
  2747. * @function
  2748. * @param {Date} dateObject Date object to set ASN.1 value(V)
  2749. * @example
  2750. * When you specify UTC time, use 'Date.UTC' method like this:<br/>
  2751. * var o = new DERUTCTime();
  2752. * var date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
  2753. * o.setByDate(date);
  2754. */
  2755. this.setByDate = function(dateObject) {
  2756. this.hTLV = null;
  2757. this.isModified = true;
  2758. this.date = dateObject;
  2759. this.s = this.formatDate(this.date, 'gen');
  2760. this.hV = stohex(this.s);
  2761. };
  2762. if (typeof params != "undefined") {
  2763. if (typeof params['str'] != "undefined") {
  2764. this.setString(params['str']);
  2765. } else if (typeof params['hex'] != "undefined") {
  2766. this.setStringHex(params['hex']);
  2767. } else if (typeof params['date'] != "undefined") {
  2768. this.setByDate(params['date']);
  2769. }
  2770. }
  2771. };
  2772. JSX.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
  2773. // ********************************************************************
  2774. /**
  2775. * class for ASN.1 DER Sequence
  2776. * @name KJUR.asn1.DERSequence
  2777. * @class class for ASN.1 DER Sequence
  2778. * @extends KJUR.asn1.DERAbstractStructured
  2779. * @description
  2780. * <br/>
  2781. * As for argument 'params' for constructor, you can specify one of
  2782. * following properties:
  2783. * <ul>
  2784. * <li>array - specify array of ASN1Object to set elements of content</li>
  2785. * </ul>
  2786. * NOTE: 'params' can be omitted.
  2787. */
  2788. KJUR.asn1.DERSequence = function(params) {
  2789. KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  2790. this.hT = "30";
  2791. this.getFreshValueHex = function() {
  2792. var h = '';
  2793. for (var i = 0; i < this.asn1Array.length; i++) {
  2794. var asn1Obj = this.asn1Array[i];
  2795. h += asn1Obj.getEncodedHex();
  2796. }
  2797. this.hV = h;
  2798. return this.hV;
  2799. };
  2800. };
  2801. JSX.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
  2802. // ********************************************************************
  2803. /**
  2804. * class for ASN.1 DER Set
  2805. * @name KJUR.asn1.DERSet
  2806. * @class class for ASN.1 DER Set
  2807. * @extends KJUR.asn1.DERAbstractStructured
  2808. * @description
  2809. * <br/>
  2810. * As for argument 'params' for constructor, you can specify one of
  2811. * following properties:
  2812. * <ul>
  2813. * <li>array - specify array of ASN1Object to set elements of content</li>
  2814. * </ul>
  2815. * NOTE: 'params' can be omitted.
  2816. */
  2817. KJUR.asn1.DERSet = function(params) {
  2818. KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  2819. this.hT = "31";
  2820. this.getFreshValueHex = function() {
  2821. var a = new Array();
  2822. for (var i = 0; i < this.asn1Array.length; i++) {
  2823. var asn1Obj = this.asn1Array[i];
  2824. a.push(asn1Obj.getEncodedHex());
  2825. }
  2826. a.sort();
  2827. this.hV = a.join('');
  2828. return this.hV;
  2829. };
  2830. };
  2831. JSX.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
  2832. // ********************************************************************
  2833. /**
  2834. * class for ASN.1 DER TaggedObject
  2835. * @name KJUR.asn1.DERTaggedObject
  2836. * @class class for ASN.1 DER TaggedObject
  2837. * @extends KJUR.asn1.ASN1Object
  2838. * @description
  2839. * <br/>
  2840. * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
  2841. * For example, if you find '[1]' tag in a ASN.1 dump,
  2842. * 'tagNoHex' will be 'a1'.
  2843. * <br/>
  2844. * As for optional argument 'params' for constructor, you can specify *ANY* of
  2845. * following properties:
  2846. * <ul>
  2847. * <li>explicit - specify true if this is explicit tag otherwise false
  2848. * (default is 'true').</li>
  2849. * <li>tag - specify tag (default is 'a0' which means [0])</li>
  2850. * <li>obj - specify ASN1Object which is tagged</li>
  2851. * </ul>
  2852. * @example
  2853. * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
  2854. * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
  2855. * hex = d2.getEncodedHex();
  2856. */
  2857. KJUR.asn1.DERTaggedObject = function(params) {
  2858. KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  2859. this.hT = "a0";
  2860. this.hV = '';
  2861. this.isExplicit = true;
  2862. this.asn1Object = null;
  2863. /**
  2864. * set value by an ASN1Object
  2865. * @name setString
  2866. * @memberOf KJUR.asn1.DERTaggedObject
  2867. * @function
  2868. * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
  2869. * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
  2870. * @param {ASN1Object} asn1Object ASN.1 to encapsulate
  2871. */
  2872. this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
  2873. this.hT = tagNoHex;
  2874. this.isExplicit = isExplicitFlag;
  2875. this.asn1Object = asn1Object;
  2876. if (this.isExplicit) {
  2877. this.hV = this.asn1Object.getEncodedHex();
  2878. this.hTLV = null;
  2879. this.isModified = true;
  2880. } else {
  2881. this.hV = null;
  2882. this.hTLV = asn1Object.getEncodedHex();
  2883. this.hTLV = this.hTLV.replace(/^../, tagNoHex);
  2884. this.isModified = false;
  2885. }
  2886. };
  2887. this.getFreshValueHex = function() {
  2888. return this.hV;
  2889. };
  2890. if (typeof params != "undefined") {
  2891. if (typeof params['tag'] != "undefined") {
  2892. this.hT = params['tag'];
  2893. }
  2894. if (typeof params['explicit'] != "undefined") {
  2895. this.isExplicit = params['explicit'];
  2896. }
  2897. if (typeof params['obj'] != "undefined") {
  2898. this.asn1Object = params['obj'];
  2899. this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
  2900. }
  2901. }
  2902. };
  2903. JSX.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
  2904. // Hex JavaScript decoder
  2905. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  2906. // Permission to use, copy, modify, and/or distribute this software for any
  2907. // purpose with or without fee is hereby granted, provided that the above
  2908. // copyright notice and this permission notice appear in all copies.
  2909. //
  2910. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  2911. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  2912. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  2913. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  2914. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  2915. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  2916. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  2917. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  2918. (function (undefined) {
  2919. "use strict";
  2920. var Hex = {},
  2921. decoder;
  2922. Hex.decode = function(a) {
  2923. var i;
  2924. if (decoder === undefined) {
  2925. var hex = "0123456789ABCDEF",
  2926. ignore = " \f\n\r\t\u00A0\u2028\u2029";
  2927. decoder = [];
  2928. for (i = 0; i < 16; ++i)
  2929. decoder[hex.charAt(i)] = i;
  2930. hex = hex.toLowerCase();
  2931. for (i = 10; i < 16; ++i)
  2932. decoder[hex.charAt(i)] = i;
  2933. for (i = 0; i < ignore.length; ++i)
  2934. decoder[ignore.charAt(i)] = -1;
  2935. }
  2936. var out = [],
  2937. bits = 0,
  2938. char_count = 0;
  2939. for (i = 0; i < a.length; ++i) {
  2940. var c = a.charAt(i);
  2941. if (c == '=')
  2942. break;
  2943. c = decoder[c];
  2944. if (c == -1)
  2945. continue;
  2946. if (c === undefined)
  2947. throw 'Illegal character at offset ' + i;
  2948. bits |= c;
  2949. if (++char_count >= 2) {
  2950. out[out.length] = bits;
  2951. bits = 0;
  2952. char_count = 0;
  2953. } else {
  2954. bits <<= 4;
  2955. }
  2956. }
  2957. if (char_count)
  2958. throw "Hex encoding incomplete: 4 bits missing";
  2959. return out;
  2960. };
  2961. // export globals
  2962. window.Hex = Hex;
  2963. })();
  2964. // Base64 JavaScript decoder
  2965. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  2966. // Permission to use, copy, modify, and/or distribute this software for any
  2967. // purpose with or without fee is hereby granted, provided that the above
  2968. // copyright notice and this permission notice appear in all copies.
  2969. //
  2970. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  2971. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  2972. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  2973. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  2974. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  2975. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  2976. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  2977. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  2978. (function (undefined) {
  2979. "use strict";
  2980. var Base64 = {},
  2981. decoder;
  2982. Base64.decode = function (a) {
  2983. var i;
  2984. if (decoder === undefined) {
  2985. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  2986. ignore = "= \f\n\r\t\u00A0\u2028\u2029";
  2987. decoder = [];
  2988. for (i = 0; i < 64; ++i)
  2989. decoder[b64.charAt(i)] = i;
  2990. for (i = 0; i < ignore.length; ++i)
  2991. decoder[ignore.charAt(i)] = -1;
  2992. }
  2993. var out = [];
  2994. var bits = 0, char_count = 0;
  2995. for (i = 0; i < a.length; ++i) {
  2996. var c = a.charAt(i);
  2997. if (c == '=')
  2998. break;
  2999. c = decoder[c];
  3000. if (c == -1)
  3001. continue;
  3002. if (c === undefined)
  3003. throw 'Illegal character at offset ' + i;
  3004. bits |= c;
  3005. if (++char_count >= 4) {
  3006. out[out.length] = (bits >> 16);
  3007. out[out.length] = (bits >> 8) & 0xFF;
  3008. out[out.length] = bits & 0xFF;
  3009. bits = 0;
  3010. char_count = 0;
  3011. } else {
  3012. bits <<= 6;
  3013. }
  3014. }
  3015. switch (char_count) {
  3016. case 1:
  3017. throw "Base64 encoding incomplete: at least 2 bits missing";
  3018. case 2:
  3019. out[out.length] = (bits >> 10);
  3020. break;
  3021. case 3:
  3022. out[out.length] = (bits >> 16);
  3023. out[out.length] = (bits >> 8) & 0xFF;
  3024. break;
  3025. }
  3026. return out;
  3027. };
  3028. Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
  3029. Base64.unarmor = function (a) {
  3030. var m = Base64.re.exec(a);
  3031. if (m) {
  3032. if (m[1])
  3033. a = m[1];
  3034. else if (m[2])
  3035. a = m[2];
  3036. else
  3037. throw "RegExp out of sync";
  3038. }
  3039. return Base64.decode(a);
  3040. };
  3041. // export globals
  3042. window.Base64 = Base64;
  3043. })();
  3044. // ASN.1 JavaScript decoder
  3045. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  3046. // Permission to use, copy, modify, and/or distribute this software for any
  3047. // purpose with or without fee is hereby granted, provided that the above
  3048. // copyright notice and this permission notice appear in all copies.
  3049. //
  3050. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  3051. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  3052. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  3053. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  3054. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  3055. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  3056. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  3057. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  3058. /*global oids */
  3059. (function (undefined) {
  3060. "use strict";
  3061. var hardLimit = 100,
  3062. ellipsis = "\u2026",
  3063. DOM = {
  3064. tag: function (tagName, className) {
  3065. var t = document.createElement(tagName);
  3066. t.className = className;
  3067. return t;
  3068. },
  3069. text: function (str) {
  3070. return document.createTextNode(str);
  3071. }
  3072. };
  3073. function Stream(enc, pos) {
  3074. if (enc instanceof Stream) {
  3075. this.enc = enc.enc;
  3076. this.pos = enc.pos;
  3077. } else {
  3078. this.enc = enc;
  3079. this.pos = pos;
  3080. }
  3081. }
  3082. Stream.prototype.get = function (pos) {
  3083. if (pos === undefined)
  3084. pos = this.pos++;
  3085. if (pos >= this.enc.length)
  3086. throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length;
  3087. return this.enc[pos];
  3088. };
  3089. Stream.prototype.hexDigits = "0123456789ABCDEF";
  3090. Stream.prototype.hexByte = function (b) {
  3091. return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
  3092. };
  3093. Stream.prototype.hexDump = function (start, end, raw) {
  3094. var s = "";
  3095. for (var i = start; i < end; ++i) {
  3096. s += this.hexByte(this.get(i));
  3097. if (raw !== true)
  3098. switch (i & 0xF) {
  3099. case 0x7: s += " "; break;
  3100. case 0xF: s += "\n"; break;
  3101. default: s += " ";
  3102. }
  3103. }
  3104. return s;
  3105. };
  3106. Stream.prototype.parseStringISO = function (start, end) {
  3107. var s = "";
  3108. for (var i = start; i < end; ++i)
  3109. s += String.fromCharCode(this.get(i));
  3110. return s;
  3111. };
  3112. Stream.prototype.parseStringUTF = function (start, end) {
  3113. var s = "";
  3114. for (var i = start; i < end; ) {
  3115. var c = this.get(i++);
  3116. if (c < 128)
  3117. s += String.fromCharCode(c);
  3118. else if ((c > 191) && (c < 224))
  3119. s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
  3120. else
  3121. s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
  3122. }
  3123. return s;
  3124. };
  3125. Stream.prototype.parseStringBMP = function (start, end) {
  3126. var str = ""
  3127. for (var i = start; i < end; i += 2) {
  3128. var high_byte = this.get(i);
  3129. var low_byte = this.get(i + 1);
  3130. str += String.fromCharCode( (high_byte << 8) + low_byte );
  3131. }
  3132. return str;
  3133. };
  3134. Stream.prototype.reTime = /^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
  3135. Stream.prototype.parseTime = function (start, end) {
  3136. var s = this.parseStringISO(start, end),
  3137. m = this.reTime.exec(s);
  3138. if (!m)
  3139. return "Unrecognized time: " + s;
  3140. s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
  3141. if (m[5]) {
  3142. s += ":" + m[5];
  3143. if (m[6]) {
  3144. s += ":" + m[6];
  3145. if (m[7])
  3146. s += "." + m[7];
  3147. }
  3148. }
  3149. if (m[8]) {
  3150. s += " UTC";
  3151. if (m[8] != 'Z') {
  3152. s += m[8];
  3153. if (m[9])
  3154. s += ":" + m[9];
  3155. }
  3156. }
  3157. return s;
  3158. };
  3159. Stream.prototype.parseInteger = function (start, end) {
  3160. //TODO support negative numbers
  3161. var len = end - start;
  3162. if (len > 4) {
  3163. len <<= 3;
  3164. var s = this.get(start);
  3165. if (s === 0)
  3166. len -= 8;
  3167. else
  3168. while (s < 128) {
  3169. s <<= 1;
  3170. --len;
  3171. }
  3172. return "(" + len + " bit)";
  3173. }
  3174. var n = 0;
  3175. for (var i = start; i < end; ++i)
  3176. n = (n << 8) | this.get(i);
  3177. return n;
  3178. };
  3179. Stream.prototype.parseBitString = function (start, end) {
  3180. var unusedBit = this.get(start),
  3181. lenBit = ((end - start - 1) << 3) - unusedBit,
  3182. s = "(" + lenBit + " bit)";
  3183. if (lenBit <= 20) {
  3184. var skip = unusedBit;
  3185. s += " ";
  3186. for (var i = end - 1; i > start; --i) {
  3187. var b = this.get(i);
  3188. for (var j = skip; j < 8; ++j)
  3189. s += (b >> j) & 1 ? "1" : "0";
  3190. skip = 0;
  3191. }
  3192. }
  3193. return s;
  3194. };
  3195. Stream.prototype.parseOctetString = function (start, end) {
  3196. var len = end - start,
  3197. s = "(" + len + " byte) ";
  3198. if (len > hardLimit)
  3199. end = start + hardLimit;
  3200. for (var i = start; i < end; ++i)
  3201. s += this.hexByte(this.get(i)); //TODO: also try Latin1?
  3202. if (len > hardLimit)
  3203. s += ellipsis;
  3204. return s;
  3205. };
  3206. Stream.prototype.parseOID = function (start, end) {
  3207. var s = '',
  3208. n = 0,
  3209. bits = 0;
  3210. for (var i = start; i < end; ++i) {
  3211. var v = this.get(i);
  3212. n = (n << 7) | (v & 0x7F);
  3213. bits += 7;
  3214. if (!(v & 0x80)) { // finished
  3215. if (s === '') {
  3216. var m = n < 80 ? n < 40 ? 0 : 1 : 2;
  3217. s = m + "." + (n - m * 40);
  3218. } else
  3219. s += "." + ((bits >= 31) ? "bigint" : n);
  3220. n = bits = 0;
  3221. }
  3222. }
  3223. return s;
  3224. };
  3225. function ASN1(stream, header, length, tag, sub) {
  3226. this.stream = stream;
  3227. this.header = header;
  3228. this.length = length;
  3229. this.tag = tag;
  3230. this.sub = sub;
  3231. }
  3232. ASN1.prototype.typeName = function () {
  3233. if (this.tag === undefined)
  3234. return "unknown";
  3235. var tagClass = this.tag >> 6,
  3236. tagConstructed = (this.tag >> 5) & 1,
  3237. tagNumber = this.tag & 0x1F;
  3238. switch (tagClass) {
  3239. case 0: // universal
  3240. switch (tagNumber) {
  3241. case 0x00: return "EOC";
  3242. case 0x01: return "BOOLEAN";
  3243. case 0x02: return "INTEGER";
  3244. case 0x03: return "BIT_STRING";
  3245. case 0x04: return "OCTET_STRING";
  3246. case 0x05: return "NULL";
  3247. case 0x06: return "OBJECT_IDENTIFIER";
  3248. case 0x07: return "ObjectDescriptor";
  3249. case 0x08: return "EXTERNAL";
  3250. case 0x09: return "REAL";
  3251. case 0x0A: return "ENUMERATED";
  3252. case 0x0B: return "EMBEDDED_PDV";
  3253. case 0x0C: return "UTF8String";
  3254. case 0x10: return "SEQUENCE";
  3255. case 0x11: return "SET";
  3256. case 0x12: return "NumericString";
  3257. case 0x13: return "PrintableString"; // ASCII subset
  3258. case 0x14: return "TeletexString"; // aka T61String
  3259. case 0x15: return "VideotexString";
  3260. case 0x16: return "IA5String"; // ASCII
  3261. case 0x17: return "UTCTime";
  3262. case 0x18: return "GeneralizedTime";
  3263. case 0x19: return "GraphicString";
  3264. case 0x1A: return "VisibleString"; // ASCII subset
  3265. case 0x1B: return "GeneralString";
  3266. case 0x1C: return "UniversalString";
  3267. case 0x1E: return "BMPString";
  3268. default: return "Universal_" + tagNumber.toString(16);
  3269. }
  3270. case 1: return "Application_" + tagNumber.toString(16);
  3271. case 2: return "[" + tagNumber + "]"; // Context
  3272. case 3: return "Private_" + tagNumber.toString(16);
  3273. }
  3274. };
  3275. ASN1.prototype.reSeemsASCII = /^[ -~]+$/;
  3276. ASN1.prototype.content = function () {
  3277. if (this.tag === undefined)
  3278. return null;
  3279. var tagClass = this.tag >> 6,
  3280. tagNumber = this.tag & 0x1F,
  3281. content = this.posContent(),
  3282. len = Math.abs(this.length);
  3283. if (tagClass !== 0) { // universal
  3284. if (this.sub !== null)
  3285. return "(" + this.sub.length + " elem)";
  3286. //TODO: TRY TO PARSE ASCII STRING
  3287. var s = this.stream.parseStringISO(content, content + Math.min(len, hardLimit));
  3288. if (this.reSeemsASCII.test(s))
  3289. return s.substring(0, 2 * hardLimit) + ((s.length > 2 * hardLimit) ? ellipsis : "");
  3290. else
  3291. return this.stream.parseOctetString(content, content + len);
  3292. }
  3293. switch (tagNumber) {
  3294. case 0x01: // BOOLEAN
  3295. return (this.stream.get(content) === 0) ? "false" : "true";
  3296. case 0x02: // INTEGER
  3297. return this.stream.parseInteger(content, content + len);
  3298. case 0x03: // BIT_STRING
  3299. return this.sub ? "(" + this.sub.length + " elem)" :
  3300. this.stream.parseBitString(content, content + len);
  3301. case 0x04: // OCTET_STRING
  3302. return this.sub ? "(" + this.sub.length + " elem)" :
  3303. this.stream.parseOctetString(content, content + len);
  3304. //case 0x05: // NULL
  3305. case 0x06: // OBJECT_IDENTIFIER
  3306. return this.stream.parseOID(content, content + len);
  3307. //case 0x07: // ObjectDescriptor
  3308. //case 0x08: // EXTERNAL
  3309. //case 0x09: // REAL
  3310. //case 0x0A: // ENUMERATED
  3311. //case 0x0B: // EMBEDDED_PDV
  3312. case 0x10: // SEQUENCE
  3313. case 0x11: // SET
  3314. return "(" + this.sub.length + " elem)";
  3315. case 0x0C: // UTF8String
  3316. return this.stream.parseStringUTF(content, content + len);
  3317. case 0x12: // NumericString
  3318. case 0x13: // PrintableString
  3319. case 0x14: // TeletexString
  3320. case 0x15: // VideotexString
  3321. case 0x16: // IA5String
  3322. //case 0x19: // GraphicString
  3323. case 0x1A: // VisibleString
  3324. //case 0x1B: // GeneralString
  3325. //case 0x1C: // UniversalString
  3326. return this.stream.parseStringISO(content, content + len);
  3327. case 0x1E: // BMPString
  3328. return this.stream.parseStringBMP(content, content + len);
  3329. case 0x17: // UTCTime
  3330. case 0x18: // GeneralizedTime
  3331. return this.stream.parseTime(content, content + len);
  3332. }
  3333. return null;
  3334. };
  3335. ASN1.prototype.toString = function () {
  3336. return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? 'null' : this.sub.length) + "]";
  3337. };
  3338. ASN1.prototype.print = function (indent) {
  3339. if (indent === undefined) indent = '';
  3340. document.writeln(indent + this);
  3341. if (this.sub !== null) {
  3342. indent += ' ';
  3343. for (var i = 0, max = this.sub.length; i < max; ++i)
  3344. this.sub[i].print(indent);
  3345. }
  3346. };
  3347. ASN1.prototype.toPrettyString = function (indent) {
  3348. if (indent === undefined) indent = '';
  3349. var s = indent + this.typeName() + " @" + this.stream.pos;
  3350. if (this.length >= 0)
  3351. s += "+";
  3352. s += this.length;
  3353. if (this.tag & 0x20)
  3354. s += " (constructed)";
  3355. else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub !== null))
  3356. s += " (encapsulates)";
  3357. s += "\n";
  3358. if (this.sub !== null) {
  3359. indent += ' ';
  3360. for (var i = 0, max = this.sub.length; i < max; ++i)
  3361. s += this.sub[i].toPrettyString(indent);
  3362. }
  3363. return s;
  3364. };
  3365. ASN1.prototype.toDOM = function () {
  3366. var node = DOM.tag("div", "node");
  3367. node.asn1 = this;
  3368. var head = DOM.tag("div", "head");
  3369. var s = this.typeName().replace(/_/g, " ");
  3370. head.innerHTML = s;
  3371. var content = this.content();
  3372. if (content !== null) {
  3373. content = String(content).replace(/</g, "&lt;");
  3374. var preview = DOM.tag("span", "preview");
  3375. preview.appendChild(DOM.text(content));
  3376. head.appendChild(preview);
  3377. }
  3378. node.appendChild(head);
  3379. this.node = node;
  3380. this.head = head;
  3381. var value = DOM.tag("div", "value");
  3382. s = "Offset: " + this.stream.pos + "<br/>";
  3383. s += "Length: " + this.header + "+";
  3384. if (this.length >= 0)
  3385. s += this.length;
  3386. else
  3387. s += (-this.length) + " (undefined)";
  3388. if (this.tag & 0x20)
  3389. s += "<br/>(constructed)";
  3390. else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub !== null))
  3391. s += "<br/>(encapsulates)";
  3392. //TODO if (this.tag == 0x03) s += "Unused bits: "
  3393. if (content !== null) {
  3394. s += "<br/>Value:<br/><b>" + content + "</b>";
  3395. if ((typeof oids === 'object') && (this.tag == 0x06)) {
  3396. var oid = oids[content];
  3397. if (oid) {
  3398. if (oid.d) s += "<br/>" + oid.d;
  3399. if (oid.c) s += "<br/>" + oid.c;
  3400. if (oid.w) s += "<br/>(warning!)";
  3401. }
  3402. }
  3403. }
  3404. value.innerHTML = s;
  3405. node.appendChild(value);
  3406. var sub = DOM.tag("div", "sub");
  3407. if (this.sub !== null) {
  3408. for (var i = 0, max = this.sub.length; i < max; ++i)
  3409. sub.appendChild(this.sub[i].toDOM());
  3410. }
  3411. node.appendChild(sub);
  3412. head.onclick = function () {
  3413. node.className = (node.className == "node collapsed") ? "node" : "node collapsed";
  3414. };
  3415. return node;
  3416. };
  3417. ASN1.prototype.posStart = function () {
  3418. return this.stream.pos;
  3419. };
  3420. ASN1.prototype.posContent = function () {
  3421. return this.stream.pos + this.header;
  3422. };
  3423. ASN1.prototype.posEnd = function () {
  3424. return this.stream.pos + this.header + Math.abs(this.length);
  3425. };
  3426. ASN1.prototype.fakeHover = function (current) {
  3427. this.node.className += " hover";
  3428. if (current)
  3429. this.head.className += " hover";
  3430. };
  3431. ASN1.prototype.fakeOut = function (current) {
  3432. var re = / ?hover/;
  3433. this.node.className = this.node.className.replace(re, "");
  3434. if (current)
  3435. this.head.className = this.head.className.replace(re, "");
  3436. };
  3437. ASN1.prototype.toHexDOM_sub = function (node, className, stream, start, end) {
  3438. if (start >= end)
  3439. return;
  3440. var sub = DOM.tag("span", className);
  3441. sub.appendChild(DOM.text(
  3442. stream.hexDump(start, end)));
  3443. node.appendChild(sub);
  3444. };
  3445. ASN1.prototype.toHexDOM = function (root) {
  3446. var node = DOM.tag("span", "hex");
  3447. if (root === undefined) root = node;
  3448. this.head.hexNode = node;
  3449. this.head.onmouseover = function () { this.hexNode.className = "hexCurrent"; };
  3450. this.head.onmouseout = function () { this.hexNode.className = "hex"; };
  3451. node.asn1 = this;
  3452. node.onmouseover = function () {
  3453. var current = !root.selected;
  3454. if (current) {
  3455. root.selected = this.asn1;
  3456. this.className = "hexCurrent";
  3457. }
  3458. this.asn1.fakeHover(current);
  3459. };
  3460. node.onmouseout = function () {
  3461. var current = (root.selected == this.asn1);
  3462. this.asn1.fakeOut(current);
  3463. if (current) {
  3464. root.selected = null;
  3465. this.className = "hex";
  3466. }
  3467. };
  3468. this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1);
  3469. this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent());
  3470. if (this.sub === null)
  3471. node.appendChild(DOM.text(
  3472. this.stream.hexDump(this.posContent(), this.posEnd())));
  3473. else if (this.sub.length > 0) {
  3474. var first = this.sub[0];
  3475. var last = this.sub[this.sub.length - 1];
  3476. this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart());
  3477. for (var i = 0, max = this.sub.length; i < max; ++i)
  3478. node.appendChild(this.sub[i].toHexDOM(root));
  3479. this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd());
  3480. }
  3481. return node;
  3482. };
  3483. ASN1.prototype.toHexString = function (root) {
  3484. return this.stream.hexDump(this.posStart(), this.posEnd(), true);
  3485. };
  3486. ASN1.decodeLength = function (stream) {
  3487. var buf = stream.get(),
  3488. len = buf & 0x7F;
  3489. if (len == buf)
  3490. return len;
  3491. if (len > 3)
  3492. throw "Length over 24 bits not supported at position " + (stream.pos - 1);
  3493. if (len === 0)
  3494. return -1; // undefined
  3495. buf = 0;
  3496. for (var i = 0; i < len; ++i)
  3497. buf = (buf << 8) | stream.get();
  3498. return buf;
  3499. };
  3500. ASN1.hasContent = function (tag, len, stream) {
  3501. if (tag & 0x20) // constructed
  3502. return true;
  3503. if ((tag < 0x03) || (tag > 0x04))
  3504. return false;
  3505. var p = new Stream(stream);
  3506. if (tag == 0x03) p.get(); // BitString unused bits, must be in [0, 7]
  3507. var subTag = p.get();
  3508. if ((subTag >> 6) & 0x01) // not (universal or context)
  3509. return false;
  3510. try {
  3511. var subLength = ASN1.decodeLength(p);
  3512. return ((p.pos - stream.pos) + subLength == len);
  3513. } catch (exception) {
  3514. return false;
  3515. }
  3516. };
  3517. ASN1.decode = function (stream) {
  3518. if (!(stream instanceof Stream))
  3519. stream = new Stream(stream, 0);
  3520. var streamStart = new Stream(stream),
  3521. tag = stream.get(),
  3522. len = ASN1.decodeLength(stream),
  3523. header = stream.pos - streamStart.pos,
  3524. sub = null;
  3525. if (ASN1.hasContent(tag, len, stream)) {
  3526. // it has content, so we decode it
  3527. var start = stream.pos;
  3528. if (tag == 0x03) stream.get(); // skip BitString unused bits, must be in [0, 7]
  3529. sub = [];
  3530. if (len >= 0) {
  3531. // definite length
  3532. var end = start + len;
  3533. while (stream.pos < end)
  3534. sub[sub.length] = ASN1.decode(stream);
  3535. if (stream.pos != end)
  3536. throw "Content size is not correct for container starting at offset " + start;
  3537. } else {
  3538. // undefined length
  3539. try {
  3540. for (;;) {
  3541. var s = ASN1.decode(stream);
  3542. if (s.tag === 0)
  3543. break;
  3544. sub[sub.length] = s;
  3545. }
  3546. len = start - stream.pos;
  3547. } catch (e) {
  3548. throw "Exception while decoding undefined length content: " + e;
  3549. }
  3550. }
  3551. } else
  3552. stream.pos += len; // skip content
  3553. return new ASN1(streamStart, header, len, tag, sub);
  3554. };
  3555. ASN1.test = function () {
  3556. var test = [
  3557. { value: [0x27], expected: 0x27 },
  3558. { value: [0x81, 0xC9], expected: 0xC9 },
  3559. { value: [0x83, 0xFE, 0xDC, 0xBA], expected: 0xFEDCBA }
  3560. ];
  3561. for (var i = 0, max = test.length; i < max; ++i) {
  3562. var pos = 0,
  3563. stream = new Stream(test[i].value, 0),
  3564. res = ASN1.decodeLength(stream);
  3565. if (res != test[i].expected)
  3566. document.write("In test[" + i + "] expected " + test[i].expected + " got " + res + "\n");
  3567. }
  3568. };
  3569. // export globals
  3570. window.ASN1 = ASN1;
  3571. })();
  3572. /**
  3573. * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
  3574. * @returns {string}
  3575. * @public
  3576. */
  3577. ASN1.prototype.getHexStringValue = function () {
  3578. var hexString = this.toHexString();
  3579. var offset = this.header * 2;
  3580. var length = this.length * 2;
  3581. return hexString.substr(offset, length);
  3582. };
  3583. /**
  3584. * Method to parse a pem encoded string containing both a public or private key.
  3585. * The method will translate the pem encoded string in a der encoded string and
  3586. * will parse private key and public key parameters. This method accepts public key
  3587. * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
  3588. *
  3589. * @todo Check how many rsa formats use the same format of pkcs #1.
  3590. *
  3591. * The format is defined as:
  3592. * PublicKeyInfo ::= SEQUENCE {
  3593. * algorithm AlgorithmIdentifier,
  3594. * PublicKey BIT STRING
  3595. * }
  3596. * Where AlgorithmIdentifier is:
  3597. * AlgorithmIdentifier ::= SEQUENCE {
  3598. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  3599. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  3600. * }
  3601. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  3602. * RSAPublicKey ::= SEQUENCE {
  3603. * modulus INTEGER, -- n
  3604. * publicExponent INTEGER -- e
  3605. * }
  3606. * it's possible to examine the structure of the keys obtained from openssl using
  3607. * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
  3608. * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
  3609. * @private
  3610. */
  3611. RSAKey.prototype.parseKey = function (pem) {
  3612. try {
  3613. var modulus = 0;
  3614. var public_exponent = 0;
  3615. var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
  3616. var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
  3617. var asn1 = ASN1.decode(der);
  3618. //Fixes a bug with OpenSSL 1.0+ private keys
  3619. if(asn1.sub.length === 3){
  3620. asn1 = asn1.sub[2].sub[0];
  3621. }
  3622. if (asn1.sub.length === 9) {
  3623. // Parse the private key.
  3624. modulus = asn1.sub[1].getHexStringValue(); //bigint
  3625. this.n = parseBigInt(modulus, 16);
  3626. public_exponent = asn1.sub[2].getHexStringValue(); //int
  3627. this.e = parseInt(public_exponent, 16);
  3628. var private_exponent = asn1.sub[3].getHexStringValue(); //bigint
  3629. this.d = parseBigInt(private_exponent, 16);
  3630. var prime1 = asn1.sub[4].getHexStringValue(); //bigint
  3631. this.p = parseBigInt(prime1, 16);
  3632. var prime2 = asn1.sub[5].getHexStringValue(); //bigint
  3633. this.q = parseBigInt(prime2, 16);
  3634. var exponent1 = asn1.sub[6].getHexStringValue(); //bigint
  3635. this.dmp1 = parseBigInt(exponent1, 16);
  3636. var exponent2 = asn1.sub[7].getHexStringValue(); //bigint
  3637. this.dmq1 = parseBigInt(exponent2, 16);
  3638. var coefficient = asn1.sub[8].getHexStringValue(); //bigint
  3639. this.coeff = parseBigInt(coefficient, 16);
  3640. }
  3641. else if (asn1.sub.length === 2) {
  3642. // Parse the public key.
  3643. var bit_string = asn1.sub[1];
  3644. var sequence = bit_string.sub[0];
  3645. modulus = sequence.sub[0].getHexStringValue();
  3646. this.n = parseBigInt(modulus, 16);
  3647. public_exponent = sequence.sub[1].getHexStringValue();
  3648. this.e = parseInt(public_exponent, 16);
  3649. }
  3650. else {
  3651. return false;
  3652. }
  3653. return true;
  3654. }
  3655. catch (ex) {
  3656. return false;
  3657. }
  3658. };
  3659. /**
  3660. * Translate rsa parameters in a hex encoded string representing the rsa key.
  3661. *
  3662. * The translation follow the ASN.1 notation :
  3663. * RSAPrivateKey ::= SEQUENCE {
  3664. * version Version,
  3665. * modulus INTEGER, -- n
  3666. * publicExponent INTEGER, -- e
  3667. * privateExponent INTEGER, -- d
  3668. * prime1 INTEGER, -- p
  3669. * prime2 INTEGER, -- q
  3670. * exponent1 INTEGER, -- d mod (p1)
  3671. * exponent2 INTEGER, -- d mod (q-1)
  3672. * coefficient INTEGER, -- (inverse of q) mod p
  3673. * }
  3674. * @returns {string} DER Encoded String representing the rsa private key
  3675. * @private
  3676. */
  3677. RSAKey.prototype.getPrivateBaseKey = function () {
  3678. var options = {
  3679. 'array': [
  3680. new KJUR.asn1.DERInteger({'int': 0}),
  3681. new KJUR.asn1.DERInteger({'bigint': this.n}),
  3682. new KJUR.asn1.DERInteger({'int': this.e}),
  3683. new KJUR.asn1.DERInteger({'bigint': this.d}),
  3684. new KJUR.asn1.DERInteger({'bigint': this.p}),
  3685. new KJUR.asn1.DERInteger({'bigint': this.q}),
  3686. new KJUR.asn1.DERInteger({'bigint': this.dmp1}),
  3687. new KJUR.asn1.DERInteger({'bigint': this.dmq1}),
  3688. new KJUR.asn1.DERInteger({'bigint': this.coeff})
  3689. ]
  3690. };
  3691. var seq = new KJUR.asn1.DERSequence(options);
  3692. return seq.getEncodedHex();
  3693. };
  3694. /**
  3695. * base64 (pem) encoded version of the DER encoded representation
  3696. * @returns {string} pem encoded representation without header and footer
  3697. * @public
  3698. */
  3699. RSAKey.prototype.getPrivateBaseKeyB64 = function () {
  3700. return hex2b64(this.getPrivateBaseKey());
  3701. };
  3702. /**
  3703. * Translate rsa parameters in a hex encoded string representing the rsa public key.
  3704. * The representation follow the ASN.1 notation :
  3705. * PublicKeyInfo ::= SEQUENCE {
  3706. * algorithm AlgorithmIdentifier,
  3707. * PublicKey BIT STRING
  3708. * }
  3709. * Where AlgorithmIdentifier is:
  3710. * AlgorithmIdentifier ::= SEQUENCE {
  3711. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  3712. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  3713. * }
  3714. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  3715. * RSAPublicKey ::= SEQUENCE {
  3716. * modulus INTEGER, -- n
  3717. * publicExponent INTEGER -- e
  3718. * }
  3719. * @returns {string} DER Encoded String representing the rsa public key
  3720. * @private
  3721. */
  3722. RSAKey.prototype.getPublicBaseKey = function () {
  3723. var options = {
  3724. 'array': [
  3725. new KJUR.asn1.DERObjectIdentifier({'oid': '1.2.840.113549.1.1.1'}), //RSA Encryption pkcs #1 oid
  3726. new KJUR.asn1.DERNull()
  3727. ]
  3728. };
  3729. var first_sequence = new KJUR.asn1.DERSequence(options);
  3730. options = {
  3731. 'array': [
  3732. new KJUR.asn1.DERInteger({'bigint': this.n}),
  3733. new KJUR.asn1.DERInteger({'int': this.e})
  3734. ]
  3735. };
  3736. var second_sequence = new KJUR.asn1.DERSequence(options);
  3737. options = {
  3738. 'hex': '00' + second_sequence.getEncodedHex()
  3739. };
  3740. var bit_string = new KJUR.asn1.DERBitString(options);
  3741. options = {
  3742. 'array': [
  3743. first_sequence,
  3744. bit_string
  3745. ]
  3746. };
  3747. var seq = new KJUR.asn1.DERSequence(options);
  3748. return seq.getEncodedHex();
  3749. };
  3750. /**
  3751. * base64 (pem) encoded version of the DER encoded representation
  3752. * @returns {string} pem encoded representation without header and footer
  3753. * @public
  3754. */
  3755. RSAKey.prototype.getPublicBaseKeyB64 = function () {
  3756. return hex2b64(this.getPublicBaseKey());
  3757. };
  3758. /**
  3759. * wrap the string in block of width chars. The default value for rsa keys is 64
  3760. * characters.
  3761. * @param {string} str the pem encoded string without header and footer
  3762. * @param {Number} [width=64] - the length the string has to be wrapped at
  3763. * @returns {string}
  3764. * @private
  3765. */
  3766. RSAKey.prototype.wordwrap = function (str, width) {
  3767. width = width || 64;
  3768. if (!str) {
  3769. return str;
  3770. }
  3771. var regex = '(.{1,' + width + '})( +|$\n?)|(.{1,' + width + '})';
  3772. return str.match(RegExp(regex, 'g')).join('\n');
  3773. };
  3774. /**
  3775. * Retrieve the pem encoded private key
  3776. * @returns {string} the pem encoded private key with header/footer
  3777. * @public
  3778. */
  3779. RSAKey.prototype.getPrivateKey = function () {
  3780. var key = "-----BEGIN RSA PRIVATE KEY-----\n";
  3781. key += this.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  3782. key += "-----END RSA PRIVATE KEY-----";
  3783. return key;
  3784. };
  3785. /**
  3786. * Retrieve the pem encoded public key
  3787. * @returns {string} the pem encoded public key with header/footer
  3788. * @public
  3789. */
  3790. RSAKey.prototype.getPublicKey = function () {
  3791. var key = "-----BEGIN PUBLIC KEY-----\n";
  3792. key += this.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  3793. key += "-----END PUBLIC KEY-----";
  3794. return key;
  3795. };
  3796. /**
  3797. * Check if the object contains the necessary parameters to populate the rsa modulus
  3798. * and public exponent parameters.
  3799. * @param {Object} [obj={}] - An object that may contain the two public key
  3800. * parameters
  3801. * @returns {boolean} true if the object contains both the modulus and the public exponent
  3802. * properties (n and e)
  3803. * @todo check for types of n and e. N should be a parseable bigInt object, E should
  3804. * be a parseable integer number
  3805. * @private
  3806. */
  3807. RSAKey.prototype.hasPublicKeyProperty = function (obj) {
  3808. obj = obj || {};
  3809. return (
  3810. obj.hasOwnProperty('n') &&
  3811. obj.hasOwnProperty('e')
  3812. );
  3813. };
  3814. /**
  3815. * Check if the object contains ALL the parameters of an RSA key.
  3816. * @param {Object} [obj={}] - An object that may contain nine rsa key
  3817. * parameters
  3818. * @returns {boolean} true if the object contains all the parameters needed
  3819. * @todo check for types of the parameters all the parameters but the public exponent
  3820. * should be parseable bigint objects, the public exponent should be a parseable integer number
  3821. * @private
  3822. */
  3823. RSAKey.prototype.hasPrivateKeyProperty = function (obj) {
  3824. obj = obj || {};
  3825. return (
  3826. obj.hasOwnProperty('n') &&
  3827. obj.hasOwnProperty('e') &&
  3828. obj.hasOwnProperty('d') &&
  3829. obj.hasOwnProperty('p') &&
  3830. obj.hasOwnProperty('q') &&
  3831. obj.hasOwnProperty('dmp1') &&
  3832. obj.hasOwnProperty('dmq1') &&
  3833. obj.hasOwnProperty('coeff')
  3834. );
  3835. };
  3836. /**
  3837. * Parse the properties of obj in the current rsa object. Obj should AT LEAST
  3838. * include the modulus and public exponent (n, e) parameters.
  3839. * @param {Object} obj - the object containing rsa parameters
  3840. * @private
  3841. */
  3842. RSAKey.prototype.parsePropertiesFrom = function (obj) {
  3843. this.n = obj.n;
  3844. this.e = obj.e;
  3845. if (obj.hasOwnProperty('d')) {
  3846. this.d = obj.d;
  3847. this.p = obj.p;
  3848. this.q = obj.q;
  3849. this.dmp1 = obj.dmp1;
  3850. this.dmq1 = obj.dmq1;
  3851. this.coeff = obj.coeff;
  3852. }
  3853. };
  3854. /**
  3855. * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
  3856. * This object is just a decorator for parsing the key parameter
  3857. * @param {string|Object} key - The key in string format, or an object containing
  3858. * the parameters needed to build a RSAKey object.
  3859. * @constructor
  3860. */
  3861. var JSEncryptRSAKey = function (key) {
  3862. // Call the super constructor.
  3863. RSAKey.call(this);
  3864. // If a key key was provided.
  3865. if (key) {
  3866. // If this is a string...
  3867. if (typeof key === 'string') {
  3868. this.parseKey(key);
  3869. }
  3870. else if (
  3871. this.hasPrivateKeyProperty(key) ||
  3872. this.hasPublicKeyProperty(key)
  3873. ) {
  3874. // Set the values for the key.
  3875. this.parsePropertiesFrom(key);
  3876. }
  3877. }
  3878. };
  3879. // Derive from RSAKey.
  3880. JSEncryptRSAKey.prototype = new RSAKey();
  3881. // Reset the contructor.
  3882. JSEncryptRSAKey.prototype.constructor = JSEncryptRSAKey;
  3883. /**
  3884. *
  3885. * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
  3886. * possible parameters are:
  3887. * - default_key_size {number} default: 1024 the key size in bit
  3888. * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
  3889. * - log {boolean} default: false whether log warn/error or not
  3890. * @constructor
  3891. */
  3892. var JSEncrypt = function (options) {
  3893. options = options || {};
  3894. this.default_key_size = parseInt(options.default_key_size) || 1024;
  3895. this.default_public_exponent = options.default_public_exponent || '010001'; //65537 default openssl public exponent for rsa key type
  3896. this.log = options.log || false;
  3897. // The private and public key.
  3898. this.key = null;
  3899. };
  3900. /**
  3901. * Method to set the rsa key parameter (one method is enough to set both the public
  3902. * and the private key, since the private key contains the public key paramenters)
  3903. * Log a warning if logs are enabled
  3904. * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
  3905. * @public
  3906. */
  3907. JSEncrypt.prototype.setKey = function (key) {
  3908. if (this.log && this.key) {
  3909. console.warn('A key was already set, overriding existing.');
  3910. }
  3911. this.key = new JSEncryptRSAKey(key);
  3912. };
  3913. /**
  3914. * Proxy method for setKey, for api compatibility
  3915. * @see setKey
  3916. * @public
  3917. */
  3918. JSEncrypt.prototype.setPrivateKey = function (privkey) {
  3919. // Create the key.
  3920. this.setKey(privkey);
  3921. };
  3922. /**
  3923. * Proxy method for setKey, for api compatibility
  3924. * @see setKey
  3925. * @public
  3926. */
  3927. JSEncrypt.prototype.setPublicKey = function (pubkey) {
  3928. // Sets the public key.
  3929. this.setKey(pubkey);
  3930. };
  3931. /**
  3932. * Proxy method for RSAKey object's decrypt, decrypt the string using the private
  3933. * components of the rsa key object. Note that if the object was not set will be created
  3934. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  3935. * @param {string} string base64 encoded crypted string to decrypt
  3936. * @return {string} the decrypted string
  3937. * @public
  3938. */
  3939. JSEncrypt.prototype.decrypt = function (string) {
  3940. // Return the decrypted string.
  3941. try {
  3942. return this.getKey().decrypt(b64tohex(string));
  3943. }
  3944. catch (ex) {
  3945. return false;
  3946. }
  3947. };
  3948. /**
  3949. * Proxy method for RSAKey object's encrypt, encrypt the string using the public
  3950. * components of the rsa key object. Note that if the object was not set will be created
  3951. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  3952. * @param {string} string the string to encrypt
  3953. * @return {string} the encrypted string encoded in base64
  3954. * @public
  3955. */
  3956. JSEncrypt.prototype.encrypt = function (string) {
  3957. // Return the encrypted string.
  3958. try {
  3959. return hex2b64(this.getKey().encrypt(string));
  3960. }
  3961. catch (ex) {
  3962. return false;
  3963. }
  3964. };
  3965. /**
  3966. * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
  3967. * will be created and returned
  3968. * @param {callback} [cb] the callback to be called if we want the key to be generated
  3969. * in an async fashion
  3970. * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
  3971. * @public
  3972. */
  3973. JSEncrypt.prototype.getKey = function (cb) {
  3974. // Only create new if it does not exist.
  3975. if (!this.key) {
  3976. // Get a new private key.
  3977. this.key = new JSEncryptRSAKey();
  3978. if (cb && {}.toString.call(cb) === '[object Function]') {
  3979. this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
  3980. return;
  3981. }
  3982. // Generate the key.
  3983. this.key.generate(this.default_key_size, this.default_public_exponent);
  3984. }
  3985. return this.key;
  3986. };
  3987. /**
  3988. * Returns the pem encoded representation of the private key
  3989. * If the key doesn't exists a new key will be created
  3990. * @returns {string} pem encoded representation of the private key WITH header and footer
  3991. * @public
  3992. */
  3993. JSEncrypt.prototype.getPrivateKey = function () {
  3994. // Return the private representation of this key.
  3995. return this.getKey().getPrivateKey();
  3996. };
  3997. /**
  3998. * Returns the pem encoded representation of the private key
  3999. * If the key doesn't exists a new key will be created
  4000. * @returns {string} pem encoded representation of the private key WITHOUT header and footer
  4001. * @public
  4002. */
  4003. JSEncrypt.prototype.getPrivateKeyB64 = function () {
  4004. // Return the private representation of this key.
  4005. return this.getKey().getPrivateBaseKeyB64();
  4006. };
  4007. /**
  4008. * Returns the pem encoded representation of the public key
  4009. * If the key doesn't exists a new key will be created
  4010. * @returns {string} pem encoded representation of the public key WITH header and footer
  4011. * @public
  4012. */
  4013. JSEncrypt.prototype.getPublicKey = function () {
  4014. // Return the private representation of this key.
  4015. return this.getKey().getPublicKey();
  4016. };
  4017. /**
  4018. * Returns the pem encoded representation of the public key
  4019. * If the key doesn't exists a new key will be created
  4020. * @returns {string} pem encoded representation of the public key WITHOUT header and footer
  4021. * @public
  4022. */
  4023. JSEncrypt.prototype.getPublicKeyB64 = function () {
  4024. // Return the private representation of this key.
  4025. return this.getKey().getPublicBaseKeyB64();
  4026. };
  4027. JSEncrypt.version = '2.3.1';
  4028. exports.JSEncrypt = JSEncrypt;
  4029. });