jsencrypt.js 132 KB

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