├── 115fullspeed.meta.js ├── 115fullspeed.user.js ├── README.md ├── icon.ico └── jsencrypt.min.js /115fullspeed.meta.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name 115fullspeed 3 | // @namespace https://github.com/gameclamp/115fullspeed 4 | // @homepageURL https://github.com/gameclamp/115fullspeed 5 | // @supportURL https://github.com/gameclamp/115fullspeed/issues 6 | // @description 批量获取下载地址;调用本地播放器(potplayer)播放原画视频;按文件大小顺序发送下载任务到aria2,更多帮助查看https://github.com/gameclamp/115fullspeed 7 | // @author 9尾雪狐(gameclamp) 8 | // @icon https://github.com/gameclamp/115fullspeed/raw/master/icon.ico 9 | // @include http*://115.com/?ct=file* 10 | // @include http*://115.com/?aid=1&cid=* 11 | // @downloadURL https://github.com/gameclamp/115fullspeed/raw/master/115fullspeed.user.js 12 | // @updateURL https://github.com/gameclamp/115fullspeed/raw/master/115fullspeed.meta.js 13 | // @version 0.3.10 14 | // @grant GM_xmlhttpRequest 15 | // ==/UserScript== 16 | -------------------------------------------------------------------------------- /115fullspeed.user.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name 115fullspeed 3 | // @namespace https://github.com/gameclamp/115fullspeed 4 | // @homepageURL https://github.com/gameclamp/115fullspeed 5 | // @supportURL https://github.com/gameclamp/115fullspeed/issues 6 | // @description 批量获取下载地址;调用本地播放器(potplayer)播放原画视频;按文件大小顺序发送下载任务到aria2,更多帮助查看https://github.com/gameclamp/115fullspeed 7 | // @author 9尾雪狐(gameclamp) 8 | // @icon https://github.com/gameclamp/115fullspeed/raw/master/icon.ico 9 | // @include http*://115.com/?ct=file* 10 | // @include http*://115.com/?aid=1&cid=* 11 | // @downloadURL https://github.com/gameclamp/115fullspeed/raw/master/115fullspeed.user.js 12 | // @updateURL https://github.com/gameclamp/115fullspeed/raw/master/115fullspeed.meta.js 13 | // @version 0.3.10 14 | // @grant GM_xmlhttpRequest 15 | // ==/UserScript== 16 | var observer = new MutationObserver(addbtu); 17 | var decoder = document.createElement('textarea'); 18 | observer.observe(document.querySelector('#js_data_list'),{'childList':true}) 19 | function addbtu(e){ 20 | var filelist = document.querySelectorAll('li[file_mode="9"],li[file_mode="4"],li[file_mode="1"]'); 21 | var elmInput; 22 | for (var i = filelist.length - 1; i >= 0; --i) { 23 | elmInput = filelist[i]; 24 | (elmInput.querySelector('div.file-opr')||elmInput.querySelector('span.file-name')).appendChild(creator('a','打开','','',getOne)); 25 | } 26 | } 27 | function getOne(e){ 28 | var elmInput = e.target.parentElement.parentElement.parentElement; 29 | if(elmInput.querySelector('.fslink')){ 30 | oneASX({'url':elmInput.querySelector('.fslink').href,'elm':elmInput}); 31 | }else{ 32 | var dl = new DOWNL(); 33 | dl.GM_get({'method':'download','pickcode':elmInput.getAttribute('pick_code'),'elm':elmInput,'callback':oneASX}) 34 | } 35 | } 36 | function oneASX(obj){ 37 | var hrefs = ''; 38 | // hrefs += '' + obj.elm.getAttribute('title') + ''; 39 | hrefs += '' + obj.elm.getAttribute('title') + ''; 40 | hrefs += '' 41 | var aFileParts = [hrefs]; 42 | var oMyBlob = new Blob(aFileParts,{'type':'video/x-ms-asf-plugin'}); 43 | var url = URL.createObjectURL(oMyBlob); 44 | location.href = url; 45 | // var a = document.createElement('a'); 46 | // var asxName = document.querySelector('#js_top_bar_box .file-path a:last-child'); 47 | // a.download = (asxName.title ||asxName.innerHTML) + '.asx'; 48 | // a.href = url; 49 | // document.body.appendChild(a); 50 | // a.click(); 51 | } 52 | // function getCookie(c_name){ 53 | // if (document.cookie.length>0){ 54 | // c_start=document.cookie.indexOf(c_name + "=") 55 | // if (c_start!=-1){ 56 | // c_start=c_start + c_name.length+1 57 | // c_end=document.cookie.indexOf(";",c_start) 58 | // if (c_end==-1) c_end=document.cookie.length 59 | // console.log(document.cookie.substring(c_start,c_end)) 60 | // return document.cookie.substring(c_start,c_end) 61 | // } 62 | // } 63 | // return "" 64 | // } 65 | function putLink(obj){ 66 | var a = document.createElement('a'); 67 | a.href = obj.url; 68 | a.innerHTML = "极速连接" 69 | a.className = "fslink"; 70 | if(obj.elm.querySelector('.fslink')){//如果已经有极速连接就替换掉 71 | obj.elm.querySelector('.fslink').remove(); 72 | } 73 | if(obj.elm.querySelector('.file-opr')){ 74 | obj.elm.querySelector('.file-opr').appendChild(a); 75 | }else{ 76 | obj.elm.querySelector('.file-name').appendChild(a); 77 | } 78 | if(obj.callback){obj.callback(obj)} 79 | } 80 | function pushtoARIA2(uri,out){ 81 | var options = {} 82 | var UID = getCookie('UID'); 83 | var CID = getCookie('CID'); 84 | var SEID = getCookie('SEID'); 85 | var cookies = `Cookie: UID=${UID};CID=${CID};SEID=${SEID}`; 86 | options.header = [cookies,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36 115Browser/7.2.5","Referer: http://115.com","Accept: */*"]; 87 | decoder.innerHTML = out; 88 | options.out = decoder.value; 89 | options['max-connection-per-server'] = 2; 90 | options['continue'] = true; 91 | var aria2 = new ARIA2('http://localhost:6800/jsonrpc'); 92 | // console.log(options); 93 | aria2.addUri(uri,options); 94 | } 95 | function by(name,order){ 96 | return function(o,p){ 97 | var a = o[name]; 98 | var b = p[name]; 99 | if(a===b){return 0} 100 | return a= 0; --i) { 221 | elmInput = filelist[i]; 222 | console.log(elmInput) 223 | if(elmInput.getAttribute('file_type')==0){ 224 | var obj = new Object(); 225 | obj.method = 'folder'; 226 | obj.cid = elmInput.getAttribute('cate_id'); 227 | obj.path = elmInput.getAttribute('title')+'/'; 228 | console.log(obj.path); 229 | this.GM_get(obj); 230 | }else{ 231 | this.downloadlist.push({'pickcode':elmInput.getAttribute('pick_code'),'size':elmInput.getAttribute('file_size'),'filename':elmInput.getAttribute('title')}); 232 | } 233 | } 234 | this.download2(); 235 | } 236 | this.fullspeed = function(){ 237 | var filelist = document.querySelectorAll('.list-contents li.selected[file_type="1"]'); 238 | if(filelist.length == 0){ 239 | filelist = document.querySelectorAll('.list-contents li[file_type="1"]'); 240 | } 241 | var elmInput; 242 | for (var i = filelist.length - 1; i >= 0; --i) { 243 | elmInput = filelist[i]; 244 | this.GM_get({'method':'download','pickcode':elmInput.getAttribute('pick_code'),'elm':elmInput}); 245 | } 246 | } 247 | } 248 | 249 | 250 | var ARIA2 = (function() { 251 | var jsonrpc_version = '2.0'; 252 | 253 | function get_auth(url) { 254 | return url.match(/^(?:(?![^:@]+:[^:@\/]*@)[^:\/?#.]+:)?(?:\/\/)?(?:([^:@]*(?::[^:@]*)?)?@)?/)[1]; 255 | }; 256 | 257 | function request(jsonrpc_path, method, params) { 258 | var request_obj = { 259 | jsonrpc: jsonrpc_version, 260 | method: method, 261 | id: (new Date()).getTime().toString(), 262 | }; 263 | if (params) request_obj['params'] = params; 264 | 265 | var auth = get_auth(jsonrpc_path); 266 | 267 | // 用 GM_xmlhttpRequest 防止 NoScript 拦截,用 setTimeout 防止外部无法调用 268 | setTimeout(function(){ 269 | GM_xmlhttpRequest({ 270 | method: 'POST', 271 | url: jsonrpc_path + '?tm=' + (new Date()).getTime().toString(), 272 | headers: { 273 | 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 274 | }, 275 | data: JSON.stringify(request_obj) 276 | }); 277 | }, 0); 278 | }; 279 | 280 | return function(jsonrpc_path) { 281 | this.jsonrpc_path = jsonrpc_path; 282 | this.addUri = function (uri, options) { 283 | request(this.jsonrpc_path, 'aria2.addUri', [[uri, ], options]); 284 | }; 285 | return this; 286 | } 287 | })(); 288 | 289 | var clrLink = function(){ 290 | var linklist = document.querySelectorAll('.list-contents .fslink'); 291 | for (var i = linklist.length,j=0; j < i; j++) { 292 | linklist[j].remove(); 293 | } 294 | } 295 | var getAll = function(){ 296 | var linklist = document.querySelectorAll('.list-contents .fslink'); 297 | var hrefs = ""; 298 | for (var i = linklist.length,j=0; j < i; j++) { 299 | hrefs += ''+linklist[j].parentElement.parentElement.getAttribute('title')+'
'; 300 | } 301 | var aFileParts = [hrefs]; 302 | var oMyBlob = new Blob(aFileParts,{'type':'text/html;charset=UTF-8'}); 303 | var url = URL.createObjectURL(oMyBlob); 304 | window.open(url); 305 | } 306 | var getASX = function(){ 307 | var linklist = document.querySelectorAll('.list-contents .fslink'); 308 | var hrefs = ''; 309 | for (var i = linklist.length,j=0; j < i; j++) { 310 | // hrefs += '' + linklist[j].parentElement.parentElement.getAttribute('title') + ''; 311 | hrefs += '' + linklist[j].parentElement.parentElement.getAttribute('title') + ''; 312 | } 313 | hrefs += '' 314 | var aFileParts = [hrefs]; 315 | var oMyBlob = new Blob(aFileParts,{'type':'video/x-ms-asf-plugin'}); 316 | var url = URL.createObjectURL(oMyBlob); 317 | location.href = url; 318 | // var a = document.createElement('a'); 319 | // var asxName = document.querySelector('#js_top_bar_box .file-path a:last-child'); 320 | // a.download = (asxName.title ||asxName.innerHTML) + '.asx'; 321 | // a.href = url; 322 | // document.body.appendChild(a); 323 | // a.click(); 324 | } 325 | var creator = function(tagname,inner,id,style,fn){ 326 | var a = document.createElement(tagname); 327 | if(fn){a.addEventListener('click',fn,false)}; 328 | a.innerHTML = inner; 329 | a.href = "javascript:;" 330 | a.id = id; 331 | a.style.cssText = style; 332 | return a; 333 | } 334 | function fullspeed(){ 335 | var obj = new DOWNL(); 336 | obj.fullspeed(); 337 | } 338 | function download(){ 339 | var obj = new DOWNL(); 340 | obj.download(); 341 | } 342 | function getCookie(name){ 343 | var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); 344 | if(arr=document.cookie.match(reg)) 345 | return unescape(arr[2]); 346 | else 347 | return null; 348 | } 349 | var div = creator('div','','','position: fixed;right: 210px;top: 5px;z-index: 10000;') 350 | div.appendChild(creator('a','下载','','margin-right:5px;',download)); 351 | div.appendChild(creator('a','clr','','margin-right:5px;',clrLink)); 352 | div.appendChild(creator('a','获取连接','','margin-right:5px;font-size:20px;',fullspeed)); 353 | div.appendChild(creator('a','输出全部','','margin-right:5px;',getAll)); 354 | div.appendChild(creator('a','导出ASX','','margin-right:5px;',getASX)); 355 | document.body.appendChild(div); 356 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 115fullspeed 2 | ### 脚本功能 3 | * 批量获取下载地址 4 | * 导出asx列表/地址列表 5 | * 生成并打开asx文件,按照系统关联调用本地播放器播放视频、音频 6 | * 调用aria2批量下载,保持文件夹目录结构,小于20M文件优先下载,大于20M文件以文件名排序下载。 7 | * 大量小文件的下载速度比115浏览器快N倍。 8 | 9 | ### 使用准备 10 | 先将火狐的ASX关联设置成本地播放器打开 11 | ![](http://ww1.sinaimg.cn/large/43c4a271gw1f2o0sdizg0j20r6064ab8.jpg) 12 | ### 效果 13 | * 打开单个文件播放 14 | ![](http://ww2.sinaimg.cn/large/43c4a271gw1f2nzameh5lg20m30cwnpe.gif) 15 | * 打开多个文件播放 16 | ![](http://ww4.sinaimg.cn/large/43c4a271gw1f2nzakv3oig20m30cwe82.gif) 17 | * aria2 18 | ![](http://ww1.sinaimg.cn/large/43c4a271gw1f2okoe9v0hj20r70fy74s.jpg) 19 | -------------------------------------------------------------------------------- /icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gameclamp/115fullspeed/7af729a05fd41b15ec4e12af0c7fa74ca8db8208/icon.ico -------------------------------------------------------------------------------- /jsencrypt.min.js: -------------------------------------------------------------------------------- 1 | (function (global, factory) { 2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : 3 | typeof define === 'function' && define.amd ? define(['exports'], factory) : 4 | (factory((global.JSEncrypt = {}))); 5 | }(this, (function (exports) { 'use strict'; 6 | 7 | var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; 8 | function int2char(n) { 9 | return BI_RM.charAt(n); 10 | } 11 | //#region BIT_OPERATIONS 12 | // (public) this & a 13 | function op_and(x, y) { 14 | return x & y; 15 | } 16 | // (public) this | a 17 | function op_or(x, y) { 18 | return x | y; 19 | } 20 | // (public) this ^ a 21 | function op_xor(x, y) { 22 | return x ^ y; 23 | } 24 | // (public) this & ~a 25 | function op_andnot(x, y) { 26 | return x & ~y; 27 | } 28 | // return index of lowest 1-bit in x, x < 2^31 29 | function lbit(x) { 30 | if (x == 0) { 31 | return -1; 32 | } 33 | var r = 0; 34 | if ((x & 0xffff) == 0) { 35 | x >>= 16; 36 | r += 16; 37 | } 38 | if ((x & 0xff) == 0) { 39 | x >>= 8; 40 | r += 8; 41 | } 42 | if ((x & 0xf) == 0) { 43 | x >>= 4; 44 | r += 4; 45 | } 46 | if ((x & 3) == 0) { 47 | x >>= 2; 48 | r += 2; 49 | } 50 | if ((x & 1) == 0) { 51 | ++r; 52 | } 53 | return r; 54 | } 55 | // return number of 1 bits in x 56 | function cbit(x) { 57 | var r = 0; 58 | while (x != 0) { 59 | x &= x - 1; 60 | ++r; 61 | } 62 | return r; 63 | } 64 | //#endregion BIT_OPERATIONS 65 | 66 | var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 67 | var b64pad = "="; 68 | function hex2b64(h) { 69 | var i; 70 | var c; 71 | var ret = ""; 72 | for (i = 0; i + 3 <= h.length; i += 3) { 73 | c = parseInt(h.substring(i, i + 3), 16); 74 | ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); 75 | } 76 | if (i + 1 == h.length) { 77 | c = parseInt(h.substring(i, i + 1), 16); 78 | ret += b64map.charAt(c << 2); 79 | } 80 | else if (i + 2 == h.length) { 81 | c = parseInt(h.substring(i, i + 2), 16); 82 | ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); 83 | } 84 | while ((ret.length & 3) > 0) { 85 | ret += b64pad; 86 | } 87 | return ret; 88 | } 89 | // convert a base64 string to hex 90 | function b64tohex(s) { 91 | var ret = ""; 92 | var i; 93 | var k = 0; // b64 state, 0-3 94 | var slop = 0; 95 | for (i = 0; i < s.length; ++i) { 96 | if (s.charAt(i) == b64pad) { 97 | break; 98 | } 99 | var v = b64map.indexOf(s.charAt(i)); 100 | if (v < 0) { 101 | continue; 102 | } 103 | if (k == 0) { 104 | ret += int2char(v >> 2); 105 | slop = v & 3; 106 | k = 1; 107 | } 108 | else if (k == 1) { 109 | ret += int2char((slop << 2) | (v >> 4)); 110 | slop = v & 0xf; 111 | k = 2; 112 | } 113 | else if (k == 2) { 114 | ret += int2char(slop); 115 | ret += int2char(v >> 2); 116 | slop = v & 3; 117 | k = 3; 118 | } 119 | else { 120 | ret += int2char((slop << 2) | (v >> 4)); 121 | ret += int2char(v & 0xf); 122 | k = 0; 123 | } 124 | } 125 | if (k == 1) { 126 | ret += int2char(slop << 2); 127 | } 128 | return ret; 129 | } 130 | 131 | /*! ***************************************************************************** 132 | Copyright (c) Microsoft Corporation. All rights reserved. 133 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 134 | this file except in compliance with the License. You may obtain a copy of the 135 | License at http://www.apache.org/licenses/LICENSE-2.0 136 | 137 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 138 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 139 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 140 | MERCHANTABLITY OR NON-INFRINGEMENT. 141 | 142 | See the Apache Version 2.0 License for specific language governing permissions 143 | and limitations under the License. 144 | ***************************************************************************** */ 145 | /* global Reflect, Promise */ 146 | 147 | var extendStatics = function(d, b) { 148 | extendStatics = Object.setPrototypeOf || 149 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 150 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 151 | return extendStatics(d, b); 152 | }; 153 | 154 | function __extends(d, b) { 155 | extendStatics(d, b); 156 | function __() { this.constructor = d; } 157 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 158 | } 159 | 160 | // Hex JavaScript decoder 161 | // Copyright (c) 2008-2013 Lapo Luchini 162 | // Permission to use, copy, modify, and/or distribute this software for any 163 | // purpose with or without fee is hereby granted, provided that the above 164 | // copyright notice and this permission notice appear in all copies. 165 | // 166 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 167 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 168 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 169 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 170 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 171 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 172 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 173 | /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ 174 | var decoder; 175 | var Hex = { 176 | decode: function (a) { 177 | var i; 178 | if (decoder === undefined) { 179 | var hex = "0123456789ABCDEF"; 180 | var ignore = " \f\n\r\t\u00A0\u2028\u2029"; 181 | decoder = {}; 182 | for (i = 0; i < 16; ++i) { 183 | decoder[hex.charAt(i)] = i; 184 | } 185 | hex = hex.toLowerCase(); 186 | for (i = 10; i < 16; ++i) { 187 | decoder[hex.charAt(i)] = i; 188 | } 189 | for (i = 0; i < ignore.length; ++i) { 190 | decoder[ignore.charAt(i)] = -1; 191 | } 192 | } 193 | var out = []; 194 | var bits = 0; 195 | var char_count = 0; 196 | for (i = 0; i < a.length; ++i) { 197 | var c = a.charAt(i); 198 | if (c == "=") { 199 | break; 200 | } 201 | c = decoder[c]; 202 | if (c == -1) { 203 | continue; 204 | } 205 | if (c === undefined) { 206 | throw new Error("Illegal character at offset " + i); 207 | } 208 | bits |= c; 209 | if (++char_count >= 2) { 210 | out[out.length] = bits; 211 | bits = 0; 212 | char_count = 0; 213 | } 214 | else { 215 | bits <<= 4; 216 | } 217 | } 218 | if (char_count) { 219 | throw new Error("Hex encoding incomplete: 4 bits missing"); 220 | } 221 | return out; 222 | } 223 | }; 224 | 225 | // Base64 JavaScript decoder 226 | // Copyright (c) 2008-2013 Lapo Luchini 227 | // Permission to use, copy, modify, and/or distribute this software for any 228 | // purpose with or without fee is hereby granted, provided that the above 229 | // copyright notice and this permission notice appear in all copies. 230 | // 231 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 232 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 233 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 234 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 235 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 236 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 237 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 238 | /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ 239 | var decoder$1; 240 | var Base64 = { 241 | decode: function (a) { 242 | var i; 243 | if (decoder$1 === undefined) { 244 | var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 245 | var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; 246 | decoder$1 = Object.create(null); 247 | for (i = 0; i < 64; ++i) { 248 | decoder$1[b64.charAt(i)] = i; 249 | } 250 | for (i = 0; i < ignore.length; ++i) { 251 | decoder$1[ignore.charAt(i)] = -1; 252 | } 253 | } 254 | var out = []; 255 | var bits = 0; 256 | var char_count = 0; 257 | for (i = 0; i < a.length; ++i) { 258 | var c = a.charAt(i); 259 | if (c == "=") { 260 | break; 261 | } 262 | c = decoder$1[c]; 263 | if (c == -1) { 264 | continue; 265 | } 266 | if (c === undefined) { 267 | throw new Error("Illegal character at offset " + i); 268 | } 269 | bits |= c; 270 | if (++char_count >= 4) { 271 | out[out.length] = (bits >> 16); 272 | out[out.length] = (bits >> 8) & 0xFF; 273 | out[out.length] = bits & 0xFF; 274 | bits = 0; 275 | char_count = 0; 276 | } 277 | else { 278 | bits <<= 6; 279 | } 280 | } 281 | switch (char_count) { 282 | case 1: 283 | throw new Error("Base64 encoding incomplete: at least 2 bits missing"); 284 | case 2: 285 | out[out.length] = (bits >> 10); 286 | break; 287 | case 3: 288 | out[out.length] = (bits >> 16); 289 | out[out.length] = (bits >> 8) & 0xFF; 290 | break; 291 | } 292 | return out; 293 | }, 294 | re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, 295 | unarmor: function (a) { 296 | var m = Base64.re.exec(a); 297 | if (m) { 298 | if (m[1]) { 299 | a = m[1]; 300 | } 301 | else if (m[2]) { 302 | a = m[2]; 303 | } 304 | else { 305 | throw new Error("RegExp out of sync"); 306 | } 307 | } 308 | return Base64.decode(a); 309 | } 310 | }; 311 | 312 | // Big integer base-10 printing library 313 | // Copyright (c) 2014 Lapo Luchini 314 | // Permission to use, copy, modify, and/or distribute this software for any 315 | // purpose with or without fee is hereby granted, provided that the above 316 | // copyright notice and this permission notice appear in all copies. 317 | // 318 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 319 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 320 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 321 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 322 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 323 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 324 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 325 | /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ 326 | var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 327 | var Int10 = /** @class */ (function () { 328 | function Int10(value) { 329 | this.buf = [+value || 0]; 330 | } 331 | Int10.prototype.mulAdd = function (m, c) { 332 | // assert(m <= 256) 333 | var b = this.buf; 334 | var l = b.length; 335 | var i; 336 | var t; 337 | for (i = 0; i < l; ++i) { 338 | t = b[i] * m + c; 339 | if (t < max) { 340 | c = 0; 341 | } 342 | else { 343 | c = 0 | (t / max); 344 | t -= c * max; 345 | } 346 | b[i] = t; 347 | } 348 | if (c > 0) { 349 | b[i] = c; 350 | } 351 | }; 352 | Int10.prototype.sub = function (c) { 353 | // assert(m <= 256) 354 | var b = this.buf; 355 | var l = b.length; 356 | var i; 357 | var t; 358 | for (i = 0; i < l; ++i) { 359 | t = b[i] - c; 360 | if (t < 0) { 361 | t += max; 362 | c = 1; 363 | } 364 | else { 365 | c = 0; 366 | } 367 | b[i] = t; 368 | } 369 | while (b[b.length - 1] === 0) { 370 | b.pop(); 371 | } 372 | }; 373 | Int10.prototype.toString = function (base) { 374 | if ((base || 10) != 10) { 375 | throw new Error("only base 10 is supported"); 376 | } 377 | var b = this.buf; 378 | var s = b[b.length - 1].toString(); 379 | for (var i = b.length - 2; i >= 0; --i) { 380 | s += (max + b[i]).toString().substring(1); 381 | } 382 | return s; 383 | }; 384 | Int10.prototype.valueOf = function () { 385 | var b = this.buf; 386 | var v = 0; 387 | for (var i = b.length - 1; i >= 0; --i) { 388 | v = v * max + b[i]; 389 | } 390 | return v; 391 | }; 392 | Int10.prototype.simplify = function () { 393 | var b = this.buf; 394 | return (b.length == 1) ? b[0] : this; 395 | }; 396 | return Int10; 397 | }()); 398 | 399 | // ASN.1 JavaScript decoder 400 | var ellipsis = "\u2026"; 401 | var reTimeS = /^(\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)?)?$/; 402 | var reTimeL = /^(\d\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)?)?$/; 403 | function stringCut(str, len) { 404 | if (str.length > len) { 405 | str = str.substring(0, len) + ellipsis; 406 | } 407 | return str; 408 | } 409 | var Stream = /** @class */ (function () { 410 | function Stream(enc, pos) { 411 | this.hexDigits = "0123456789ABCDEF"; 412 | if (enc instanceof Stream) { 413 | this.enc = enc.enc; 414 | this.pos = enc.pos; 415 | } 416 | else { 417 | // enc should be an array or a binary string 418 | this.enc = enc; 419 | this.pos = pos; 420 | } 421 | } 422 | Stream.prototype.get = function (pos) { 423 | if (pos === undefined) { 424 | pos = this.pos++; 425 | } 426 | if (pos >= this.enc.length) { 427 | throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length); 428 | } 429 | return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; 430 | }; 431 | Stream.prototype.hexByte = function (b) { 432 | return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); 433 | }; 434 | Stream.prototype.hexDump = function (start, end, raw) { 435 | var s = ""; 436 | for (var i = start; i < end; ++i) { 437 | s += this.hexByte(this.get(i)); 438 | if (raw !== true) { 439 | switch (i & 0xF) { 440 | case 0x7: 441 | s += " "; 442 | break; 443 | case 0xF: 444 | s += "\n"; 445 | break; 446 | default: 447 | s += " "; 448 | } 449 | } 450 | } 451 | return s; 452 | }; 453 | Stream.prototype.isASCII = function (start, end) { 454 | for (var i = start; i < end; ++i) { 455 | var c = this.get(i); 456 | if (c < 32 || c > 176) { 457 | return false; 458 | } 459 | } 460 | return true; 461 | }; 462 | Stream.prototype.parseStringISO = function (start, end) { 463 | var s = ""; 464 | for (var i = start; i < end; ++i) { 465 | s += String.fromCharCode(this.get(i)); 466 | } 467 | return s; 468 | }; 469 | Stream.prototype.parseStringUTF = function (start, end) { 470 | var s = ""; 471 | for (var i = start; i < end;) { 472 | var c = this.get(i++); 473 | if (c < 128) { 474 | s += String.fromCharCode(c); 475 | } 476 | else if ((c > 191) && (c < 224)) { 477 | s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); 478 | } 479 | else { 480 | s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); 481 | } 482 | } 483 | return s; 484 | }; 485 | Stream.prototype.parseStringBMP = function (start, end) { 486 | var str = ""; 487 | var hi; 488 | var lo; 489 | for (var i = start; i < end;) { 490 | hi = this.get(i++); 491 | lo = this.get(i++); 492 | str += String.fromCharCode((hi << 8) | lo); 493 | } 494 | return str; 495 | }; 496 | Stream.prototype.parseTime = function (start, end, shortYear) { 497 | var s = this.parseStringISO(start, end); 498 | var m = (shortYear ? reTimeS : reTimeL).exec(s); 499 | if (!m) { 500 | return "Unrecognized time: " + s; 501 | } 502 | if (shortYear) { 503 | // to avoid querying the timer, use the fixed range [1970, 2069] 504 | // it will conform with ITU X.400 [-10, +40] sliding window until 2030 505 | m[1] = +m[1]; 506 | m[1] += (+m[1] < 70) ? 2000 : 1900; 507 | } 508 | s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; 509 | if (m[5]) { 510 | s += ":" + m[5]; 511 | if (m[6]) { 512 | s += ":" + m[6]; 513 | if (m[7]) { 514 | s += "." + m[7]; 515 | } 516 | } 517 | } 518 | if (m[8]) { 519 | s += " UTC"; 520 | if (m[8] != "Z") { 521 | s += m[8]; 522 | if (m[9]) { 523 | s += ":" + m[9]; 524 | } 525 | } 526 | } 527 | return s; 528 | }; 529 | Stream.prototype.parseInteger = function (start, end) { 530 | var v = this.get(start); 531 | var neg = (v > 127); 532 | var pad = neg ? 255 : 0; 533 | var len; 534 | var s = ""; 535 | // skip unuseful bits (not allowed in DER) 536 | while (v == pad && ++start < end) { 537 | v = this.get(start); 538 | } 539 | len = end - start; 540 | if (len === 0) { 541 | return neg ? -1 : 0; 542 | } 543 | // show bit length of huge integers 544 | if (len > 4) { 545 | s = v; 546 | len <<= 3; 547 | while (((+s ^ pad) & 0x80) == 0) { 548 | s = +s << 1; 549 | --len; 550 | } 551 | s = "(" + len + " bit)\n"; 552 | } 553 | // decode the integer 554 | if (neg) { 555 | v = v - 256; 556 | } 557 | var n = new Int10(v); 558 | for (var i = start + 1; i < end; ++i) { 559 | n.mulAdd(256, this.get(i)); 560 | } 561 | return s + n.toString(); 562 | }; 563 | Stream.prototype.parseBitString = function (start, end, maxLength) { 564 | var unusedBit = this.get(start); 565 | var lenBit = ((end - start - 1) << 3) - unusedBit; 566 | var intro = "(" + lenBit + " bit)\n"; 567 | var s = ""; 568 | for (var i = start + 1; i < end; ++i) { 569 | var b = this.get(i); 570 | var skip = (i == end - 1) ? unusedBit : 0; 571 | for (var j = 7; j >= skip; --j) { 572 | s += (b >> j) & 1 ? "1" : "0"; 573 | } 574 | if (s.length > maxLength) { 575 | return intro + stringCut(s, maxLength); 576 | } 577 | } 578 | return intro + s; 579 | }; 580 | Stream.prototype.parseOctetString = function (start, end, maxLength) { 581 | if (this.isASCII(start, end)) { 582 | return stringCut(this.parseStringISO(start, end), maxLength); 583 | } 584 | var len = end - start; 585 | var s = "(" + len + " byte)\n"; 586 | maxLength /= 2; // we work in bytes 587 | if (len > maxLength) { 588 | end = start + maxLength; 589 | } 590 | for (var i = start; i < end; ++i) { 591 | s += this.hexByte(this.get(i)); 592 | } 593 | if (len > maxLength) { 594 | s += ellipsis; 595 | } 596 | return s; 597 | }; 598 | Stream.prototype.parseOID = function (start, end, maxLength) { 599 | var s = ""; 600 | var n = new Int10(); 601 | var bits = 0; 602 | for (var i = start; i < end; ++i) { 603 | var v = this.get(i); 604 | n.mulAdd(128, v & 0x7F); 605 | bits += 7; 606 | if (!(v & 0x80)) { // finished 607 | if (s === "") { 608 | n = n.simplify(); 609 | if (n instanceof Int10) { 610 | n.sub(80); 611 | s = "2." + n.toString(); 612 | } 613 | else { 614 | var m = n < 80 ? n < 40 ? 0 : 1 : 2; 615 | s = m + "." + (n - m * 40); 616 | } 617 | } 618 | else { 619 | s += "." + n.toString(); 620 | } 621 | if (s.length > maxLength) { 622 | return stringCut(s, maxLength); 623 | } 624 | n = new Int10(); 625 | bits = 0; 626 | } 627 | } 628 | if (bits > 0) { 629 | s += ".incomplete"; 630 | } 631 | return s; 632 | }; 633 | return Stream; 634 | }()); 635 | var ASN1 = /** @class */ (function () { 636 | function ASN1(stream, header, length, tag, sub) { 637 | if (!(tag instanceof ASN1Tag)) { 638 | throw new Error("Invalid tag value."); 639 | } 640 | this.stream = stream; 641 | this.header = header; 642 | this.length = length; 643 | this.tag = tag; 644 | this.sub = sub; 645 | } 646 | ASN1.prototype.typeName = function () { 647 | switch (this.tag.tagClass) { 648 | case 0: // universal 649 | switch (this.tag.tagNumber) { 650 | case 0x00: 651 | return "EOC"; 652 | case 0x01: 653 | return "BOOLEAN"; 654 | case 0x02: 655 | return "INTEGER"; 656 | case 0x03: 657 | return "BIT_STRING"; 658 | case 0x04: 659 | return "OCTET_STRING"; 660 | case 0x05: 661 | return "NULL"; 662 | case 0x06: 663 | return "OBJECT_IDENTIFIER"; 664 | case 0x07: 665 | return "ObjectDescriptor"; 666 | case 0x08: 667 | return "EXTERNAL"; 668 | case 0x09: 669 | return "REAL"; 670 | case 0x0A: 671 | return "ENUMERATED"; 672 | case 0x0B: 673 | return "EMBEDDED_PDV"; 674 | case 0x0C: 675 | return "UTF8String"; 676 | case 0x10: 677 | return "SEQUENCE"; 678 | case 0x11: 679 | return "SET"; 680 | case 0x12: 681 | return "NumericString"; 682 | case 0x13: 683 | return "PrintableString"; // ASCII subset 684 | case 0x14: 685 | return "TeletexString"; // aka T61String 686 | case 0x15: 687 | return "VideotexString"; 688 | case 0x16: 689 | return "IA5String"; // ASCII 690 | case 0x17: 691 | return "UTCTime"; 692 | case 0x18: 693 | return "GeneralizedTime"; 694 | case 0x19: 695 | return "GraphicString"; 696 | case 0x1A: 697 | return "VisibleString"; // ASCII subset 698 | case 0x1B: 699 | return "GeneralString"; 700 | case 0x1C: 701 | return "UniversalString"; 702 | case 0x1E: 703 | return "BMPString"; 704 | } 705 | return "Universal_" + this.tag.tagNumber.toString(); 706 | case 1: 707 | return "Application_" + this.tag.tagNumber.toString(); 708 | case 2: 709 | return "[" + this.tag.tagNumber.toString() + "]"; // Context 710 | case 3: 711 | return "Private_" + this.tag.tagNumber.toString(); 712 | } 713 | }; 714 | ASN1.prototype.content = function (maxLength) { 715 | if (this.tag === undefined) { 716 | return null; 717 | } 718 | if (maxLength === undefined) { 719 | maxLength = Infinity; 720 | } 721 | var content = this.posContent(); 722 | var len = Math.abs(this.length); 723 | if (!this.tag.isUniversal()) { 724 | if (this.sub !== null) { 725 | return "(" + this.sub.length + " elem)"; 726 | } 727 | return this.stream.parseOctetString(content, content + len, maxLength); 728 | } 729 | switch (this.tag.tagNumber) { 730 | case 0x01: // BOOLEAN 731 | return (this.stream.get(content) === 0) ? "false" : "true"; 732 | case 0x02: // INTEGER 733 | return this.stream.parseInteger(content, content + len); 734 | case 0x03: // BIT_STRING 735 | return this.sub ? "(" + this.sub.length + " elem)" : 736 | this.stream.parseBitString(content, content + len, maxLength); 737 | case 0x04: // OCTET_STRING 738 | return this.sub ? "(" + this.sub.length + " elem)" : 739 | this.stream.parseOctetString(content, content + len, maxLength); 740 | // case 0x05: // NULL 741 | case 0x06: // OBJECT_IDENTIFIER 742 | return this.stream.parseOID(content, content + len, maxLength); 743 | // case 0x07: // ObjectDescriptor 744 | // case 0x08: // EXTERNAL 745 | // case 0x09: // REAL 746 | // case 0x0A: // ENUMERATED 747 | // case 0x0B: // EMBEDDED_PDV 748 | case 0x10: // SEQUENCE 749 | case 0x11: // SET 750 | if (this.sub !== null) { 751 | return "(" + this.sub.length + " elem)"; 752 | } 753 | else { 754 | return "(no elem)"; 755 | } 756 | case 0x0C: // UTF8String 757 | return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); 758 | case 0x12: // NumericString 759 | case 0x13: // PrintableString 760 | case 0x14: // TeletexString 761 | case 0x15: // VideotexString 762 | case 0x16: // IA5String 763 | // case 0x19: // GraphicString 764 | case 0x1A: // VisibleString 765 | // case 0x1B: // GeneralString 766 | // case 0x1C: // UniversalString 767 | return stringCut(this.stream.parseStringISO(content, content + len), maxLength); 768 | case 0x1E: // BMPString 769 | return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); 770 | case 0x17: // UTCTime 771 | case 0x18: // GeneralizedTime 772 | return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); 773 | } 774 | return null; 775 | }; 776 | ASN1.prototype.toString = function () { 777 | return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]"; 778 | }; 779 | ASN1.prototype.toPrettyString = function (indent) { 780 | if (indent === undefined) { 781 | indent = ""; 782 | } 783 | var s = indent + this.typeName() + " @" + this.stream.pos; 784 | if (this.length >= 0) { 785 | s += "+"; 786 | } 787 | s += this.length; 788 | if (this.tag.tagConstructed) { 789 | s += " (constructed)"; 790 | } 791 | else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) { 792 | s += " (encapsulates)"; 793 | } 794 | s += "\n"; 795 | if (this.sub !== null) { 796 | indent += " "; 797 | for (var i = 0, max = this.sub.length; i < max; ++i) { 798 | s += this.sub[i].toPrettyString(indent); 799 | } 800 | } 801 | return s; 802 | }; 803 | ASN1.prototype.posStart = function () { 804 | return this.stream.pos; 805 | }; 806 | ASN1.prototype.posContent = function () { 807 | return this.stream.pos + this.header; 808 | }; 809 | ASN1.prototype.posEnd = function () { 810 | return this.stream.pos + this.header + Math.abs(this.length); 811 | }; 812 | ASN1.prototype.toHexString = function () { 813 | return this.stream.hexDump(this.posStart(), this.posEnd(), true); 814 | }; 815 | ASN1.decodeLength = function (stream) { 816 | var buf = stream.get(); 817 | var len = buf & 0x7F; 818 | if (len == buf) { 819 | return len; 820 | } 821 | // no reason to use Int10, as it would be a huge buffer anyways 822 | if (len > 6) { 823 | throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1)); 824 | } 825 | if (len === 0) { 826 | return null; 827 | } // undefined 828 | buf = 0; 829 | for (var i = 0; i < len; ++i) { 830 | buf = (buf * 256) + stream.get(); 831 | } 832 | return buf; 833 | }; 834 | /** 835 | * Retrieve the hexadecimal value (as a string) of the current ASN.1 element 836 | * @returns {string} 837 | * @public 838 | */ 839 | ASN1.prototype.getHexStringValue = function () { 840 | var hexString = this.toHexString(); 841 | var offset = this.header * 2; 842 | var length = this.length * 2; 843 | return hexString.substr(offset, length); 844 | }; 845 | ASN1.decode = function (str) { 846 | var stream; 847 | if (!(str instanceof Stream)) { 848 | stream = new Stream(str, 0); 849 | } 850 | else { 851 | stream = str; 852 | } 853 | var streamStart = new Stream(stream); 854 | var tag = new ASN1Tag(stream); 855 | var len = ASN1.decodeLength(stream); 856 | var start = stream.pos; 857 | var header = start - streamStart.pos; 858 | var sub = null; 859 | var getSub = function () { 860 | var ret = []; 861 | if (len !== null) { 862 | // definite length 863 | var end = start + len; 864 | while (stream.pos < end) { 865 | ret[ret.length] = ASN1.decode(stream); 866 | } 867 | if (stream.pos != end) { 868 | throw new Error("Content size is not correct for container starting at offset " + start); 869 | } 870 | } 871 | else { 872 | // undefined length 873 | try { 874 | for (;;) { 875 | var s = ASN1.decode(stream); 876 | if (s.tag.isEOC()) { 877 | break; 878 | } 879 | ret[ret.length] = s; 880 | } 881 | len = start - stream.pos; // undefined lengths are represented as negative values 882 | } 883 | catch (e) { 884 | throw new Error("Exception while decoding undefined length content: " + e); 885 | } 886 | } 887 | return ret; 888 | }; 889 | if (tag.tagConstructed) { 890 | // must have valid content 891 | sub = getSub(); 892 | } 893 | else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { 894 | // sometimes BitString and OctetString are used to encapsulate ASN.1 895 | try { 896 | if (tag.tagNumber == 0x03) { 897 | if (stream.get() != 0) { 898 | throw new Error("BIT STRINGs with unused bits cannot encapsulate."); 899 | } 900 | } 901 | sub = getSub(); 902 | for (var i = 0; i < sub.length; ++i) { 903 | if (sub[i].tag.isEOC()) { 904 | throw new Error("EOC is not supposed to be actual content."); 905 | } 906 | } 907 | } 908 | catch (e) { 909 | // but silently ignore when they don't 910 | sub = null; 911 | } 912 | } 913 | if (sub === null) { 914 | if (len === null) { 915 | throw new Error("We can't skip over an invalid tag with undefined length at offset " + start); 916 | } 917 | stream.pos = start + Math.abs(len); 918 | } 919 | return new ASN1(streamStart, header, len, tag, sub); 920 | }; 921 | return ASN1; 922 | }()); 923 | var ASN1Tag = /** @class */ (function () { 924 | function ASN1Tag(stream) { 925 | var buf = stream.get(); 926 | this.tagClass = buf >> 6; 927 | this.tagConstructed = ((buf & 0x20) !== 0); 928 | this.tagNumber = buf & 0x1F; 929 | if (this.tagNumber == 0x1F) { // long tag 930 | var n = new Int10(); 931 | do { 932 | buf = stream.get(); 933 | n.mulAdd(128, buf & 0x7F); 934 | } while (buf & 0x80); 935 | this.tagNumber = n.simplify(); 936 | } 937 | } 938 | ASN1Tag.prototype.isUniversal = function () { 939 | return this.tagClass === 0x00; 940 | }; 941 | ASN1Tag.prototype.isEOC = function () { 942 | return this.tagClass === 0x00 && this.tagNumber === 0x00; 943 | }; 944 | return ASN1Tag; 945 | }()); 946 | 947 | // Copyright (c) 2005 Tom Wu 948 | // Bits per digit 949 | var dbits; 950 | // JavaScript engine analysis 951 | var canary = 0xdeadbeefcafe; 952 | var j_lm = ((canary & 0xffffff) == 0xefcafe); 953 | //#region 954 | 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]; 955 | var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; 956 | //#endregion 957 | // (public) Constructor 958 | var BigInteger = /** @class */ (function () { 959 | function BigInteger(a, b, c) { 960 | if (a != null) { 961 | if ("number" == typeof a) { 962 | this.fromNumber(a, b, c); 963 | } 964 | else if (b == null && "string" != typeof a) { 965 | this.fromString(a, 256); 966 | } 967 | else { 968 | this.fromString(a, b); 969 | } 970 | } 971 | } 972 | //#region PUBLIC 973 | // BigInteger.prototype.toString = bnToString; 974 | // (public) return string representation in given radix 975 | BigInteger.prototype.toString = function (b) { 976 | if (this.s < 0) { 977 | return "-" + this.negate().toString(b); 978 | } 979 | var k; 980 | if (b == 16) { 981 | k = 4; 982 | } 983 | else if (b == 8) { 984 | k = 3; 985 | } 986 | else if (b == 2) { 987 | k = 1; 988 | } 989 | else if (b == 32) { 990 | k = 5; 991 | } 992 | else if (b == 4) { 993 | k = 2; 994 | } 995 | else { 996 | return this.toRadix(b); 997 | } 998 | var km = (1 << k) - 1; 999 | var d; 1000 | var m = false; 1001 | var r = ""; 1002 | var i = this.t; 1003 | var p = this.DB - (i * this.DB) % k; 1004 | if (i-- > 0) { 1005 | if (p < this.DB && (d = this[i] >> p) > 0) { 1006 | m = true; 1007 | r = int2char(d); 1008 | } 1009 | while (i >= 0) { 1010 | if (p < k) { 1011 | d = (this[i] & ((1 << p) - 1)) << (k - p); 1012 | d |= this[--i] >> (p += this.DB - k); 1013 | } 1014 | else { 1015 | d = (this[i] >> (p -= k)) & km; 1016 | if (p <= 0) { 1017 | p += this.DB; 1018 | --i; 1019 | } 1020 | } 1021 | if (d > 0) { 1022 | m = true; 1023 | } 1024 | if (m) { 1025 | r += int2char(d); 1026 | } 1027 | } 1028 | } 1029 | return m ? r : "0"; 1030 | }; 1031 | // BigInteger.prototype.negate = bnNegate; 1032 | // (public) -this 1033 | BigInteger.prototype.negate = function () { 1034 | var r = nbi(); 1035 | BigInteger.ZERO.subTo(this, r); 1036 | return r; 1037 | }; 1038 | // BigInteger.prototype.abs = bnAbs; 1039 | // (public) |this| 1040 | BigInteger.prototype.abs = function () { 1041 | return (this.s < 0) ? this.negate() : this; 1042 | }; 1043 | // BigInteger.prototype.compareTo = bnCompareTo; 1044 | // (public) return + if this > a, - if this < a, 0 if equal 1045 | BigInteger.prototype.compareTo = function (a) { 1046 | var r = this.s - a.s; 1047 | if (r != 0) { 1048 | return r; 1049 | } 1050 | var i = this.t; 1051 | r = i - a.t; 1052 | if (r != 0) { 1053 | return (this.s < 0) ? -r : r; 1054 | } 1055 | while (--i >= 0) { 1056 | if ((r = this[i] - a[i]) != 0) { 1057 | return r; 1058 | } 1059 | } 1060 | return 0; 1061 | }; 1062 | // BigInteger.prototype.bitLength = bnBitLength; 1063 | // (public) return the number of bits in "this" 1064 | BigInteger.prototype.bitLength = function () { 1065 | if (this.t <= 0) { 1066 | return 0; 1067 | } 1068 | return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); 1069 | }; 1070 | // BigInteger.prototype.mod = bnMod; 1071 | // (public) this mod a 1072 | BigInteger.prototype.mod = function (a) { 1073 | var r = nbi(); 1074 | this.abs().divRemTo(a, null, r); 1075 | if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { 1076 | a.subTo(r, r); 1077 | } 1078 | return r; 1079 | }; 1080 | // BigInteger.prototype.modPowInt = bnModPowInt; 1081 | // (public) this^e % m, 0 <= e < 2^32 1082 | BigInteger.prototype.modPowInt = function (e, m) { 1083 | var z; 1084 | if (e < 256 || m.isEven()) { 1085 | z = new Classic(m); 1086 | } 1087 | else { 1088 | z = new Montgomery(m); 1089 | } 1090 | return this.exp(e, z); 1091 | }; 1092 | // BigInteger.prototype.clone = bnClone; 1093 | // (public) 1094 | BigInteger.prototype.clone = function () { 1095 | var r = nbi(); 1096 | this.copyTo(r); 1097 | return r; 1098 | }; 1099 | // BigInteger.prototype.intValue = bnIntValue; 1100 | // (public) return value as integer 1101 | BigInteger.prototype.intValue = function () { 1102 | if (this.s < 0) { 1103 | if (this.t == 1) { 1104 | return this[0] - this.DV; 1105 | } 1106 | else if (this.t == 0) { 1107 | return -1; 1108 | } 1109 | } 1110 | else if (this.t == 1) { 1111 | return this[0]; 1112 | } 1113 | else if (this.t == 0) { 1114 | return 0; 1115 | } 1116 | // assumes 16 < DB < 32 1117 | return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; 1118 | }; 1119 | // BigInteger.prototype.byteValue = bnByteValue; 1120 | // (public) return value as byte 1121 | BigInteger.prototype.byteValue = function () { 1122 | return (this.t == 0) ? this.s : (this[0] << 24) >> 24; 1123 | }; 1124 | // BigInteger.prototype.shortValue = bnShortValue; 1125 | // (public) return value as short (assumes DB>=16) 1126 | BigInteger.prototype.shortValue = function () { 1127 | return (this.t == 0) ? this.s : (this[0] << 16) >> 16; 1128 | }; 1129 | // BigInteger.prototype.signum = bnSigNum; 1130 | // (public) 0 if this == 0, 1 if this > 0 1131 | BigInteger.prototype.signum = function () { 1132 | if (this.s < 0) { 1133 | return -1; 1134 | } 1135 | else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { 1136 | return 0; 1137 | } 1138 | else { 1139 | return 1; 1140 | } 1141 | }; 1142 | // BigInteger.prototype.toByteArray = bnToByteArray; 1143 | // (public) convert to bigendian byte array 1144 | BigInteger.prototype.toByteArray = function () { 1145 | var i = this.t; 1146 | var r = []; 1147 | r[0] = this.s; 1148 | var p = this.DB - (i * this.DB) % 8; 1149 | var d; 1150 | var k = 0; 1151 | if (i-- > 0) { 1152 | if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { 1153 | r[k++] = d | (this.s << (this.DB - p)); 1154 | } 1155 | while (i >= 0) { 1156 | if (p < 8) { 1157 | d = (this[i] & ((1 << p) - 1)) << (8 - p); 1158 | d |= this[--i] >> (p += this.DB - 8); 1159 | } 1160 | else { 1161 | d = (this[i] >> (p -= 8)) & 0xff; 1162 | if (p <= 0) { 1163 | p += this.DB; 1164 | --i; 1165 | } 1166 | } 1167 | if ((d & 0x80) != 0) { 1168 | d |= -256; 1169 | } 1170 | if (k == 0 && (this.s & 0x80) != (d & 0x80)) { 1171 | ++k; 1172 | } 1173 | if (k > 0 || d != this.s) { 1174 | r[k++] = d; 1175 | } 1176 | } 1177 | } 1178 | return r; 1179 | }; 1180 | // BigInteger.prototype.equals = bnEquals; 1181 | BigInteger.prototype.equals = function (a) { 1182 | return (this.compareTo(a) == 0); 1183 | }; 1184 | // BigInteger.prototype.min = bnMin; 1185 | BigInteger.prototype.min = function (a) { 1186 | return (this.compareTo(a) < 0) ? this : a; 1187 | }; 1188 | // BigInteger.prototype.max = bnMax; 1189 | BigInteger.prototype.max = function (a) { 1190 | return (this.compareTo(a) > 0) ? this : a; 1191 | }; 1192 | // BigInteger.prototype.and = bnAnd; 1193 | BigInteger.prototype.and = function (a) { 1194 | var r = nbi(); 1195 | this.bitwiseTo(a, op_and, r); 1196 | return r; 1197 | }; 1198 | // BigInteger.prototype.or = bnOr; 1199 | BigInteger.prototype.or = function (a) { 1200 | var r = nbi(); 1201 | this.bitwiseTo(a, op_or, r); 1202 | return r; 1203 | }; 1204 | // BigInteger.prototype.xor = bnXor; 1205 | BigInteger.prototype.xor = function (a) { 1206 | var r = nbi(); 1207 | this.bitwiseTo(a, op_xor, r); 1208 | return r; 1209 | }; 1210 | // BigInteger.prototype.andNot = bnAndNot; 1211 | BigInteger.prototype.andNot = function (a) { 1212 | var r = nbi(); 1213 | this.bitwiseTo(a, op_andnot, r); 1214 | return r; 1215 | }; 1216 | // BigInteger.prototype.not = bnNot; 1217 | // (public) ~this 1218 | BigInteger.prototype.not = function () { 1219 | var r = nbi(); 1220 | for (var i = 0; i < this.t; ++i) { 1221 | r[i] = this.DM & ~this[i]; 1222 | } 1223 | r.t = this.t; 1224 | r.s = ~this.s; 1225 | return r; 1226 | }; 1227 | // BigInteger.prototype.shiftLeft = bnShiftLeft; 1228 | // (public) this << n 1229 | BigInteger.prototype.shiftLeft = function (n) { 1230 | var r = nbi(); 1231 | if (n < 0) { 1232 | this.rShiftTo(-n, r); 1233 | } 1234 | else { 1235 | this.lShiftTo(n, r); 1236 | } 1237 | return r; 1238 | }; 1239 | // BigInteger.prototype.shiftRight = bnShiftRight; 1240 | // (public) this >> n 1241 | BigInteger.prototype.shiftRight = function (n) { 1242 | var r = nbi(); 1243 | if (n < 0) { 1244 | this.lShiftTo(-n, r); 1245 | } 1246 | else { 1247 | this.rShiftTo(n, r); 1248 | } 1249 | return r; 1250 | }; 1251 | // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; 1252 | // (public) returns index of lowest 1-bit (or -1 if none) 1253 | BigInteger.prototype.getLowestSetBit = function () { 1254 | for (var i = 0; i < this.t; ++i) { 1255 | if (this[i] != 0) { 1256 | return i * this.DB + lbit(this[i]); 1257 | } 1258 | } 1259 | if (this.s < 0) { 1260 | return this.t * this.DB; 1261 | } 1262 | return -1; 1263 | }; 1264 | // BigInteger.prototype.bitCount = bnBitCount; 1265 | // (public) return number of set bits 1266 | BigInteger.prototype.bitCount = function () { 1267 | var r = 0; 1268 | var x = this.s & this.DM; 1269 | for (var i = 0; i < this.t; ++i) { 1270 | r += cbit(this[i] ^ x); 1271 | } 1272 | return r; 1273 | }; 1274 | // BigInteger.prototype.testBit = bnTestBit; 1275 | // (public) true iff nth bit is set 1276 | BigInteger.prototype.testBit = function (n) { 1277 | var j = Math.floor(n / this.DB); 1278 | if (j >= this.t) { 1279 | return (this.s != 0); 1280 | } 1281 | return ((this[j] & (1 << (n % this.DB))) != 0); 1282 | }; 1283 | // BigInteger.prototype.setBit = bnSetBit; 1284 | // (public) this | (1< 1) { 1382 | var g2 = nbi(); 1383 | z.sqrTo(g[1], g2); 1384 | while (n <= km) { 1385 | g[n] = nbi(); 1386 | z.mulTo(g2, g[n - 2], g[n]); 1387 | n += 2; 1388 | } 1389 | } 1390 | var j = e.t - 1; 1391 | var w; 1392 | var is1 = true; 1393 | var r2 = nbi(); 1394 | var t; 1395 | i = nbits(e[j]) - 1; 1396 | while (j >= 0) { 1397 | if (i >= k1) { 1398 | w = (e[j] >> (i - k1)) & km; 1399 | } 1400 | else { 1401 | w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); 1402 | if (j > 0) { 1403 | w |= e[j - 1] >> (this.DB + i - k1); 1404 | } 1405 | } 1406 | n = k; 1407 | while ((w & 1) == 0) { 1408 | w >>= 1; 1409 | --n; 1410 | } 1411 | if ((i -= n) < 0) { 1412 | i += this.DB; 1413 | --j; 1414 | } 1415 | if (is1) { // ret == 1, don't bother squaring or multiplying it 1416 | g[w].copyTo(r); 1417 | is1 = false; 1418 | } 1419 | else { 1420 | while (n > 1) { 1421 | z.sqrTo(r, r2); 1422 | z.sqrTo(r2, r); 1423 | n -= 2; 1424 | } 1425 | if (n > 0) { 1426 | z.sqrTo(r, r2); 1427 | } 1428 | else { 1429 | t = r; 1430 | r = r2; 1431 | r2 = t; 1432 | } 1433 | z.mulTo(r2, g[w], r); 1434 | } 1435 | while (j >= 0 && (e[j] & (1 << i)) == 0) { 1436 | z.sqrTo(r, r2); 1437 | t = r; 1438 | r = r2; 1439 | r2 = t; 1440 | if (--i < 0) { 1441 | i = this.DB - 1; 1442 | --j; 1443 | } 1444 | } 1445 | } 1446 | return z.revert(r); 1447 | }; 1448 | // BigInteger.prototype.modInverse = bnModInverse; 1449 | // (public) 1/this % m (HAC 14.61) 1450 | BigInteger.prototype.modInverse = function (m) { 1451 | var ac = m.isEven(); 1452 | if ((this.isEven() && ac) || m.signum() == 0) { 1453 | return BigInteger.ZERO; 1454 | } 1455 | var u = m.clone(); 1456 | var v = this.clone(); 1457 | var a = nbv(1); 1458 | var b = nbv(0); 1459 | var c = nbv(0); 1460 | var d = nbv(1); 1461 | while (u.signum() != 0) { 1462 | while (u.isEven()) { 1463 | u.rShiftTo(1, u); 1464 | if (ac) { 1465 | if (!a.isEven() || !b.isEven()) { 1466 | a.addTo(this, a); 1467 | b.subTo(m, b); 1468 | } 1469 | a.rShiftTo(1, a); 1470 | } 1471 | else if (!b.isEven()) { 1472 | b.subTo(m, b); 1473 | } 1474 | b.rShiftTo(1, b); 1475 | } 1476 | while (v.isEven()) { 1477 | v.rShiftTo(1, v); 1478 | if (ac) { 1479 | if (!c.isEven() || !d.isEven()) { 1480 | c.addTo(this, c); 1481 | d.subTo(m, d); 1482 | } 1483 | c.rShiftTo(1, c); 1484 | } 1485 | else if (!d.isEven()) { 1486 | d.subTo(m, d); 1487 | } 1488 | d.rShiftTo(1, d); 1489 | } 1490 | if (u.compareTo(v) >= 0) { 1491 | u.subTo(v, u); 1492 | if (ac) { 1493 | a.subTo(c, a); 1494 | } 1495 | b.subTo(d, b); 1496 | } 1497 | else { 1498 | v.subTo(u, v); 1499 | if (ac) { 1500 | c.subTo(a, c); 1501 | } 1502 | d.subTo(b, d); 1503 | } 1504 | } 1505 | if (v.compareTo(BigInteger.ONE) != 0) { 1506 | return BigInteger.ZERO; 1507 | } 1508 | if (d.compareTo(m) >= 0) { 1509 | return d.subtract(m); 1510 | } 1511 | if (d.signum() < 0) { 1512 | d.addTo(m, d); 1513 | } 1514 | else { 1515 | return d; 1516 | } 1517 | if (d.signum() < 0) { 1518 | return d.add(m); 1519 | } 1520 | else { 1521 | return d; 1522 | } 1523 | }; 1524 | // BigInteger.prototype.pow = bnPow; 1525 | // (public) this^e 1526 | BigInteger.prototype.pow = function (e) { 1527 | return this.exp(e, new NullExp()); 1528 | }; 1529 | // BigInteger.prototype.gcd = bnGCD; 1530 | // (public) gcd(this,a) (HAC 14.54) 1531 | BigInteger.prototype.gcd = function (a) { 1532 | var x = (this.s < 0) ? this.negate() : this.clone(); 1533 | var y = (a.s < 0) ? a.negate() : a.clone(); 1534 | if (x.compareTo(y) < 0) { 1535 | var t = x; 1536 | x = y; 1537 | y = t; 1538 | } 1539 | var i = x.getLowestSetBit(); 1540 | var g = y.getLowestSetBit(); 1541 | if (g < 0) { 1542 | return x; 1543 | } 1544 | if (i < g) { 1545 | g = i; 1546 | } 1547 | if (g > 0) { 1548 | x.rShiftTo(g, x); 1549 | y.rShiftTo(g, y); 1550 | } 1551 | while (x.signum() > 0) { 1552 | if ((i = x.getLowestSetBit()) > 0) { 1553 | x.rShiftTo(i, x); 1554 | } 1555 | if ((i = y.getLowestSetBit()) > 0) { 1556 | y.rShiftTo(i, y); 1557 | } 1558 | if (x.compareTo(y) >= 0) { 1559 | x.subTo(y, x); 1560 | x.rShiftTo(1, x); 1561 | } 1562 | else { 1563 | y.subTo(x, y); 1564 | y.rShiftTo(1, y); 1565 | } 1566 | } 1567 | if (g > 0) { 1568 | y.lShiftTo(g, y); 1569 | } 1570 | return y; 1571 | }; 1572 | // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; 1573 | // (public) test primality with certainty >= 1-.5^t 1574 | BigInteger.prototype.isProbablePrime = function (t) { 1575 | var i; 1576 | var x = this.abs(); 1577 | if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { 1578 | for (i = 0; i < lowprimes.length; ++i) { 1579 | if (x[0] == lowprimes[i]) { 1580 | return true; 1581 | } 1582 | } 1583 | return false; 1584 | } 1585 | if (x.isEven()) { 1586 | return false; 1587 | } 1588 | i = 1; 1589 | while (i < lowprimes.length) { 1590 | var m = lowprimes[i]; 1591 | var j = i + 1; 1592 | while (j < lowprimes.length && m < lplim) { 1593 | m *= lowprimes[j++]; 1594 | } 1595 | m = x.modInt(m); 1596 | while (i < j) { 1597 | if (m % lowprimes[i++] == 0) { 1598 | return false; 1599 | } 1600 | } 1601 | } 1602 | return x.millerRabin(t); 1603 | }; 1604 | //#endregion PUBLIC 1605 | //#region PROTECTED 1606 | // BigInteger.prototype.copyTo = bnpCopyTo; 1607 | // (protected) copy this to r 1608 | BigInteger.prototype.copyTo = function (r) { 1609 | for (var i = this.t - 1; i >= 0; --i) { 1610 | r[i] = this[i]; 1611 | } 1612 | r.t = this.t; 1613 | r.s = this.s; 1614 | }; 1615 | // BigInteger.prototype.fromInt = bnpFromInt; 1616 | // (protected) set from integer value x, -DV <= x < DV 1617 | BigInteger.prototype.fromInt = function (x) { 1618 | this.t = 1; 1619 | this.s = (x < 0) ? -1 : 0; 1620 | if (x > 0) { 1621 | this[0] = x; 1622 | } 1623 | else if (x < -1) { 1624 | this[0] = x + this.DV; 1625 | } 1626 | else { 1627 | this.t = 0; 1628 | } 1629 | }; 1630 | // BigInteger.prototype.fromString = bnpFromString; 1631 | // (protected) set from string and radix 1632 | BigInteger.prototype.fromString = function (s, b) { 1633 | var k; 1634 | if (b == 16) { 1635 | k = 4; 1636 | } 1637 | else if (b == 8) { 1638 | k = 3; 1639 | } 1640 | else if (b == 256) { 1641 | k = 8; 1642 | /* byte array */ 1643 | } 1644 | else if (b == 2) { 1645 | k = 1; 1646 | } 1647 | else if (b == 32) { 1648 | k = 5; 1649 | } 1650 | else if (b == 4) { 1651 | k = 2; 1652 | } 1653 | else { 1654 | this.fromRadix(s, b); 1655 | return; 1656 | } 1657 | this.t = 0; 1658 | this.s = 0; 1659 | var i = s.length; 1660 | var mi = false; 1661 | var sh = 0; 1662 | while (--i >= 0) { 1663 | var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); 1664 | if (x < 0) { 1665 | if (s.charAt(i) == "-") { 1666 | mi = true; 1667 | } 1668 | continue; 1669 | } 1670 | mi = false; 1671 | if (sh == 0) { 1672 | this[this.t++] = x; 1673 | } 1674 | else if (sh + k > this.DB) { 1675 | this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; 1676 | this[this.t++] = (x >> (this.DB - sh)); 1677 | } 1678 | else { 1679 | this[this.t - 1] |= x << sh; 1680 | } 1681 | sh += k; 1682 | if (sh >= this.DB) { 1683 | sh -= this.DB; 1684 | } 1685 | } 1686 | if (k == 8 && ((+s[0]) & 0x80) != 0) { 1687 | this.s = -1; 1688 | if (sh > 0) { 1689 | this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; 1690 | } 1691 | } 1692 | this.clamp(); 1693 | if (mi) { 1694 | BigInteger.ZERO.subTo(this, this); 1695 | } 1696 | }; 1697 | // BigInteger.prototype.clamp = bnpClamp; 1698 | // (protected) clamp off excess high words 1699 | BigInteger.prototype.clamp = function () { 1700 | var c = this.s & this.DM; 1701 | while (this.t > 0 && this[this.t - 1] == c) { 1702 | --this.t; 1703 | } 1704 | }; 1705 | // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; 1706 | // (protected) r = this << n*DB 1707 | BigInteger.prototype.dlShiftTo = function (n, r) { 1708 | var i; 1709 | for (i = this.t - 1; i >= 0; --i) { 1710 | r[i + n] = this[i]; 1711 | } 1712 | for (i = n - 1; i >= 0; --i) { 1713 | r[i] = 0; 1714 | } 1715 | r.t = this.t + n; 1716 | r.s = this.s; 1717 | }; 1718 | // BigInteger.prototype.drShiftTo = bnpDRShiftTo; 1719 | // (protected) r = this >> n*DB 1720 | BigInteger.prototype.drShiftTo = function (n, r) { 1721 | for (var i = n; i < this.t; ++i) { 1722 | r[i - n] = this[i]; 1723 | } 1724 | r.t = Math.max(this.t - n, 0); 1725 | r.s = this.s; 1726 | }; 1727 | // BigInteger.prototype.lShiftTo = bnpLShiftTo; 1728 | // (protected) r = this << n 1729 | BigInteger.prototype.lShiftTo = function (n, r) { 1730 | var bs = n % this.DB; 1731 | var cbs = this.DB - bs; 1732 | var bm = (1 << cbs) - 1; 1733 | var ds = Math.floor(n / this.DB); 1734 | var c = (this.s << bs) & this.DM; 1735 | for (var i = this.t - 1; i >= 0; --i) { 1736 | r[i + ds + 1] = (this[i] >> cbs) | c; 1737 | c = (this[i] & bm) << bs; 1738 | } 1739 | for (var i = ds - 1; i >= 0; --i) { 1740 | r[i] = 0; 1741 | } 1742 | r[ds] = c; 1743 | r.t = this.t + ds + 1; 1744 | r.s = this.s; 1745 | r.clamp(); 1746 | }; 1747 | // BigInteger.prototype.rShiftTo = bnpRShiftTo; 1748 | // (protected) r = this >> n 1749 | BigInteger.prototype.rShiftTo = function (n, r) { 1750 | r.s = this.s; 1751 | var ds = Math.floor(n / this.DB); 1752 | if (ds >= this.t) { 1753 | r.t = 0; 1754 | return; 1755 | } 1756 | var bs = n % this.DB; 1757 | var cbs = this.DB - bs; 1758 | var bm = (1 << bs) - 1; 1759 | r[0] = this[ds] >> bs; 1760 | for (var i = ds + 1; i < this.t; ++i) { 1761 | r[i - ds - 1] |= (this[i] & bm) << cbs; 1762 | r[i - ds] = this[i] >> bs; 1763 | } 1764 | if (bs > 0) { 1765 | r[this.t - ds - 1] |= (this.s & bm) << cbs; 1766 | } 1767 | r.t = this.t - ds; 1768 | r.clamp(); 1769 | }; 1770 | // BigInteger.prototype.subTo = bnpSubTo; 1771 | // (protected) r = this - a 1772 | BigInteger.prototype.subTo = function (a, r) { 1773 | var i = 0; 1774 | var c = 0; 1775 | var m = Math.min(a.t, this.t); 1776 | while (i < m) { 1777 | c += this[i] - a[i]; 1778 | r[i++] = c & this.DM; 1779 | c >>= this.DB; 1780 | } 1781 | if (a.t < this.t) { 1782 | c -= a.s; 1783 | while (i < this.t) { 1784 | c += this[i]; 1785 | r[i++] = c & this.DM; 1786 | c >>= this.DB; 1787 | } 1788 | c += this.s; 1789 | } 1790 | else { 1791 | c += this.s; 1792 | while (i < a.t) { 1793 | c -= a[i]; 1794 | r[i++] = c & this.DM; 1795 | c >>= this.DB; 1796 | } 1797 | c -= a.s; 1798 | } 1799 | r.s = (c < 0) ? -1 : 0; 1800 | if (c < -1) { 1801 | r[i++] = this.DV + c; 1802 | } 1803 | else if (c > 0) { 1804 | r[i++] = c; 1805 | } 1806 | r.t = i; 1807 | r.clamp(); 1808 | }; 1809 | // BigInteger.prototype.multiplyTo = bnpMultiplyTo; 1810 | // (protected) r = this * a, r != this,a (HAC 14.12) 1811 | // "this" should be the larger one if appropriate. 1812 | BigInteger.prototype.multiplyTo = function (a, r) { 1813 | var x = this.abs(); 1814 | var y = a.abs(); 1815 | var i = x.t; 1816 | r.t = i + y.t; 1817 | while (--i >= 0) { 1818 | r[i] = 0; 1819 | } 1820 | for (i = 0; i < y.t; ++i) { 1821 | r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); 1822 | } 1823 | r.s = 0; 1824 | r.clamp(); 1825 | if (this.s != a.s) { 1826 | BigInteger.ZERO.subTo(r, r); 1827 | } 1828 | }; 1829 | // BigInteger.prototype.squareTo = bnpSquareTo; 1830 | // (protected) r = this^2, r != this (HAC 14.16) 1831 | BigInteger.prototype.squareTo = function (r) { 1832 | var x = this.abs(); 1833 | var i = r.t = 2 * x.t; 1834 | while (--i >= 0) { 1835 | r[i] = 0; 1836 | } 1837 | for (i = 0; i < x.t - 1; ++i) { 1838 | var c = x.am(i, x[i], r, 2 * i, 0, 1); 1839 | if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { 1840 | r[i + x.t] -= x.DV; 1841 | r[i + x.t + 1] = 1; 1842 | } 1843 | } 1844 | if (r.t > 0) { 1845 | r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); 1846 | } 1847 | r.s = 0; 1848 | r.clamp(); 1849 | }; 1850 | // BigInteger.prototype.divRemTo = bnpDivRemTo; 1851 | // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) 1852 | // r != q, this != m. q or r may be null. 1853 | BigInteger.prototype.divRemTo = function (m, q, r) { 1854 | var pm = m.abs(); 1855 | if (pm.t <= 0) { 1856 | return; 1857 | } 1858 | var pt = this.abs(); 1859 | if (pt.t < pm.t) { 1860 | if (q != null) { 1861 | q.fromInt(0); 1862 | } 1863 | if (r != null) { 1864 | this.copyTo(r); 1865 | } 1866 | return; 1867 | } 1868 | if (r == null) { 1869 | r = nbi(); 1870 | } 1871 | var y = nbi(); 1872 | var ts = this.s; 1873 | var ms = m.s; 1874 | var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus 1875 | if (nsh > 0) { 1876 | pm.lShiftTo(nsh, y); 1877 | pt.lShiftTo(nsh, r); 1878 | } 1879 | else { 1880 | pm.copyTo(y); 1881 | pt.copyTo(r); 1882 | } 1883 | var ys = y.t; 1884 | var y0 = y[ys - 1]; 1885 | if (y0 == 0) { 1886 | return; 1887 | } 1888 | var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); 1889 | var d1 = this.FV / yt; 1890 | var d2 = (1 << this.F1) / yt; 1891 | var e = 1 << this.F2; 1892 | var i = r.t; 1893 | var j = i - ys; 1894 | var t = (q == null) ? nbi() : q; 1895 | y.dlShiftTo(j, t); 1896 | if (r.compareTo(t) >= 0) { 1897 | r[r.t++] = 1; 1898 | r.subTo(t, r); 1899 | } 1900 | BigInteger.ONE.dlShiftTo(ys, t); 1901 | t.subTo(y, y); // "negative" y so we can replace sub with am later 1902 | while (y.t < ys) { 1903 | y[y.t++] = 0; 1904 | } 1905 | while (--j >= 0) { 1906 | // Estimate quotient digit 1907 | var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); 1908 | if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out 1909 | y.dlShiftTo(j, t); 1910 | r.subTo(t, r); 1911 | while (r[i] < --qd) { 1912 | r.subTo(t, r); 1913 | } 1914 | } 1915 | } 1916 | if (q != null) { 1917 | r.drShiftTo(ys, q); 1918 | if (ts != ms) { 1919 | BigInteger.ZERO.subTo(q, q); 1920 | } 1921 | } 1922 | r.t = ys; 1923 | r.clamp(); 1924 | if (nsh > 0) { 1925 | r.rShiftTo(nsh, r); 1926 | } // Denormalize remainder 1927 | if (ts < 0) { 1928 | BigInteger.ZERO.subTo(r, r); 1929 | } 1930 | }; 1931 | // BigInteger.prototype.invDigit = bnpInvDigit; 1932 | // (protected) return "-1/this % 2^DB"; useful for Mont. reduction 1933 | // justification: 1934 | // xy == 1 (mod m) 1935 | // xy = 1+km 1936 | // xy(2-xy) = (1+km)(1-km) 1937 | // x[y(2-xy)] = 1-k^2m^2 1938 | // x[y(2-xy)] == 1 (mod m^2) 1939 | // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 1940 | // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. 1941 | // JS multiply "overflows" differently from C/C++, so care is needed here. 1942 | BigInteger.prototype.invDigit = function () { 1943 | if (this.t < 1) { 1944 | return 0; 1945 | } 1946 | var x = this[0]; 1947 | if ((x & 1) == 0) { 1948 | return 0; 1949 | } 1950 | var y = x & 3; // y == 1/x mod 2^2 1951 | y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 1952 | y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 1953 | y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 1954 | // last step - calculate inverse mod DV directly; 1955 | // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints 1956 | y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits 1957 | // we really want the negative inverse, and -DV < y < DV 1958 | return (y > 0) ? this.DV - y : -y; 1959 | }; 1960 | // BigInteger.prototype.isEven = bnpIsEven; 1961 | // (protected) true iff this is even 1962 | BigInteger.prototype.isEven = function () { 1963 | return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; 1964 | }; 1965 | // BigInteger.prototype.exp = bnpExp; 1966 | // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) 1967 | BigInteger.prototype.exp = function (e, z) { 1968 | if (e > 0xffffffff || e < 1) { 1969 | return BigInteger.ONE; 1970 | } 1971 | var r = nbi(); 1972 | var r2 = nbi(); 1973 | var g = z.convert(this); 1974 | var i = nbits(e) - 1; 1975 | g.copyTo(r); 1976 | while (--i >= 0) { 1977 | z.sqrTo(r, r2); 1978 | if ((e & (1 << i)) > 0) { 1979 | z.mulTo(r2, g, r); 1980 | } 1981 | else { 1982 | var t = r; 1983 | r = r2; 1984 | r2 = t; 1985 | } 1986 | } 1987 | return z.revert(r); 1988 | }; 1989 | // BigInteger.prototype.chunkSize = bnpChunkSize; 1990 | // (protected) return x s.t. r^x < DV 1991 | BigInteger.prototype.chunkSize = function (r) { 1992 | return Math.floor(Math.LN2 * this.DB / Math.log(r)); 1993 | }; 1994 | // BigInteger.prototype.toRadix = bnpToRadix; 1995 | // (protected) convert to radix string 1996 | BigInteger.prototype.toRadix = function (b) { 1997 | if (b == null) { 1998 | b = 10; 1999 | } 2000 | if (this.signum() == 0 || b < 2 || b > 36) { 2001 | return "0"; 2002 | } 2003 | var cs = this.chunkSize(b); 2004 | var a = Math.pow(b, cs); 2005 | var d = nbv(a); 2006 | var y = nbi(); 2007 | var z = nbi(); 2008 | var r = ""; 2009 | this.divRemTo(d, y, z); 2010 | while (y.signum() > 0) { 2011 | r = (a + z.intValue()).toString(b).substr(1) + r; 2012 | y.divRemTo(d, y, z); 2013 | } 2014 | return z.intValue().toString(b) + r; 2015 | }; 2016 | // BigInteger.prototype.fromRadix = bnpFromRadix; 2017 | // (protected) convert from radix string 2018 | BigInteger.prototype.fromRadix = function (s, b) { 2019 | this.fromInt(0); 2020 | if (b == null) { 2021 | b = 10; 2022 | } 2023 | var cs = this.chunkSize(b); 2024 | var d = Math.pow(b, cs); 2025 | var mi = false; 2026 | var j = 0; 2027 | var w = 0; 2028 | for (var i = 0; i < s.length; ++i) { 2029 | var x = intAt(s, i); 2030 | if (x < 0) { 2031 | if (s.charAt(i) == "-" && this.signum() == 0) { 2032 | mi = true; 2033 | } 2034 | continue; 2035 | } 2036 | w = b * w + x; 2037 | if (++j >= cs) { 2038 | this.dMultiply(d); 2039 | this.dAddOffset(w, 0); 2040 | j = 0; 2041 | w = 0; 2042 | } 2043 | } 2044 | if (j > 0) { 2045 | this.dMultiply(Math.pow(b, j)); 2046 | this.dAddOffset(w, 0); 2047 | } 2048 | if (mi) { 2049 | BigInteger.ZERO.subTo(this, this); 2050 | } 2051 | }; 2052 | // BigInteger.prototype.fromNumber = bnpFromNumber; 2053 | // (protected) alternate constructor 2054 | BigInteger.prototype.fromNumber = function (a, b, c) { 2055 | if ("number" == typeof b) { 2056 | // new BigInteger(int,int,RNG) 2057 | if (a < 2) { 2058 | this.fromInt(1); 2059 | } 2060 | else { 2061 | this.fromNumber(a, c); 2062 | if (!this.testBit(a - 1)) { 2063 | // force MSB set 2064 | this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); 2065 | } 2066 | if (this.isEven()) { 2067 | this.dAddOffset(1, 0); 2068 | } // force odd 2069 | while (!this.isProbablePrime(b)) { 2070 | this.dAddOffset(2, 0); 2071 | if (this.bitLength() > a) { 2072 | this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); 2073 | } 2074 | } 2075 | } 2076 | } 2077 | else { 2078 | // new BigInteger(int,RNG) 2079 | var x = []; 2080 | var t = a & 7; 2081 | x.length = (a >> 3) + 1; 2082 | b.nextBytes(x); 2083 | if (t > 0) { 2084 | x[0] &= ((1 << t) - 1); 2085 | } 2086 | else { 2087 | x[0] = 0; 2088 | } 2089 | this.fromString(x, 256); 2090 | } 2091 | }; 2092 | // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; 2093 | // (protected) r = this op a (bitwise) 2094 | BigInteger.prototype.bitwiseTo = function (a, op, r) { 2095 | var i; 2096 | var f; 2097 | var m = Math.min(a.t, this.t); 2098 | for (i = 0; i < m; ++i) { 2099 | r[i] = op(this[i], a[i]); 2100 | } 2101 | if (a.t < this.t) { 2102 | f = a.s & this.DM; 2103 | for (i = m; i < this.t; ++i) { 2104 | r[i] = op(this[i], f); 2105 | } 2106 | r.t = this.t; 2107 | } 2108 | else { 2109 | f = this.s & this.DM; 2110 | for (i = m; i < a.t; ++i) { 2111 | r[i] = op(f, a[i]); 2112 | } 2113 | r.t = a.t; 2114 | } 2115 | r.s = op(this.s, a.s); 2116 | r.clamp(); 2117 | }; 2118 | // BigInteger.prototype.changeBit = bnpChangeBit; 2119 | // (protected) this op (1<>= this.DB; 2135 | } 2136 | if (a.t < this.t) { 2137 | c += a.s; 2138 | while (i < this.t) { 2139 | c += this[i]; 2140 | r[i++] = c & this.DM; 2141 | c >>= this.DB; 2142 | } 2143 | c += this.s; 2144 | } 2145 | else { 2146 | c += this.s; 2147 | while (i < a.t) { 2148 | c += a[i]; 2149 | r[i++] = c & this.DM; 2150 | c >>= this.DB; 2151 | } 2152 | c += a.s; 2153 | } 2154 | r.s = (c < 0) ? -1 : 0; 2155 | if (c > 0) { 2156 | r[i++] = c; 2157 | } 2158 | else if (c < -1) { 2159 | r[i++] = this.DV + c; 2160 | } 2161 | r.t = i; 2162 | r.clamp(); 2163 | }; 2164 | // BigInteger.prototype.dMultiply = bnpDMultiply; 2165 | // (protected) this *= n, this >= 0, 1 < n < DV 2166 | BigInteger.prototype.dMultiply = function (n) { 2167 | this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); 2168 | ++this.t; 2169 | this.clamp(); 2170 | }; 2171 | // BigInteger.prototype.dAddOffset = bnpDAddOffset; 2172 | // (protected) this += n << w words, this >= 0 2173 | BigInteger.prototype.dAddOffset = function (n, w) { 2174 | if (n == 0) { 2175 | return; 2176 | } 2177 | while (this.t <= w) { 2178 | this[this.t++] = 0; 2179 | } 2180 | this[w] += n; 2181 | while (this[w] >= this.DV) { 2182 | this[w] -= this.DV; 2183 | if (++w >= this.t) { 2184 | this[this.t++] = 0; 2185 | } 2186 | ++this[w]; 2187 | } 2188 | }; 2189 | // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; 2190 | // (protected) r = lower n words of "this * a", a.t <= n 2191 | // "this" should be the larger one if appropriate. 2192 | BigInteger.prototype.multiplyLowerTo = function (a, n, r) { 2193 | var i = Math.min(this.t + a.t, n); 2194 | r.s = 0; // assumes a,this >= 0 2195 | r.t = i; 2196 | while (i > 0) { 2197 | r[--i] = 0; 2198 | } 2199 | for (var j = r.t - this.t; i < j; ++i) { 2200 | r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); 2201 | } 2202 | for (var j = Math.min(a.t, n); i < j; ++i) { 2203 | this.am(0, a[i], r, i, 0, n - i); 2204 | } 2205 | r.clamp(); 2206 | }; 2207 | // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; 2208 | // (protected) r = "this * a" without lower n words, n > 0 2209 | // "this" should be the larger one if appropriate. 2210 | BigInteger.prototype.multiplyUpperTo = function (a, n, r) { 2211 | --n; 2212 | var i = r.t = this.t + a.t - n; 2213 | r.s = 0; // assumes a,this >= 0 2214 | while (--i >= 0) { 2215 | r[i] = 0; 2216 | } 2217 | for (i = Math.max(n - this.t, 0); i < a.t; ++i) { 2218 | r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); 2219 | } 2220 | r.clamp(); 2221 | r.drShiftTo(1, r); 2222 | }; 2223 | // BigInteger.prototype.modInt = bnpModInt; 2224 | // (protected) this % n, n < 2^26 2225 | BigInteger.prototype.modInt = function (n) { 2226 | if (n <= 0) { 2227 | return 0; 2228 | } 2229 | var d = this.DV % n; 2230 | var r = (this.s < 0) ? n - 1 : 0; 2231 | if (this.t > 0) { 2232 | if (d == 0) { 2233 | r = this[0] % n; 2234 | } 2235 | else { 2236 | for (var i = this.t - 1; i >= 0; --i) { 2237 | r = (d * r + this[i]) % n; 2238 | } 2239 | } 2240 | } 2241 | return r; 2242 | }; 2243 | // BigInteger.prototype.millerRabin = bnpMillerRabin; 2244 | // (protected) true if probably prime (HAC 4.24, Miller-Rabin) 2245 | BigInteger.prototype.millerRabin = function (t) { 2246 | var n1 = this.subtract(BigInteger.ONE); 2247 | var k = n1.getLowestSetBit(); 2248 | if (k <= 0) { 2249 | return false; 2250 | } 2251 | var r = n1.shiftRight(k); 2252 | t = (t + 1) >> 1; 2253 | if (t > lowprimes.length) { 2254 | t = lowprimes.length; 2255 | } 2256 | var a = nbi(); 2257 | for (var i = 0; i < t; ++i) { 2258 | // Pick bases at random, instead of starting at 2 2259 | a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); 2260 | var y = a.modPow(r, this); 2261 | if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { 2262 | var j = 1; 2263 | while (j++ < k && y.compareTo(n1) != 0) { 2264 | y = y.modPowInt(2, this); 2265 | if (y.compareTo(BigInteger.ONE) == 0) { 2266 | return false; 2267 | } 2268 | } 2269 | if (y.compareTo(n1) != 0) { 2270 | return false; 2271 | } 2272 | } 2273 | } 2274 | return true; 2275 | }; 2276 | // BigInteger.prototype.square = bnSquare; 2277 | // (public) this^2 2278 | BigInteger.prototype.square = function () { 2279 | var r = nbi(); 2280 | this.squareTo(r); 2281 | return r; 2282 | }; 2283 | //#region ASYNC 2284 | // Public API method 2285 | BigInteger.prototype.gcda = function (a, callback) { 2286 | var x = (this.s < 0) ? this.negate() : this.clone(); 2287 | var y = (a.s < 0) ? a.negate() : a.clone(); 2288 | if (x.compareTo(y) < 0) { 2289 | var t = x; 2290 | x = y; 2291 | y = t; 2292 | } 2293 | var i = x.getLowestSetBit(); 2294 | var g = y.getLowestSetBit(); 2295 | if (g < 0) { 2296 | callback(x); 2297 | return; 2298 | } 2299 | if (i < g) { 2300 | g = i; 2301 | } 2302 | if (g > 0) { 2303 | x.rShiftTo(g, x); 2304 | y.rShiftTo(g, y); 2305 | } 2306 | // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. 2307 | var gcda1 = function () { 2308 | if ((i = x.getLowestSetBit()) > 0) { 2309 | x.rShiftTo(i, x); 2310 | } 2311 | if ((i = y.getLowestSetBit()) > 0) { 2312 | y.rShiftTo(i, y); 2313 | } 2314 | if (x.compareTo(y) >= 0) { 2315 | x.subTo(y, x); 2316 | x.rShiftTo(1, x); 2317 | } 2318 | else { 2319 | y.subTo(x, y); 2320 | y.rShiftTo(1, y); 2321 | } 2322 | if (!(x.signum() > 0)) { 2323 | if (g > 0) { 2324 | y.lShiftTo(g, y); 2325 | } 2326 | setTimeout(function () { callback(y); }, 0); // escape 2327 | } 2328 | else { 2329 | setTimeout(gcda1, 0); 2330 | } 2331 | }; 2332 | setTimeout(gcda1, 10); 2333 | }; 2334 | // (protected) alternate constructor 2335 | BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) { 2336 | if ("number" == typeof b) { 2337 | if (a < 2) { 2338 | this.fromInt(1); 2339 | } 2340 | else { 2341 | this.fromNumber(a, c); 2342 | if (!this.testBit(a - 1)) { 2343 | this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); 2344 | } 2345 | if (this.isEven()) { 2346 | this.dAddOffset(1, 0); 2347 | } 2348 | var bnp_1 = this; 2349 | var bnpfn1_1 = function () { 2350 | bnp_1.dAddOffset(2, 0); 2351 | if (bnp_1.bitLength() > a) { 2352 | bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); 2353 | } 2354 | if (bnp_1.isProbablePrime(b)) { 2355 | setTimeout(function () { callback(); }, 0); // escape 2356 | } 2357 | else { 2358 | setTimeout(bnpfn1_1, 0); 2359 | } 2360 | }; 2361 | setTimeout(bnpfn1_1, 0); 2362 | } 2363 | } 2364 | else { 2365 | var x = []; 2366 | var t = a & 7; 2367 | x.length = (a >> 3) + 1; 2368 | b.nextBytes(x); 2369 | if (t > 0) { 2370 | x[0] &= ((1 << t) - 1); 2371 | } 2372 | else { 2373 | x[0] = 0; 2374 | } 2375 | this.fromString(x, 256); 2376 | } 2377 | }; 2378 | return BigInteger; 2379 | }()); 2380 | //#region REDUCERS 2381 | //#region NullExp 2382 | var NullExp = /** @class */ (function () { 2383 | function NullExp() { 2384 | } 2385 | // NullExp.prototype.convert = nNop; 2386 | NullExp.prototype.convert = function (x) { 2387 | return x; 2388 | }; 2389 | // NullExp.prototype.revert = nNop; 2390 | NullExp.prototype.revert = function (x) { 2391 | return x; 2392 | }; 2393 | // NullExp.prototype.mulTo = nMulTo; 2394 | NullExp.prototype.mulTo = function (x, y, r) { 2395 | x.multiplyTo(y, r); 2396 | }; 2397 | // NullExp.prototype.sqrTo = nSqrTo; 2398 | NullExp.prototype.sqrTo = function (x, r) { 2399 | x.squareTo(r); 2400 | }; 2401 | return NullExp; 2402 | }()); 2403 | // Modular reduction using "classic" algorithm 2404 | var Classic = /** @class */ (function () { 2405 | function Classic(m) { 2406 | this.m = m; 2407 | } 2408 | // Classic.prototype.convert = cConvert; 2409 | Classic.prototype.convert = function (x) { 2410 | if (x.s < 0 || x.compareTo(this.m) >= 0) { 2411 | return x.mod(this.m); 2412 | } 2413 | else { 2414 | return x; 2415 | } 2416 | }; 2417 | // Classic.prototype.revert = cRevert; 2418 | Classic.prototype.revert = function (x) { 2419 | return x; 2420 | }; 2421 | // Classic.prototype.reduce = cReduce; 2422 | Classic.prototype.reduce = function (x) { 2423 | x.divRemTo(this.m, null, x); 2424 | }; 2425 | // Classic.prototype.mulTo = cMulTo; 2426 | Classic.prototype.mulTo = function (x, y, r) { 2427 | x.multiplyTo(y, r); 2428 | this.reduce(r); 2429 | }; 2430 | // Classic.prototype.sqrTo = cSqrTo; 2431 | Classic.prototype.sqrTo = function (x, r) { 2432 | x.squareTo(r); 2433 | this.reduce(r); 2434 | }; 2435 | return Classic; 2436 | }()); 2437 | //#endregion 2438 | //#region Montgomery 2439 | // Montgomery reduction 2440 | var Montgomery = /** @class */ (function () { 2441 | function Montgomery(m) { 2442 | this.m = m; 2443 | this.mp = m.invDigit(); 2444 | this.mpl = this.mp & 0x7fff; 2445 | this.mph = this.mp >> 15; 2446 | this.um = (1 << (m.DB - 15)) - 1; 2447 | this.mt2 = 2 * m.t; 2448 | } 2449 | // Montgomery.prototype.convert = montConvert; 2450 | // xR mod m 2451 | Montgomery.prototype.convert = function (x) { 2452 | var r = nbi(); 2453 | x.abs().dlShiftTo(this.m.t, r); 2454 | r.divRemTo(this.m, null, r); 2455 | if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { 2456 | this.m.subTo(r, r); 2457 | } 2458 | return r; 2459 | }; 2460 | // Montgomery.prototype.revert = montRevert; 2461 | // x/R mod m 2462 | Montgomery.prototype.revert = function (x) { 2463 | var r = nbi(); 2464 | x.copyTo(r); 2465 | this.reduce(r); 2466 | return r; 2467 | }; 2468 | // Montgomery.prototype.reduce = montReduce; 2469 | // x = x/R mod m (HAC 14.32) 2470 | Montgomery.prototype.reduce = function (x) { 2471 | while (x.t <= this.mt2) { 2472 | // pad x so am has enough room later 2473 | x[x.t++] = 0; 2474 | } 2475 | for (var i = 0; i < this.m.t; ++i) { 2476 | // faster way of calculating u0 = x[i]*mp mod DV 2477 | var j = x[i] & 0x7fff; 2478 | var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; 2479 | // use am to combine the multiply-shift-add into one call 2480 | j = i + this.m.t; 2481 | x[j] += this.m.am(0, u0, x, i, 0, this.m.t); 2482 | // propagate carry 2483 | while (x[j] >= x.DV) { 2484 | x[j] -= x.DV; 2485 | x[++j]++; 2486 | } 2487 | } 2488 | x.clamp(); 2489 | x.drShiftTo(this.m.t, x); 2490 | if (x.compareTo(this.m) >= 0) { 2491 | x.subTo(this.m, x); 2492 | } 2493 | }; 2494 | // Montgomery.prototype.mulTo = montMulTo; 2495 | // r = "xy/R mod m"; x,y != r 2496 | Montgomery.prototype.mulTo = function (x, y, r) { 2497 | x.multiplyTo(y, r); 2498 | this.reduce(r); 2499 | }; 2500 | // Montgomery.prototype.sqrTo = montSqrTo; 2501 | // r = "x^2/R mod m"; x != r 2502 | Montgomery.prototype.sqrTo = function (x, r) { 2503 | x.squareTo(r); 2504 | this.reduce(r); 2505 | }; 2506 | return Montgomery; 2507 | }()); 2508 | //#endregion Montgomery 2509 | //#region Barrett 2510 | // Barrett modular reduction 2511 | var Barrett = /** @class */ (function () { 2512 | function Barrett(m) { 2513 | this.m = m; 2514 | // setup Barrett 2515 | this.r2 = nbi(); 2516 | this.q3 = nbi(); 2517 | BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); 2518 | this.mu = this.r2.divide(m); 2519 | } 2520 | // Barrett.prototype.convert = barrettConvert; 2521 | Barrett.prototype.convert = function (x) { 2522 | if (x.s < 0 || x.t > 2 * this.m.t) { 2523 | return x.mod(this.m); 2524 | } 2525 | else if (x.compareTo(this.m) < 0) { 2526 | return x; 2527 | } 2528 | else { 2529 | var r = nbi(); 2530 | x.copyTo(r); 2531 | this.reduce(r); 2532 | return r; 2533 | } 2534 | }; 2535 | // Barrett.prototype.revert = barrettRevert; 2536 | Barrett.prototype.revert = function (x) { 2537 | return x; 2538 | }; 2539 | // Barrett.prototype.reduce = barrettReduce; 2540 | // x = x mod m (HAC 14.42) 2541 | Barrett.prototype.reduce = function (x) { 2542 | x.drShiftTo(this.m.t - 1, this.r2); 2543 | if (x.t > this.m.t + 1) { 2544 | x.t = this.m.t + 1; 2545 | x.clamp(); 2546 | } 2547 | this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); 2548 | this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); 2549 | while (x.compareTo(this.r2) < 0) { 2550 | x.dAddOffset(1, this.m.t + 1); 2551 | } 2552 | x.subTo(this.r2, x); 2553 | while (x.compareTo(this.m) >= 0) { 2554 | x.subTo(this.m, x); 2555 | } 2556 | }; 2557 | // Barrett.prototype.mulTo = barrettMulTo; 2558 | // r = x*y mod m; x,y != r 2559 | Barrett.prototype.mulTo = function (x, y, r) { 2560 | x.multiplyTo(y, r); 2561 | this.reduce(r); 2562 | }; 2563 | // Barrett.prototype.sqrTo = barrettSqrTo; 2564 | // r = x^2 mod m; x != r 2565 | Barrett.prototype.sqrTo = function (x, r) { 2566 | x.squareTo(r); 2567 | this.reduce(r); 2568 | }; 2569 | return Barrett; 2570 | }()); 2571 | //#endregion 2572 | //#endregion REDUCERS 2573 | // return new, unset BigInteger 2574 | function nbi() { return new BigInteger(null); } 2575 | function parseBigInt(str, r) { 2576 | return new BigInteger(str, r); 2577 | } 2578 | // am: Compute w_j += (x*this_i), propagate carries, 2579 | // c is initial carry, returns final carry. 2580 | // c < 3*dvalue, x < 2*dvalue, this_i < dvalue 2581 | // We need to select the fastest one that works in this environment. 2582 | // am1: use a single mult and divide to get the high bits, 2583 | // max digit bits should be 26 because 2584 | // max internal value = 2*dvalue^2-2*dvalue (< 2^53) 2585 | function am1(i, x, w, j, c, n) { 2586 | while (--n >= 0) { 2587 | var v = x * this[i++] + w[j] + c; 2588 | c = Math.floor(v / 0x4000000); 2589 | w[j++] = v & 0x3ffffff; 2590 | } 2591 | return c; 2592 | } 2593 | // am2 avoids a big mult-and-extract completely. 2594 | // Max digit bits should be <= 30 because we do bitwise ops 2595 | // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) 2596 | function am2(i, x, w, j, c, n) { 2597 | var xl = x & 0x7fff; 2598 | var xh = x >> 15; 2599 | while (--n >= 0) { 2600 | var l = this[i] & 0x7fff; 2601 | var h = this[i++] >> 15; 2602 | var m = xh * l + h * xl; 2603 | l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); 2604 | c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); 2605 | w[j++] = l & 0x3fffffff; 2606 | } 2607 | return c; 2608 | } 2609 | // Alternately, set max digit bits to 28 since some 2610 | // browsers slow down when dealing with 32-bit numbers. 2611 | function am3(i, x, w, j, c, n) { 2612 | var xl = x & 0x3fff; 2613 | var xh = x >> 14; 2614 | while (--n >= 0) { 2615 | var l = this[i] & 0x3fff; 2616 | var h = this[i++] >> 14; 2617 | var m = xh * l + h * xl; 2618 | l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; 2619 | c = (l >> 28) + (m >> 14) + xh * h; 2620 | w[j++] = l & 0xfffffff; 2621 | } 2622 | return c; 2623 | } 2624 | if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { 2625 | BigInteger.prototype.am = am2; 2626 | dbits = 30; 2627 | } 2628 | else if (j_lm && (navigator.appName != "Netscape")) { 2629 | BigInteger.prototype.am = am1; 2630 | dbits = 26; 2631 | } 2632 | else { // Mozilla/Netscape seems to prefer am3 2633 | BigInteger.prototype.am = am3; 2634 | dbits = 28; 2635 | } 2636 | BigInteger.prototype.DB = dbits; 2637 | BigInteger.prototype.DM = ((1 << dbits) - 1); 2638 | BigInteger.prototype.DV = (1 << dbits); 2639 | var BI_FP = 52; 2640 | BigInteger.prototype.FV = Math.pow(2, BI_FP); 2641 | BigInteger.prototype.F1 = BI_FP - dbits; 2642 | BigInteger.prototype.F2 = 2 * dbits - BI_FP; 2643 | // Digit conversions 2644 | var BI_RC = []; 2645 | var rr; 2646 | var vv; 2647 | rr = "0".charCodeAt(0); 2648 | for (vv = 0; vv <= 9; ++vv) { 2649 | BI_RC[rr++] = vv; 2650 | } 2651 | rr = "a".charCodeAt(0); 2652 | for (vv = 10; vv < 36; ++vv) { 2653 | BI_RC[rr++] = vv; 2654 | } 2655 | rr = "A".charCodeAt(0); 2656 | for (vv = 10; vv < 36; ++vv) { 2657 | BI_RC[rr++] = vv; 2658 | } 2659 | function intAt(s, i) { 2660 | var c = BI_RC[s.charCodeAt(i)]; 2661 | return (c == null) ? -1 : c; 2662 | } 2663 | // return bigint initialized to value 2664 | function nbv(i) { 2665 | var r = nbi(); 2666 | r.fromInt(i); 2667 | return r; 2668 | } 2669 | // returns bit length of the integer x 2670 | function nbits(x) { 2671 | var r = 1; 2672 | var t; 2673 | if ((t = x >>> 16) != 0) { 2674 | x = t; 2675 | r += 16; 2676 | } 2677 | if ((t = x >> 8) != 0) { 2678 | x = t; 2679 | r += 8; 2680 | } 2681 | if ((t = x >> 4) != 0) { 2682 | x = t; 2683 | r += 4; 2684 | } 2685 | if ((t = x >> 2) != 0) { 2686 | x = t; 2687 | r += 2; 2688 | } 2689 | if ((t = x >> 1) != 0) { 2690 | x = t; 2691 | r += 1; 2692 | } 2693 | return r; 2694 | } 2695 | // "constants" 2696 | BigInteger.ZERO = nbv(0); 2697 | BigInteger.ONE = nbv(1); 2698 | 2699 | // prng4.js - uses Arcfour as a PRNG 2700 | var Arcfour = /** @class */ (function () { 2701 | function Arcfour() { 2702 | this.i = 0; 2703 | this.j = 0; 2704 | this.S = []; 2705 | } 2706 | // Arcfour.prototype.init = ARC4init; 2707 | // Initialize arcfour context from key, an array of ints, each from [0..255] 2708 | Arcfour.prototype.init = function (key) { 2709 | var i; 2710 | var j; 2711 | var t; 2712 | for (i = 0; i < 256; ++i) { 2713 | this.S[i] = i; 2714 | } 2715 | j = 0; 2716 | for (i = 0; i < 256; ++i) { 2717 | j = (j + this.S[i] + key[i % key.length]) & 255; 2718 | t = this.S[i]; 2719 | this.S[i] = this.S[j]; 2720 | this.S[j] = t; 2721 | } 2722 | this.i = 0; 2723 | this.j = 0; 2724 | }; 2725 | // Arcfour.prototype.next = ARC4next; 2726 | Arcfour.prototype.next = function () { 2727 | var t; 2728 | this.i = (this.i + 1) & 255; 2729 | this.j = (this.j + this.S[this.i]) & 255; 2730 | t = this.S[this.i]; 2731 | this.S[this.i] = this.S[this.j]; 2732 | this.S[this.j] = t; 2733 | return this.S[(t + this.S[this.i]) & 255]; 2734 | }; 2735 | return Arcfour; 2736 | }()); 2737 | // Plug in your RNG constructor here 2738 | function prng_newstate() { 2739 | return new Arcfour(); 2740 | } 2741 | // Pool size must be a multiple of 4 and greater than 32. 2742 | // An array of bytes the size of the pool will be passed to init() 2743 | var rng_psize = 256; 2744 | 2745 | // Random number generator - requires a PRNG backend, e.g. prng4.js 2746 | var rng_state; 2747 | var rng_pool = null; 2748 | var rng_pptr; 2749 | // Initialize the pool with junk if needed. 2750 | if (rng_pool == null) { 2751 | rng_pool = []; 2752 | rng_pptr = 0; 2753 | var t = void 0; 2754 | if (window.crypto && window.crypto.getRandomValues) { 2755 | // Extract entropy (2048 bits) from RNG if available 2756 | var z = new Uint32Array(256); 2757 | window.crypto.getRandomValues(z); 2758 | for (t = 0; t < z.length; ++t) { 2759 | rng_pool[rng_pptr++] = z[t] & 255; 2760 | } 2761 | } 2762 | // Use mouse events for entropy, if we do not have enough entropy by the time 2763 | // we need it, entropy will be generated by Math.random. 2764 | var onMouseMoveListener_1 = function (ev) { 2765 | this.count = this.count || 0; 2766 | if (this.count >= 256 || rng_pptr >= rng_psize) { 2767 | if (window.removeEventListener) { 2768 | window.removeEventListener("mousemove", onMouseMoveListener_1, false); 2769 | } 2770 | else if (window.detachEvent) { 2771 | window.detachEvent("onmousemove", onMouseMoveListener_1); 2772 | } 2773 | return; 2774 | } 2775 | try { 2776 | var mouseCoordinates = ev.x + ev.y; 2777 | rng_pool[rng_pptr++] = mouseCoordinates & 255; 2778 | this.count += 1; 2779 | } 2780 | catch (e) { 2781 | // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. 2782 | } 2783 | }; 2784 | if (window.addEventListener) { 2785 | window.addEventListener("mousemove", onMouseMoveListener_1, false); 2786 | } 2787 | else if (window.attachEvent) { 2788 | window.attachEvent("onmousemove", onMouseMoveListener_1); 2789 | } 2790 | } 2791 | function rng_get_byte() { 2792 | if (rng_state == null) { 2793 | rng_state = prng_newstate(); 2794 | // At this point, we may not have collected enough entropy. If not, fall back to Math.random 2795 | while (rng_pptr < rng_psize) { 2796 | var random = Math.floor(65536 * Math.random()); 2797 | rng_pool[rng_pptr++] = random & 255; 2798 | } 2799 | rng_state.init(rng_pool); 2800 | for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { 2801 | rng_pool[rng_pptr] = 0; 2802 | } 2803 | rng_pptr = 0; 2804 | } 2805 | // TODO: allow reseeding after first request 2806 | return rng_state.next(); 2807 | } 2808 | var SecureRandom = /** @class */ (function () { 2809 | function SecureRandom() { 2810 | } 2811 | SecureRandom.prototype.nextBytes = function (ba) { 2812 | for (var i = 0; i < ba.length; ++i) { 2813 | ba[i] = rng_get_byte(); 2814 | } 2815 | }; 2816 | return SecureRandom; 2817 | }()); 2818 | 2819 | // Depends on jsbn.js and rng.js 2820 | // function linebrk(s,n) { 2821 | // var ret = ""; 2822 | // var i = 0; 2823 | // while(i + n < s.length) { 2824 | // ret += s.substring(i,i+n) + "\n"; 2825 | // i += n; 2826 | // } 2827 | // return ret + s.substring(i,s.length); 2828 | // } 2829 | // function byte2Hex(b) { 2830 | // if(b < 0x10) 2831 | // return "0" + b.toString(16); 2832 | // else 2833 | // return b.toString(16); 2834 | // } 2835 | function pkcs1pad1(s, n) { 2836 | if (n < s.length + 22) { 2837 | console.error("Message too long for RSA"); 2838 | return null; 2839 | } 2840 | var len = n - s.length - 6; 2841 | var filler = ""; 2842 | for (var f = 0; f < len; f += 2) { 2843 | filler += "ff"; 2844 | } 2845 | var m = "0001" + filler + "00" + s; 2846 | return parseBigInt(m, 16); 2847 | } 2848 | // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint 2849 | function pkcs1pad2(s, n) { 2850 | if (n < s.length + 11) { // TODO: fix for utf-8 2851 | console.error("Message too long for RSA"); 2852 | return null; 2853 | } 2854 | var ba = []; 2855 | var i = s.length - 1; 2856 | while (i >= 0 && n > 0) { 2857 | ba[--n] = s.charCodeAt(i--); 2858 | } 2859 | ba[--n] = 0; 2860 | var rng = new SecureRandom(); 2861 | var x = []; 2862 | while (n > 2) { // random non-zero pad 2863 | x[0] = 0; 2864 | while (x[0] == 0) { 2865 | rng.nextBytes(x); 2866 | } 2867 | ba[--n] = x[0]; 2868 | } 2869 | ba[--n] = 2; 2870 | ba[--n] = 0; 2871 | return new BigInteger(ba); 2872 | } 2873 | // "empty" RSA key constructor 2874 | var RSAKey = /** @class */ (function () { 2875 | function RSAKey() { 2876 | this.n = null; 2877 | this.e = 0; 2878 | this.d = null; 2879 | this.p = null; 2880 | this.q = null; 2881 | this.dmp1 = null; 2882 | this.dmq1 = null; 2883 | this.coeff = null; 2884 | } 2885 | //#region PROTECTED 2886 | // protected 2887 | // RSAKey.prototype.doPublic = RSADoPublic; 2888 | // Perform raw public operation on "x": return x^e (mod n) 2889 | RSAKey.prototype.doPublic = function (x) { 2890 | return x.modPowInt(this.e, this.n); 2891 | }; 2892 | // RSAKey.prototype.doPrivate = RSADoPrivate; 2893 | // Perform raw private operation on "x": return x^d (mod n) 2894 | RSAKey.prototype.doPrivate = function (x) { 2895 | if (this.p == null || this.q == null) { 2896 | return x.modPow(this.d, this.n); 2897 | } 2898 | // TODO: re-calculate any missing CRT params 2899 | var xp = x.mod(this.p).modPow(this.dmp1, this.p); 2900 | var xq = x.mod(this.q).modPow(this.dmq1, this.q); 2901 | while (xp.compareTo(xq) < 0) { 2902 | xp = xp.add(this.p); 2903 | } 2904 | return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); 2905 | }; 2906 | //#endregion PROTECTED 2907 | //#region PUBLIC 2908 | // RSAKey.prototype.setPublic = RSASetPublic; 2909 | // Set the public key fields N and e from hex strings 2910 | RSAKey.prototype.setPublic = function (N, E) { 2911 | if (N != null && E != null && N.length > 0 && E.length > 0) { 2912 | this.n = parseBigInt(N, 16); 2913 | this.e = parseInt(E, 16); 2914 | } 2915 | else { 2916 | console.error("Invalid RSA public key"); 2917 | } 2918 | }; 2919 | // RSAKey.prototype.encrypt = RSAEncrypt; 2920 | // Return the PKCS#1 RSA encryption of "text" as an even-length hex string 2921 | RSAKey.prototype.encrypt = function (text) { 2922 | var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); 2923 | if (m == null) { 2924 | return null; 2925 | } 2926 | var c = this.doPublic(m); 2927 | if (c == null) { 2928 | return null; 2929 | } 2930 | var h = c.toString(16); 2931 | if ((h.length & 1) == 0) { 2932 | return h; 2933 | } 2934 | else { 2935 | return "0" + h; 2936 | } 2937 | }; 2938 | // RSAKey.prototype.setPrivate = RSASetPrivate; 2939 | // Set the private key fields N, e, and d from hex strings 2940 | RSAKey.prototype.setPrivate = function (N, E, D) { 2941 | if (N != null && E != null && N.length > 0 && E.length > 0) { 2942 | this.n = parseBigInt(N, 16); 2943 | this.e = parseInt(E, 16); 2944 | this.d = parseBigInt(D, 16); 2945 | } 2946 | else { 2947 | console.error("Invalid RSA private key"); 2948 | } 2949 | }; 2950 | // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; 2951 | // Set the private key fields N, e, d and CRT params from hex strings 2952 | RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) { 2953 | if (N != null && E != null && N.length > 0 && E.length > 0) { 2954 | this.n = parseBigInt(N, 16); 2955 | this.e = parseInt(E, 16); 2956 | this.d = parseBigInt(D, 16); 2957 | this.p = parseBigInt(P, 16); 2958 | this.q = parseBigInt(Q, 16); 2959 | this.dmp1 = parseBigInt(DP, 16); 2960 | this.dmq1 = parseBigInt(DQ, 16); 2961 | this.coeff = parseBigInt(C, 16); 2962 | } 2963 | else { 2964 | console.error("Invalid RSA private key"); 2965 | } 2966 | }; 2967 | // RSAKey.prototype.generate = RSAGenerate; 2968 | // Generate a new random private key B bits long, using public expt E 2969 | RSAKey.prototype.generate = function (B, E) { 2970 | var rng = new SecureRandom(); 2971 | var qs = B >> 1; 2972 | this.e = parseInt(E, 16); 2973 | var ee = new BigInteger(E, 16); 2974 | for (;;) { 2975 | for (;;) { 2976 | this.p = new BigInteger(B - qs, 1, rng); 2977 | if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) { 2978 | break; 2979 | } 2980 | } 2981 | for (;;) { 2982 | this.q = new BigInteger(qs, 1, rng); 2983 | if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) { 2984 | break; 2985 | } 2986 | } 2987 | if (this.p.compareTo(this.q) <= 0) { 2988 | var t = this.p; 2989 | this.p = this.q; 2990 | this.q = t; 2991 | } 2992 | var p1 = this.p.subtract(BigInteger.ONE); 2993 | var q1 = this.q.subtract(BigInteger.ONE); 2994 | var phi = p1.multiply(q1); 2995 | if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { 2996 | this.n = this.p.multiply(this.q); 2997 | this.d = ee.modInverse(phi); 2998 | this.dmp1 = this.d.mod(p1); 2999 | this.dmq1 = this.d.mod(q1); 3000 | this.coeff = this.q.modInverse(this.p); 3001 | break; 3002 | } 3003 | } 3004 | }; 3005 | // RSAKey.prototype.decrypt = RSADecrypt; 3006 | // Return the PKCS#1 RSA decryption of "ctext". 3007 | // "ctext" is an even-length hex string and the output is a plain string. 3008 | RSAKey.prototype.decrypt = function (ctext) { 3009 | var c = parseBigInt(ctext, 16); 3010 | var m = this.doPrivate(c); 3011 | if (m == null) { 3012 | return null; 3013 | } 3014 | return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); 3015 | }; 3016 | // Generate a new random private key B bits long, using public expt E 3017 | RSAKey.prototype.generateAsync = function (B, E, callback) { 3018 | var rng = new SecureRandom(); 3019 | var qs = B >> 1; 3020 | this.e = parseInt(E, 16); 3021 | var ee = new BigInteger(E, 16); 3022 | var rsa = this; 3023 | // These functions have non-descript names because they were originally for(;;) loops. 3024 | // I don't know about cryptography to give them better names than loop1-4. 3025 | var loop1 = function () { 3026 | var loop4 = function () { 3027 | if (rsa.p.compareTo(rsa.q) <= 0) { 3028 | var t = rsa.p; 3029 | rsa.p = rsa.q; 3030 | rsa.q = t; 3031 | } 3032 | var p1 = rsa.p.subtract(BigInteger.ONE); 3033 | var q1 = rsa.q.subtract(BigInteger.ONE); 3034 | var phi = p1.multiply(q1); 3035 | if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { 3036 | rsa.n = rsa.p.multiply(rsa.q); 3037 | rsa.d = ee.modInverse(phi); 3038 | rsa.dmp1 = rsa.d.mod(p1); 3039 | rsa.dmq1 = rsa.d.mod(q1); 3040 | rsa.coeff = rsa.q.modInverse(rsa.p); 3041 | setTimeout(function () { callback(); }, 0); // escape 3042 | } 3043 | else { 3044 | setTimeout(loop1, 0); 3045 | } 3046 | }; 3047 | var loop3 = function () { 3048 | rsa.q = nbi(); 3049 | rsa.q.fromNumberAsync(qs, 1, rng, function () { 3050 | rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) { 3051 | if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) { 3052 | setTimeout(loop4, 0); 3053 | } 3054 | else { 3055 | setTimeout(loop3, 0); 3056 | } 3057 | }); 3058 | }); 3059 | }; 3060 | var loop2 = function () { 3061 | rsa.p = nbi(); 3062 | rsa.p.fromNumberAsync(B - qs, 1, rng, function () { 3063 | rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) { 3064 | if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) { 3065 | setTimeout(loop3, 0); 3066 | } 3067 | else { 3068 | setTimeout(loop2, 0); 3069 | } 3070 | }); 3071 | }); 3072 | }; 3073 | setTimeout(loop2, 0); 3074 | }; 3075 | setTimeout(loop1, 0); 3076 | }; 3077 | RSAKey.prototype.sign = function (text, digestMethod, digestName) { 3078 | var header = getDigestHeader(digestName); 3079 | var digest = header + digestMethod(text).toString(); 3080 | var m = pkcs1pad1(digest, this.n.bitLength() / 4); 3081 | if (m == null) { 3082 | return null; 3083 | } 3084 | var c = this.doPrivate(m); 3085 | if (c == null) { 3086 | return null; 3087 | } 3088 | var h = c.toString(16); 3089 | if ((h.length & 1) == 0) { 3090 | return h; 3091 | } 3092 | else { 3093 | return "0" + h; 3094 | } 3095 | }; 3096 | RSAKey.prototype.verify = function (text, signature, digestMethod) { 3097 | var c = parseBigInt(signature, 16); 3098 | var m = this.doPublic(c); 3099 | if (m == null) { 3100 | return null; 3101 | } 3102 | var unpadded = m.toString(16).replace(/^1f+00/, ""); 3103 | var digest = removeDigestHeader(unpadded); 3104 | return digest == digestMethod(text).toString(); 3105 | }; 3106 | return RSAKey; 3107 | }()); 3108 | // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext 3109 | function pkcs1unpad2(d, n) { 3110 | var b = d.toByteArray(); 3111 | var i = 0; 3112 | while (i < b.length && b[i] == 0) { 3113 | ++i; 3114 | } 3115 | if (b.length - i != n - 1 || b[i] != 2) { 3116 | return null; 3117 | } 3118 | ++i; 3119 | while (b[i] != 0) { 3120 | if (++i >= b.length) { 3121 | return null; 3122 | } 3123 | } 3124 | var ret = ""; 3125 | while (++i < b.length) { 3126 | ret += String.fromCharCode(b[i] & 255); 3127 | } 3128 | return ret; 3129 | } 3130 | // https://tools.ietf.org/html/rfc3447#page-43 3131 | var DIGEST_HEADERS = { 3132 | md2: "3020300c06082a864886f70d020205000410", 3133 | md5: "3020300c06082a864886f70d020505000410", 3134 | sha1: "3021300906052b0e03021a05000414", 3135 | sha224: "302d300d06096086480165030402040500041c", 3136 | sha256: "3031300d060960864801650304020105000420", 3137 | sha384: "3041300d060960864801650304020205000430", 3138 | sha512: "3051300d060960864801650304020305000440", 3139 | ripemd160: "3021300906052b2403020105000414", 3140 | }; 3141 | function getDigestHeader(name) { 3142 | return DIGEST_HEADERS[name] || ""; 3143 | } 3144 | function removeDigestHeader(str) { 3145 | for (var name_1 in DIGEST_HEADERS) { 3146 | if (DIGEST_HEADERS.hasOwnProperty(name_1)) { 3147 | var header = DIGEST_HEADERS[name_1]; 3148 | var len = header.length; 3149 | if (str.substr(0, len) == header) { 3150 | return str.substr(len); 3151 | } 3152 | } 3153 | } 3154 | return str; 3155 | } 3156 | // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string 3157 | // function RSAEncryptB64(text) { 3158 | // var h = this.encrypt(text); 3159 | // if(h) return hex2b64(h); else return null; 3160 | // } 3161 | // public 3162 | // RSAKey.prototype.encrypt_b64 = RSAEncryptB64; 3163 | 3164 | /*! 3165 | Copyright (c) 2011, Yahoo! Inc. All rights reserved. 3166 | Code licensed under the BSD License: 3167 | http://developer.yahoo.com/yui/license.html 3168 | version: 2.9.0 3169 | */ 3170 | var YAHOO = {}; 3171 | YAHOO.lang = { 3172 | /** 3173 | * Utility to set up the prototype, constructor and superclass properties to 3174 | * support an inheritance strategy that can chain constructors and methods. 3175 | * Static members will not be inherited. 3176 | * 3177 | * @method extend 3178 | * @static 3179 | * @param {Function} subc the object to modify 3180 | * @param {Function} superc the object to inherit 3181 | * @param {Object} overrides additional properties/methods to add to the 3182 | * subclass prototype. These will override the 3183 | * matching items obtained from the superclass 3184 | * if present. 3185 | */ 3186 | extend: function(subc, superc, overrides) { 3187 | if (! superc || ! subc) { 3188 | throw new Error("YAHOO.lang.extend failed, please check that " + 3189 | "all dependencies are included."); 3190 | } 3191 | 3192 | var F = function() {}; 3193 | F.prototype = superc.prototype; 3194 | subc.prototype = new F(); 3195 | subc.prototype.constructor = subc; 3196 | subc.superclass = superc.prototype; 3197 | 3198 | if (superc.prototype.constructor == Object.prototype.constructor) { 3199 | superc.prototype.constructor = superc; 3200 | } 3201 | 3202 | if (overrides) { 3203 | var i; 3204 | for (i in overrides) { 3205 | subc.prototype[i] = overrides[i]; 3206 | } 3207 | 3208 | /* 3209 | * IE will not enumerate native functions in a derived object even if the 3210 | * function was overridden. This is a workaround for specific functions 3211 | * we care about on the Object prototype. 3212 | * @property _IEEnumFix 3213 | * @param {Function} r the object to receive the augmentation 3214 | * @param {Function} s the object that supplies the properties to augment 3215 | * @static 3216 | * @private 3217 | */ 3218 | var _IEEnumFix = function() {}, 3219 | ADD = ["toString", "valueOf"]; 3220 | try { 3221 | if (/MSIE/.test(navigator.userAgent)) { 3222 | _IEEnumFix = function(r, s) { 3223 | for (i = 0; i < ADD.length; i = i + 1) { 3224 | var fname = ADD[i], f = s[fname]; 3225 | if (typeof f === 'function' && f != Object.prototype[fname]) { 3226 | r[fname] = f; 3227 | } 3228 | } 3229 | }; 3230 | } 3231 | } catch (ex) {} _IEEnumFix(subc.prototype, overrides); 3232 | } 3233 | } 3234 | }; 3235 | 3236 | /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license 3237 | */ 3238 | 3239 | /** 3240 | * @fileOverview 3241 | * @name asn1-1.0.js 3242 | * @author Kenji Urushima kenji.urushima@gmail.com 3243 | * @version asn1 1.0.13 (2017-Jun-02) 3244 | * @since jsrsasign 2.1 3245 | * @license MIT License 3246 | */ 3247 | 3248 | /** 3249 | * kjur's class library name space 3250 | *

3251 | * This name space provides following name spaces: 3252 | *

    3253 | *
  • {@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder
  • 3254 | *
  • {@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL
  • 3255 | *
  • {@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature 3256 | * class and utilities
  • 3257 | *
3258 | *

3259 | * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. 3260 | * @name KJUR 3261 | * @namespace kjur's class library name space 3262 | */ 3263 | var KJUR = {}; 3264 | 3265 | /** 3266 | * kjur's ASN.1 class library name space 3267 | *

3268 | * This is ITU-T X.690 ASN.1 DER encoder class library and 3269 | * class structure and methods is very similar to 3270 | * org.bouncycastle.asn1 package of 3271 | * well known BouncyCaslte Cryptography Library. 3272 | *

PROVIDING ASN.1 PRIMITIVES

3273 | * Here are ASN.1 DER primitive classes. 3274 | *
    3275 | *
  • 0x01 {@link KJUR.asn1.DERBoolean}
  • 3276 | *
  • 0x02 {@link KJUR.asn1.DERInteger}
  • 3277 | *
  • 0x03 {@link KJUR.asn1.DERBitString}
  • 3278 | *
  • 0x04 {@link KJUR.asn1.DEROctetString}
  • 3279 | *
  • 0x05 {@link KJUR.asn1.DERNull}
  • 3280 | *
  • 0x06 {@link KJUR.asn1.DERObjectIdentifier}
  • 3281 | *
  • 0x0a {@link KJUR.asn1.DEREnumerated}
  • 3282 | *
  • 0x0c {@link KJUR.asn1.DERUTF8String}
  • 3283 | *
  • 0x12 {@link KJUR.asn1.DERNumericString}
  • 3284 | *
  • 0x13 {@link KJUR.asn1.DERPrintableString}
  • 3285 | *
  • 0x14 {@link KJUR.asn1.DERTeletexString}
  • 3286 | *
  • 0x16 {@link KJUR.asn1.DERIA5String}
  • 3287 | *
  • 0x17 {@link KJUR.asn1.DERUTCTime}
  • 3288 | *
  • 0x18 {@link KJUR.asn1.DERGeneralizedTime}
  • 3289 | *
  • 0x30 {@link KJUR.asn1.DERSequence}
  • 3290 | *
  • 0x31 {@link KJUR.asn1.DERSet}
  • 3291 | *
3292 | *

OTHER ASN.1 CLASSES

3293 | *
    3294 | *
  • {@link KJUR.asn1.ASN1Object}
  • 3295 | *
  • {@link KJUR.asn1.DERAbstractString}
  • 3296 | *
  • {@link KJUR.asn1.DERAbstractTime}
  • 3297 | *
  • {@link KJUR.asn1.DERAbstractStructured}
  • 3298 | *
  • {@link KJUR.asn1.DERTaggedObject}
  • 3299 | *
3300 | *

SUB NAME SPACES

3301 | *
    3302 | *
  • {@link KJUR.asn1.cades} - CAdES long term signature format
  • 3303 | *
  • {@link KJUR.asn1.cms} - Cryptographic Message Syntax
  • 3304 | *
  • {@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)
  • 3305 | *
  • {@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format
  • 3306 | *
  • {@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL
  • 3307 | *
3308 | *

3309 | * NOTE: Please ignore method summary and document of this namespace. 3310 | * This caused by a bug of jsdoc2. 3311 | * @name KJUR.asn1 3312 | * @namespace 3313 | */ 3314 | if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; 3315 | 3316 | /** 3317 | * ASN1 utilities class 3318 | * @name KJUR.asn1.ASN1Util 3319 | * @class ASN1 utilities class 3320 | * @since asn1 1.0.2 3321 | */ 3322 | KJUR.asn1.ASN1Util = new function() { 3323 | this.integerToByteHex = function(i) { 3324 | var h = i.toString(16); 3325 | if ((h.length % 2) == 1) h = '0' + h; 3326 | return h; 3327 | }; 3328 | this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { 3329 | var h = bigIntegerValue.toString(16); 3330 | if (h.substr(0, 1) != '-') { 3331 | if (h.length % 2 == 1) { 3332 | h = '0' + h; 3333 | } else { 3334 | if (! h.match(/^[0-7]/)) { 3335 | h = '00' + h; 3336 | } 3337 | } 3338 | } else { 3339 | var hPos = h.substr(1); 3340 | var xorLen = hPos.length; 3341 | if (xorLen % 2 == 1) { 3342 | xorLen += 1; 3343 | } else { 3344 | if (! h.match(/^[0-7]/)) { 3345 | xorLen += 2; 3346 | } 3347 | } 3348 | var hMask = ''; 3349 | for (var i = 0; i < xorLen; i++) { 3350 | hMask += 'f'; 3351 | } 3352 | var biMask = new BigInteger(hMask, 16); 3353 | var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); 3354 | h = biNeg.toString(16).replace(/^-/, ''); 3355 | } 3356 | return h; 3357 | }; 3358 | /** 3359 | * get PEM string from hexadecimal data and header string 3360 | * @name getPEMStringFromHex 3361 | * @memberOf KJUR.asn1.ASN1Util 3362 | * @function 3363 | * @param {String} dataHex hexadecimal string of PEM body 3364 | * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') 3365 | * @return {String} PEM formatted string of input data 3366 | * @description 3367 | * This method converts a hexadecimal string to a PEM string with 3368 | * a specified header. Its line break will be CRLF("\r\n"). 3369 | * @example 3370 | * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); 3371 | * // value of pem will be: 3372 | * -----BEGIN PRIVATE KEY----- 3373 | * YWFh 3374 | * -----END PRIVATE KEY----- 3375 | */ 3376 | this.getPEMStringFromHex = function(dataHex, pemHeader) { 3377 | return hextopem(dataHex, pemHeader); 3378 | }; 3379 | 3380 | /** 3381 | * generate ASN1Object specifed by JSON parameters 3382 | * @name newObject 3383 | * @memberOf KJUR.asn1.ASN1Util 3384 | * @function 3385 | * @param {Array} param JSON parameter to generate ASN1Object 3386 | * @return {KJUR.asn1.ASN1Object} generated object 3387 | * @since asn1 1.0.3 3388 | * @description 3389 | * generate any ASN1Object specified by JSON param 3390 | * including ASN.1 primitive or structured. 3391 | * Generally 'param' can be described as follows: 3392 | *
3393 | * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} 3394 | *
3395 | * 'TYPE-OF-ASN1OBJ' can be one of following symbols: 3396 | *
    3397 | *
  • 'bool' - DERBoolean
  • 3398 | *
  • 'int' - DERInteger
  • 3399 | *
  • 'bitstr' - DERBitString
  • 3400 | *
  • 'octstr' - DEROctetString
  • 3401 | *
  • 'null' - DERNull
  • 3402 | *
  • 'oid' - DERObjectIdentifier
  • 3403 | *
  • 'enum' - DEREnumerated
  • 3404 | *
  • 'utf8str' - DERUTF8String
  • 3405 | *
  • 'numstr' - DERNumericString
  • 3406 | *
  • 'prnstr' - DERPrintableString
  • 3407 | *
  • 'telstr' - DERTeletexString
  • 3408 | *
  • 'ia5str' - DERIA5String
  • 3409 | *
  • 'utctime' - DERUTCTime
  • 3410 | *
  • 'gentime' - DERGeneralizedTime
  • 3411 | *
  • 'seq' - DERSequence
  • 3412 | *
  • 'set' - DERSet
  • 3413 | *
  • 'tag' - DERTaggedObject
  • 3414 | *
3415 | * @example 3416 | * newObject({'prnstr': 'aaa'}); 3417 | * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) 3418 | * // ASN.1 Tagged Object 3419 | * newObject({'tag': {'tag': 'a1', 3420 | * 'explicit': true, 3421 | * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); 3422 | * // more simple representation of ASN.1 Tagged Object 3423 | * newObject({'tag': ['a1', 3424 | * true, 3425 | * {'seq': [ 3426 | * {'int': 3}, 3427 | * {'prnstr': 'aaa'}]} 3428 | * ]}); 3429 | */ 3430 | this.newObject = function(param) { 3431 | var _KJUR = KJUR, 3432 | _KJUR_asn1 = _KJUR.asn1, 3433 | _DERBoolean = _KJUR_asn1.DERBoolean, 3434 | _DERInteger = _KJUR_asn1.DERInteger, 3435 | _DERBitString = _KJUR_asn1.DERBitString, 3436 | _DEROctetString = _KJUR_asn1.DEROctetString, 3437 | _DERNull = _KJUR_asn1.DERNull, 3438 | _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, 3439 | _DEREnumerated = _KJUR_asn1.DEREnumerated, 3440 | _DERUTF8String = _KJUR_asn1.DERUTF8String, 3441 | _DERNumericString = _KJUR_asn1.DERNumericString, 3442 | _DERPrintableString = _KJUR_asn1.DERPrintableString, 3443 | _DERTeletexString = _KJUR_asn1.DERTeletexString, 3444 | _DERIA5String = _KJUR_asn1.DERIA5String, 3445 | _DERUTCTime = _KJUR_asn1.DERUTCTime, 3446 | _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, 3447 | _DERSequence = _KJUR_asn1.DERSequence, 3448 | _DERSet = _KJUR_asn1.DERSet, 3449 | _DERTaggedObject = _KJUR_asn1.DERTaggedObject, 3450 | _newObject = _KJUR_asn1.ASN1Util.newObject; 3451 | 3452 | var keys = Object.keys(param); 3453 | if (keys.length != 1) 3454 | throw "key of param shall be only one."; 3455 | var key = keys[0]; 3456 | 3457 | if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1) 3458 | throw "undefined key: " + key; 3459 | 3460 | if (key == "bool") return new _DERBoolean(param[key]); 3461 | if (key == "int") return new _DERInteger(param[key]); 3462 | if (key == "bitstr") return new _DERBitString(param[key]); 3463 | if (key == "octstr") return new _DEROctetString(param[key]); 3464 | if (key == "null") return new _DERNull(param[key]); 3465 | if (key == "oid") return new _DERObjectIdentifier(param[key]); 3466 | if (key == "enum") return new _DEREnumerated(param[key]); 3467 | if (key == "utf8str") return new _DERUTF8String(param[key]); 3468 | if (key == "numstr") return new _DERNumericString(param[key]); 3469 | if (key == "prnstr") return new _DERPrintableString(param[key]); 3470 | if (key == "telstr") return new _DERTeletexString(param[key]); 3471 | if (key == "ia5str") return new _DERIA5String(param[key]); 3472 | if (key == "utctime") return new _DERUTCTime(param[key]); 3473 | if (key == "gentime") return new _DERGeneralizedTime(param[key]); 3474 | 3475 | if (key == "seq") { 3476 | var paramList = param[key]; 3477 | var a = []; 3478 | for (var i = 0; i < paramList.length; i++) { 3479 | var asn1Obj = _newObject(paramList[i]); 3480 | a.push(asn1Obj); 3481 | } 3482 | return new _DERSequence({'array': a}); 3483 | } 3484 | 3485 | if (key == "set") { 3486 | var paramList = param[key]; 3487 | var a = []; 3488 | for (var i = 0; i < paramList.length; i++) { 3489 | var asn1Obj = _newObject(paramList[i]); 3490 | a.push(asn1Obj); 3491 | } 3492 | return new _DERSet({'array': a}); 3493 | } 3494 | 3495 | if (key == "tag") { 3496 | var tagParam = param[key]; 3497 | if (Object.prototype.toString.call(tagParam) === '[object Array]' && 3498 | tagParam.length == 3) { 3499 | var obj = _newObject(tagParam[2]); 3500 | return new _DERTaggedObject({tag: tagParam[0], 3501 | explicit: tagParam[1], 3502 | obj: obj}); 3503 | } else { 3504 | var newParam = {}; 3505 | if (tagParam.explicit !== undefined) 3506 | newParam.explicit = tagParam.explicit; 3507 | if (tagParam.tag !== undefined) 3508 | newParam.tag = tagParam.tag; 3509 | if (tagParam.obj === undefined) 3510 | throw "obj shall be specified for 'tag'."; 3511 | newParam.obj = _newObject(tagParam.obj); 3512 | return new _DERTaggedObject(newParam); 3513 | } 3514 | } 3515 | }; 3516 | 3517 | /** 3518 | * get encoded hexadecimal string of ASN1Object specifed by JSON parameters 3519 | * @name jsonToASN1HEX 3520 | * @memberOf KJUR.asn1.ASN1Util 3521 | * @function 3522 | * @param {Array} param JSON parameter to generate ASN1Object 3523 | * @return hexadecimal string of ASN1Object 3524 | * @since asn1 1.0.4 3525 | * @description 3526 | * As for ASN.1 object representation of JSON object, 3527 | * please see {@link newObject}. 3528 | * @example 3529 | * jsonToASN1HEX({'prnstr': 'aaa'}); 3530 | */ 3531 | this.jsonToASN1HEX = function(param) { 3532 | var asn1Obj = this.newObject(param); 3533 | return asn1Obj.getEncodedHex(); 3534 | }; 3535 | }; 3536 | 3537 | /** 3538 | * get dot noted oid number string from hexadecimal value of OID 3539 | * @name oidHexToInt 3540 | * @memberOf KJUR.asn1.ASN1Util 3541 | * @function 3542 | * @param {String} hex hexadecimal value of object identifier 3543 | * @return {String} dot noted string of object identifier 3544 | * @since jsrsasign 4.8.3 asn1 1.0.7 3545 | * @description 3546 | * This static method converts from hexadecimal string representation of 3547 | * ASN.1 value of object identifier to oid number string. 3548 | * @example 3549 | * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6" 3550 | */ 3551 | KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { 3552 | var s = ""; 3553 | var i01 = parseInt(hex.substr(0, 2), 16); 3554 | var i0 = Math.floor(i01 / 40); 3555 | var i1 = i01 % 40; 3556 | var s = i0 + "." + i1; 3557 | 3558 | var binbuf = ""; 3559 | for (var i = 2; i < hex.length; i += 2) { 3560 | var value = parseInt(hex.substr(i, 2), 16); 3561 | var bin = ("00000000" + value.toString(2)).slice(- 8); 3562 | binbuf = binbuf + bin.substr(1, 7); 3563 | if (bin.substr(0, 1) == "0") { 3564 | var bi = new BigInteger(binbuf, 2); 3565 | s = s + "." + bi.toString(10); 3566 | binbuf = ""; 3567 | } 3568 | } 3569 | return s; 3570 | }; 3571 | 3572 | /** 3573 | * get hexadecimal value of object identifier from dot noted oid value 3574 | * @name oidIntToHex 3575 | * @memberOf KJUR.asn1.ASN1Util 3576 | * @function 3577 | * @param {String} oidString dot noted string of object identifier 3578 | * @return {String} hexadecimal value of object identifier 3579 | * @since jsrsasign 4.8.3 asn1 1.0.7 3580 | * @description 3581 | * This static method converts from object identifier value string. 3582 | * to hexadecimal string representation of it. 3583 | * @example 3584 | * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406" 3585 | */ 3586 | KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { 3587 | var itox = function(i) { 3588 | var h = i.toString(16); 3589 | if (h.length == 1) h = '0' + h; 3590 | return h; 3591 | }; 3592 | 3593 | var roidtox = function(roid) { 3594 | var h = ''; 3595 | var bi = new BigInteger(roid, 10); 3596 | var b = bi.toString(2); 3597 | var padLen = 7 - b.length % 7; 3598 | if (padLen == 7) padLen = 0; 3599 | var bPad = ''; 3600 | for (var i = 0; i < padLen; i++) bPad += '0'; 3601 | b = bPad + b; 3602 | for (var i = 0; i < b.length - 1; i += 7) { 3603 | var b8 = b.substr(i, 7); 3604 | if (i != b.length - 7) b8 = '1' + b8; 3605 | h += itox(parseInt(b8, 2)); 3606 | } 3607 | return h; 3608 | }; 3609 | 3610 | if (! oidString.match(/^[0-9.]+$/)) { 3611 | throw "malformed oid string: " + oidString; 3612 | } 3613 | var h = ''; 3614 | var a = oidString.split('.'); 3615 | var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); 3616 | h += itox(i0); 3617 | a.splice(0, 2); 3618 | for (var i = 0; i < a.length; i++) { 3619 | h += roidtox(a[i]); 3620 | } 3621 | return h; 3622 | }; 3623 | 3624 | 3625 | // ******************************************************************** 3626 | // Abstract ASN.1 Classes 3627 | // ******************************************************************** 3628 | 3629 | // ******************************************************************** 3630 | 3631 | /** 3632 | * base class for ASN.1 DER encoder object 3633 | * @name KJUR.asn1.ASN1Object 3634 | * @class base class for ASN.1 DER encoder object 3635 | * @property {Boolean} isModified flag whether internal data was changed 3636 | * @property {String} hTLV hexadecimal string of ASN.1 TLV 3637 | * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) 3638 | * @property {String} hL hexadecimal string of ASN.1 TLV length(L) 3639 | * @property {String} hV hexadecimal string of ASN.1 TLV value(V) 3640 | * @description 3641 | */ 3642 | KJUR.asn1.ASN1Object = function() { 3643 | var hV = ''; 3644 | 3645 | /** 3646 | * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) 3647 | * @name getLengthHexFromValue 3648 | * @memberOf KJUR.asn1.ASN1Object# 3649 | * @function 3650 | * @return {String} hexadecimal string of ASN.1 TLV length(L) 3651 | */ 3652 | this.getLengthHexFromValue = function() { 3653 | if (typeof this.hV == "undefined" || this.hV == null) { 3654 | throw "this.hV is null or undefined."; 3655 | } 3656 | if (this.hV.length % 2 == 1) { 3657 | throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; 3658 | } 3659 | var n = this.hV.length / 2; 3660 | var hN = n.toString(16); 3661 | if (hN.length % 2 == 1) { 3662 | hN = "0" + hN; 3663 | } 3664 | if (n < 128) { 3665 | return hN; 3666 | } else { 3667 | var hNlen = hN.length / 2; 3668 | if (hNlen > 15) { 3669 | throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); 3670 | } 3671 | var head = 128 + hNlen; 3672 | return head.toString(16) + hN; 3673 | } 3674 | }; 3675 | 3676 | /** 3677 | * get hexadecimal string of ASN.1 TLV bytes 3678 | * @name getEncodedHex 3679 | * @memberOf KJUR.asn1.ASN1Object# 3680 | * @function 3681 | * @return {String} hexadecimal string of ASN.1 TLV 3682 | */ 3683 | this.getEncodedHex = function() { 3684 | if (this.hTLV == null || this.isModified) { 3685 | this.hV = this.getFreshValueHex(); 3686 | this.hL = this.getLengthHexFromValue(); 3687 | this.hTLV = this.hT + this.hL + this.hV; 3688 | this.isModified = false; 3689 | //alert("first time: " + this.hTLV); 3690 | } 3691 | return this.hTLV; 3692 | }; 3693 | 3694 | /** 3695 | * get hexadecimal string of ASN.1 TLV value(V) bytes 3696 | * @name getValueHex 3697 | * @memberOf KJUR.asn1.ASN1Object# 3698 | * @function 3699 | * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes 3700 | */ 3701 | this.getValueHex = function() { 3702 | this.getEncodedHex(); 3703 | return this.hV; 3704 | }; 3705 | 3706 | this.getFreshValueHex = function() { 3707 | return ''; 3708 | }; 3709 | }; 3710 | 3711 | // == BEGIN DERAbstractString ================================================ 3712 | /** 3713 | * base class for ASN.1 DER string classes 3714 | * @name KJUR.asn1.DERAbstractString 3715 | * @class base class for ASN.1 DER string classes 3716 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 3717 | * @property {String} s internal string of value 3718 | * @extends KJUR.asn1.ASN1Object 3719 | * @description 3720 | *
3721 | * As for argument 'params' for constructor, you can specify one of 3722 | * following properties: 3723 | *
    3724 | *
  • str - specify initial ASN.1 value(V) by a string
  • 3725 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 3726 | *
3727 | * NOTE: 'params' can be omitted. 3728 | */ 3729 | KJUR.asn1.DERAbstractString = function(params) { 3730 | KJUR.asn1.DERAbstractString.superclass.constructor.call(this); 3731 | 3732 | /** 3733 | * get string value of this string object 3734 | * @name getString 3735 | * @memberOf KJUR.asn1.DERAbstractString# 3736 | * @function 3737 | * @return {String} string value of this string object 3738 | */ 3739 | this.getString = function() { 3740 | return this.s; 3741 | }; 3742 | 3743 | /** 3744 | * set value by a string 3745 | * @name setString 3746 | * @memberOf KJUR.asn1.DERAbstractString# 3747 | * @function 3748 | * @param {String} newS value by a string to set 3749 | */ 3750 | this.setString = function(newS) { 3751 | this.hTLV = null; 3752 | this.isModified = true; 3753 | this.s = newS; 3754 | this.hV = stohex(this.s); 3755 | }; 3756 | 3757 | /** 3758 | * set value by a hexadecimal string 3759 | * @name setStringHex 3760 | * @memberOf KJUR.asn1.DERAbstractString# 3761 | * @function 3762 | * @param {String} newHexString value by a hexadecimal string to set 3763 | */ 3764 | this.setStringHex = function(newHexString) { 3765 | this.hTLV = null; 3766 | this.isModified = true; 3767 | this.s = null; 3768 | this.hV = newHexString; 3769 | }; 3770 | 3771 | this.getFreshValueHex = function() { 3772 | return this.hV; 3773 | }; 3774 | 3775 | if (typeof params != "undefined") { 3776 | if (typeof params == "string") { 3777 | this.setString(params); 3778 | } else if (typeof params['str'] != "undefined") { 3779 | this.setString(params['str']); 3780 | } else if (typeof params['hex'] != "undefined") { 3781 | this.setStringHex(params['hex']); 3782 | } 3783 | } 3784 | }; 3785 | YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); 3786 | // == END DERAbstractString ================================================ 3787 | 3788 | // == BEGIN DERAbstractTime ================================================== 3789 | /** 3790 | * base class for ASN.1 DER Generalized/UTCTime class 3791 | * @name KJUR.asn1.DERAbstractTime 3792 | * @class base class for ASN.1 DER Generalized/UTCTime class 3793 | * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) 3794 | * @extends KJUR.asn1.ASN1Object 3795 | * @description 3796 | * @see KJUR.asn1.ASN1Object - superclass 3797 | */ 3798 | KJUR.asn1.DERAbstractTime = function(params) { 3799 | KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); 3800 | 3801 | // --- PRIVATE METHODS -------------------- 3802 | this.localDateToUTC = function(d) { 3803 | utc = d.getTime() + (d.getTimezoneOffset() * 60000); 3804 | var utcDate = new Date(utc); 3805 | return utcDate; 3806 | }; 3807 | 3808 | /* 3809 | * format date string by Data object 3810 | * @name formatDate 3811 | * @memberOf KJUR.asn1.AbstractTime; 3812 | * @param {Date} dateObject 3813 | * @param {string} type 'utc' or 'gen' 3814 | * @param {boolean} withMillis flag for with millisections or not 3815 | * @description 3816 | * 'withMillis' flag is supported from asn1 1.0.6. 3817 | */ 3818 | this.formatDate = function(dateObject, type, withMillis) { 3819 | var pad = this.zeroPadding; 3820 | var d = this.localDateToUTC(dateObject); 3821 | var year = String(d.getFullYear()); 3822 | if (type == 'utc') year = year.substr(2, 2); 3823 | var month = pad(String(d.getMonth() + 1), 2); 3824 | var day = pad(String(d.getDate()), 2); 3825 | var hour = pad(String(d.getHours()), 2); 3826 | var min = pad(String(d.getMinutes()), 2); 3827 | var sec = pad(String(d.getSeconds()), 2); 3828 | var s = year + month + day + hour + min + sec; 3829 | if (withMillis === true) { 3830 | var millis = d.getMilliseconds(); 3831 | if (millis != 0) { 3832 | var sMillis = pad(String(millis), 3); 3833 | sMillis = sMillis.replace(/[0]+$/, ""); 3834 | s = s + "." + sMillis; 3835 | } 3836 | } 3837 | return s + "Z"; 3838 | }; 3839 | 3840 | this.zeroPadding = function(s, len) { 3841 | if (s.length >= len) return s; 3842 | return new Array(len - s.length + 1).join('0') + s; 3843 | }; 3844 | 3845 | // --- PUBLIC METHODS -------------------- 3846 | /** 3847 | * get string value of this string object 3848 | * @name getString 3849 | * @memberOf KJUR.asn1.DERAbstractTime# 3850 | * @function 3851 | * @return {String} string value of this time object 3852 | */ 3853 | this.getString = function() { 3854 | return this.s; 3855 | }; 3856 | 3857 | /** 3858 | * set value by a string 3859 | * @name setString 3860 | * @memberOf KJUR.asn1.DERAbstractTime# 3861 | * @function 3862 | * @param {String} newS value by a string to set such like "130430235959Z" 3863 | */ 3864 | this.setString = function(newS) { 3865 | this.hTLV = null; 3866 | this.isModified = true; 3867 | this.s = newS; 3868 | this.hV = stohex(newS); 3869 | }; 3870 | 3871 | /** 3872 | * set value by a Date object 3873 | * @name setByDateValue 3874 | * @memberOf KJUR.asn1.DERAbstractTime# 3875 | * @function 3876 | * @param {Integer} year year of date (ex. 2013) 3877 | * @param {Integer} month month of date between 1 and 12 (ex. 12) 3878 | * @param {Integer} day day of month 3879 | * @param {Integer} hour hours of date 3880 | * @param {Integer} min minutes of date 3881 | * @param {Integer} sec seconds of date 3882 | */ 3883 | this.setByDateValue = function(year, month, day, hour, min, sec) { 3884 | var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); 3885 | this.setByDate(dateObject); 3886 | }; 3887 | 3888 | this.getFreshValueHex = function() { 3889 | return this.hV; 3890 | }; 3891 | }; 3892 | YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); 3893 | // == END DERAbstractTime ================================================== 3894 | 3895 | // == BEGIN DERAbstractStructured ============================================ 3896 | /** 3897 | * base class for ASN.1 DER structured class 3898 | * @name KJUR.asn1.DERAbstractStructured 3899 | * @class base class for ASN.1 DER structured class 3900 | * @property {Array} asn1Array internal array of ASN1Object 3901 | * @extends KJUR.asn1.ASN1Object 3902 | * @description 3903 | * @see KJUR.asn1.ASN1Object - superclass 3904 | */ 3905 | KJUR.asn1.DERAbstractStructured = function(params) { 3906 | KJUR.asn1.DERAbstractString.superclass.constructor.call(this); 3907 | 3908 | /** 3909 | * set value by array of ASN1Object 3910 | * @name setByASN1ObjectArray 3911 | * @memberOf KJUR.asn1.DERAbstractStructured# 3912 | * @function 3913 | * @param {array} asn1ObjectArray array of ASN1Object to set 3914 | */ 3915 | this.setByASN1ObjectArray = function(asn1ObjectArray) { 3916 | this.hTLV = null; 3917 | this.isModified = true; 3918 | this.asn1Array = asn1ObjectArray; 3919 | }; 3920 | 3921 | /** 3922 | * append an ASN1Object to internal array 3923 | * @name appendASN1Object 3924 | * @memberOf KJUR.asn1.DERAbstractStructured# 3925 | * @function 3926 | * @param {ASN1Object} asn1Object to add 3927 | */ 3928 | this.appendASN1Object = function(asn1Object) { 3929 | this.hTLV = null; 3930 | this.isModified = true; 3931 | this.asn1Array.push(asn1Object); 3932 | }; 3933 | 3934 | this.asn1Array = new Array(); 3935 | if (typeof params != "undefined") { 3936 | if (typeof params['array'] != "undefined") { 3937 | this.asn1Array = params['array']; 3938 | } 3939 | } 3940 | }; 3941 | YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); 3942 | 3943 | 3944 | // ******************************************************************** 3945 | // ASN.1 Object Classes 3946 | // ******************************************************************** 3947 | 3948 | // ******************************************************************** 3949 | /** 3950 | * class for ASN.1 DER Boolean 3951 | * @name KJUR.asn1.DERBoolean 3952 | * @class class for ASN.1 DER Boolean 3953 | * @extends KJUR.asn1.ASN1Object 3954 | * @description 3955 | * @see KJUR.asn1.ASN1Object - superclass 3956 | */ 3957 | KJUR.asn1.DERBoolean = function() { 3958 | KJUR.asn1.DERBoolean.superclass.constructor.call(this); 3959 | this.hT = "01"; 3960 | this.hTLV = "0101ff"; 3961 | }; 3962 | YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); 3963 | 3964 | // ******************************************************************** 3965 | /** 3966 | * class for ASN.1 DER Integer 3967 | * @name KJUR.asn1.DERInteger 3968 | * @class class for ASN.1 DER Integer 3969 | * @extends KJUR.asn1.ASN1Object 3970 | * @description 3971 | *
3972 | * As for argument 'params' for constructor, you can specify one of 3973 | * following properties: 3974 | *
    3975 | *
  • int - specify initial ASN.1 value(V) by integer value
  • 3976 | *
  • bigint - specify initial ASN.1 value(V) by BigInteger object
  • 3977 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 3978 | *
3979 | * NOTE: 'params' can be omitted. 3980 | */ 3981 | KJUR.asn1.DERInteger = function(params) { 3982 | KJUR.asn1.DERInteger.superclass.constructor.call(this); 3983 | this.hT = "02"; 3984 | 3985 | /** 3986 | * set value by Tom Wu's BigInteger object 3987 | * @name setByBigInteger 3988 | * @memberOf KJUR.asn1.DERInteger# 3989 | * @function 3990 | * @param {BigInteger} bigIntegerValue to set 3991 | */ 3992 | this.setByBigInteger = function(bigIntegerValue) { 3993 | this.hTLV = null; 3994 | this.isModified = true; 3995 | this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); 3996 | }; 3997 | 3998 | /** 3999 | * set value by integer value 4000 | * @name setByInteger 4001 | * @memberOf KJUR.asn1.DERInteger 4002 | * @function 4003 | * @param {Integer} integer value to set 4004 | */ 4005 | this.setByInteger = function(intValue) { 4006 | var bi = new BigInteger(String(intValue), 10); 4007 | this.setByBigInteger(bi); 4008 | }; 4009 | 4010 | /** 4011 | * set value by integer value 4012 | * @name setValueHex 4013 | * @memberOf KJUR.asn1.DERInteger# 4014 | * @function 4015 | * @param {String} hexadecimal string of integer value 4016 | * @description 4017 | *
4018 | * NOTE: Value shall be represented by minimum octet length of 4019 | * two's complement representation. 4020 | * @example 4021 | * new KJUR.asn1.DERInteger(123); 4022 | * new KJUR.asn1.DERInteger({'int': 123}); 4023 | * new KJUR.asn1.DERInteger({'hex': '1fad'}); 4024 | */ 4025 | this.setValueHex = function(newHexString) { 4026 | this.hV = newHexString; 4027 | }; 4028 | 4029 | this.getFreshValueHex = function() { 4030 | return this.hV; 4031 | }; 4032 | 4033 | if (typeof params != "undefined") { 4034 | if (typeof params['bigint'] != "undefined") { 4035 | this.setByBigInteger(params['bigint']); 4036 | } else if (typeof params['int'] != "undefined") { 4037 | this.setByInteger(params['int']); 4038 | } else if (typeof params == "number") { 4039 | this.setByInteger(params); 4040 | } else if (typeof params['hex'] != "undefined") { 4041 | this.setValueHex(params['hex']); 4042 | } 4043 | } 4044 | }; 4045 | YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); 4046 | 4047 | // ******************************************************************** 4048 | /** 4049 | * class for ASN.1 DER encoded BitString primitive 4050 | * @name KJUR.asn1.DERBitString 4051 | * @class class for ASN.1 DER encoded BitString primitive 4052 | * @extends KJUR.asn1.ASN1Object 4053 | * @description 4054 | *
4055 | * As for argument 'params' for constructor, you can specify one of 4056 | * following properties: 4057 | *
    4058 | *
  • bin - specify binary string (ex. '10111')
  • 4059 | *
  • array - specify array of boolean (ex. [true,false,true,true])
  • 4060 | *
  • hex - specify hexadecimal string of ASN.1 value(V) including unused bits
  • 4061 | *
  • obj - specify {@link KJUR.asn1.ASN1Util.newObject} 4062 | * argument for "BitString encapsulates" structure.
  • 4063 | *
4064 | * NOTE1: 'params' can be omitted.
4065 | * NOTE2: 'obj' parameter have been supported since 4066 | * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
4067 | * @example 4068 | * // default constructor 4069 | * o = new KJUR.asn1.DERBitString(); 4070 | * // initialize with binary string 4071 | * o = new KJUR.asn1.DERBitString({bin: "1011"}); 4072 | * // initialize with boolean array 4073 | * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); 4074 | * // initialize with hexadecimal string (04 is unused bits) 4075 | * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); 4076 | * // initialize with ASN1Util.newObject argument for encapsulated 4077 | * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); 4078 | * // above generates a ASN.1 data like this: 4079 | * // BIT STRING, encapsulates { 4080 | * // SEQUENCE { 4081 | * // INTEGER 3 4082 | * // PrintableString 'aaa' 4083 | * // } 4084 | * // } 4085 | */ 4086 | KJUR.asn1.DERBitString = function(params) { 4087 | if (params !== undefined && typeof params.obj !== "undefined") { 4088 | var o = KJUR.asn1.ASN1Util.newObject(params.obj); 4089 | params.hex = "00" + o.getEncodedHex(); 4090 | } 4091 | KJUR.asn1.DERBitString.superclass.constructor.call(this); 4092 | this.hT = "03"; 4093 | 4094 | /** 4095 | * set ASN.1 value(V) by a hexadecimal string including unused bits 4096 | * @name setHexValueIncludingUnusedBits 4097 | * @memberOf KJUR.asn1.DERBitString# 4098 | * @function 4099 | * @param {String} newHexStringIncludingUnusedBits 4100 | */ 4101 | this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { 4102 | this.hTLV = null; 4103 | this.isModified = true; 4104 | this.hV = newHexStringIncludingUnusedBits; 4105 | }; 4106 | 4107 | /** 4108 | * set ASN.1 value(V) by unused bit and hexadecimal string of value 4109 | * @name setUnusedBitsAndHexValue 4110 | * @memberOf KJUR.asn1.DERBitString# 4111 | * @function 4112 | * @param {Integer} unusedBits 4113 | * @param {String} hValue 4114 | */ 4115 | this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { 4116 | if (unusedBits < 0 || 7 < unusedBits) { 4117 | throw "unused bits shall be from 0 to 7: u = " + unusedBits; 4118 | } 4119 | var hUnusedBits = "0" + unusedBits; 4120 | this.hTLV = null; 4121 | this.isModified = true; 4122 | this.hV = hUnusedBits + hValue; 4123 | }; 4124 | 4125 | /** 4126 | * set ASN.1 DER BitString by binary string
4127 | * @name setByBinaryString 4128 | * @memberOf KJUR.asn1.DERBitString# 4129 | * @function 4130 | * @param {String} binaryString binary value string (i.e. '10111') 4131 | * @description 4132 | * Its unused bits will be calculated automatically by length of 4133 | * 'binaryValue'.
4134 | * NOTE: Trailing zeros '0' will be ignored. 4135 | * @example 4136 | * o = new KJUR.asn1.DERBitString(); 4137 | * o.setByBooleanArray("01011"); 4138 | */ 4139 | this.setByBinaryString = function(binaryString) { 4140 | binaryString = binaryString.replace(/0+$/, ''); 4141 | var unusedBits = 8 - binaryString.length % 8; 4142 | if (unusedBits == 8) unusedBits = 0; 4143 | for (var i = 0; i <= unusedBits; i++) { 4144 | binaryString += '0'; 4145 | } 4146 | var h = ''; 4147 | for (var i = 0; i < binaryString.length - 1; i += 8) { 4148 | var b = binaryString.substr(i, 8); 4149 | var x = parseInt(b, 2).toString(16); 4150 | if (x.length == 1) x = '0' + x; 4151 | h += x; 4152 | } 4153 | this.hTLV = null; 4154 | this.isModified = true; 4155 | this.hV = '0' + unusedBits + h; 4156 | }; 4157 | 4158 | /** 4159 | * set ASN.1 TLV value(V) by an array of boolean
4160 | * @name setByBooleanArray 4161 | * @memberOf KJUR.asn1.DERBitString# 4162 | * @function 4163 | * @param {array} booleanArray array of boolean (ex. [true, false, true]) 4164 | * @description 4165 | * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. 4166 | * @example 4167 | * o = new KJUR.asn1.DERBitString(); 4168 | * o.setByBooleanArray([false, true, false, true, true]); 4169 | */ 4170 | this.setByBooleanArray = function(booleanArray) { 4171 | var s = ''; 4172 | for (var i = 0; i < booleanArray.length; i++) { 4173 | if (booleanArray[i] == true) { 4174 | s += '1'; 4175 | } else { 4176 | s += '0'; 4177 | } 4178 | } 4179 | this.setByBinaryString(s); 4180 | }; 4181 | 4182 | /** 4183 | * generate an array of falses with specified length
4184 | * @name newFalseArray 4185 | * @memberOf KJUR.asn1.DERBitString 4186 | * @function 4187 | * @param {Integer} nLength length of array to generate 4188 | * @return {array} array of boolean falses 4189 | * @description 4190 | * This static method may be useful to initialize boolean array. 4191 | * @example 4192 | * o = new KJUR.asn1.DERBitString(); 4193 | * o.newFalseArray(3) → [false, false, false] 4194 | */ 4195 | this.newFalseArray = function(nLength) { 4196 | var a = new Array(nLength); 4197 | for (var i = 0; i < nLength; i++) { 4198 | a[i] = false; 4199 | } 4200 | return a; 4201 | }; 4202 | 4203 | this.getFreshValueHex = function() { 4204 | return this.hV; 4205 | }; 4206 | 4207 | if (typeof params != "undefined") { 4208 | if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { 4209 | this.setHexValueIncludingUnusedBits(params); 4210 | } else if (typeof params['hex'] != "undefined") { 4211 | this.setHexValueIncludingUnusedBits(params['hex']); 4212 | } else if (typeof params['bin'] != "undefined") { 4213 | this.setByBinaryString(params['bin']); 4214 | } else if (typeof params['array'] != "undefined") { 4215 | this.setByBooleanArray(params['array']); 4216 | } 4217 | } 4218 | }; 4219 | YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); 4220 | 4221 | // ******************************************************************** 4222 | /** 4223 | * class for ASN.1 DER OctetString
4224 | * @name KJUR.asn1.DEROctetString 4225 | * @class class for ASN.1 DER OctetString 4226 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4227 | * @extends KJUR.asn1.DERAbstractString 4228 | * @description 4229 | * This class provides ASN.1 OctetString simple type.
4230 | * Supported "params" attributes are: 4231 | *
    4232 | *
  • str - to set a string as a value
  • 4233 | *
  • hex - to set a hexadecimal string as a value
  • 4234 | *
  • obj - to set a encapsulated ASN.1 value by JSON object 4235 | * which is defined in {@link KJUR.asn1.ASN1Util.newObject}
  • 4236 | *
4237 | * NOTE: A parameter 'obj' have been supported 4238 | * for "OCTET STRING, encapsulates" structure. 4239 | * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). 4240 | * @see KJUR.asn1.DERAbstractString - superclass 4241 | * @example 4242 | * // default constructor 4243 | * o = new KJUR.asn1.DEROctetString(); 4244 | * // initialize with string 4245 | * o = new KJUR.asn1.DEROctetString({str: "aaa"}); 4246 | * // initialize with hexadecimal string 4247 | * o = new KJUR.asn1.DEROctetString({hex: "616161"}); 4248 | * // initialize with ASN1Util.newObject argument 4249 | * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); 4250 | * // above generates a ASN.1 data like this: 4251 | * // OCTET STRING, encapsulates { 4252 | * // SEQUENCE { 4253 | * // INTEGER 3 4254 | * // PrintableString 'aaa' 4255 | * // } 4256 | * // } 4257 | */ 4258 | KJUR.asn1.DEROctetString = function(params) { 4259 | if (params !== undefined && typeof params.obj !== "undefined") { 4260 | var o = KJUR.asn1.ASN1Util.newObject(params.obj); 4261 | params.hex = o.getEncodedHex(); 4262 | } 4263 | KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); 4264 | this.hT = "04"; 4265 | }; 4266 | YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); 4267 | 4268 | // ******************************************************************** 4269 | /** 4270 | * class for ASN.1 DER Null 4271 | * @name KJUR.asn1.DERNull 4272 | * @class class for ASN.1 DER Null 4273 | * @extends KJUR.asn1.ASN1Object 4274 | * @description 4275 | * @see KJUR.asn1.ASN1Object - superclass 4276 | */ 4277 | KJUR.asn1.DERNull = function() { 4278 | KJUR.asn1.DERNull.superclass.constructor.call(this); 4279 | this.hT = "05"; 4280 | this.hTLV = "0500"; 4281 | }; 4282 | YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); 4283 | 4284 | // ******************************************************************** 4285 | /** 4286 | * class for ASN.1 DER ObjectIdentifier 4287 | * @name KJUR.asn1.DERObjectIdentifier 4288 | * @class class for ASN.1 DER ObjectIdentifier 4289 | * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) 4290 | * @extends KJUR.asn1.ASN1Object 4291 | * @description 4292 | *
4293 | * As for argument 'params' for constructor, you can specify one of 4294 | * following properties: 4295 | *
    4296 | *
  • oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)
  • 4297 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 4298 | *
4299 | * NOTE: 'params' can be omitted. 4300 | */ 4301 | KJUR.asn1.DERObjectIdentifier = function(params) { 4302 | var itox = function(i) { 4303 | var h = i.toString(16); 4304 | if (h.length == 1) h = '0' + h; 4305 | return h; 4306 | }; 4307 | var roidtox = function(roid) { 4308 | var h = ''; 4309 | var bi = new BigInteger(roid, 10); 4310 | var b = bi.toString(2); 4311 | var padLen = 7 - b.length % 7; 4312 | if (padLen == 7) padLen = 0; 4313 | var bPad = ''; 4314 | for (var i = 0; i < padLen; i++) bPad += '0'; 4315 | b = bPad + b; 4316 | for (var i = 0; i < b.length - 1; i += 7) { 4317 | var b8 = b.substr(i, 7); 4318 | if (i != b.length - 7) b8 = '1' + b8; 4319 | h += itox(parseInt(b8, 2)); 4320 | } 4321 | return h; 4322 | }; 4323 | 4324 | KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this); 4325 | this.hT = "06"; 4326 | 4327 | /** 4328 | * set value by a hexadecimal string 4329 | * @name setValueHex 4330 | * @memberOf KJUR.asn1.DERObjectIdentifier# 4331 | * @function 4332 | * @param {String} newHexString hexadecimal value of OID bytes 4333 | */ 4334 | this.setValueHex = function(newHexString) { 4335 | this.hTLV = null; 4336 | this.isModified = true; 4337 | this.s = null; 4338 | this.hV = newHexString; 4339 | }; 4340 | 4341 | /** 4342 | * set value by a OID string
4343 | * @name setValueOidString 4344 | * @memberOf KJUR.asn1.DERObjectIdentifier# 4345 | * @function 4346 | * @param {String} oidString OID string (ex. 2.5.4.13) 4347 | * @example 4348 | * o = new KJUR.asn1.DERObjectIdentifier(); 4349 | * o.setValueOidString("2.5.4.13"); 4350 | */ 4351 | this.setValueOidString = function(oidString) { 4352 | if (! oidString.match(/^[0-9.]+$/)) { 4353 | throw "malformed oid string: " + oidString; 4354 | } 4355 | var h = ''; 4356 | var a = oidString.split('.'); 4357 | var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); 4358 | h += itox(i0); 4359 | a.splice(0, 2); 4360 | for (var i = 0; i < a.length; i++) { 4361 | h += roidtox(a[i]); 4362 | } 4363 | this.hTLV = null; 4364 | this.isModified = true; 4365 | this.s = null; 4366 | this.hV = h; 4367 | }; 4368 | 4369 | /** 4370 | * set value by a OID name 4371 | * @name setValueName 4372 | * @memberOf KJUR.asn1.DERObjectIdentifier# 4373 | * @function 4374 | * @param {String} oidName OID name (ex. 'serverAuth') 4375 | * @since 1.0.1 4376 | * @description 4377 | * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. 4378 | * Otherwise raise error. 4379 | * @example 4380 | * o = new KJUR.asn1.DERObjectIdentifier(); 4381 | * o.setValueName("serverAuth"); 4382 | */ 4383 | this.setValueName = function(oidName) { 4384 | var oid = KJUR.asn1.x509.OID.name2oid(oidName); 4385 | if (oid !== '') { 4386 | this.setValueOidString(oid); 4387 | } else { 4388 | throw "DERObjectIdentifier oidName undefined: " + oidName; 4389 | } 4390 | }; 4391 | 4392 | this.getFreshValueHex = function() { 4393 | return this.hV; 4394 | }; 4395 | 4396 | if (params !== undefined) { 4397 | if (typeof params === "string") { 4398 | if (params.match(/^[0-2].[0-9.]+$/)) { 4399 | this.setValueOidString(params); 4400 | } else { 4401 | this.setValueName(params); 4402 | } 4403 | } else if (params.oid !== undefined) { 4404 | this.setValueOidString(params.oid); 4405 | } else if (params.hex !== undefined) { 4406 | this.setValueHex(params.hex); 4407 | } else if (params.name !== undefined) { 4408 | this.setValueName(params.name); 4409 | } 4410 | } 4411 | }; 4412 | YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); 4413 | 4414 | // ******************************************************************** 4415 | /** 4416 | * class for ASN.1 DER Enumerated 4417 | * @name KJUR.asn1.DEREnumerated 4418 | * @class class for ASN.1 DER Enumerated 4419 | * @extends KJUR.asn1.ASN1Object 4420 | * @description 4421 | *
4422 | * As for argument 'params' for constructor, you can specify one of 4423 | * following properties: 4424 | *
    4425 | *
  • int - specify initial ASN.1 value(V) by integer value
  • 4426 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 4427 | *
4428 | * NOTE: 'params' can be omitted. 4429 | * @example 4430 | * new KJUR.asn1.DEREnumerated(123); 4431 | * new KJUR.asn1.DEREnumerated({int: 123}); 4432 | * new KJUR.asn1.DEREnumerated({hex: '1fad'}); 4433 | */ 4434 | KJUR.asn1.DEREnumerated = function(params) { 4435 | KJUR.asn1.DEREnumerated.superclass.constructor.call(this); 4436 | this.hT = "0a"; 4437 | 4438 | /** 4439 | * set value by Tom Wu's BigInteger object 4440 | * @name setByBigInteger 4441 | * @memberOf KJUR.asn1.DEREnumerated# 4442 | * @function 4443 | * @param {BigInteger} bigIntegerValue to set 4444 | */ 4445 | this.setByBigInteger = function(bigIntegerValue) { 4446 | this.hTLV = null; 4447 | this.isModified = true; 4448 | this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); 4449 | }; 4450 | 4451 | /** 4452 | * set value by integer value 4453 | * @name setByInteger 4454 | * @memberOf KJUR.asn1.DEREnumerated# 4455 | * @function 4456 | * @param {Integer} integer value to set 4457 | */ 4458 | this.setByInteger = function(intValue) { 4459 | var bi = new BigInteger(String(intValue), 10); 4460 | this.setByBigInteger(bi); 4461 | }; 4462 | 4463 | /** 4464 | * set value by integer value 4465 | * @name setValueHex 4466 | * @memberOf KJUR.asn1.DEREnumerated# 4467 | * @function 4468 | * @param {String} hexadecimal string of integer value 4469 | * @description 4470 | *
4471 | * NOTE: Value shall be represented by minimum octet length of 4472 | * two's complement representation. 4473 | */ 4474 | this.setValueHex = function(newHexString) { 4475 | this.hV = newHexString; 4476 | }; 4477 | 4478 | this.getFreshValueHex = function() { 4479 | return this.hV; 4480 | }; 4481 | 4482 | if (typeof params != "undefined") { 4483 | if (typeof params['int'] != "undefined") { 4484 | this.setByInteger(params['int']); 4485 | } else if (typeof params == "number") { 4486 | this.setByInteger(params); 4487 | } else if (typeof params['hex'] != "undefined") { 4488 | this.setValueHex(params['hex']); 4489 | } 4490 | } 4491 | }; 4492 | YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); 4493 | 4494 | // ******************************************************************** 4495 | /** 4496 | * class for ASN.1 DER UTF8String 4497 | * @name KJUR.asn1.DERUTF8String 4498 | * @class class for ASN.1 DER UTF8String 4499 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4500 | * @extends KJUR.asn1.DERAbstractString 4501 | * @description 4502 | * @see KJUR.asn1.DERAbstractString - superclass 4503 | */ 4504 | KJUR.asn1.DERUTF8String = function(params) { 4505 | KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); 4506 | this.hT = "0c"; 4507 | }; 4508 | YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); 4509 | 4510 | // ******************************************************************** 4511 | /** 4512 | * class for ASN.1 DER NumericString 4513 | * @name KJUR.asn1.DERNumericString 4514 | * @class class for ASN.1 DER NumericString 4515 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4516 | * @extends KJUR.asn1.DERAbstractString 4517 | * @description 4518 | * @see KJUR.asn1.DERAbstractString - superclass 4519 | */ 4520 | KJUR.asn1.DERNumericString = function(params) { 4521 | KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); 4522 | this.hT = "12"; 4523 | }; 4524 | YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); 4525 | 4526 | // ******************************************************************** 4527 | /** 4528 | * class for ASN.1 DER PrintableString 4529 | * @name KJUR.asn1.DERPrintableString 4530 | * @class class for ASN.1 DER PrintableString 4531 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4532 | * @extends KJUR.asn1.DERAbstractString 4533 | * @description 4534 | * @see KJUR.asn1.DERAbstractString - superclass 4535 | */ 4536 | KJUR.asn1.DERPrintableString = function(params) { 4537 | KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); 4538 | this.hT = "13"; 4539 | }; 4540 | YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); 4541 | 4542 | // ******************************************************************** 4543 | /** 4544 | * class for ASN.1 DER TeletexString 4545 | * @name KJUR.asn1.DERTeletexString 4546 | * @class class for ASN.1 DER TeletexString 4547 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4548 | * @extends KJUR.asn1.DERAbstractString 4549 | * @description 4550 | * @see KJUR.asn1.DERAbstractString - superclass 4551 | */ 4552 | KJUR.asn1.DERTeletexString = function(params) { 4553 | KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); 4554 | this.hT = "14"; 4555 | }; 4556 | YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); 4557 | 4558 | // ******************************************************************** 4559 | /** 4560 | * class for ASN.1 DER IA5String 4561 | * @name KJUR.asn1.DERIA5String 4562 | * @class class for ASN.1 DER IA5String 4563 | * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) 4564 | * @extends KJUR.asn1.DERAbstractString 4565 | * @description 4566 | * @see KJUR.asn1.DERAbstractString - superclass 4567 | */ 4568 | KJUR.asn1.DERIA5String = function(params) { 4569 | KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); 4570 | this.hT = "16"; 4571 | }; 4572 | YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); 4573 | 4574 | // ******************************************************************** 4575 | /** 4576 | * class for ASN.1 DER UTCTime 4577 | * @name KJUR.asn1.DERUTCTime 4578 | * @class class for ASN.1 DER UTCTime 4579 | * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) 4580 | * @extends KJUR.asn1.DERAbstractTime 4581 | * @description 4582 | *
4583 | * As for argument 'params' for constructor, you can specify one of 4584 | * following properties: 4585 | *
    4586 | *
  • str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')
  • 4587 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 4588 | *
  • date - specify Date object.
  • 4589 | *
4590 | * NOTE: 'params' can be omitted. 4591 | *

EXAMPLES

4592 | * @example 4593 | * d1 = new KJUR.asn1.DERUTCTime(); 4594 | * d1.setString('130430125959Z'); 4595 | * 4596 | * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); 4597 | * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); 4598 | * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); 4599 | */ 4600 | KJUR.asn1.DERUTCTime = function(params) { 4601 | KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); 4602 | this.hT = "17"; 4603 | 4604 | /** 4605 | * set value by a Date object
4606 | * @name setByDate 4607 | * @memberOf KJUR.asn1.DERUTCTime# 4608 | * @function 4609 | * @param {Date} dateObject Date object to set ASN.1 value(V) 4610 | * @example 4611 | * o = new KJUR.asn1.DERUTCTime(); 4612 | * o.setByDate(new Date("2016/12/31")); 4613 | */ 4614 | this.setByDate = function(dateObject) { 4615 | this.hTLV = null; 4616 | this.isModified = true; 4617 | this.date = dateObject; 4618 | this.s = this.formatDate(this.date, 'utc'); 4619 | this.hV = stohex(this.s); 4620 | }; 4621 | 4622 | this.getFreshValueHex = function() { 4623 | if (typeof this.date == "undefined" && typeof this.s == "undefined") { 4624 | this.date = new Date(); 4625 | this.s = this.formatDate(this.date, 'utc'); 4626 | this.hV = stohex(this.s); 4627 | } 4628 | return this.hV; 4629 | }; 4630 | 4631 | if (params !== undefined) { 4632 | if (params.str !== undefined) { 4633 | this.setString(params.str); 4634 | } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { 4635 | this.setString(params); 4636 | } else if (params.hex !== undefined) { 4637 | this.setStringHex(params.hex); 4638 | } else if (params.date !== undefined) { 4639 | this.setByDate(params.date); 4640 | } 4641 | } 4642 | }; 4643 | YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); 4644 | 4645 | // ******************************************************************** 4646 | /** 4647 | * class for ASN.1 DER GeneralizedTime 4648 | * @name KJUR.asn1.DERGeneralizedTime 4649 | * @class class for ASN.1 DER GeneralizedTime 4650 | * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) 4651 | * @property {Boolean} withMillis flag to show milliseconds or not 4652 | * @extends KJUR.asn1.DERAbstractTime 4653 | * @description 4654 | *
4655 | * As for argument 'params' for constructor, you can specify one of 4656 | * following properties: 4657 | *
    4658 | *
  • str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')
  • 4659 | *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • 4660 | *
  • date - specify Date object.
  • 4661 | *
  • millis - specify flag to show milliseconds (from 1.0.6)
  • 4662 | *
4663 | * NOTE1: 'params' can be omitted. 4664 | * NOTE2: 'withMillis' property is supported from asn1 1.0.6. 4665 | */ 4666 | KJUR.asn1.DERGeneralizedTime = function(params) { 4667 | KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); 4668 | this.hT = "18"; 4669 | this.withMillis = false; 4670 | 4671 | /** 4672 | * set value by a Date object 4673 | * @name setByDate 4674 | * @memberOf KJUR.asn1.DERGeneralizedTime# 4675 | * @function 4676 | * @param {Date} dateObject Date object to set ASN.1 value(V) 4677 | * @example 4678 | * When you specify UTC time, use 'Date.UTC' method like this:
4679 | * o1 = new DERUTCTime(); 4680 | * o1.setByDate(date); 4681 | * 4682 | * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 4683 | */ 4684 | this.setByDate = function(dateObject) { 4685 | this.hTLV = null; 4686 | this.isModified = true; 4687 | this.date = dateObject; 4688 | this.s = this.formatDate(this.date, 'gen', this.withMillis); 4689 | this.hV = stohex(this.s); 4690 | }; 4691 | 4692 | this.getFreshValueHex = function() { 4693 | if (this.date === undefined && this.s === undefined) { 4694 | this.date = new Date(); 4695 | this.s = this.formatDate(this.date, 'gen', this.withMillis); 4696 | this.hV = stohex(this.s); 4697 | } 4698 | return this.hV; 4699 | }; 4700 | 4701 | if (params !== undefined) { 4702 | if (params.str !== undefined) { 4703 | this.setString(params.str); 4704 | } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { 4705 | this.setString(params); 4706 | } else if (params.hex !== undefined) { 4707 | this.setStringHex(params.hex); 4708 | } else if (params.date !== undefined) { 4709 | this.setByDate(params.date); 4710 | } 4711 | if (params.millis === true) { 4712 | this.withMillis = true; 4713 | } 4714 | } 4715 | }; 4716 | YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); 4717 | 4718 | // ******************************************************************** 4719 | /** 4720 | * class for ASN.1 DER Sequence 4721 | * @name KJUR.asn1.DERSequence 4722 | * @class class for ASN.1 DER Sequence 4723 | * @extends KJUR.asn1.DERAbstractStructured 4724 | * @description 4725 | *
4726 | * As for argument 'params' for constructor, you can specify one of 4727 | * following properties: 4728 | *
    4729 | *
  • array - specify array of ASN1Object to set elements of content
  • 4730 | *
4731 | * NOTE: 'params' can be omitted. 4732 | */ 4733 | KJUR.asn1.DERSequence = function(params) { 4734 | KJUR.asn1.DERSequence.superclass.constructor.call(this, params); 4735 | this.hT = "30"; 4736 | this.getFreshValueHex = function() { 4737 | var h = ''; 4738 | for (var i = 0; i < this.asn1Array.length; i++) { 4739 | var asn1Obj = this.asn1Array[i]; 4740 | h += asn1Obj.getEncodedHex(); 4741 | } 4742 | this.hV = h; 4743 | return this.hV; 4744 | }; 4745 | }; 4746 | YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); 4747 | 4748 | // ******************************************************************** 4749 | /** 4750 | * class for ASN.1 DER Set 4751 | * @name KJUR.asn1.DERSet 4752 | * @class class for ASN.1 DER Set 4753 | * @extends KJUR.asn1.DERAbstractStructured 4754 | * @description 4755 | *
4756 | * As for argument 'params' for constructor, you can specify one of 4757 | * following properties: 4758 | *
    4759 | *
  • array - specify array of ASN1Object to set elements of content
  • 4760 | *
  • sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.
  • 4761 | *
4762 | * NOTE1: 'params' can be omitted.
4763 | * NOTE2: sortflag is supported since 1.0.5. 4764 | */ 4765 | KJUR.asn1.DERSet = function(params) { 4766 | KJUR.asn1.DERSet.superclass.constructor.call(this, params); 4767 | this.hT = "31"; 4768 | this.sortFlag = true; // item shall be sorted only in ASN.1 DER 4769 | this.getFreshValueHex = function() { 4770 | var a = new Array(); 4771 | for (var i = 0; i < this.asn1Array.length; i++) { 4772 | var asn1Obj = this.asn1Array[i]; 4773 | a.push(asn1Obj.getEncodedHex()); 4774 | } 4775 | if (this.sortFlag == true) a.sort(); 4776 | this.hV = a.join(''); 4777 | return this.hV; 4778 | }; 4779 | 4780 | if (typeof params != "undefined") { 4781 | if (typeof params.sortflag != "undefined" && 4782 | params.sortflag == false) 4783 | this.sortFlag = false; 4784 | } 4785 | }; 4786 | YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); 4787 | 4788 | // ******************************************************************** 4789 | /** 4790 | * class for ASN.1 DER TaggedObject 4791 | * @name KJUR.asn1.DERTaggedObject 4792 | * @class class for ASN.1 DER TaggedObject 4793 | * @extends KJUR.asn1.ASN1Object 4794 | * @description 4795 | *
4796 | * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object. 4797 | * For example, if you find '[1]' tag in a ASN.1 dump, 4798 | * 'tagNoHex' will be 'a1'. 4799 | *
4800 | * As for optional argument 'params' for constructor, you can specify *ANY* of 4801 | * following properties: 4802 | *
    4803 | *
  • explicit - specify true if this is explicit tag otherwise false 4804 | * (default is 'true').
  • 4805 | *
  • tag - specify tag (default is 'a0' which means [0])
  • 4806 | *
  • obj - specify ASN1Object which is tagged
  • 4807 | *
4808 | * @example 4809 | * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); 4810 | * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); 4811 | * hex = d2.getEncodedHex(); 4812 | */ 4813 | KJUR.asn1.DERTaggedObject = function(params) { 4814 | KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); 4815 | this.hT = "a0"; 4816 | this.hV = ''; 4817 | this.isExplicit = true; 4818 | this.asn1Object = null; 4819 | 4820 | /** 4821 | * set value by an ASN1Object 4822 | * @name setString 4823 | * @memberOf KJUR.asn1.DERTaggedObject# 4824 | * @function 4825 | * @param {Boolean} isExplicitFlag flag for explicit/implicit tag 4826 | * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag 4827 | * @param {ASN1Object} asn1Object ASN.1 to encapsulate 4828 | */ 4829 | this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { 4830 | this.hT = tagNoHex; 4831 | this.isExplicit = isExplicitFlag; 4832 | this.asn1Object = asn1Object; 4833 | if (this.isExplicit) { 4834 | this.hV = this.asn1Object.getEncodedHex(); 4835 | this.hTLV = null; 4836 | this.isModified = true; 4837 | } else { 4838 | this.hV = null; 4839 | this.hTLV = asn1Object.getEncodedHex(); 4840 | this.hTLV = this.hTLV.replace(/^../, tagNoHex); 4841 | this.isModified = false; 4842 | } 4843 | }; 4844 | 4845 | this.getFreshValueHex = function() { 4846 | return this.hV; 4847 | }; 4848 | 4849 | if (typeof params != "undefined") { 4850 | if (typeof params['tag'] != "undefined") { 4851 | this.hT = params['tag']; 4852 | } 4853 | if (typeof params['explicit'] != "undefined") { 4854 | this.isExplicit = params['explicit']; 4855 | } 4856 | if (typeof params['obj'] != "undefined") { 4857 | this.asn1Object = params['obj']; 4858 | this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); 4859 | } 4860 | } 4861 | }; 4862 | YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); 4863 | 4864 | /** 4865 | * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. 4866 | * This object is just a decorator for parsing the key parameter 4867 | * @param {string|Object} key - The key in string format, or an object containing 4868 | * the parameters needed to build a RSAKey object. 4869 | * @constructor 4870 | */ 4871 | var JSEncryptRSAKey = /** @class */ (function (_super) { 4872 | __extends(JSEncryptRSAKey, _super); 4873 | function JSEncryptRSAKey(key) { 4874 | var _this = _super.call(this) || this; 4875 | // Call the super constructor. 4876 | // RSAKey.call(this); 4877 | // If a key key was provided. 4878 | if (key) { 4879 | // If this is a string... 4880 | if (typeof key === "string") { 4881 | _this.parseKey(key); 4882 | } 4883 | else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || 4884 | JSEncryptRSAKey.hasPublicKeyProperty(key)) { 4885 | // Set the values for the key. 4886 | _this.parsePropertiesFrom(key); 4887 | } 4888 | } 4889 | return _this; 4890 | } 4891 | /** 4892 | * Method to parse a pem encoded string containing both a public or private key. 4893 | * The method will translate the pem encoded string in a der encoded string and 4894 | * will parse private key and public key parameters. This method accepts public key 4895 | * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). 4896 | * 4897 | * @todo Check how many rsa formats use the same format of pkcs #1. 4898 | * 4899 | * The format is defined as: 4900 | * PublicKeyInfo ::= SEQUENCE { 4901 | * algorithm AlgorithmIdentifier, 4902 | * PublicKey BIT STRING 4903 | * } 4904 | * Where AlgorithmIdentifier is: 4905 | * AlgorithmIdentifier ::= SEQUENCE { 4906 | * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm 4907 | * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) 4908 | * } 4909 | * and PublicKey is a SEQUENCE encapsulated in a BIT STRING 4910 | * RSAPublicKey ::= SEQUENCE { 4911 | * modulus INTEGER, -- n 4912 | * publicExponent INTEGER -- e 4913 | * } 4914 | * it's possible to examine the structure of the keys obtained from openssl using 4915 | * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ 4916 | * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer 4917 | * @private 4918 | */ 4919 | JSEncryptRSAKey.prototype.parseKey = function (pem) { 4920 | try { 4921 | var modulus = 0; 4922 | var public_exponent = 0; 4923 | var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; 4924 | var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); 4925 | var asn1 = ASN1.decode(der); 4926 | // Fixes a bug with OpenSSL 1.0+ private keys 4927 | if (asn1.sub.length === 3) { 4928 | asn1 = asn1.sub[2].sub[0]; 4929 | } 4930 | if (asn1.sub.length === 9) { 4931 | // Parse the private key. 4932 | modulus = asn1.sub[1].getHexStringValue(); // bigint 4933 | this.n = parseBigInt(modulus, 16); 4934 | public_exponent = asn1.sub[2].getHexStringValue(); // int 4935 | this.e = parseInt(public_exponent, 16); 4936 | var private_exponent = asn1.sub[3].getHexStringValue(); // bigint 4937 | this.d = parseBigInt(private_exponent, 16); 4938 | var prime1 = asn1.sub[4].getHexStringValue(); // bigint 4939 | this.p = parseBigInt(prime1, 16); 4940 | var prime2 = asn1.sub[5].getHexStringValue(); // bigint 4941 | this.q = parseBigInt(prime2, 16); 4942 | var exponent1 = asn1.sub[6].getHexStringValue(); // bigint 4943 | this.dmp1 = parseBigInt(exponent1, 16); 4944 | var exponent2 = asn1.sub[7].getHexStringValue(); // bigint 4945 | this.dmq1 = parseBigInt(exponent2, 16); 4946 | var coefficient = asn1.sub[8].getHexStringValue(); // bigint 4947 | this.coeff = parseBigInt(coefficient, 16); 4948 | } 4949 | else if (asn1.sub.length === 2) { 4950 | // Parse the public key. 4951 | var bit_string = asn1.sub[1]; 4952 | var sequence = bit_string.sub[0]; 4953 | modulus = sequence.sub[0].getHexStringValue(); 4954 | this.n = parseBigInt(modulus, 16); 4955 | public_exponent = sequence.sub[1].getHexStringValue(); 4956 | this.e = parseInt(public_exponent, 16); 4957 | } 4958 | else { 4959 | return false; 4960 | } 4961 | return true; 4962 | } 4963 | catch (ex) { 4964 | return false; 4965 | } 4966 | }; 4967 | /** 4968 | * Translate rsa parameters in a hex encoded string representing the rsa key. 4969 | * 4970 | * The translation follow the ASN.1 notation : 4971 | * RSAPrivateKey ::= SEQUENCE { 4972 | * version Version, 4973 | * modulus INTEGER, -- n 4974 | * publicExponent INTEGER, -- e 4975 | * privateExponent INTEGER, -- d 4976 | * prime1 INTEGER, -- p 4977 | * prime2 INTEGER, -- q 4978 | * exponent1 INTEGER, -- d mod (p1) 4979 | * exponent2 INTEGER, -- d mod (q-1) 4980 | * coefficient INTEGER, -- (inverse of q) mod p 4981 | * } 4982 | * @returns {string} DER Encoded String representing the rsa private key 4983 | * @private 4984 | */ 4985 | JSEncryptRSAKey.prototype.getPrivateBaseKey = function () { 4986 | var options = { 4987 | array: [ 4988 | new KJUR.asn1.DERInteger({ int: 0 }), 4989 | new KJUR.asn1.DERInteger({ bigint: this.n }), 4990 | new KJUR.asn1.DERInteger({ int: this.e }), 4991 | new KJUR.asn1.DERInteger({ bigint: this.d }), 4992 | new KJUR.asn1.DERInteger({ bigint: this.p }), 4993 | new KJUR.asn1.DERInteger({ bigint: this.q }), 4994 | new KJUR.asn1.DERInteger({ bigint: this.dmp1 }), 4995 | new KJUR.asn1.DERInteger({ bigint: this.dmq1 }), 4996 | new KJUR.asn1.DERInteger({ bigint: this.coeff }) 4997 | ] 4998 | }; 4999 | var seq = new KJUR.asn1.DERSequence(options); 5000 | return seq.getEncodedHex(); 5001 | }; 5002 | /** 5003 | * base64 (pem) encoded version of the DER encoded representation 5004 | * @returns {string} pem encoded representation without header and footer 5005 | * @public 5006 | */ 5007 | JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () { 5008 | return hex2b64(this.getPrivateBaseKey()); 5009 | }; 5010 | /** 5011 | * Translate rsa parameters in a hex encoded string representing the rsa public key. 5012 | * The representation follow the ASN.1 notation : 5013 | * PublicKeyInfo ::= SEQUENCE { 5014 | * algorithm AlgorithmIdentifier, 5015 | * PublicKey BIT STRING 5016 | * } 5017 | * Where AlgorithmIdentifier is: 5018 | * AlgorithmIdentifier ::= SEQUENCE { 5019 | * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm 5020 | * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) 5021 | * } 5022 | * and PublicKey is a SEQUENCE encapsulated in a BIT STRING 5023 | * RSAPublicKey ::= SEQUENCE { 5024 | * modulus INTEGER, -- n 5025 | * publicExponent INTEGER -- e 5026 | * } 5027 | * @returns {string} DER Encoded String representing the rsa public key 5028 | * @private 5029 | */ 5030 | JSEncryptRSAKey.prototype.getPublicBaseKey = function () { 5031 | var first_sequence = new KJUR.asn1.DERSequence({ 5032 | array: [ 5033 | new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }), 5034 | new KJUR.asn1.DERNull() 5035 | ] 5036 | }); 5037 | var second_sequence = new KJUR.asn1.DERSequence({ 5038 | array: [ 5039 | new KJUR.asn1.DERInteger({ bigint: this.n }), 5040 | new KJUR.asn1.DERInteger({ int: this.e }) 5041 | ] 5042 | }); 5043 | var bit_string = new KJUR.asn1.DERBitString({ 5044 | hex: "00" + second_sequence.getEncodedHex() 5045 | }); 5046 | var seq = new KJUR.asn1.DERSequence({ 5047 | array: [ 5048 | first_sequence, 5049 | bit_string 5050 | ] 5051 | }); 5052 | return seq.getEncodedHex(); 5053 | }; 5054 | /** 5055 | * base64 (pem) encoded version of the DER encoded representation 5056 | * @returns {string} pem encoded representation without header and footer 5057 | * @public 5058 | */ 5059 | JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () { 5060 | return hex2b64(this.getPublicBaseKey()); 5061 | }; 5062 | /** 5063 | * wrap the string in block of width chars. The default value for rsa keys is 64 5064 | * characters. 5065 | * @param {string} str the pem encoded string without header and footer 5066 | * @param {Number} [width=64] - the length the string has to be wrapped at 5067 | * @returns {string} 5068 | * @private 5069 | */ 5070 | JSEncryptRSAKey.wordwrap = function (str, width) { 5071 | width = width || 64; 5072 | if (!str) { 5073 | return str; 5074 | } 5075 | var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; 5076 | return str.match(RegExp(regex, "g")).join("\n"); 5077 | }; 5078 | /** 5079 | * Retrieve the pem encoded private key 5080 | * @returns {string} the pem encoded private key with header/footer 5081 | * @public 5082 | */ 5083 | JSEncryptRSAKey.prototype.getPrivateKey = function () { 5084 | var key = "-----BEGIN RSA PRIVATE KEY-----\n"; 5085 | key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; 5086 | key += "-----END RSA PRIVATE KEY-----"; 5087 | return key; 5088 | }; 5089 | /** 5090 | * Retrieve the pem encoded public key 5091 | * @returns {string} the pem encoded public key with header/footer 5092 | * @public 5093 | */ 5094 | JSEncryptRSAKey.prototype.getPublicKey = function () { 5095 | var key = "-----BEGIN PUBLIC KEY-----\n"; 5096 | key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; 5097 | key += "-----END PUBLIC KEY-----"; 5098 | return key; 5099 | }; 5100 | /** 5101 | * Check if the object contains the necessary parameters to populate the rsa modulus 5102 | * and public exponent parameters. 5103 | * @param {Object} [obj={}] - An object that may contain the two public key 5104 | * parameters 5105 | * @returns {boolean} true if the object contains both the modulus and the public exponent 5106 | * properties (n and e) 5107 | * @todo check for types of n and e. N should be a parseable bigInt object, E should 5108 | * be a parseable integer number 5109 | * @private 5110 | */ 5111 | JSEncryptRSAKey.hasPublicKeyProperty = function (obj) { 5112 | obj = obj || {}; 5113 | return (obj.hasOwnProperty("n") && 5114 | obj.hasOwnProperty("e")); 5115 | }; 5116 | /** 5117 | * Check if the object contains ALL the parameters of an RSA key. 5118 | * @param {Object} [obj={}] - An object that may contain nine rsa key 5119 | * parameters 5120 | * @returns {boolean} true if the object contains all the parameters needed 5121 | * @todo check for types of the parameters all the parameters but the public exponent 5122 | * should be parseable bigint objects, the public exponent should be a parseable integer number 5123 | * @private 5124 | */ 5125 | JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) { 5126 | obj = obj || {}; 5127 | return (obj.hasOwnProperty("n") && 5128 | obj.hasOwnProperty("e") && 5129 | obj.hasOwnProperty("d") && 5130 | obj.hasOwnProperty("p") && 5131 | obj.hasOwnProperty("q") && 5132 | obj.hasOwnProperty("dmp1") && 5133 | obj.hasOwnProperty("dmq1") && 5134 | obj.hasOwnProperty("coeff")); 5135 | }; 5136 | /** 5137 | * Parse the properties of obj in the current rsa object. Obj should AT LEAST 5138 | * include the modulus and public exponent (n, e) parameters. 5139 | * @param {Object} obj - the object containing rsa parameters 5140 | * @private 5141 | */ 5142 | JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) { 5143 | this.n = obj.n; 5144 | this.e = obj.e; 5145 | if (obj.hasOwnProperty("d")) { 5146 | this.d = obj.d; 5147 | this.p = obj.p; 5148 | this.q = obj.q; 5149 | this.dmp1 = obj.dmp1; 5150 | this.dmq1 = obj.dmq1; 5151 | this.coeff = obj.coeff; 5152 | } 5153 | }; 5154 | return JSEncryptRSAKey; 5155 | }(RSAKey)); 5156 | 5157 | /** 5158 | * 5159 | * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour 5160 | * possible parameters are: 5161 | * - default_key_size {number} default: 1024 the key size in bit 5162 | * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent 5163 | * - log {boolean} default: false whether log warn/error or not 5164 | * @constructor 5165 | */ 5166 | var JSEncrypt = /** @class */ (function () { 5167 | function JSEncrypt(options) { 5168 | options = options || {}; 5169 | this.default_key_size = parseInt(options.default_key_size, 10) || 1024; 5170 | this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type 5171 | this.log = options.log || false; 5172 | // The private and public key. 5173 | this.key = null; 5174 | } 5175 | /** 5176 | * Method to set the rsa key parameter (one method is enough to set both the public 5177 | * and the private key, since the private key contains the public key paramenters) 5178 | * Log a warning if logs are enabled 5179 | * @param {Object|string} key the pem encoded string or an object (with or without header/footer) 5180 | * @public 5181 | */ 5182 | JSEncrypt.prototype.setKey = function (key) { 5183 | if (this.log && this.key) { 5184 | console.warn("A key was already set, overriding existing."); 5185 | } 5186 | this.key = new JSEncryptRSAKey(key); 5187 | }; 5188 | /** 5189 | * Proxy method for setKey, for api compatibility 5190 | * @see setKey 5191 | * @public 5192 | */ 5193 | JSEncrypt.prototype.setPrivateKey = function (privkey) { 5194 | // Create the key. 5195 | this.setKey(privkey); 5196 | }; 5197 | /** 5198 | * Proxy method for setKey, for api compatibility 5199 | * @see setKey 5200 | * @public 5201 | */ 5202 | JSEncrypt.prototype.setPublicKey = function (pubkey) { 5203 | // Sets the public key. 5204 | this.setKey(pubkey); 5205 | }; 5206 | /** 5207 | * Proxy method for RSAKey object's decrypt, decrypt the string using the private 5208 | * components of the rsa key object. Note that if the object was not set will be created 5209 | * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor 5210 | * @param {string} str base64 encoded crypted string to decrypt 5211 | * @return {string} the decrypted string 5212 | * @public 5213 | */ 5214 | JSEncrypt.prototype.decrypt = function (str) { 5215 | // Return the decrypted string. 5216 | try { 5217 | return this.getKey().decrypt(b64tohex(str)); 5218 | } 5219 | catch (ex) { 5220 | return false; 5221 | } 5222 | }; 5223 | /** 5224 | * Proxy method for RSAKey object's encrypt, encrypt the string using the public 5225 | * components of the rsa key object. Note that if the object was not set will be created 5226 | * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor 5227 | * @param {string} str the string to encrypt 5228 | * @return {string} the encrypted string encoded in base64 5229 | * @public 5230 | */ 5231 | JSEncrypt.prototype.encrypt = function (str) { 5232 | // Return the encrypted string. 5233 | try { 5234 | return hex2b64(this.getKey().encrypt(str)); 5235 | } 5236 | catch (ex) { 5237 | return false; 5238 | } 5239 | }; 5240 | /** 5241 | * Proxy method for RSAKey object's sign. 5242 | * @param {string} str the string to sign 5243 | * @param {function} digestMethod hash method 5244 | * @param {string} digestName the name of the hash algorithm 5245 | * @return {string} the signature encoded in base64 5246 | * @public 5247 | */ 5248 | JSEncrypt.prototype.sign = function (str, digestMethod, digestName) { 5249 | // return the RSA signature of 'str' in 'hex' format. 5250 | try { 5251 | return hex2b64(this.getKey().sign(str, digestMethod, digestName)); 5252 | } 5253 | catch (ex) { 5254 | return false; 5255 | } 5256 | }; 5257 | /** 5258 | * Proxy method for RSAKey object's verify. 5259 | * @param {string} str the string to verify 5260 | * @param {string} signature the signature encoded in base64 to compare the string to 5261 | * @param {function} digestMethod hash method 5262 | * @return {boolean} whether the data and signature match 5263 | * @public 5264 | */ 5265 | JSEncrypt.prototype.verify = function (str, signature, digestMethod) { 5266 | // Return the decrypted 'digest' of the signature. 5267 | try { 5268 | return this.getKey().verify(str, b64tohex(signature), digestMethod); 5269 | } 5270 | catch (ex) { 5271 | return false; 5272 | } 5273 | }; 5274 | /** 5275 | * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object 5276 | * will be created and returned 5277 | * @param {callback} [cb] the callback to be called if we want the key to be generated 5278 | * in an async fashion 5279 | * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object 5280 | * @public 5281 | */ 5282 | JSEncrypt.prototype.getKey = function (cb) { 5283 | // Only create new if it does not exist. 5284 | if (!this.key) { 5285 | // Get a new private key. 5286 | this.key = new JSEncryptRSAKey(); 5287 | if (cb && {}.toString.call(cb) === "[object Function]") { 5288 | this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb); 5289 | return; 5290 | } 5291 | // Generate the key. 5292 | this.key.generate(this.default_key_size, this.default_public_exponent); 5293 | } 5294 | return this.key; 5295 | }; 5296 | /** 5297 | * Returns the pem encoded representation of the private key 5298 | * If the key doesn't exists a new key will be created 5299 | * @returns {string} pem encoded representation of the private key WITH header and footer 5300 | * @public 5301 | */ 5302 | JSEncrypt.prototype.getPrivateKey = function () { 5303 | // Return the private representation of this key. 5304 | return this.getKey().getPrivateKey(); 5305 | }; 5306 | /** 5307 | * Returns the pem encoded representation of the private key 5308 | * If the key doesn't exists a new key will be created 5309 | * @returns {string} pem encoded representation of the private key WITHOUT header and footer 5310 | * @public 5311 | */ 5312 | JSEncrypt.prototype.getPrivateKeyB64 = function () { 5313 | // Return the private representation of this key. 5314 | return this.getKey().getPrivateBaseKeyB64(); 5315 | }; 5316 | /** 5317 | * Returns the pem encoded representation of the public key 5318 | * If the key doesn't exists a new key will be created 5319 | * @returns {string} pem encoded representation of the public key WITH header and footer 5320 | * @public 5321 | */ 5322 | JSEncrypt.prototype.getPublicKey = function () { 5323 | // Return the private representation of this key. 5324 | return this.getKey().getPublicKey(); 5325 | }; 5326 | /** 5327 | * Returns the pem encoded representation of the public key 5328 | * If the key doesn't exists a new key will be created 5329 | * @returns {string} pem encoded representation of the public key WITHOUT header and footer 5330 | * @public 5331 | */ 5332 | JSEncrypt.prototype.getPublicKeyB64 = function () { 5333 | // Return the private representation of this key. 5334 | return this.getKey().getPublicBaseKeyB64(); 5335 | }; 5336 | JSEncrypt.version = "3.0.0-rc.1"; 5337 | return JSEncrypt; 5338 | }()); 5339 | 5340 | window.JSEncrypt = JSEncrypt; 5341 | 5342 | exports.JSEncrypt = JSEncrypt; 5343 | exports.default = JSEncrypt; 5344 | 5345 | Object.defineProperty(exports, '__esModule', { value: true }); 5346 | 5347 | }))); 5348 | --------------------------------------------------------------------------------