zouyong преди 5 години
родител
ревизия
2f51fe22a1
променени са 62 файла, в които са добавени 10445 реда и са изтрити 32 реда
  1. 1 3
      assets/Scenes/Launch.scene
  2. 1 0
      assets/Scripts/Data/g.ts
  3. 20 18
      assets/Scripts/Launch/App.ts
  4. 28 11
      assets/Scripts/Launch/Login.ts
  5. 12 0
      assets/Scripts/mk.meta
  6. 12 0
      assets/Scripts/mk/data.meta
  7. 101 0
      assets/Scripts/mk/data/AppData.ts
  8. 9 0
      assets/Scripts/mk/data/AppData.ts.meta
  9. 63 0
      assets/Scripts/mk/data/GData.ts
  10. 9 0
      assets/Scripts/mk/data/GData.ts.meta
  11. 515 0
      assets/Scripts/mk/data/GameData.ts
  12. 9 0
      assets/Scripts/mk/data/GameData.ts.meta
  13. 32 0
      assets/Scripts/mk/data/HttpData.ts
  14. 9 0
      assets/Scripts/mk/data/HttpData.ts.meta
  15. 297 0
      assets/Scripts/mk/data/LoginData.ts
  16. 9 0
      assets/Scripts/mk/data/LoginData.ts.meta
  17. 26 0
      assets/Scripts/mk/data/StorageData.ts
  18. 9 0
      assets/Scripts/mk/data/StorageData.ts.meta
  19. 12 0
      assets/Scripts/mk/data/WechatData.ts
  20. 9 0
      assets/Scripts/mk/data/WechatData.ts.meta
  21. 12 0
      assets/Scripts/mk/system.meta
  22. 109 0
      assets/Scripts/mk/system/HttpSystem.ts
  23. 9 0
      assets/Scripts/mk/system/HttpSystem.ts.meta
  24. 71 0
      assets/Scripts/mk/system/MKSystem.ts
  25. 9 0
      assets/Scripts/mk/system/MKSystem.ts.meta
  26. 12 0
      assets/Scripts/mk/util.meta
  27. 325 0
      assets/Scripts/mk/util/EncryptUtil.ts
  28. 9 0
      assets/Scripts/mk/util/EncryptUtil.ts.meta
  29. 114 0
      assets/Scripts/mk/util/FileUtil.ts
  30. 9 0
      assets/Scripts/mk/util/FileUtil.ts.meta
  31. 81 0
      assets/Scripts/mk/util/GameUtil.ts
  32. 9 0
      assets/Scripts/mk/util/GameUtil.ts.meta
  33. 190 0
      assets/Scripts/mk/util/LoadResUtil.ts
  34. 9 0
      assets/Scripts/mk/util/LoadResUtil.ts.meta
  35. 180 0
      assets/Scripts/mk/util/LogUtil.ts
  36. 9 0
      assets/Scripts/mk/util/LogUtil.ts.meta
  37. 265 0
      assets/Scripts/mk/util/MathUtil.ts
  38. 9 0
      assets/Scripts/mk/util/MathUtil.ts.meta
  39. 56 0
      assets/Scripts/mk/util/StorageUtil.ts
  40. 9 0
      assets/Scripts/mk/util/StorageUtil.ts.meta
  41. 169 0
      assets/Scripts/mk/util/StringUtil.ts
  42. 9 0
      assets/Scripts/mk/util/StringUtil.ts.meta
  43. 183 0
      assets/Scripts/mk/util/TimeUtil.ts
  44. 9 0
      assets/Scripts/mk/util/TimeUtil.ts.meta
  45. 122 0
      assets/Scripts/mk/util/TweenUtil.ts
  46. 9 0
      assets/Scripts/mk/util/TweenUtil.ts.meta
  47. 12 0
      assets/Scripts/mk/util/encrypt.meta
  48. 701 0
      assets/Scripts/mk/util/encrypt/aes.js
  49. 9 0
      assets/Scripts/mk/util/encrypt/aes.js.meta
  50. 123 0
      assets/Scripts/mk/util/encrypt/base64.ts
  51. 9 0
      assets/Scripts/mk/util/encrypt/base64.ts.meta
  52. 325 0
      assets/Scripts/mk/util/encrypt/hmacSha256.ts
  53. 9 0
      assets/Scripts/mk/util/encrypt/hmacSha256.ts.meta
  54. 260 0
      assets/Scripts/mk/util/encrypt/md5.js
  55. 9 0
      assets/Scripts/mk/util/encrypt/md5.js.meta
  56. 12 0
      assets/Scripts/mk/util/encrypt/rsa.meta
  57. 87 0
      assets/Scripts/mk/util/encrypt/rsa/jsencrypt.d.ts
  58. 9 0
      assets/Scripts/mk/util/encrypt/rsa/jsencrypt.d.ts.meta
  59. 5481 0
      assets/Scripts/mk/util/encrypt/rsa/jsencrypt.js
  60. 9 0
      assets/Scripts/mk/util/encrypt/rsa/jsencrypt.js.meta
  61. 201 0
      assets/Scripts/mk/util/encrypt/sha1.js
  62. 9 0
      assets/Scripts/mk/util/encrypt/sha1.js.meta

+ 1 - 3
assets/Scenes/Launch.scene

@@ -279,7 +279,6 @@
       "__id__": 10
     },
     "_enabled": true,
-    "__prefab": null,
     "login": {
       "__id__": 13
     },
@@ -302,7 +301,6 @@
       "__id__": 14
     },
     "_enabled": true,
-    "__prefab": null,
     "progressBar": {
       "__id__": 16
     },
@@ -1333,7 +1331,7 @@
       "__id__": 18
     },
     "_children": [],
-    "_active": true,
+    "_active": false,
     "_components": [
       {
         "__id__": 46

+ 1 - 0
assets/Scripts/Data/g.ts

@@ -17,6 +17,7 @@ export class g {
     public static deviceData = new DeviceData();
     public static adData = globalThis["adData"] || new ADData();
     public static wechatData = new WechatData();
+
     /**
      * 激励视频加载失败
      */

+ 20 - 18
assets/Scripts/Launch/App.ts

@@ -33,24 +33,26 @@ export class App extends Component {
     }
     update() {
         if (this.configLoaded) {
-            if (ISJSB) {
-                if (this.hotUpdate.versionIsNew && this.appUpdate.versionIsNew != -1 && g.deviceData.needlogin && (g.deviceData.imei || g.deviceData.oaid || g.deviceData.androId || g.deviceData.mac)) {
-                    let account = new md5().hex_md5(g.deviceData.imei + g.deviceData.oaid + g.deviceData.androId + g.deviceData.mac);
-                    this.login.login(account);
-                    g.deviceData.needlogin = false;
-                }
-                else if (g.deviceData.channel && g.deviceData.version) {
-                    this.appUpdate.checkNativeVersion(g.deviceData.version);
-                    g.deviceData.version = null;
-                }
-                if (g.deviceData.apkDownloading) {//如果apk正在下载
-                    this.appUpdate.setDownloadAPKProgress();
-                }
-            }
-            else {
-                this.login.login();
-                this.configLoaded = false;
-            }
+            this.login.init();
+            this.configLoaded = false;
+            // if (ISJSB) {
+            //     if (this.hotUpdate.versionIsNew && this.appUpdate.versionIsNew != -1 && g.deviceData.needlogin && (g.deviceData.imei || g.deviceData.oaid || g.deviceData.androId || g.deviceData.mac)) {
+            //         let account = new md5().hex_md5(g.deviceData.imei + g.deviceData.oaid + g.deviceData.androId + g.deviceData.mac);
+            //         this.login.login(account);
+            //         g.deviceData.needlogin = false;
+            //     }
+            //     else if (g.deviceData.channel && g.deviceData.version) {
+            //         this.appUpdate.checkNativeVersion(g.deviceData.version);
+            //         g.deviceData.version = null;
+            //     }
+            //     if (g.deviceData.apkDownloading) {//如果apk正在下载
+            //         this.appUpdate.setDownloadAPKProgress();
+            //     }
+            // }
+            // else {
+            //     this.login.login();
+            //     this.configLoaded = false;
+            // }
         }
     }
     onHotUpdateProgress(progress: number) {

+ 28 - 11
assets/Scripts/Launch/Login.ts

@@ -37,21 +37,14 @@ export class Login extends Component {
             }
             else {
                 this.progressBar.node.active = false;
-                this.wechatButton.node.active = true;
+                // this.wechatButton.node.active = true;
             }
         }
     }
     public onWechatLogin() {
         platform.wxLogin();
     }
-    update() {
-        if (g.wechatData.code) {
-            this.progressBar.node.active = true;
-            this.wechatButton.node.active = false;
-            this.doLogin(g.wechatData.code, g.wechatData.nickName, g.wechatData.avatar);
-            g.wechatData.code = null;
-        }
-    }
+
     private async doLogin(account: string = null, nickName: string = '', avator: string = '') {
         account = account || this.account;
         let onlyLogin = false;
@@ -64,7 +57,7 @@ export class Login extends Component {
         if (!data) {
             if (this.loginType == LoginType.wechat) {
                 this.progressBar.node.active = false;
-                this.wechatButton.node.active = true;
+                // this.wechatButton.node.active = true;
             }
             WindowManager.showTips("登录失败,请检查网络");
             return;
@@ -116,7 +109,7 @@ export class Login extends Component {
             localStorage.removeItem("account");
             if (this.loginType == LoginType.wechat) {
                 this.progressBar.node.active = false;
-                this.wechatButton.node.active = true;
+                // this.wechatButton.node.active = true;
             }
             WindowManager.showTips("登录失败,请检查网络");
         }
@@ -129,4 +122,28 @@ export class Login extends Component {
         platform.reportThinking("login");
         director.loadScene("Main");
     }
+
+
+    /** --------------------------------- 通用登录 ------------------------------------------ */
+
+    public init() {
+        director.preloadScene("Main", this.onProgress.bind(this), this.preLoadFinish.bind(this));
+    }
+
+    private preLoadFinish(): void {
+        gData.loginData.init()
+    }
+
+    update() {
+        // if (g.wechatData.code) {
+        //     this.progressBar.node.active = true;
+        //     this.wechatButton.node.active = false;
+        //     this.doLogin(g.wechatData.code, g.wechatData.nickName, g.wechatData.avatar);
+        //     g.wechatData.code = null;
+        // }
+        if (gData.gameData.dataFinish) {
+            platform.reportThinking("login");
+            director.loadScene("Main");
+        }
+    }
 }

+ 12 - 0
assets/Scripts/mk.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "fb6bb772-9acf-4eea-9c39-2b86e8387049",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 12 - 0
assets/Scripts/mk/data.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "a496f86b-9577-46a5-9ebf-ac8f40881fd1",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 101 - 0
assets/Scripts/mk/data/AppData.ts

@@ -0,0 +1,101 @@
+/**
+ * @description 应用数据
+ * @author 邹勇
+ */
+export class AppData {
+
+    public getDeviceInfoCompelete: boolean = false;
+
+    /** 错误日志游戏名标志,尽量短 */
+    public appNameBugly: string = '3xiao';
+
+    public appVersion: string = '';
+
+    /** 投放渠道号 */
+    public tfChannel: string = '';
+
+    /** api版本 */
+    public version: string = '1.0.0';
+
+    /** 李杨/悍国服的appId */
+    // public appId: string = 'wxcf31f0e54f7fefda';
+    /** 测试服/正式服的appId */
+    public appId: string = 'wxcf31f0e54f7fefda';
+
+    /** 友盟渠道 */
+    public umengChannel: string = '';
+
+    /** 设备型号 */
+    public deviceType: string = '';
+
+    /** 安卓版本号 */
+    public androidVersion: string = '';
+
+    public mac: string = '1e:06:e5:13:b3:23,f6:60:e4:1a:b7:27';
+
+    /** 设备信息 */
+    public machineInfo = {
+        "android_id": "",
+        "idfa": "",
+        "imei": "",
+        "mac": "",
+        "oaid": "",
+        "umid": ""
+    };
+
+    /**
+     * 更新设备信息
+     * @description 自定义功能 JavaToCocos
+     * @param info  info(Java返回)
+     */
+    public updateDeviceInfo(info) {
+        let arr = info.split('#')
+        this.machineInfo.android_id = arr[0];
+        this.machineInfo.idfa = arr[1];
+        this.machineInfo.imei = arr[2];
+        this.machineInfo.mac = this.mac = arr[3];
+        this.machineInfo.oaid = arr[4];
+        this.machineInfo.umid = arr[5];
+        this.tfChannel = arr[6];
+        this.appVersion = arr[7];
+
+        /** 友盟渠道 */
+        this.umengChannel = arr[8];
+        /** 设备型号 */
+        this.deviceType = arr[9];
+        /** 安卓版本号 */
+        this.androidVersion = arr[10];
+
+        this.getDeviceInfoCompelete = true;
+        console.log("===[this.tfChannel", this.tfChannel);
+        console.log("===[this.appVersion", this.appVersion);
+    }
+
+    public init() {
+
+    }
+
+    /** 更新状态 */
+    public updateState: UpdateState = UpdateState.None;
+
+    //强更信息--------------------------------------------------------
+    /** 需要强制更新 */
+    public needForceUpdate;
+    /** 安装版本 */
+    public installVersion;
+    /** 安装路径 */
+    public installUrl;
+    /** 更新信息 */
+    public updateDes;
+    /** 修复信息 */
+    public fixDes;
+}
+
+/** 更新状态 */
+export enum UpdateState {
+    None = -1,
+    CheckForce = 0,
+    ForceUpdateFinish = 1,
+    CheckHot = 2,
+    UpdateFinish = 3,
+}

+ 9 - 0
assets/Scripts/mk/data/AppData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "bb3de142-222d-4bac-921b-1c7b88e24311",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 63 - 0
assets/Scripts/mk/data/GData.ts

@@ -0,0 +1,63 @@
+
+import { AppData } from "./AppData";
+import { GameData } from "./GameData";
+import { HttpData } from "./HttpData";
+import { LoginData } from "./LoginData";
+import { StorageData } from "./StorageData";
+import { WechatData } from "./WechatData";
+
+
+/**
+ * 数据集合全局类
+ * @description 所有数据都通过这个类创建,修改,删除
+ * @author 邹勇
+ */
+class GData {
+    constructor() {
+        this.init();
+    }
+
+    public loginData: LoginData;
+    public appData: AppData;
+    public gameData: GameData;
+    public wechatData: WechatData;
+    public httpData: HttpData;
+    // public adData: AdData;
+    public storageData: StorageData;
+
+
+    init() {
+        this.appData = new AppData();
+        this.loginData = new LoginData();
+        this.gameData = new GameData();
+        this.wechatData = new WechatData();
+        this.httpData = new HttpData();
+        // this.adData = new AdData();
+        this.storageData = new StorageData();
+
+
+    }
+}
+
+/**
+ * 提现模块的功能ID
+ */
+export enum Fun {
+    moreGame = 1,   //互推
+    turnable = 2,   //转盘
+    fission = 3,    //裂变
+    pigbank = 4,    //存钱罐
+    blessingBag = 5,   //福袋
+    sign = 6,       //签到
+    cashNormal = 7, //常规提现
+    redBagCash = 8, //红包提现
+    redeem = 9,     //兑换码
+}
+
+declare global {
+    const gData: GData;
+}
+window['gData'] = new GData();
+
+
+

+ 9 - 0
assets/Scripts/mk/data/GData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "047dc194-d483-4fae-9401-bcb9e2fc5a07",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 515 - 0
assets/Scripts/mk/data/GameData.ts

@@ -0,0 +1,515 @@
+
+
+/**
+ * @description 游戏核心玩法数据
+ * @author 邹勇
+ */
+export class GameData {
+
+
+    public dataFinish: boolean = false;
+
+    public savePropFinish: boolean = false;
+
+    public savePropsFinish: boolean = false;
+
+    public getPropsFnish: boolean = false;
+
+
+    public configs: any = {};
+    public adShowConfig: ADShowCfg;
+    /** 功能开启 */
+    public funOpenData: string[] = [];
+
+    public gameData: PlayerProp = null;
+    /** 标志位:刷新主界面货币 */
+    public init_coin: boolean = false;
+
+    public updatePiggyBankValue:boolean = false;
+
+    /** 标志位:刷新主界面头像 */
+    public init_head: boolean = false;
+
+    /** 标志位:刷新主界面红点 */
+    public init_red_point: boolean = true;
+
+    public props: Map<number, number> = new Map<number, number>();
+
+    public pools = [
+        { url: "game/prefab/tips", num: 20 },
+        { url: "game/prefab/coin", num: 20 }
+    ];
+
+
+    /**
+     * 初始化游戏数据:网络配置信息,用户信息
+     * @returns 
+     */
+    public async init() {
+
+        let data: any = { "versionCode": gData.appData.version };
+        let response = await mk.http.sendData('getAllConfigInfo', data);
+        if (response.errcode != 0) {
+            if (response.errcode == -10003 || response.errcode == -20003) {
+                //清除缓存
+                gData.loginData.reload();
+            }
+            return;
+        }
+        mk.console.logSingle("getAllConfigInfo", response.data);
+        this.initConfigs(response.data);
+
+        data = {};
+        response = await mk.http.sendData('getInfoCrypt', data);
+        if (response.errcode != 0) {
+            return;
+        }
+        mk.console.logSingle("getInfoCrypt", response.data);
+        this.initPlayerProp(response.data)
+        this.initProps(response.data.gameUserData);
+
+
+        data = {};
+        response = await mk.http.sendData('user/adShowConfig', data);
+        if (response.errcode != 0) {
+            return;
+        }
+        this.adShowConfig = response.data;
+        mk.console.logSingle("user/adShowConfig", response.data);
+
+        this.dataFinish = true;
+    }
+
+    private initConfigs(data) {
+        // console.log('config  ', data);
+        this.configs = data;
+        this.funOpenData = this.configs.ServerConfig.Functionswitch.split(",");
+    }
+
+    /**
+     * 初始化玩家数据
+     */
+    private initPlayerProp(res_data) {
+        this.gameData = new PlayerProp();
+        this.gameData.cashIndex = res_data.cashIndex;
+        this.gameData.gameUserData = res_data.gameUserData;
+        this.gameData.isSignInToday = res_data.isSignInToday;
+        this.gameData.isWithdrawable = res_data.isWithdrawable;
+        this.gameData.lastTime = res_data.lastTime;
+        this.gameData.loginDays = res_data.loginDays;
+        this.gameData.newPlayer = res_data.newPlayer;
+        this.gameData.initPiggyBank(res_data.piggyBank);
+        this.gameData.piggyBankCashTimes = res_data.piggyBankCashTimes;
+        this.gameData.redMoney = res_data.redMoney;
+        this.gameData.signInDay = res_data.signInDay;
+        this.gameData.totalPiggyBankCashTimes = res_data.totalPiggyBankCashTimes;
+        this.gameData.turntableTimes = res_data.turntableTimes;
+        this.gameData.userTuCaoInfo = res_data.userTuCaoInfo;
+        this.gameData.versioncfg = res_data.versioncfg;
+        this.gameData.isFirstRedMoney = res_data.isFirstRedMoney;
+        // gData.adData.watchNumToday = res_data.dayVideoTimesForRedMoney == null ? 0 : res_data.dayVideoTimesForRedMoney;
+    }
+
+    /**
+     * 保存单个数据
+     */
+    public async setProp(key: GameProp, value: number) {
+        let data = {
+            key: key + '',
+            value: value + ''
+        };
+        this.props.set(key, value);
+        await mk.http.sendData('savePlayerProp', data);
+        this.savePropFinish = true;
+    }
+
+    /**
+     * 保存多个数据
+     */
+    public async setProps(arr: { key: GameProp, value: number }[]) {
+        let needProp = {};
+        for (let i = 0; i < arr.length; i++) {
+            needProp[arr[i].key + ''] = arr[i].value + "";
+        }
+        let data = {
+            needProp: needProp
+        };
+
+        for (let i = 0; i < arr.length; i++) {
+            this.props.set(arr[i].key, arr[i].value);
+        }
+        await mk.http.sendData('saveAllPlayerProp', data);
+        this.savePropsFinish = true;
+    }
+
+    /** 获取属性 */
+    public getProp(key: GameProp): number {
+        if (this.props == null) {
+            return 0;
+        }
+        let value = this.props.get(key);
+        return value == null ? 0 : value;
+    }
+
+    /**
+     * 向服务器请求所有属性后更新
+     */
+    public async getAllProps() {
+        let response = await mk.http.sendData('getAllPlayerProp', {});
+        if (response.errcode != 0) {
+            return;
+        }
+
+        this.initProps(response.data);
+
+        this.getPropsFnish = true;
+    }
+
+    private initProps(data) {
+        if (data == null) {
+            return;
+        }
+        for (let key in data) {
+            this.props.set(parseInt(key), JSON.parse(data[key]));
+        }
+    }
+
+    /**
+     * 第二天需要重置的数据
+     */
+    public resetProps() {
+        let arr = [];
+        arr.push({ key: GameProp.sign_can, value: 1 });
+        arr.push({ key: GameProp.isAutoOpenPanel, value: 1 });
+        arr.push({ key: GameProp.isOpenBankOnCloseCash, value: 0 });
+
+        this.setProps(arr);
+    }
+
+    /** 是否是新用户 */
+    public isNewPlayer(): boolean {
+        let v = this.getProp(GameProp.newPlayer);
+        return v == 0;
+    }
+}
+
+/**
+ * 所有模块的非校验数据
+ */
+export enum GameProp {
+    /** -------------------- 通用玩家数据 ------------------------- */
+    /** 是否新手 0新手 1老手 */
+    newPlayer = 1,
+    /** 当前新手引导步骤 */
+    guideID = 2,
+    /** 需要自动弹界面 每次登录都弹 除首次 表示今日是否要自动开 1自动开 2不自动开 其他不处理*/
+    isAutoOpenPanel = 3,
+    /** 关闭常规提现时需要自动开存钱罐 每天一次 表示今日有没有开过 */
+    isOpenBankOnCloseCash = 4,
+
+    /** ------------------ 游戏核心数据 --------------------------- */
+    /** 关卡数 */
+    levelNum = 10,
+    /** 锤子道具数目 */
+    hammerPropNum = 1001,
+    /** 重设道具数目 */
+    resetPropNum = 1002,
+    /** 变色道具数目 */
+    changePropNum = 1003,
+    /** 当前总分 */
+    curTotalScore = 11,
+
+    /** ------------------ 转盘数据 ------------------------------ */
+    turnable_leftTimes = 20,
+
+    /** ------------------ 存钱罐数据 ----------------------------- */
+
+    /** ------------------ 签到数据 ----------------------------- */
+    /** 上次签到进度 */
+    sign_last_bar = 120,
+    /** 当前能否签到 */
+    sign_can = 121,
+    /** ------------------ 红包提现 ----------------------------- */
+    /** 提现进度 */
+    redBag_cash_bar = 220,
+}
+
+/**
+ * 玩家数据
+ */
+class PlayerProp {
+    /** 自定义不需要校验的数据 */
+    gameUserData = 0;
+
+    _isSignInToday = 0;
+    /**
+     * 今日是否有签到
+     * - 0 未签到,表示可以签到
+     * - 1 有签到,表示不可签到
+     */
+    set isSignInToday(value: number) {
+        // this._isSignInToday = value;
+        // gData.sign.init_data = true;
+        // gData.gameData.init_red_point = true;
+    }
+    get isSignInToday(): number {
+        return this._isSignInToday;
+    }
+
+    private _piggyBank: number = 0;
+    /** 存钱罐存款 */
+    set piggyBank(value: number) {
+        // if (this._piggyBank === value) return;
+        // if (gData.gameData.gameData.isWithdrawable && value > 0) return;// 存钱罐可提现状态,不能增加存钱罐金额
+        // this._piggyBank = value;
+        // gData.gameData.init_coin = true;
+        // gData.pigbank.init_data = true;
+        // gData.gameData.init_red_point = true;
+    }
+    get piggyBank(): number {
+        return this._piggyBank;
+    }
+
+    /** 初始化 */
+    initPiggyBank(v){
+        this._piggyBank = v;
+    }
+
+    _isWithdrawable = 0;
+    /**
+     * 存钱罐能否提现
+     * - 0 不能提现
+     * - 1 能提现
+     */
+    set isWithdrawable(value: number) {
+        // if (this._isWithdrawable != value) {
+        //     this._isWithdrawable = value;
+        //     gData.pigbank.init_data = true;
+        //     gData.gameData.init_red_point = true;
+        // }
+    }
+    get isWithdrawable(): number {
+        return this._isWithdrawable;
+    }
+
+    /** 存钱罐每日提现次数 */
+    piggyBankCashTimes = 0;
+    /** 累计存钱罐每日提现次数 */
+    totalPiggyBankCashTimes = 0;
+    /** 提现进度 */
+    cashIndex = 0;
+    /** 上次登录时间 */
+    lastTime = 0;
+    /** 登录天数 */
+    loginDays = 0;
+    newPlayer = 0;
+
+    private _redMoney: number = 0;
+    /** 红包币数量 */
+    set redMoney(value: number) {
+        // this._redMoney = value;
+        // gData.gameData.init_coin = true;
+        // gData.gameData.init_red_point = true;
+    }
+    get redMoney(): number {
+        return this._redMoney;
+    }
+
+    _signInDay = 0;
+    /** 累计签到次数 客户端理解 上次签到天数 */
+    set signInDay(value: number) {
+        // if (this._signInDay === value) return;
+        // this._signInDay = value;
+        // gData.sign.init_data = true;
+    }
+    get signInDay(): number {
+        return this._signInDay;
+    }
+    /** 转盘次数 */
+    turntableTimes = 0;
+    /** 版本号 */
+    versioncfg = 0;
+    /** 福袋数据 */
+    userTuCaoInfo = 0;
+    /** 关卡数 */
+    levelNum = 0;
+    /** 锤子道具数目 */
+    hammerPropNum = 0;
+    /** 重设道具数目 */
+    resetPropNum = 0;
+    /** 变色道具数目 */
+    changePropNum = 0;
+    /** 能免费领红包 1 表示是新人第一次产出红包币,不用看视频*/
+    isFirstRedMoney = 0;
+}
+
+/**
+ * 奖励状态
+ */
+export enum RewardState {
+    /** 已领取 */
+    none = 1,
+    /** 未解锁 */
+    lock = 2,
+    /** 可领取 */
+    unlock = 3
+}
+
+/**
+ * 奖励类型
+ */
+export enum RewardType {
+    /** 红包币 */
+    redBag = 1,
+    /** 毛币 */
+    rmb = 2,
+    /** 金猪币 */
+    pigRmb = 3,
+}
+
+/**
+ * 音频路径
+ */
+export enum AUDIO_TYPE {
+    /**主界面背景音乐*/
+    bgm = 'bgm',
+    /**打开存钱罐界面播放一次*/
+    pigBank = 'pigBank',
+    /**关卡玩法背景音乐*/
+    missionBg = 'missionBg',
+    /**红包币领取界面关闭音效*/
+    rewardClose = 'rewardClose',
+    /**红包币领取界面开启音效*/
+    rewardOpen = 'rewardOpen',
+    /**红包界面打开音效*/
+    reward = 'reward',
+    /**提现到账界面打开播放一次*/
+    receiptNotice = 'receiptNotice',
+    /**通用按钮点击音效 */
+    button = 'button',
+    /**转盘转动音效*/
+    turnableplay = 'turnableplay',
+    /**转盘转动音效*/
+    turnplateDrawEnd = 'turnplateDrawEnd',
+    /**主页背景音乐 */
+    music_startBg = "music_startBg",
+    /**游戏背景音乐 */
+    music_gameBg = "music_gameBg",
+    /**按钮点击 */
+    ef_button_click = "ef_button_click",
+    /**红包打开 */
+    ef_redPacket_open = "ef_redPacket_open",
+    /**红包来了音效 */
+    ef_redPacket_come = "ef_redPacket_come",
+    /**消除4个 */
+    ef_bonus4 = "ef_bonus4",
+    /**消除5个 */
+    ef_bonus5 = "ef_bonus5",
+    /**消除6个 */
+    ef_bonus6 = "ef_bonus6",
+    /**消除7个 */
+    ef_bonus7 = "ef_bonus7",
+    /**消除8个 */
+    ef_bonus8 = "ef_bonus8",
+    /**普通消除音效 */
+    ef_eliminate = "ef_eliminate",
+    /**bouns消除音效 */
+    ef_eliminate_bonus = "ef_eliminate_bonus",
+    /**胜利音效 */
+    ef_win = "ef_win",
+    /**锤子 */
+    ef_change = "ef_change",
+    /**刷新 */
+    ef_refresh = "ef_refresh",
+    /**飞翔 */
+    ef_fly = "ef_fly",
+}
+
+/** ECPM */
+type ADShowCfg = {
+    average_ecpm: number,
+    insert_probability: number,
+    is_show_banner: number,
+    is_show_inter: number,
+}
+
+type PlayerInfoType = {
+    /** 自定义不需要校验的数据 */
+    gameUserData: object,
+    /** 今日是否有签到 */
+    isSignInToday: number,
+    /** 存钱罐存款 */
+    piggyBank: number,
+    /** 存钱罐能否提现 */
+    isWithdrawable: boolean,
+    /** 存钱罐每日提现次数 */
+    piggyBankCashTimes: number,
+    /** 累计存钱罐每日提现次数 */
+    totalPiggyBankCashTimes: number,
+    /** 提现进度 */
+    cashIndex: number,
+    /** 上次登录时间 */
+    lastTime: number,
+    /** 登录天数 */
+    loginDays: number,
+    newPlayer: Boolean,
+    /** 红包币数量 */
+    redMoney: number,
+    /** 累计签到次数 客户端理解 上次签到天数 */
+    signInDay: number,
+    /** 转盘次数 */
+    turntableTimes: number,
+    /** 版本号 */
+    versioncfg: string,
+    /** 福袋数据 */
+    userTuCaoInfo: object,
+}
+
+/**事件类型 */
+export enum EVENT_TYPE {
+    BACK_WxAuth = "BACK_WxAuth",
+    UPDATE_CashNum = "UPDATE_CashNum",
+}
+
+
+/** 数据事件Id */
+export enum DataEventId {
+    /** 点击 */
+    guide = "guide",
+    /** 按钮点击 */
+    button_click = "button_click",
+    /** 看视频 */
+    video_init = "video_init",
+    /** 看视频完成 */
+    video_end = "video_end",
+    /** 福袋功能 */
+    fudaiFunction = "fudaiFunction",
+    /** 互推功能 */
+    hutuiFunction = "hutuiFunction",
+    /** 关卡 */
+    level = "level",
+    /** 常规提现-红包币提现 */
+    commonWithDrawal = "commonWithDrawl",
+    /** 存钱罐提现 */
+    jarWithDrawal = "jarWithDrawal",
+    /** 签到提现 */
+    signWithDrawal = "signWithDrawal",
+}
+
+
+/** 视频广告类型 */
+export enum VideoAdType {
+    Null = "",
+    /** 关卡积分红包 */
+    LevelScoreRedBag = "关卡积分红包",
+    /** 主界面气泡红包 */
+    StartQiPaoRedBag = "主界面气泡红包",
+    /** 关卡气泡红包 */
+    LevelQiPaoRedBag = "关卡气泡红包",
+    /** 转盘 */
+    Turntable = "转盘视频",
+    /** 福袋视频" */
+    Fudai = "福袋视频",
+    /** 签到视频 */
+    Sign = "签到视频"
+}

+ 9 - 0
assets/Scripts/mk/data/GameData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "9aa2781d-b5fc-4394-ad7a-14c2511b9159",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 32 - 0
assets/Scripts/mk/data/HttpData.ts

@@ -0,0 +1,32 @@
+/**
+ * @description 服务器相关数据
+ * @author 邹勇
+ */
+export class HttpData {
+
+    /** 服务器类型 0测试服 1正式服 2李扬服 3悍国服 */
+    public serverType: number = 0;
+
+    public getServerUrl(): string {
+        switch (this.serverType) {
+            case 0:
+                return ServerUrl.test;
+            case 1:
+                return ServerUrl.formal;
+            case 2:
+                return ServerUrl.liyang;
+            case 3:
+                return ServerUrl.hanguo;
+        }
+        return ServerUrl.formal;
+    }
+
+}
+
+
+export enum ServerUrl {
+    test = 'https://cutfruitage-test.duiweize.com/', //测试服地址
+    formal = 'https://cutfruitage.duiweize.com/',    //正式服地址
+    liyang = 'http://172.16.15.231:9162/',  //李杨服地址
+    hanguo = 'http://172.16.15.167:9162/',  //悍国服地址
+}

+ 9 - 0
assets/Scripts/mk/data/HttpData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "0d6e022e-377c-47ab-af9f-9be766619afa",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 297 - 0
assets/Scripts/mk/data/LoginData.ts

@@ -0,0 +1,297 @@
+import { StorageKey } from "./StorageData";
+
+/**
+ * @description 登录数据
+ * @author 邹勇
+ */
+export class LoginData {
+
+    public loadResCompelete: boolean = false;
+
+    /** 是否登录 */
+    public isLogin: boolean = false;
+
+    public sessionKey: string = '';
+
+    public randomKey: string = "abcdefghijklopqrstuvwxyzabcdefgh";
+
+    /** 玩家唯一id */
+    public uin: string = '';
+
+    /** 玩家临时id */
+    public tempUin: string = '';
+
+    public loginTicket: string = '';
+
+    public isFirstIn: boolean;
+
+    public isNew: boolean;
+
+    /** 是否授权 */
+    public isAuth: boolean;
+
+    /** 服务协议 */
+    public rule_data: string[];
+
+    /** 隐私协议 */
+    public privacy_data: string[];
+
+    /**
+     * 初始化本地配置
+     * @returns 
+     */
+    // public async loadLocalRes() {
+    //     let result = await mk.loader.load("data/rule_data", JsonAsset);
+    //     if (result && result.json) {
+    //         this.rule_data = result.json.server;
+    //         this.privacy_data = result.json.privacy;
+    //         this.loadResCompelete = true;
+    //     }
+    // }
+
+    /**
+     * 初始化
+     */
+    public init() {
+        let uin = mk.storage.getStorage(StorageKey.uin);
+        this.uin = uin ? uin : "";
+        let sessionKey = mk.storage.getStorage(StorageKey.sessionKey);
+        this.sessionKey = sessionKey ? sessionKey : "";
+        let loginTicket = mk.storage.getStorage(StorageKey.loginTicket);
+        this.loginTicket = loginTicket ? loginTicket : "";
+
+        console.log(`===[LoginData] uin =${uin} sessionKey = ${sessionKey}"`);
+
+        this.login();
+    }
+
+    /**
+     * 登录流程 
+     * @description initApp-->initAd-->connect-->wxLogin-->checkLogin-->getAccountInfo
+     */
+    public async login() {
+        mk.console.logSingle("login...", this.sessionKey + "..." + this.uin);
+        //有登录记录直接跳转到登录流程最后一步
+        if (this.sessionKey != '' && this.uin != '' && this.loginTicket != '') {
+            console.log("=== login 有登录记录直接跳转到登录流程最后一步");
+            this.getAccountInfo();
+            return;
+        }
+        else {
+            console.log("=== login 无登录记录");
+            this.connect();
+        }
+
+    }
+
+    /**
+     * 链接 
+     * @description 获取临时的uin
+     */
+    private async connect() {
+        //connect
+        this.randomKey = mk.encrypt.randomString();
+        let data: any = {
+            "mac": gData.appData.mac,
+            "psk": this.randomKey,
+            "appId": gData.appData.appId
+        }
+
+        let response = await mk.http.sendRequest('connectTest', 'POST', JSON.stringify(data));
+        if (response.errcode != 0) {
+            return;
+        }
+        data = mk.encrypt.decrypt(response.encrypt, this.randomKey, gData.appData.appId);
+        this.tempUin = JSON.parse(data).tmp_uin;
+        mk.storage.setStorage(StorageKey.uin, this.tempUin);
+        this.wxLogin();
+    }
+
+    public async wxLogin() {
+        //wxLogin
+        let data;
+        let encode;
+        if (gData.wechatData.code != null) {
+            //微信登录
+            encode = mk.encrypt.encrypt(JSON.stringify({ "code": gData.wechatData.code }), this.sessionKey, gData.appData.appId);
+            data = {
+                "uin": this.uin,
+                "encrypt": encode
+            };
+        }
+        else {
+            //游客登录
+            encode = mk.encrypt.encrypt(JSON.stringify({ "code": '' }), this.randomKey, gData.appData.appId);
+            data = {
+                "uin": this.tempUin,
+                "encrypt": encode
+            };
+        }
+        let response = await mk.http.sendRequest('wxlogin', 'POST', JSON.stringify(data), false, false);
+        if (response.errcode != 0) {
+            if (response.errcode == -10003 || response.errcode == -20003) {
+                //清除缓存
+                this.reload();
+            }
+            return;
+        }
+        if (gData.wechatData.code != null) {
+            data = mk.encrypt.decrypt(response.encrypt, this.sessionKey, gData.appData.appId);
+        }
+        else {
+            data = mk.encrypt.decrypt(response.encrypt, this.randomKey, gData.appData.appId);
+        }
+        data = JSON.parse(data);
+        this.loginTicket = data.login_ticket;
+        mk.console.logSingle("[FC]wxLogin decrypt", data);
+        mk.storage.setStorage(StorageKey.loginTicket, this.loginTicket);
+
+        let isFirstIn = mk.storage.getStorage(StorageKey.isFirstIn);
+        if (isFirstIn == null) {
+            this.isFirstIn = true;
+            mk.storage.setStorage(StorageKey.isFirstIn, 1);
+        }
+
+        if (this.uin != data.uin) {
+            this.uin = data.uin;
+            this.isNew = false;
+        }
+        else {
+            this.isNew = true;
+        }
+        mk.storage.setStorage(StorageKey.uin, this.uin);
+        this.checkLogin();
+    }
+
+    /**
+     * 检测登录
+     * @returns 
+     */
+    private async checkLogin() {
+        //checkLogin
+        let tmp_key = '';
+        if (gData.wechatData.code != null) {
+            tmp_key = this.sessionKey;
+        }
+        else {
+            tmp_key = mk.encrypt.randomString();
+        }
+
+        let data = {
+            "tmp_key": tmp_key,
+            "uin": this.uin,
+            "login_ticket": this.loginTicket,
+            "appId": gData.appData.appId
+        }
+        let response = await mk.http.sendRequest('checklogin', 'POST', JSON.stringify(data));
+        if (response.errcode != 0) {
+            return;
+        }
+        let decryptData;
+        if (gData.wechatData.code != null) {
+            decryptData = mk.encrypt.decrypt(response.encrypt, this.sessionKey, gData.appData.appId);
+        }
+        else {
+            decryptData = mk.encrypt.decrypt(response.encrypt, tmp_key, gData.appData.appId);
+        }
+
+        let parseData = JSON.parse(decryptData);
+        this.sessionKey = parseData.session_key;
+        mk.console.logSingle("[FC]checkLogin decrypt", parseData);
+        mk.storage.setStorage(StorageKey.sessionKey, this.sessionKey);
+        this.getUserInfo();
+    }
+
+    private async getUserInfo() {
+
+        // if (gData.wechatData.code != null) {
+        //     if (this.isNew) {//玩过此游戏并且本地数据是本机的
+        //         this.getAccountInfo();
+        //     }
+        //     else {//玩过此游戏 但 本地数据不是本账户的 清空数据 重新登录游戏
+        //         this.isNew = false;
+        //         gData.wechatData.code = null;
+        //         this.reload();
+        //     }
+        // }
+        // else {
+        //     this.getAccountInfo();
+        // }
+
+        this.getAccountInfo();
+    }
+
+    private async getAccountInfo() {
+        // let nickname = mk.storage.getStorage(StorageKey.nickname);
+        // if (nickname) {
+        //     gData.wechatData.nickName = nickname;
+        // }
+        // else {
+        let aa = {
+            "uin": this.uin,
+            "login_ticket": this.loginTicket
+        };
+
+        let data: any = {
+            "uin": this.uin,
+            "encrypt": mk.encrypt.encrypt(JSON.stringify(aa), this.sessionKey, gData.appData.appId)
+        };
+
+        let response = await mk.http.sendRequest('user', 'POST', JSON.stringify(data), false, false);
+        if (response.errcode != 0) {
+            if (response.errcode == -10003 || response.errcode == -20003) {
+                //清除缓存
+                this.reload();
+            }
+            return;
+        }
+        response = mk.http.checkData(response, true);
+        data = response.data;
+        mk.console.logSingle("[FC] getAccountInfo decrypt", data);
+        this.isAuth = data.is_auth;
+        if (this.isAuth) {
+            gData.wechatData.nickName = data.nickname;
+            gData.wechatData.avatar = data.headimgurl;
+            gData.wechatData.unionid = this.uin;
+            gData.gameData.init_head = true;
+            mk.storage.setStorage(StorageKey.isAuth, 1);
+            mk.storage.setStorage(StorageKey.nickname, gData.wechatData.nickName, false);
+            mk.storage.setStorage(StorageKey.avatar, gData.wechatData.avatar, false);
+        }
+
+        // }
+
+        //获取游戏数据
+        gData.gameData.init();
+    }
+
+    /**
+     * 本地数据不是本账户的 清空数据 重新登录游戏
+     */
+    public reload() {
+        // let path = cc.sys.localStorage.getItem('HotUpdateSearchPaths');
+        // gData.storageData.clear();
+        // cc.sys.localStorage.setItem('HotUpdateSearchPaths', path);
+        setTimeout(() => {
+            this.sessionKey = '';
+            this.uin = '';
+            this.loginTicket = '';
+            this.isAuth = false;
+            this.tempUin = '';
+            this.randomKey = '';
+            gData.wechatData.nickName = '';
+            gData.wechatData.avatar = '';
+
+            cc.sys.localStorage.removeItem(StorageKey.sessionKey);
+            cc.sys.localStorage.removeItem(StorageKey.uin);
+            cc.sys.localStorage.removeItem(StorageKey.loginTicket);
+            cc.sys.localStorage.removeItem(StorageKey.isAuth);
+            cc.sys.localStorage.removeItem(StorageKey.nickname);
+            cc.sys.localStorage.removeItem(StorageKey.avatar);
+
+            cc.audioEngine.stopAll();
+            //调用Android的更好
+            cc.game.restart();
+        })
+    }
+}

+ 9 - 0
assets/Scripts/mk/data/LoginData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "f274cf29-4f33-4128-8bf8-f4ae9b318e25",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 26 - 0
assets/Scripts/mk/data/StorageData.ts

@@ -0,0 +1,26 @@
+/**
+ * @description 本地缓存
+ * @author 邹勇
+ */
+ export class StorageData {
+
+    /** 本地缓存key,必须是32位 */
+    public storageKey: string = 'mzmNr2s358irB3WQC3AmGaWMFkMx2HQs';
+
+    public clear(){
+        mk.storage.clear();
+    }
+}
+
+/**
+ * 常用的 本地缓存
+ */
+export enum StorageKey{
+    loginTicket = 'loginTicket',
+    isFirstIn = 'isFirstIn',
+    uin = 'uin',
+    sessionKey = 'sessionKey',
+    nickname = 'nickname',
+    isAuth = 'isAuth',
+    avatar = 'avatar',
+}

+ 9 - 0
assets/Scripts/mk/data/StorageData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "4cc82d47-1f2c-48e9-9fcf-f8eea30b91f3",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 12 - 0
assets/Scripts/mk/data/WechatData.ts

@@ -0,0 +1,12 @@
+/**
+ * @description 微信授权数据
+ * @author 邹勇
+ */
+export class WechatData {
+    public ifAuth: boolean = false;
+    public code: string = null;
+    public unionid: string = '123456789';
+    public nickName: string = '点我授权提现';
+    public avatar: string = '';
+    public shareSuccess = false;
+}

+ 9 - 0
assets/Scripts/mk/data/WechatData.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "f4097ed1-9d7c-447f-aa23-3d96b143b298",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 12 - 0
assets/Scripts/mk/system.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "9e191534-2590-4d0a-b2d1-5716edfbf521",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 109 - 0
assets/Scripts/mk/system/HttpSystem.ts

@@ -0,0 +1,109 @@
+/**
+ * @description http请求管理类
+ * @author 邹勇
+ */
+export default class HttpSystem {
+    constructor() {
+    }
+
+    /**
+     * 游戏接口,通用
+     * @param url 接口完整地址
+     * @param data 加密前数据
+     * @param async 是否异步请求(后端要求防阻塞)
+     */
+    public async sendData(url, data: any, async = true) {
+        let encode = '';
+        let dataN = null;
+        data.timestamp = Math.floor(new Date().getTime() / 1000);
+        data.appVersion = gData.appData.appVersion;
+        data.tfChannel = gData.appData.tfChannel;
+        data.versioncfg = gData.appData.version;
+        encode = mk.encrypt.encrypt(JSON.stringify(data), gData.loginData.sessionKey, gData.appData.appId);
+        dataN = {
+            "uin": gData.loginData.uin,
+            "encrypt": encode
+        }
+        let result = await this.sendRequest(url, 'POST', JSON.stringify(dataN), false, async);
+        return this.checkData(result);
+    }
+
+    /**
+     * http请求 登录用
+     * @param url 请求头
+     * @param method 'GET' || 'POST' 
+     * @param data 数据
+     * @param isRsa 是否加密
+     * @param async 是否异步请求
+     */
+    public sendRequest(url, method: string = 'POST', data: string = null, isRsa: boolean = true, async = true) {
+        url = gData.httpData.getServerUrl() + url;
+        return new Promise<any>((resolve: (data: any) => void, reject) => {
+            let requesttimes = 0;
+            let httpRequest = new XMLHttpRequest();
+            let send = () => {
+                httpRequest.open(method, url, async);
+                httpRequest.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');
+                if (isRsa && data != null) {
+                    data = mk.encrypt.rsaEncrypt(data);
+                }
+                httpRequest.send(data);
+            };
+
+            // httpRequest.timeout = 30000;
+            httpRequest.onreadystatechange = function () {
+                if (httpRequest.readyState === 4) {
+                    if (httpRequest.status === 200) {
+                        var responseStr = httpRequest.responseText;
+                        let response = JSON.parse(responseStr);
+                        mk.console.logSingle("response:" + url, response)
+                        resolve(response);
+                    }
+                    else {
+                        mk.console.error("httpRequest.status", httpRequest.status);
+                        reject({ errcode: 1, errmsg: "status..." + httpRequest.status });
+                    }
+                }
+            }
+
+            httpRequest.ontimeout = function (e) {
+                requesttimes++;
+                if (requesttimes >= 3) {
+                    mk.console.error("http.ontimeout", url);
+                    reject({ errcode: 1, errmsg: "ontimeout" });
+                }
+                else {
+                    send();
+                }
+            };
+            httpRequest.onerror = function (e) {
+                mk.console.error("http.onerror", url);
+                reject({ errcode: 1, errmsg: "onerror" });
+            };
+            send();
+        });
+    }
+
+    /** 
+     * 检测用明文还是密文
+     * @param response 返回消息
+     * @param forceData true 明文  false 有密文优先密文,没密文情况下用明文
+     */
+    checkData(response, forceData = false) {
+        let data = null
+        if (forceData) {
+            data = response.data;
+        }
+        else {
+            if (response.encrypt) {
+                data = mk.encrypt.decrypt(response.encrypt, gData.loginData.sessionKey, gData.appData.appId);
+                data = JSON.parse(data);
+            }
+            else if (response.data) {
+                data = response.data;
+            }
+        }
+        response.data = data;
+        return response;
+    }
+}

+ 9 - 0
assets/Scripts/mk/system/HttpSystem.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "d7405eb8-e851-4b0b-823b-0b54e943685b",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 71 - 0
assets/Scripts/mk/system/MKSystem.ts

@@ -0,0 +1,71 @@
+import { EncryptUtil } from "../util/EncryptUtil";
+import FileUtil from "../util/FileUtil";
+import GameUtil from "../util/GameUtil";
+import LoadResUtil from "../util/LoadResUtil";
+import LogUtil from "../util/LogUtil";
+import MathUtil from "../util/MathUtil";
+import StorageUtil from "../util/StorageUtil";
+import StringUtil from "../util/StringUtil";
+import TimeUtil from "../util/TimeUtil";
+import HttpSystem from "./HttpSystem";
+
+
+/**
+ * @description mk系统
+ * @author 邹勇,冯聪,薛鸿潇,kaka
+ */
+class MKSystem {
+    constructor() {
+
+    }
+
+    /** 工具 */
+    private _time: TimeUtil;
+    public get time(): TimeUtil {
+        return this._time || (this._time = new TimeUtil());
+    }
+    private _file: FileUtil;
+    public get file(): FileUtil {
+        return this._file || (this._file = new FileUtil());
+    }
+    private _encrypt: EncryptUtil;
+    public get encrypt(): EncryptUtil {
+        return this._encrypt || (this._encrypt = new EncryptUtil());
+    }
+    private _console: LogUtil;
+    public get console(): LogUtil {
+        return this._console || (this._console = new LogUtil());
+    }
+    private _game: GameUtil;
+    public get game(): GameUtil {
+        return this._game || (this._game = new GameUtil());
+    }
+    private _loader: LoadResUtil;
+    public get loader(): LoadResUtil {
+        return this._loader || (this._loader = new LoadResUtil());
+    }
+    private _storage: StorageUtil;
+    public get storage(): StorageUtil {
+        return this._storage || (this._storage = new StorageUtil());
+    }
+    private _math: MathUtil;
+    public get math(): MathUtil {
+        return this._math || (this._math = new MathUtil());
+    }
+    private _string: StringUtil;
+    public get string(): StringUtil {
+        return this._string || (this._string = new StringUtil());
+    }
+
+    private _http: HttpSystem;
+    public get http(): HttpSystem {
+        return this._http || (this._http = new HttpSystem());
+    }
+}
+
+declare global {
+    /** 牛逼的梦嘉引擎 */
+    const mk: MKSystem;
+}
+window['mk'] = new MKSystem();
+

+ 9 - 0
assets/Scripts/mk/system/MKSystem.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "e1d0b58f-49aa-4c7c-869b-c18282bd7cb5",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 12 - 0
assets/Scripts/mk/util.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "8f355401-46c9-46af-b8db-ea16e5498da3",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 325 - 0
assets/Scripts/mk/util/EncryptUtil.ts

@@ -0,0 +1,325 @@
+import { hmacSha256 } from "./encrypt/hmacSha256";
+import * as CryptoJS from "./encrypt/rsa/crypto-js";
+
+
+/**
+ * 加密解密工具类
+ * @author 邹勇
+ */
+export class EncryptUtil {
+
+    /**
+     * 随机生成多位字符串
+     * @param   len    字符串长度
+     * @returns 
+     */
+    public randomString(len = 32) {
+        let $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoprstuvwxyz123456789';
+        let maxPos = $chars.length;
+        let pwd = '';
+        for (let i = 0; i < len; i++) {
+            pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
+        }
+        return pwd;
+    }
+
+    //说明:
+    //  1.如果加密解密涉及到前端和后端,则这里的key要保持和后端的key一致
+    //  2.AES的算法模式有好几种(ECB,CBC,CFB,OFB),所以也要和后端保持一致
+    //  3.AES的补码方式有两种(PKS5,PKS7),所以也要和后端保持一致
+    //  4.AES的密钥长度有三种(128,192,256,默认是128),所以也要和后端保持一致
+    //  5.AES的加密结果编码方式有两种(base64和十六进制),具体怎么选择由自己定,但是加密和解密的编码方式要统一
+    //十六位十六进制数作为秘钥
+    // private public key = fun_aes.CryptoJS.enc.Utf8.parse("3454345434543454");
+    //十六位十六进制数作为秘钥偏移量
+    // private public iv = fun_aes.CryptoJS.enc.Utf8.parse('6666666666666666');
+
+    /**
+     * 说明:
+     * 1.如果加密解密涉及到前端和后端,则这里的key要保持和后端的key一致
+     * 2.AES的算法模式有好几种(ECB,CBC,CFB,OFB),所以也要和后端保持一致
+     * 3.AES的补码方式有两种(PKS5,PKS7),所以也要和后端保持一致
+     * 4.AES的密钥长度有三种(128,192,256,默认是128),所以也要和后端保持一致
+     * 5.AES的加密结果编码方式有两种(base64和十六进制),具体怎么选择由自己定,但是加密和解密的编码方式要统一
+     * 十六位十六进制数作为秘钥
+     * private public key = fun_aes.CryptoJS.enc.Utf8.parse("3454345434543454");
+     * 十六位十六进制数作为秘钥偏移量
+     * private public iv = fun_aes.CryptoJS.enc.Utf8.parse('6666666666666666');
+     * 
+     * aes加密
+     * @param   word    需要加密的字符串
+     * @param   tkey    !!!加密key,32位字符串,一般为sessionkey
+     * @param   appid   游戏的appid
+     * @param   state   true 存包长 false /r/n
+     * @returns 
+    */
+    public encrypt(word, tkey, appid, state = true) {
+        let tiv = tkey.substr(0, 16);
+
+        //明文拼接
+        let newStr = '';
+        if (state) {
+            newStr = tiv + word + appid;
+        }
+        else {
+            newStr = tiv + word + '\r\n' + appid;
+        }
+
+        //加密后
+        let key = CryptoJS.enc.Utf8.parse(tkey);
+        let iv = CryptoJS.enc.Utf8.parse(tiv);
+
+        newStr = CryptoJS.enc.Utf8.parse(newStr);
+        let encrypted = CryptoJS.AES.encrypt(newStr, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
+        let encryptedStr = encrypted.toString();
+        let mac = hmacSha256.Instance.hex_hmac_sha256(tkey, encryptedStr);
+        return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(tiv + encryptedStr + mac));
+    }
+
+    /**
+     * aes解密
+     * @param   word    需要加密的字符串
+     * @param   tkey    加密key,一般为sessionkey
+     * @param   appid   游戏的appid
+     * @param   state   true 存包长 false /r/n
+     * @returns 
+     */
+    public decrypt(word, tkey, appid, state = true) {
+        let en = CryptoJS.enc.Base64.parse(word).toString(CryptoJS.enc.Utf8);
+        let newStrOne = en.substr(16);
+        let temp = newStrOne.substr(0, newStrOne.length - 64);
+        let de = temp;
+
+        let key = CryptoJS.enc.Utf8.parse(tkey);
+        let iv = CryptoJS.enc.Utf8.parse(tkey.substr(0, 16));
+
+        let decrypt = CryptoJS.AES.decrypt(de, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
+        let decryptedStr = CryptoJS.enc.Utf8.stringify(decrypt);
+        decryptedStr = decryptedStr.toString();
+
+        let newStrThree = '';
+        if (state) {
+            newStrThree = decryptedStr.slice(16).replace(new RegExp("(.*)" + appid), '$1');
+        }
+        else {
+            newStrThree = decryptedStr.slice(16).split('\r\n')[0];
+        }
+        return newStrThree;
+    }
+
+    private options = {
+        default_key_size: 2048,
+        default_public_exponent: new Uint8Array([0x01, 0x00, 0x01])
+    }
+    /**
+     * rsa加密
+     * @param   word        需要加密的字符串
+     * @param   isLong      字符串加长版
+     * @returns 
+     */
+    public rsaEncrypt(word, isLong: boolean = false) {
+        let jsb = new window['JSEncrypt'](this.options);
+
+        //公钥
+        let publicString = '-----BEGIN PUBLIC KEY-----\n' +
+            'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuwz5V8wt525dMS+A9wOd\n' +
+            'NAjvKgxdyoXYuZSlAJEXLhvJlaXwFCKEsUg/qBBeo4nrRnwaFAjG7ItqbCWR9Ozv\n' +
+            '6oY5tMYQnFFK82XkMGbKm1gG0z9vYKhcNYgHZHi+QKAw4tLLWXWO/QBTGelEXptD\n' +
+            'azlNmdM+8wHOknTcMuIyjc9Yo5qCoNsCJpA465vnREiBezBbKB3rSw+LmrRcZcFk\n' +
+            's8hmGtjpabcQ8sCxco7mRzVh6/DomNWfNm7hUP6shrrJirwjQtaS51grlScj8KhN\n' +
+            'h+kBoiI4Ad0Xz0GHasK5hAMf3sXDsN61r0An8KTfa/nsYSJDwogPIKkeKAsmw9Df\n' +
+            'EQIDAQAB\n' +
+            '-----END PUBLIC KEY-----'
+        jsb.setPublicKey(publicString);
+        // 加密内容
+        let encrypted = isLong ? jsb.encryptLong(word) : jsb.encrypt(word);
+        return encrypted;
+    }
+
+    /**
+     * for php pack( N , length )
+     * @param   len    
+     * @returns 
+     */
+    public pack(len: number) {
+        let buf: ArrayBuffer = new ArrayBuffer(4);
+        let dataView = new DataView(buf);
+        dataView.setUint32(0, len);
+        let str2 = this.ab2str(buf);
+        return str2;
+    }
+
+    /**
+     * 
+     * @param array 
+     * @returns 
+     */
+    public utf8ArrayToStr(array) {
+        let out, i, len, c;
+        let char2, char3;
+
+        out = "";
+        len = array.length;
+        i = 0;
+        while (i < len) {
+            c = array[i++];
+            switch (c >> 4) {
+                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
+                    // 0xxxxxxx
+                    out += String.fromCharCode(c);
+                    break;
+                case 12: case 13:
+                    // 110x xxxx   10xx xxxx
+                    char2 = array[i++];
+                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
+                    break;
+                case 14:
+                    // 1110 xxxx  10xx xxxx  10xx xxxx
+                    char2 = array[i++];
+                    char3 = array[i++];
+                    out += String.fromCharCode(((c & 0x0F) << 12) |
+                        ((char2 & 0x3F) << 6) |
+                        ((char3 & 0x3F) << 0));
+                    break;
+            }
+        }
+
+        return out;
+    }
+
+    /**
+     * UTF-16转UTF-8
+     * @param   s 
+     * @returns 
+     */
+    public utf16ToUtf8(s) {
+        if (!s) {
+            return;
+        }
+
+        let i, code, ret = [], len = s.length;
+        for (i = 0; i < len; i++) {
+            code = s.charCodeAt(i);
+            if (code > 0x0 && code <= 0x7f) {
+                //单字节
+                //UTF-16 0000 - 007F
+                //UTF-8  0xxxxxxx
+                ret.push(s.charAt(i));
+            } else if (code >= 0x80 && code <= 0x7ff) {
+                //双字节
+                //UTF-16 0080 - 07FF
+                //UTF-8  110xxxxx 10xxxxxx
+                ret.push(
+                    //110xxxxx
+                    String.fromCharCode(0xc0 | ((code >> 6) & 0x1f)),
+                    //10xxxxxx
+                    String.fromCharCode(0x80 | (code & 0x3f))
+                );
+            } else if (code >= 0x800 && code <= 0xffff) {
+                //三字节
+                //UTF-16 0800 - FFFF
+                //UTF-8  1110xxxx 10xxxxxx 10xxxxxx
+                ret.push(
+                    //1110xxxx
+                    String.fromCharCode(0xe0 | ((code >> 12) & 0xf)),
+                    //10xxxxxx
+                    String.fromCharCode(0x80 | ((code >> 6) & 0x3f)),
+                    //10xxxxxx
+                    String.fromCharCode(0x80 | (code & 0x3f))
+                );
+            }
+        }
+
+        return ret.join('');
+    }
+
+    /**
+     * UTF-8转UTF-16
+     * @param s 
+     * @returns 
+     */
+    public utf8ToUtf16(s) {
+        if (!s) {
+            return;
+        }
+
+        let i, codes, bytes, ret = [], len = s.length;
+        for (i = 0; i < len; i++) {
+            codes = [];
+            codes.push(s.charCodeAt(i));
+            if (((codes[0] >> 7) & 0xff) == 0x0) {
+                //单字节  0xxxxxxx
+                ret.push(s.charAt(i));
+            } else if (((codes[0] >> 5) & 0xff) == 0x6) {
+                //双字节  110xxxxx 10xxxxxx
+                codes.push(s.charCodeAt(++i));
+                bytes = [];
+                bytes.push(codes[0] & 0x1f);
+                bytes.push(codes[1] & 0x3f);
+                ret.push(String.fromCharCode((bytes[0] << 6) | bytes[1]));
+            } else if (((codes[0] >> 4) & 0xff) == 0xe) {
+                //三字节  1110xxxx 10xxxxxx 10xxxxxx
+                codes.push(s.charCodeAt(++i));
+                codes.push(s.charCodeAt(++i));
+                bytes = [];
+                bytes.push((codes[0] << 4) | ((codes[1] >> 2) & 0xf));
+                bytes.push(((codes[1] & 0x3) << 6) | (codes[2] & 0x3f));
+                ret.push(String.fromCharCode((bytes[0] << 8) | bytes[1]));
+            }
+        }
+        return ret.join('');
+    }
+
+    /**
+     * ArrayBuffer转为字符串,参数为ArrayBuffer对象
+     * @param buf 
+     * @returns 
+     */
+    public ab2str(buf: ArrayBuffer) {
+        return String.fromCharCode.apply(null, new Uint8Array(buf));
+    }
+
+    /**
+     * 
+     * @param fileData 
+     * @returns 
+     */
+    public uint8ArrayToString(fileData) {
+        let dataString = "";
+        for (let i = 0; i < fileData.length; i++) {
+            dataString += String.fromCharCode(fileData[i]);
+        }
+
+        return dataString
+    }
+
+    /**
+     * 
+     * @param str 
+     * @returns 
+     */
+    public stringToUint8Array(str) {
+        let arr = [];
+        for (let i = 0, j = str.length; i < j; ++i) {
+            arr.push(str.charCodeAt(i));
+        }
+
+        let tmpUint8Array = new Uint8Array(arr);
+        return tmpUint8Array
+    }
+
+    /**
+     * 字符串转为ArrayBuffer对象,参数为字符串
+     * @param str 
+     * @returns 
+     */
+    public str2ab(str) {
+        let buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
+        let bufView = new Uint8Array(buf);
+        for (let i = 0, strLen = str.length; i < strLen; i++) {
+            bufView[i] = str.charCodeAt(i);
+        }
+        return buf;
+    }
+
+}

+ 9 - 0
assets/Scripts/mk/util/EncryptUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "eca52add-bfd5-4e36-b9d7-7db55982a480",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 114 - 0
assets/Scripts/mk/util/FileUtil.ts

@@ -0,0 +1,114 @@
+
+/**
+ * 文件操作工具类
+ * @author 薛鸿潇
+ */
+export default class FileUtil {
+
+    /**
+     * 打开文件选择器
+     * @param {string} accept
+     * @param {(file: File) => void} callback
+     * @memberof FileUtil
+     */
+    public openLocalFile(accept: string, callback: (file: File) => void) {
+        let inputEl: HTMLInputElement = <HTMLInputElement>document.getElementById('file_input');
+        if (!inputEl) {
+            inputEl = document.createElement('input');
+            inputEl.id = 'file_input';
+            inputEl.setAttribute('id', 'file_input');
+            inputEl.setAttribute('type', 'file');
+            inputEl.setAttribute('class', 'fileToUpload');
+            inputEl.style.opacity = '0';
+            inputEl.style.position = 'absolute';
+            inputEl.setAttribute('left', '-999px');
+            document.body.appendChild(inputEl);
+        }
+
+        accept = accept || ".*";
+        inputEl.setAttribute('accept', accept);
+
+        inputEl.onchange = (event) => {
+            let files = inputEl.files
+            if (files && files.length > 0) {
+                var file = files[0];
+                if (callback) callback(file);
+            }
+        }
+        inputEl.click();
+    }
+
+    /**
+     * 读取本地文件数据
+     * @param {File} file
+     * @param {READ_FILE_TYPE} readType
+     * @param {((result: string | ArrayBuffer) => void)} callback
+     * @memberof FileUtil
+     */
+    public readLocalFile(file: File, readType: READ_FILE_TYPE, callback: (result: string | ArrayBuffer) => void) {
+        var reader = new FileReader();
+        reader.onload = function (event) {
+            if (callback) {
+                if (reader.readyState == FileReader.DONE) {
+                    callback(reader.result);
+                } else {
+                    callback(null);
+                }
+            }
+        };
+        switch (readType) {
+            case READ_FILE_TYPE.DATA_URL:
+                reader.readAsDataURL(file);
+                break;
+            case READ_FILE_TYPE.TEXT:
+                reader.readAsText(file);// 作为字符串读出
+                break;
+            case READ_FILE_TYPE.BINARY:
+                reader.readAsBinaryString(file);
+                break;
+            case READ_FILE_TYPE.ARRAYBUFFER:
+                reader.readAsArrayBuffer(file);
+                break;
+        }
+    }
+
+    /**
+     * 保存数据到本地
+     * @param {*} fileNameToSaveAs 要保存的文件名
+     * @param {*} textToWrite 要保存的文件内容
+     * @memberof FileUtil
+     */
+    public saveForBrowser(fileNameToSaveAs: any, textToWrite: any) {
+        if (cc.sys.isBrowser) {
+            console.log("浏览器");
+            let textFileAsBlob = new Blob([textToWrite], { type: 'application/json' });
+            let downloadLink = document.createElement("a");
+            downloadLink.download = fileNameToSaveAs;
+            downloadLink.innerHTML = "Download File";
+            if (window.webkitURL != null) {
+                // Chrome allows the link to be clicked            
+                // without actually adding it to the DOM.            
+                downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
+            } else {
+                // Firefox requires the link to be added to the DOM            
+                // before it can be clicked.            
+                downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
+                // downloadLink.onclick = destroyClickedElement;            
+                downloadLink.style.display = "none";
+                document.body.appendChild(downloadLink);
+            }
+
+            downloadLink.click();
+        }
+    }
+
+}
+/**
+ * 读取文件方式
+ */
+enum READ_FILE_TYPE {
+    DATA_URL,// readAsDataURL, base64
+    TEXT,// readAsText
+    BINARY,// readAsBinaryString
+    ARRAYBUFFER,// readAsArrayBuffer
+}

+ 9 - 0
assets/Scripts/mk/util/FileUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "d269f103-028b-42ba-92e8-9360bde1fcee",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 81 - 0
assets/Scripts/mk/util/GameUtil.ts

@@ -0,0 +1,81 @@
+
+/**
+ * 游戏工具类
+ * @description 依据引擎Api的工具类,用于操作引擎相关系统的开关、操作引擎相关的api属性,比如坐标
+ * @author 冯聪
+ */
+export default class GameUtil {
+
+    /** 获取屏幕尺寸 */
+    public getWinSize(): cc.Size {
+        return cc.winSize;
+    }
+
+    /** 激活物理系统 */
+    public enablePhysics() {
+        cc.director.getPhysicsManager().enabled = true;
+    }
+
+    /** 绘制物理信息 */
+    public debugDrawPhysicsFlag(ifDraw: boolean = false) {
+        if (ifDraw) {
+            cc.director.getPhysicsManager().debugDrawFlags =
+                cc.PhysicsManager.DrawBits.e_aabbBit |
+                cc.PhysicsManager.DrawBits.e_jointBit |
+                cc.PhysicsManager.DrawBits.e_shapeBit;
+        }
+        else {
+            cc.director.getPhysicsManager().debugDrawFlags = 0;
+        }
+    }
+
+    private btnTimeDic: Object;
+    /**给按钮做连续点击检测
+     * @param btn 点击的按钮
+     * @param delay 按钮连续点击间隔,delay间隔内不能连续点击
+     * @return true 可以点击
+     */
+	public checkContinuousClick(btn:cc.Node, delay: number = 1): boolean {
+		if (this.btnTimeDic == null) {
+			this.btnTimeDic = {};
+		}
+		let key = (btn as any)._id;
+		let last: number = this.btnTimeDic[key];
+		let now: number = new Date().getTime();
+		var b = last == null || now - last > delay * 1000;
+		if (b) {
+			this.btnTimeDic[key] = now;
+		}
+		return b;
+	}
+
+    /**
+     * 获取世界坐标
+     * @param 需要获取的节点
+     */
+    public getWorldPos(node: cc.Node): cc.Vec2 {
+        let originX = node.x;
+        let originY = node.y;
+        let curNode = node;
+
+        while (curNode.parent) {
+            let parent = curNode.parent;
+            if (parent.name == 'Canvas') {
+                break;
+            }
+            originX += parent.x;
+            originY += parent.y;
+            curNode = parent;
+        }
+        return new cc.Vec2(originX, originY);
+    }
+
+    /** node的坐标改为全局坐标 中间为原点 */
+    public localConvertWorldPointARCenter(node: cc.Node) {
+        let o1 = cc.view.getVisibleSize();
+        let o2 = node.convertToWorldSpaceAR(cc.v2(0, 0));
+        o2.x = o2.x - o1.width / 2;
+        o2.y = o2.y - o1.height / 2;
+        return o2;
+    }
+}

+ 9 - 0
assets/Scripts/mk/util/GameUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "35053b24-2156-41d1-a771-59a8bf6d93cc",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 190 - 0
assets/Scripts/mk/util/LoadResUtil.ts

@@ -0,0 +1,190 @@
+
+/**
+ * 加载资源工具类
+ * @description 
+ * @author 冯聪
+ */
+export default class LoadResUtil {
+
+    /**
+     * 日志标签
+     * @description 
+     */
+    private static _logTag = "[LoadResUtil]";
+
+    /**
+     * 预加载本地资源 
+     * @description   https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param  paths  加载路径
+     * @param  type   资源类型(cc.Asset)
+     * @returns Promise
+     */
+    public preload(paths: string | any, type: typeof cc.Asset): Promise<any> {
+        return new Promise<cc.AssetManager.RequestItem[]>((resolve: (data: cc.AssetManager.RequestItem[]) => void, reject) => {
+            cc.resources.preload(paths, type,
+                //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                //onComplete
+                (err: Error = null, data: cc.AssetManager.RequestItem[]): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 加载本地资源 
+     * @description   https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param  paths  加载路径
+     * @param  type   资源类型(cc.Asset)
+     * @returns Promise
+     */
+    public load<T extends cc.Asset>(paths: string | any, type: typeof cc.Asset): Promise<any> {
+        return new Promise<T>((resolve: (data: T) => void, reject) => {
+            cc.resources.load(paths, type,
+                //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                //onComplete
+                (err: Error = null, data: T): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 预加载文件夹资源 
+     * @description   https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param   dir   文件夹路径
+     * @param   type  资源类型(cc.Asset)
+     * @returns Promise
+     */
+    public preloadDir(dir: string, type: typeof cc.Asset): Promise<any> {
+        return new Promise<cc.AssetManager.RequestItem[]>((resolve: (data: cc.AssetManager.RequestItem[]) => void, reject) => {
+            cc.resources.preloadDir(dir, type,  //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                (err: Error = null, data: cc.AssetManager.RequestItem[]): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 加载文件夹资源 
+     * @description   https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param   dir   文件夹路径
+     * @param   type  资源类型(cc.Asset)
+     * @returns Promise
+     */
+    public loadDir<T extends cc.Asset>(dir: string, type: typeof cc.Asset): Promise<any> {
+        return new Promise<T>((resolve: (data: T) => void, reject) => {
+            cc.resources.loadDir(dir, type,
+                //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                //onComplete
+                (err: Error = null, data: T | any): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 加载远程资源 
+     * @description      https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param   url      加载路径
+     * @param   options  
+     * @returns Promise
+     */
+    public loadRemote<T extends cc.Asset>(url: string, options: Record<string, any>): Promise<any> {
+        return new Promise<T>((resolve: (data: T) => void, reject) => {
+            cc.assetManager.loadRemote(url, options,
+                //onComplete
+                (err: Error = null, data: T): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 预加载场景 
+     * @description     https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param   url     加载路径
+     * @param   options  
+     * @returns Promise
+     */
+    public preloadScene(sceneName: string, options: Record<string, any>) {
+        return new Promise<void>((resolve: () => void, reject) => {
+            cc.resources.preloadScene(sceneName, options,
+                //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                //onComplete
+                (err: Error = null): void => {
+                    if (!err) {
+                        resolve();
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+
+    /**
+     * 加载场景 
+     * @description     https://docs.cocos.com/creator/manual/zh/release-notes/subpackage-upgrade-guide.html
+     * @param   url     加载路径
+     * @param   options 
+     * @returns Promise
+     */
+    public loadScene(sceneName: string, options: Record<string, any>): Promise<any> {
+        return new Promise<any>((resolve: (data: any) => void, reject) => {
+            cc.resources.loadScene(sceneName, options,
+                //onProgress
+                (finish: number, total: number, item: cc.AssetManager.RequestItem) => {
+
+                },
+                //onComplete
+                (err: Error = null, data: cc.SceneAsset): void => {
+                    if (!err) {
+                        resolve(data);
+                    }
+                    else {
+                        reject(err);
+                    }
+                });
+        });
+    }
+}

+ 9 - 0
assets/Scripts/mk/util/LoadResUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "7a7cd764-b07b-4a0d-a0fb-5547d08e489d",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 180 - 0
assets/Scripts/mk/util/LogUtil.ts

@@ -0,0 +1,180 @@
+/**
+ * 日志打印工具类
+ * @description 
+ * @author 冯聪
+ */
+export default class LogUtil {
+
+    /**
+     * 是否显示Log
+     * @description
+     */
+    public ifShowLog: boolean = true;
+
+    /**
+     * 标签符号
+     * @description 标签与打印内容之间的拼接符号
+     */
+    private _tagChar: string = "...";
+
+    /**
+     * 标签符号
+     * @description 标签与打印内容之间的拼接符号
+     */
+    private _frontChar: string = "    ";
+
+    /**
+     * 对象key&value间隔符号
+     * @description 打印对象时,key与value之间的拼接符号
+     */
+    private _keyValueChar: string = " = ";
+
+    /**
+     * 打印普通日志
+     * @description
+     * @param  tag  日志标签(用于标识日志)
+     * @param  data 日志内容
+     */
+    public log(tag: string, ...data: any[]) {
+        if (!this.ifShowLog) {
+            return;
+        }
+        let totalTag = tag + this._tagChar;
+        console.log(totalTag, ...data);
+    }
+
+    /**
+     * 打印普通日志
+     * @description
+     * @param  tag  日志标签(用于标识日志)
+     * @param  data 日志内容
+     */
+    public logWithColor(tag: string, ...data: any[]) {
+        if (!this.ifShowLog) {
+            return;
+        }
+        let totalTag = tag + this._tagChar;
+        console.log("%c " + totalTag, "color: " + LogTagColor.skyblue, ...data);
+    }
+
+    /**
+     * 打印警告日志
+     * @description
+     * @param  tag   日志标签(用于标识日志)
+     * @param  data  日志内容
+     */
+    public warn(tag: string, ...data: any[]) {
+        if (!this.ifShowLog) {
+            return;
+        }
+        let totalTag = tag + this._tagChar;
+        console.warn("%c " + totalTag, "color: " + LogTagColor.orange, ...data);
+    }
+
+    /**
+     * 打印错误日志
+     * @description
+     * @param  tag   日志标签(用于标识日志)
+     * @param  data  日志内容
+     */
+    public error(tag: string, ...data: any[]) {
+        if (!this.ifShowLog) {
+            return;
+        }
+        let totalTag = tag + this._tagChar;
+        console.warn("%c " + totalTag, "color: " + LogTagColor.red, ...data);
+    }
+
+    /**
+     * 打印单个对象日志
+     * @description        逐个分层打印所有对象的key,value值
+     * @param tag          日志标签(用于标识日志)
+     * @param obj          日志对象
+     * @param frontStrNum  前缀字符数量(不用填)
+     * @returns 
+     */
+    public logSingle(tag: string, obj: any, frontStrNum: number = 0) {
+        if (cc.sys.os != cc.sys.OS_ANDROID) {
+            this.log(tag, obj);
+            return;
+        }
+        if (!this.ifShowLog) {
+            return;
+        }
+
+        if (obj == null || obj == undefined) {
+            return
+        }
+
+        if (typeof obj === "number" || typeof obj === "string" || typeof obj === "boolean") {
+            this.log(`${this.getFrontStr(frontStrNum)}${tag}`, obj);
+        } else {
+            let objKeys = Object.keys(obj);
+            for (const key of objKeys) {
+                if (obj.hasOwnProperty(key)) {
+                    let index = objKeys.indexOf(key);
+                    if (typeof obj[key] === "object") {
+                        this.log(`${this.getFrontStr(frontStrNum)}`, key, ": ")
+                        this.logSingle(tag, obj[key], frontStrNum + 1)
+                    } else {
+                        if (!frontStrNum && index === 0) {
+                            this.log(`${this.getFrontStr(frontStrNum)}${tag}\n`, key, this._keyValueChar, obj[key]);
+                        }
+                        else {
+                            this.log(`${this.getFrontStr(frontStrNum)}`, key, this._keyValueChar, obj[key]);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * 把日志内容拼接成字符串
+     * @param data 
+     * @returns 
+     */
+    public getMessage(...data: any[]) {
+        let message = "";
+        for (var i = 0; i < data.length; i++) {
+            let str = data[i];
+            let str_new = "";
+            //屏蔽逗号
+            for (var j = 0; j < str.length; j++) {
+                let char: string = str[j];
+                str_new += char;
+            }
+            message += str_new;
+        }
+        return message;
+    }
+
+    /**
+     * 获取前缀字符串
+     * @description         根据前缀字符串数目生成前缀字符串,用以标记层级
+     * @param  frontStrNum  字符串数量
+     * @returns             返回前缀字符串(string)
+     */
+    public getFrontStr(frontStrNum: number): string {
+        let str = "";
+        if (frontStrNum > 0) {
+            for (let i = 0; i < frontStrNum; i++) {
+                str += this._frontChar;
+            }
+            return str;
+        }
+        return str;
+    }
+}
+
+/** 日志字体颜色 */
+export enum LogTagColor {
+    red = "red;font-weight:bold",
+    white = "white;font-weight:bold",
+    yellow = "yellow;font-weight:bold",
+    green = "green;font-weight:bold",
+    bule = "blue;font-weight:bold",
+    skyblue = "#3DB2EF;font-weight:bold",
+    orange = "orange;font-weight:bold",
+    black = "black;font-weight:bold"
+}

+ 9 - 0
assets/Scripts/mk/util/LogUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "cbc3aac1-4c54-45dc-a4cf-dbaa82ab1b47",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 265 - 0
assets/Scripts/mk/util/MathUtil.ts

@@ -0,0 +1,265 @@
+
+/**
+ * 数学计算工具类
+ * @author 冯聪
+ */
+export default class MathUtil {
+
+    /** 计算两点之间距离 */
+    dis(x1, y1, x2, y2): number {
+        return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
+    }
+
+    /**
+    * 取一个区间内随机整数
+    * @param n 开始位置
+    * @param m 结束位置
+    * @param ifInt 是否是整数
+    * @returns 返回的随机整数
+    */
+    public random(n: number, m: number, ifInt: boolean = true): number {
+        let random: number = n;
+        if (ifInt) {
+            random = Math.floor(Math.random() * (m - n + 1) + n);
+        }
+        else {
+            random = Math.random() * (m - n) + n;
+        }
+        return random;
+    }
+
+    /**
+     * 根据权重随机
+     * @param weights 权重数组
+     * @param total 权重总值 默认100
+     * @param asc 权重为降序排列
+     * @returns 
+     */
+    public randomByWeight(weights: number[], total = 100, asc: boolean = true): number {
+        if (total != 100) {
+            total = 0;
+            for (let i = 0; i < weights.length; i++) {
+                total += weights[i];
+            }
+        }
+        let random = Math.random() * total;
+        let arr = weights.concat(random);
+        arr = arr.sort((a, b) => {
+            return asc ? a - b : b - a;
+        });
+
+        var randomIndex = arr.indexOf(random);
+        randomIndex = Math.min(randomIndex, weights.length - 1);
+        return randomIndex;
+    }
+
+    //---------------------------------------------------------科学计数法-----------------------------------------------------
+    /**数字单位 */
+    private numUnit = { 4: "万", 8: "亿", 12: "兆", 16: "万兆", 20: "亿兆", 24: "兆兆", 28: "万兆兆", 32: "亿兆兆", 36: "兆兆兆" };
+
+    /**
+     * 超大数值加法运算  忽略小数部分
+     * @param a
+     * @param b
+     */
+    public addition(a: string, b: string): string {
+        var res: any = '',
+            temp: any = 0;
+        let a1 = a.split('.')[0].split('');
+        let b1 = b.split('.')[0].split('');
+        while (a1.length || b1.length || temp) {
+            temp += ~~a1.pop() + ~~b1.pop();
+            res = (temp % 10) + res;
+            temp = temp > 9;
+        }
+        return res.replace(/^0+/, '');
+    }
+
+    /**
+     * 超大数值减法运算  忽略小数部分
+     * @param a
+     * @param b
+     */
+    public subtraction(a: any, b: any): string {
+        a = a.split('.')[0].split('');
+        b = b.split('.')[0].split('');
+        var aMaxb = a.length > b.length;
+        if (a.length == b.length) {
+            for (var i = 0, len = a.length; i < len; i++) {
+                if (a[i] == b[i]) continue;
+                aMaxb = a[i] > b[i];
+                break;
+            }
+        }
+        if (!aMaxb) a = [b, b = a][0];
+        var result = '';
+        while (a.length) {
+            var temp = parseInt(a.pop()) - parseInt(b.pop() || 0);
+            if (temp >= 0) result = temp + result;
+            else {
+                result = temp + 10 + result;
+                a[a.length - 1]--;
+            }
+        }
+        result = (aMaxb ? '' : '-') + result.replace(/^0*/g, '');
+        if (result == '-') {
+            result = '0'
+        }
+
+        return result
+    }
+
+    /**
+     * 超大数值高位对比  忽略小数部分
+     * @param a
+     * @param b
+     */
+    public contrastNumber(a: any, b: any): boolean {
+        a = a.split('.')[0].split('');
+        b = b.split('.')[0].split('');
+        var aMaxb = a.length > b.length;
+        if (a.length == b.length) {
+            for (var i = 0, len = a.length; i < len; i++) {
+                if (a[i] == b[i]) continue;
+                aMaxb = a[i] > b[i];
+                break;
+            }
+        }
+        if (!aMaxb) a = [b, b = a][0];
+        var result = '';
+        while (a.length) {
+            var temp = parseInt(a.pop()) - parseInt(b.pop() || 0);
+            if (temp >= 0) result = temp + result;
+            else {
+                result = temp + 10 + result;
+                a[a.length - 1]--;
+            }
+        }
+        if (a === b) return true;
+        return Boolean(aMaxb);
+    }
+
+    /**
+     * 数值乘法
+     * @param a 
+     * @param b
+     */
+    public accMuls(a, b): string {
+        let arra = a.split('').reverse(),
+            arrb = b.split('').reverse(),
+            lena = arra.length,
+            lenb = arrb.length,
+            result: any = Array(lena + lenb + 1).join('0').split('');
+        arra.map((itema, indexa) => {
+            arrb.map((itemb, indexb) => {
+                result[indexa + indexb] = +result[indexa + indexb] + itema * itemb;
+            });
+        });
+        result.map((item, index) => {
+            if (item >= 10) {
+                result[index + 1] = ~~result[index + 1] + ~~(result[index] / 10);
+                result[index] %= 10;
+            }
+        });
+        return result.reverse().join('').replace(/^0+/, '');
+    }
+
+    /**
+     * 超大数值乘法
+     * @param arg1
+     * @param arg2
+     */
+    public accMul(arg1: string, arg2: string): string {
+        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
+        try { m += s1.split(".")[1].length } catch (e) { }
+        try { m += s2.split(".")[1].length } catch (e) { }
+        let targe = this.accMuls(s1.replace(".", ""), s2.replace(".", ""));
+
+        return this.accDiv(targe, Math.pow(10, m).toString())
+    }
+
+    /** 科学技术法转为数值字符串形式 */
+    public toNonExponential(num: number): string {
+        return num.toLocaleString().replace(/[,]/g, '')
+    }
+
+    /**
+     * 超大数值除法运算
+     * @param arg1
+     * @param arg2
+     */
+    public accDiv(arg1: string, arg2: string): string {
+
+        var t1 = 0, t2 = 0, t3 = 0, r1, r2;
+
+        try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
+
+        try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
+
+        r1 = Number(arg1.toString().replace(".", ""))
+
+        r2 = Number(arg2.toString().replace(".", ""))
+
+        if (r2 == 0)
+            return '0';
+
+        var result = String(r1 / r2);
+
+        try { t3 = result.toString().split(".")[1].length } catch (e) { }
+
+        var index = t2 - t1 - t3;
+
+        if (index < 0) {
+            result = result.replace(".", "");
+
+            while (result.length <= Math.abs(index)) {
+                result = '0' + result;
+            }
+
+            var start = result.substring(0, result.length + index);
+            var end = result.substring(result.length + index, result.length);
+
+            result = start + '.' + end;
+
+            return this.toNonExponential(Number(result));
+        }
+        else if (index > 0) {
+            result = result.replace(".", "");
+
+            while (result.length <= Math.abs(index)) {
+                result += '0';
+            }
+            return this.toNonExponential(Number(result));
+        }
+        else return this.toNonExponential(Number(result.replace(".", "")));
+    }
+
+    /**
+     * 数值格式化
+     * @param value
+     * @param showDeci
+     */
+    public format(value: string, showDeci: boolean = true): string {
+        var a = value.split('.')[0];
+        var b;
+        for (let i in this.numUnit) {
+            let ii = Number(i);
+            if (a.length - 1 >= ii) {
+                if (showDeci) {
+                    let deci = a.slice(a.length - ii, a.length - ii + 1)
+                    if (Number(deci) >= 1) {
+                        b = a.slice(0, a.length - ii) + "." + deci + this.numUnit[ii];
+                    }
+                    else {
+                        b = a.slice(0, a.length - ii) + this.numUnit[ii];
+                    }
+                }
+                else {
+                    b = a.slice(0, a.length - ii) + this.numUnit[ii];
+                }
+            }
+        };
+        if (!b) return a;
+        return b;
+    }
+}

+ 9 - 0
assets/Scripts/mk/util/MathUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "e055a573-1dbc-4eb1-bc0b-dd1851178edf",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 56 - 0
assets/Scripts/mk/util/StorageUtil.ts

@@ -0,0 +1,56 @@
+/**
+ * 本地存储工具类 
+ * @author 冯聪
+ */
+export default class StorageUtil {
+
+    /**
+     * 获取存储
+     * @param   key         key值
+     * @param   decrypt     是否需要解密
+     */
+    public getStorage(key: string, decrypt = true): any {
+        let value = cc.sys.localStorage.getItem(key);
+        if (value) {
+            try {
+                if (decrypt) {
+                    value = mk.encrypt.decrypt(value, gData.storageData.storageKey, gData.appData.appId);
+                }
+                else {
+                    value = JSON.parse(value);
+                }
+                return value;
+            }
+            catch (err) {
+                return value;
+            }
+        }
+        else {
+            return null;
+        }
+    }
+
+    /**
+     * 存储
+     * @param   key     key值
+     * @param   value   要存储的value值
+     * @param   encrypt 是否需要加密
+     */
+    public setStorage(key: string, value: any, encrypt: boolean = true) {
+        if (encrypt) {
+            value = mk.encrypt.encrypt(value, gData.storageData.storageKey, gData.appData.appId);
+            cc.sys.localStorage.setItem(key, value);
+        }
+        else {
+            cc.sys.localStorage.setItem(key, JSON.stringify(value));
+        }
+
+    }
+
+    /**
+     * 清除所有缓存
+     */
+    public clear() {
+        cc.sys.localStorage.clear();
+    }
+}

+ 9 - 0
assets/Scripts/mk/util/StorageUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "2505f396-8767-47e4-8ef8-3185fea7295c",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 169 - 0
assets/Scripts/mk/util/StringUtil.ts

@@ -0,0 +1,169 @@
+/**
+ * 字符串工具类
+ * @author 薛鸿潇
+ */
+export default class StringUtil {
+
+    /** 
+     * 颜色表
+     */
+    private str_color = {
+        /** 红色1 */
+        red1: '#be2c1d',
+        /** 棕色1 */
+        bro1: '#4E301B',
+    }
+
+    /** 
+     * 将数据表里的字符串转成相对颜色
+     * @param 需要转换的字符串 比如  "你好[red中国]" 其中“中国”为红色...你好[red{s40}中国]
+     * @return 返回一个富文本字符串
+     * @author xhx
+     */
+    public getTextByStringInData(str: string): string {
+        var newStr: string = str;
+        var i: number = 0;
+        var begin: number;
+        var end: number;
+        var sub: string;
+        var searchValue: string;
+        var replaceValue: string;
+        var color_key: string;
+
+        // 解析颜色
+        while (i < str.length) {
+            begin = str.indexOf("[", i);
+            end = str.indexOf("]", begin);
+            if (begin != -1 && end != -1)//把[redXXX]转成富文本
+            {
+                searchValue = str.slice(begin, end + 1);
+                // 颜色内容
+                color_key = str.slice(begin + 1, begin + 5);
+                let color_str = this.str_color[color_key]
+                if (color_str) {
+                    sub = str.slice(begin + 6, end);
+                    replaceValue = this.getColorStringColor(sub, color_str);
+                    newStr = newStr.replace(searchValue, replaceValue);
+                }
+                i = end;
+            }
+            else {
+                break;
+            }
+        }
+        let size_index: number = 0;
+        let size_begin: number = 0;
+        let size_end: number = 0;
+        let size_searchValue: string;
+        // let size_sub: string
+
+        // 解析尺寸{40=100%},100%是40尺寸.例子2:[bro对目标造成][red{40=104%}][bro攻击伤害]
+        while (size_index < newStr.length) {
+            size_begin = newStr.indexOf("{", size_index);
+            size_end = newStr.indexOf("}", size_begin);
+            if (size_begin != -1 && size_end != -1) {
+                // 尺寸内容
+                size_searchValue = newStr.slice(size_begin, size_end + 1);
+                let size_value = newStr.slice(size_begin + 1, size_begin + 3);
+                let size_sub = size_searchValue.slice(4, size_searchValue.length - 1);
+                if (size_sub) {
+                    let new_value = '<size = ' + size_value + '>' + size_sub + '</color>';
+                    newStr = newStr.replace(size_searchValue, new_value);
+                }
+
+                size_index = size_end;
+            } else {
+                break;
+            }
+        }
+        return newStr;
+    }
+    /**按品质转换字符串颜色 */
+    private getColorStringColor(str: string = '#FFFFFF', color_str: string): string {
+        return '<color=' + color_str + '>' + str + '</color>';
+    }
+
+
+    /**
+     * 阿拉伯数字 转 汉字
+     * @param num 要转的数字
+     * @returns 汉字数字
+     * @author xhx
+     */
+    public arabicToChinese(num: number): string {
+        let unit_section = ['', '万', '亿', '万亿', '亿亿'];
+        let unit_chn = ['', '十', '百', '千'];
+        let chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
+        let unit_index = 0;
+        let str_ins = '', zh_str = '';
+        let need_zero = false;
+
+        let SectionToChinese = function (section) {
+            let _zh_str = '';
+            let _unit_index = 0;
+            let zero = true;
+            while (section > 0) {
+                let v = section % 10;
+                let _str_ins = '';
+                if (v === 0) {
+                    if (!zero) {
+                        zero = true;
+                        _zh_str = chars[v] + _zh_str;
+                    }
+                } else {
+                    zero = false;
+                    if (_unit_index !== 1 || section > 1) {
+                        _str_ins = chars[v];
+                    }
+
+                    _str_ins += unit_chn[_unit_index];
+                    _zh_str = _str_ins + _zh_str;
+                }
+                ++_unit_index;
+                section = Math.floor(section / 10);
+            }
+            return _zh_str;
+        };
+
+        if (num === 0) {
+            return chars[0];
+        }
+
+        while (num > 0) {
+            let section = num % 10000;
+            if (need_zero) {
+                zh_str = chars[0] + zh_str;
+            }
+            str_ins = SectionToChinese(section);
+            str_ins += (section !== 0) ? unit_section[unit_index] : unit_section[0];
+            zh_str = str_ins + zh_str;
+            need_zero = (section < 1000) && (section > 0);
+            num = Math.floor(num / 10000);
+            ++unit_index;
+        }
+
+        return zh_str;
+    }
+    /**
+     * 限制字符串长度,超出部分用...代替
+     * @param str 要拆分的字符串
+     * @param max_len 最大长度
+     * @returns 被限制后的字符串
+     * @author xhx
+     */
+    public getNewLimitStr(str: string, max_len: number) {
+        let arr_str = str.split("");
+        let new_str = '';
+        max_len = arr_str.length >= max_len ? max_len : arr_str.length;//字符串不能超出的长度,否则用...显示
+        for (let i = 0; i < max_len; i++) {
+            if (i == (max_len - 1)) {
+                new_str += '...';
+            } else {
+                new_str += arr_str[i];
+            }
+        }
+        return new_str;
+    }
+}
+
+

+ 9 - 0
assets/Scripts/mk/util/StringUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "77df0889-1da8-4133-9913-b1d214771b7c",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 183 - 0
assets/Scripts/mk/util/TimeUtil.ts

@@ -0,0 +1,183 @@
+/**
+ * @description 时间工具类
+ * @author 邹勇
+ */
+export default class TimeUtil {
+    constructor() {
+
+    }
+
+    /**
+     * 本地时间与服务器时间的差值
+     */
+    private offTime: number = 0;
+    /**
+     * 设置服务器时间
+     * @param time  服务器时间戳(秒)
+     */
+    public setServerTime(time: number) {
+        this.offTime = time - Math.ceil(new Date().getTime() / 1000);
+    }
+
+    /**
+     * 获取当前服务器时间,如果没有设置过服务器时间,默认为本地时间
+     * @returns     当前服务器时间戳(秒)
+     */
+    public getServerTime(): number {
+        return Math.ceil(new Date().getTime() / 1000 + this.offTime);
+    }
+
+    /**
+     * 倒计时转换为时间格式(h:m:s),没有单位
+     * @param   t  时间(秒)
+     * @param   f  格式,默认"h:m:s",可以过滤,如 "m:s"
+     * @returns    规定格式的字符串 如"04:22:06"
+     */
+    public format(t: number, f: string = "h:m:s"): string {
+        let d: number = Math.floor(t / 24 / 3600);
+        let h: number = Math.floor((t / 3600) % 24);
+        let m: number = Math.floor((t % 3600) / 60);
+        let s: number = (t % 3600) % 60;
+
+        function parse_format(t: number): string {
+            let s: string = t.toString();
+            if (t < 10) {
+                s = "0" + t;
+            }
+            return s;
+        }
+
+        if (f.indexOf("d") != -1) {
+            f = f.replace(/d/g, parse_format(d));
+        }
+        else {
+            h += d * 24;
+        }
+
+        if (f.indexOf("h") != -1) {
+            f = f.replace(/h/g, parse_format(h));
+        }
+        else {
+            m += h * 60;
+        }
+
+        if (f.indexOf("m") != -1) {
+            f = f.replace(/m/g, parse_format(m));
+        }
+        else {
+            if (f.indexOf("h") != -1) {
+                s += m * 60;
+            } else {
+                s = t;
+            }
+        }
+
+        if (f.indexOf("s") != -1) {
+            f = f.replace(/s/g, parse_format(s));
+        }
+        return f;
+    }
+
+    /**
+     * 倒计时转换为时间格式,带中文单位 ,可过滤
+     * @param   t     时间(秒)
+     * @param   f     格式,默认"天时分秒",可以过滤,如 "分秒"
+     * @returns       规定格式的字符串 如“2天13时11分05秒”
+     */
+    public formatWithUnit(t: number, f: string = "天时分秒"): string {
+        let d: number = Math.floor(t / 24 / 3600);
+        let h: number = Math.floor((t / 3600) % 24);
+        let m: number = Math.floor((t % 3600) / 60);
+        let s: number = (t % 3600) % 60;
+
+        function parse_format(t: number, unit: string): string {
+            let s: string = t.toString();
+            if (t < 10) {
+                s = "0" + t;
+            }
+            return s + unit;
+        }
+
+        let str = '';
+
+        if (f.indexOf("天") != -1) {
+            str += d + "天";
+        }
+        else {
+            h += d * 24;
+        }
+
+        if (f.indexOf("时") != -1) {
+            str += parse_format(h, "时");
+        }
+        else {
+            m += h * 60;
+        }
+
+        if (f.indexOf("分") != -1) {
+            str += parse_format(m, "分");
+        }
+        else {
+            s += m * 60;
+        }
+
+        if (f.indexOf("秒") != -1) {
+            str += parse_format(s, "秒");
+        }
+        return str;
+    }
+
+    /**
+     * 获取一年中的第n天
+     * @param   t   时间戳(毫秒)
+     * @returns     一年中的第n天
+     */
+    public getDayInYear(t: number): number {
+        var time: Date = new Date(t);
+        var month = time.getMonth() + 1;
+        var year = time.getFullYear();
+        var days = time.getDate();
+        var sum = 0;
+
+        let a = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+        let b = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
+            for (var i: number = 0; i < month - 1; i++) {
+                sum += b[i];
+            }
+            return sum + days;
+        } else {
+            for (var i: number = 0; i < month - 1; i++) {
+                sum += a[i];
+            }
+            return sum + days;
+        }
+    }
+
+    /**
+     * 返回时间点在当天的秒数
+     * @param   date    时间
+     * @returns         从零点开始的秒数
+     */
+    public getSecondsInDay(date: Date) {
+        return date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();
+    }
+
+    /**
+     * 获取当前日期
+     * @param   data        1997年起的秒数
+     * @param   replace     间隔符,默认'-',则返回2020-10-10
+     * @returns             当前时间字符串
+     */
+    public getNowDayString(data?: number, replace: string = '-'): string {
+        let date = data ? new Date(data) : new Date();
+        return date.getFullYear() + replace + (date.getMonth() + 1) + replace + date.getDate();
+    }
+
+    //等待seconds时间戳
+    public WaitForSeconds(seconds: number) {
+        return new Promise<void>(resolve => {
+            setTimeout(() => resolve(), seconds * 1000);
+        })
+    }
+}

+ 9 - 0
assets/Scripts/mk/util/TimeUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "945514b5-01a9-4898-8fe6-d746e0964f0c",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 122 - 0
assets/Scripts/mk/util/TweenUtil.ts

@@ -0,0 +1,122 @@
+
+const { ccclass, property } = cc._decorator;
+/**
+ * 动画工具类
+ * @author 薛鸿潇
+ */
+@ccclass
+export default class TweenUtil {
+    /** 
+     * 缓动类型
+     */
+    public easing: typeof TweenEasing = TweenEasing
+    
+    /**
+     * 缩放效果
+     * @param node 动画节点
+     * @param time 动画时间
+     * @param start_scale 起始缩放属性
+     * @param end_scale 目标缩放属性
+     * @param complete_fun 完成回调
+     */
+    public scale(node: cc.Node, time: number = 0.15, start_scale: number = 0, end_scale: number = 1, complete_fun?: Function, easing?: keyof typeof TweenEasing) {
+        node.scale = start_scale;
+        let scale1 = cc.tween().to(time, { scale: end_scale }, { easing: easing });
+        let call1 = cc.tween().call(() => { if (typeof complete_fun == 'function') complete_fun(); })
+        cc.tween(node).then(scale1).then(call1).start()
+    }
+
+    /**
+    * 缩放效果
+    * @param node 动画节点
+    * @param time 动画时间
+    * @param start_scale 起始缩放属性
+    * @param end_scale 目标缩放属性
+    * @param complete_fun 完成回调
+    */
+    public scaleX(node: cc.Node, time: number = 0.15, start_scale: number = 0, end_scale: number = 1, complete_fun?: Function, easing?: keyof typeof TweenEasing) {
+        node.scaleX = start_scale;
+        let scale1 = cc.tween().to(time, { scaleX: end_scale }, { easing: easing });
+        let call1 = cc.tween().call(() => { if (typeof complete_fun == 'function') complete_fun(); })
+        cc.tween(node).then(scale1).then(call1).start()
+    }
+
+    /**
+     * 缩放移动效果
+     * @param node 动画节点
+     * @param time 动画时间
+     * @param start_scale 起始缩放属性
+     * @param end_scale 结束缩放属性
+     * @param end_pos 结束节点位置
+     * @param complete_fun 完成回调
+     */
+    public scaleParallelMove(node: cc.Node, time: number = 0.15, start_scale: number = 0, end_scale: number = 1, end_pos: cc.Vec2 = cc.Vec2.ZERO, complete_fun?: Function) {
+        node.scale = start_scale;
+        let scale1 = cc.tween().to(time, { scale: end_scale });
+        let pos1 = cc.tween().to(time, { position: new cc.Vec3(end_pos.x, end_pos.y, 0) });
+        let call1 = cc.tween().call(() => { if (typeof complete_fun == 'function') complete_fun(); })
+        let parallel = cc.tween().parallel(scale1, pos1)
+        cc.tween(node).then(parallel).then(call1).start();
+    }
+
+    /**
+     * 移动效果
+     * @param node 
+     * @param time 
+     * @param complete_fun 
+     */
+    public move(node: cc.Node, time: number = 0.15, start_pos: cc.Vec2 = cc.Vec2.ZERO, end_pos: cc.Vec2 = cc.Vec2.ZERO, complete_fun?: Function, easing?: keyof typeof TweenEasing) {
+        node.setPosition(start_pos);
+        let pos1 = cc.tween().to(time, { position: new cc.Vec3(end_pos.x, end_pos.y, 0) }, { easing: easing });// cc.easeOut(3)
+        let call1 = cc.tween().call(() => { if (typeof complete_fun == 'function') complete_fun(); })
+        cc.tween(node).then(pos1).then(call1).start();
+    }
+}
+/**
+ * 缓动类型
+ */
+enum TweenEasing {
+    linear,
+    smooth,
+    fade,
+    quadIn,
+    quadOut,
+    quadInOut,
+    quadOutIn,
+    cubicIn,
+    cubicOut,
+    cubicInOut,
+    cubicOutIn,
+    quartIn,
+    quartOut,
+    quartInOut,
+    quartOutIn,
+    quintIn,
+    quintOut,
+    quintInOut,
+    quintOutIn,
+    sineIn,
+    sineOut,
+    sineInOut,
+    sineOutIn,
+    expoIn,
+    expoOut,
+    expoInOut,
+    expoOutIn,
+    circIn,
+    circOut,
+    circInOut,
+    circOutIn,
+    elasticIn,
+    elasticOut,
+    elasticInOut,
+    elasticOutIn,
+    backIn,
+    backOut,
+    backInOut,
+    backOutIn,
+    bounceIn,
+    bounceOut,
+    bounceInOut,
+    bounceOutIn
+}

+ 9 - 0
assets/Scripts/mk/util/TweenUtil.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "333a54a6-5249-49b8-8512-cff64f593384",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 12 - 0
assets/Scripts/mk/util/encrypt.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "3928efbe-5f85-44ff-aa63-9d98d928b3bc",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 701 - 0
assets/Scripts/mk/util/encrypt/aes.js

@@ -0,0 +1,701 @@
+/**
+ * [description] CryptoJS v3.1.2 
+ * [description] zhuangzhudada sort out 
+ */
+var CryptoJS = CryptoJS || function(u, p) {
+  var d = {},
+      l = d.lib = {},
+      s = function() {},
+      t = l.Base = {
+          extend: function(a) {
+              s.prototype = this;
+              var c = new s;
+              a && c.mixIn(a);
+              c.hasOwnProperty("init") || (c.init = function() {
+                  c.$super.init.apply(this, arguments)
+              });
+              c.init.prototype = c;
+              c.$super = this;
+              return c
+          },
+          create: function() {
+              var a = this.extend();
+              a.init.apply(a, arguments);
+              return a
+          },
+          init: function() {},
+          mixIn: function(a) {
+              for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]);
+              a.hasOwnProperty("toString") && (this.toString = a.toString)
+          },
+          clone: function() {
+              return this.init.prototype.extend(this)
+          }
+      },
+      r = l.WordArray = t.extend({
+          init: function(a, c) {
+              a = this.words = a || [];
+              this.sigBytes = c != p ? c : 4 * a.length
+          },
+          toString: function(a) {
+              return (a || v).stringify(this)
+          },
+          concat: function(a) {
+              var c = this.words,
+                  e = a.words,
+                  j = this.sigBytes;
+              a = a.sigBytes;
+              this.clamp();
+              if (j % 4)
+                  for (var k = 0; k < a; k++) c[j + k >>> 2] |= (e[k >>> 2] >>> 24 - 8 * (k % 4) & 255) << 24 - 8 * ((j + k) % 4);
+              else if (65535 < e.length)
+                  for (k = 0; k < a; k += 4) c[j + k >>> 2] = e[k >>> 2];
+              else c.push.apply(c, e);
+              this.sigBytes += a;
+              return this
+          },
+          clamp: function() {
+              var a = this.words,
+                  c = this.sigBytes;
+              a[c >>> 2] &= 4294967295 <<
+                  32 - 8 * (c % 4);
+              a.length = u.ceil(c / 4)
+          },
+          clone: function() {
+              var a = t.clone.call(this);
+              a.words = this.words.slice(0);
+              return a
+          },
+          random: function(a) {
+              for (var c = [], e = 0; e < a; e += 4) c.push(4294967296 * u.random() | 0);
+              return new r.init(c, a)
+          }
+      }),
+      w = d.enc = {},
+      v = w.Hex = {
+          stringify: function(a) {
+              var c = a.words;
+              a = a.sigBytes;
+              for (var e = [], j = 0; j < a; j++) {
+                  var k = c[j >>> 2] >>> 24 - 8 * (j % 4) & 255;
+                  e.push((k >>> 4).toString(16));
+                  e.push((k & 15).toString(16))
+              }
+              return e.join("")
+          },
+          parse: function(a) {
+              for (var c = a.length, e = [], j = 0; j < c; j += 2) e[j >>> 3] |= parseInt(a.substr(j,
+                  2), 16) << 24 - 4 * (j % 8);
+              return new r.init(e, c / 2)
+          }
+      },
+      b = w.Latin1 = {
+          stringify: function(a) {
+              var c = a.words;
+              a = a.sigBytes;
+              for (var e = [], j = 0; j < a; j++) e.push(String.fromCharCode(c[j >>> 2] >>> 24 - 8 * (j % 4) & 255));
+              return e.join("")
+          },
+          parse: function(a) {
+              for (var c = a.length, e = [], j = 0; j < c; j++) e[j >>> 2] |= (a.charCodeAt(j) & 255) << 24 - 8 * (j % 4);
+              return new r.init(e, c)
+          }
+      },
+      x = w.Utf8 = {
+          stringify: function(a) {
+              try {
+                  return decodeURIComponent(escape(b.stringify(a)))
+              } catch (c) {
+                  throw Error("Malformed UTF-8 data");
+              }
+          },
+          parse: function(a) {
+              return b.parse(unescape(encodeURIComponent(a)))
+          }
+      },
+      q = l.BufferedBlockAlgorithm = t.extend({
+          reset: function() {
+              this._data = new r.init;
+              this._nDataBytes = 0
+          },
+          _append: function(a) {
+              "string" == typeof a && (a = x.parse(a));
+              this._data.concat(a);
+              this._nDataBytes += a.sigBytes
+          },
+          _process: function(a) {
+              var c = this._data,
+                  e = c.words,
+                  j = c.sigBytes,
+                  k = this.blockSize,
+                  b = j / (4 * k),
+                  b = a ? u.ceil(b) : u.max((b | 0) - this._minBufferSize, 0);
+              a = b * k;
+              j = u.min(4 * a, j);
+              if (a) {
+                  for (var q = 0; q < a; q += k) this._doProcessBlock(e, q);
+                  q = e.splice(0, a);
+                  c.sigBytes -= j
+              }
+              return new r.init(q, j)
+          },
+          clone: function() {
+              var a = t.clone.call(this);
+              a._data = this._data.clone();
+              return a
+          },
+          _minBufferSize: 0
+      });
+  l.Hasher = q.extend({
+      cfg: t.extend(),
+      init: function(a) {
+          this.cfg = this.cfg.extend(a);
+          this.reset()
+      },
+      reset: function() {
+          q.reset.call(this);
+          this._doReset()
+      },
+      update: function(a) {
+          this._append(a);
+          this._process();
+          return this
+      },
+      finalize: function(a) {
+          a && this._append(a);
+          return this._doFinalize()
+      },
+      blockSize: 16,
+      _createHelper: function(a) {
+          return function(b, e) {
+              return (new a.init(e)).finalize(b)
+          }
+      },
+      _createHmacHelper: function(a) {
+          return function(b, e) {
+              return (new n.HMAC.init(a,
+                  e)).finalize(b)
+          }
+      }
+  });
+  var n = d.algo = {};
+  return d
+}(Math);
+(function() {
+  var u = CryptoJS,
+      p = u.lib.WordArray;
+  u.enc.Base64 = {
+      stringify: function(d) {
+          var l = d.words,
+              p = d.sigBytes,
+              t = this._map;
+          d.clamp();
+          d = [];
+          for (var r = 0; r < p; r += 3)
+              for (var w = (l[r >>> 2] >>> 24 - 8 * (r % 4) & 255) << 16 | (l[r + 1 >>> 2] >>> 24 - 8 * ((r + 1) % 4) & 255) << 8 | l[r + 2 >>> 2] >>> 24 - 8 * ((r + 2) % 4) & 255, v = 0; 4 > v && r + 0.75 * v < p; v++) d.push(t.charAt(w >>> 6 * (3 - v) & 63));
+          if (l = t.charAt(64))
+              for (; d.length % 4;) d.push(l);
+          return d.join("")
+      },
+      parse: function(d) {
+          var l = d.length,
+              s = this._map,
+              t = s.charAt(64);
+          t && (t = d.indexOf(t), -1 != t && (l = t));
+          for (var t = [], r = 0, w = 0; w <
+              l; w++)
+              if (w % 4) {
+                  var v = s.indexOf(d.charAt(w - 1)) << 2 * (w % 4),
+                      b = s.indexOf(d.charAt(w)) >>> 6 - 2 * (w % 4);
+                  t[r >>> 2] |= (v | b) << 24 - 8 * (r % 4);
+                  r++
+              }
+          return p.create(t, r)
+      },
+      _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
+  }
+})();
+(function(u) {
+  function p(b, n, a, c, e, j, k) {
+      b = b + (n & a | ~n & c) + e + k;
+      return (b << j | b >>> 32 - j) + n
+  }
+
+  function d(b, n, a, c, e, j, k) {
+      b = b + (n & c | a & ~c) + e + k;
+      return (b << j | b >>> 32 - j) + n
+  }
+
+  function l(b, n, a, c, e, j, k) {
+      b = b + (n ^ a ^ c) + e + k;
+      return (b << j | b >>> 32 - j) + n
+  }
+
+  function s(b, n, a, c, e, j, k) {
+      b = b + (a ^ (n | ~c)) + e + k;
+      return (b << j | b >>> 32 - j) + n
+  }
+  for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) b[x] = 4294967296 * u.abs(u.sin(x + 1)) | 0;
+  r = r.MD5 = v.extend({
+      _doReset: function() {
+          this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878])
+      },
+      _doProcessBlock: function(q, n) {
+          for (var a = 0; 16 > a; a++) {
+              var c = n + a,
+                  e = q[c];
+              q[c] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360
+          }
+          var a = this._hash.words,
+              c = q[n + 0],
+              e = q[n + 1],
+              j = q[n + 2],
+              k = q[n + 3],
+              z = q[n + 4],
+              r = q[n + 5],
+              t = q[n + 6],
+              w = q[n + 7],
+              v = q[n + 8],
+              A = q[n + 9],
+              B = q[n + 10],
+              C = q[n + 11],
+              u = q[n + 12],
+              D = q[n + 13],
+              E = q[n + 14],
+              x = q[n + 15],
+              f = a[0],
+              m = a[1],
+              g = a[2],
+              h = a[3],
+              f = p(f, m, g, h, c, 7, b[0]),
+              h = p(h, f, m, g, e, 12, b[1]),
+              g = p(g, h, f, m, j, 17, b[2]),
+              m = p(m, g, h, f, k, 22, b[3]),
+              f = p(f, m, g, h, z, 7, b[4]),
+              h = p(h, f, m, g, r, 12, b[5]),
+              g = p(g, h, f, m, t, 17, b[6]),
+              m = p(m, g, h, f, w, 22, b[7]),
+              f = p(f, m, g, h, v, 7, b[8]),
+              h = p(h, f, m, g, A, 12, b[9]),
+              g = p(g, h, f, m, B, 17, b[10]),
+              m = p(m, g, h, f, C, 22, b[11]),
+              f = p(f, m, g, h, u, 7, b[12]),
+              h = p(h, f, m, g, D, 12, b[13]),
+              g = p(g, h, f, m, E, 17, b[14]),
+              m = p(m, g, h, f, x, 22, b[15]),
+              f = d(f, m, g, h, e, 5, b[16]),
+              h = d(h, f, m, g, t, 9, b[17]),
+              g = d(g, h, f, m, C, 14, b[18]),
+              m = d(m, g, h, f, c, 20, b[19]),
+              f = d(f, m, g, h, r, 5, b[20]),
+              h = d(h, f, m, g, B, 9, b[21]),
+              g = d(g, h, f, m, x, 14, b[22]),
+              m = d(m, g, h, f, z, 20, b[23]),
+              f = d(f, m, g, h, A, 5, b[24]),
+              h = d(h, f, m, g, E, 9, b[25]),
+              g = d(g, h, f, m, k, 14, b[26]),
+              m = d(m, g, h, f, v, 20, b[27]),
+              f = d(f, m, g, h, D, 5, b[28]),
+              h = d(h, f,
+                  m, g, j, 9, b[29]),
+              g = d(g, h, f, m, w, 14, b[30]),
+              m = d(m, g, h, f, u, 20, b[31]),
+              f = l(f, m, g, h, r, 4, b[32]),
+              h = l(h, f, m, g, v, 11, b[33]),
+              g = l(g, h, f, m, C, 16, b[34]),
+              m = l(m, g, h, f, E, 23, b[35]),
+              f = l(f, m, g, h, e, 4, b[36]),
+              h = l(h, f, m, g, z, 11, b[37]),
+              g = l(g, h, f, m, w, 16, b[38]),
+              m = l(m, g, h, f, B, 23, b[39]),
+              f = l(f, m, g, h, D, 4, b[40]),
+              h = l(h, f, m, g, c, 11, b[41]),
+              g = l(g, h, f, m, k, 16, b[42]),
+              m = l(m, g, h, f, t, 23, b[43]),
+              f = l(f, m, g, h, A, 4, b[44]),
+              h = l(h, f, m, g, u, 11, b[45]),
+              g = l(g, h, f, m, x, 16, b[46]),
+              m = l(m, g, h, f, j, 23, b[47]),
+              f = s(f, m, g, h, c, 6, b[48]),
+              h = s(h, f, m, g, w, 10, b[49]),
+              g = s(g, h, f, m,
+                  E, 15, b[50]),
+              m = s(m, g, h, f, r, 21, b[51]),
+              f = s(f, m, g, h, u, 6, b[52]),
+              h = s(h, f, m, g, k, 10, b[53]),
+              g = s(g, h, f, m, B, 15, b[54]),
+              m = s(m, g, h, f, e, 21, b[55]),
+              f = s(f, m, g, h, v, 6, b[56]),
+              h = s(h, f, m, g, x, 10, b[57]),
+              g = s(g, h, f, m, t, 15, b[58]),
+              m = s(m, g, h, f, D, 21, b[59]),
+              f = s(f, m, g, h, z, 6, b[60]),
+              h = s(h, f, m, g, C, 10, b[61]),
+              g = s(g, h, f, m, j, 15, b[62]),
+              m = s(m, g, h, f, A, 21, b[63]);
+          a[0] = a[0] + f | 0;
+          a[1] = a[1] + m | 0;
+          a[2] = a[2] + g | 0;
+          a[3] = a[3] + h | 0
+      },
+      _doFinalize: function() {
+          var b = this._data,
+              n = b.words,
+              a = 8 * this._nDataBytes,
+              c = 8 * b.sigBytes;
+          n[c >>> 5] |= 128 << 24 - c % 32;
+          var e = u.floor(a /
+              4294967296);
+          n[(c + 64 >>> 9 << 4) + 15] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360;
+          n[(c + 64 >>> 9 << 4) + 14] = (a << 8 | a >>> 24) & 16711935 | (a << 24 | a >>> 8) & 4278255360;
+          b.sigBytes = 4 * (n.length + 1);
+          this._process();
+          b = this._hash;
+          n = b.words;
+          for (a = 0; 4 > a; a++) c = n[a], n[a] = (c << 8 | c >>> 24) & 16711935 | (c << 24 | c >>> 8) & 4278255360;
+          return b
+      },
+      clone: function() {
+          var b = v.clone.call(this);
+          b._hash = this._hash.clone();
+          return b
+      }
+  });
+  t.MD5 = v._createHelper(r);
+  t.HmacMD5 = v._createHmacHelper(r)
+})(Math);
+(function() {
+  var u = CryptoJS,
+      p = u.lib,
+      d = p.Base,
+      l = p.WordArray,
+      p = u.algo,
+      s = p.EvpKDF = d.extend({
+          cfg: d.extend({
+              keySize: 4,
+              hasher: p.MD5,
+              iterations: 1
+          }),
+          init: function(d) {
+              this.cfg = this.cfg.extend(d)
+          },
+          compute: function(d, r) {
+              for (var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; u.length < q;) {
+                  n && s.update(n);
+                  var n = s.update(d).finalize(r);
+                  s.reset();
+                  for (var a = 1; a < p; a++) n = s.finalize(n), s.reset();
+                  b.concat(n)
+              }
+              b.sigBytes = 4 * q;
+              return b
+          }
+      });
+  u.EvpKDF = function(d, l, p) {
+      return s.create(p).compute(d,
+          l)
+  }
+})();
+CryptoJS.lib.Cipher || function(u) {
+  var p = CryptoJS,
+      d = p.lib,
+      l = d.Base,
+      s = d.WordArray,
+      t = d.BufferedBlockAlgorithm,
+      r = p.enc.Base64,
+      w = p.algo.EvpKDF,
+      v = d.Cipher = t.extend({
+          cfg: l.extend(),
+          createEncryptor: function(e, a) {
+              return this.create(this._ENC_XFORM_MODE, e, a)
+          },
+          createDecryptor: function(e, a) {
+              return this.create(this._DEC_XFORM_MODE, e, a)
+          },
+          init: function(e, a, b) {
+              this.cfg = this.cfg.extend(b);
+              this._xformMode = e;
+              this._key = a;
+              this.reset()
+          },
+          reset: function() {
+              t.reset.call(this);
+              this._doReset()
+          },
+          process: function(e) {
+              this._append(e);
+              return this._process()
+          },
+          finalize: function(e) {
+              e && this._append(e);
+              return this._doFinalize()
+          },
+          keySize: 4,
+          ivSize: 4,
+          _ENC_XFORM_MODE: 1,
+          _DEC_XFORM_MODE: 2,
+          _createHelper: function(e) {
+              return {
+                  encrypt: function(b, k, d) {
+                      return ("string" == typeof k ? c : a).encrypt(e, b, k, d)
+                  },
+                  decrypt: function(b, k, d) {
+                      return ("string" == typeof k ? c : a).decrypt(e, b, k, d)
+                  }
+              }
+          }
+      });
+  d.StreamCipher = v.extend({
+      _doFinalize: function() {
+          return this._process(!0)
+      },
+      blockSize: 1
+  });
+  var b = p.mode = {},
+      x = function(e, a, b) {
+          var c = this._iv;
+          c ? this._iv = u : c = this._prevBlock;
+          for (var d = 0; d < b; d++) e[a + d] ^=
+              c[d]
+      },
+      q = (d.BlockCipherMode = l.extend({
+          createEncryptor: function(e, a) {
+              return this.Encryptor.create(e, a)
+          },
+          createDecryptor: function(e, a) {
+              return this.Decryptor.create(e, a)
+          },
+          init: function(e, a) {
+              this._cipher = e;
+              this._iv = a
+          }
+      })).extend();
+  q.Encryptor = q.extend({
+      processBlock: function(e, a) {
+          var b = this._cipher,
+              c = b.blockSize;
+          x.call(this, e, a, c);
+          b.encryptBlock(e, a);
+          this._prevBlock = e.slice(a, a + c)
+      }
+  });
+  q.Decryptor = q.extend({
+      processBlock: function(e, a) {
+          var b = this._cipher,
+              c = b.blockSize,
+              d = e.slice(a, a + c);
+          b.decryptBlock(e, a);
+          x.call(this,
+              e, a, c);
+          this._prevBlock = d
+      }
+  });
+  b = b.CBC = q;
+  q = (p.pad = {}).Pkcs7 = {
+      pad: function(a, b) {
+          for (var c = 4 * b, c = c - a.sigBytes % c, d = c << 24 | c << 16 | c << 8 | c, l = [], n = 0; n < c; n += 4) l.push(d);
+          c = s.create(l, c);
+          a.concat(c)
+      },
+      unpad: function(a) {
+          a.sigBytes -= a.words[a.sigBytes - 1 >>> 2] & 255
+      }
+  };
+  d.BlockCipher = v.extend({
+      cfg: v.cfg.extend({
+          mode: b,
+          padding: q
+      }),
+      reset: function() {
+          v.reset.call(this);
+          var a = this.cfg,
+              b = a.iv,
+              a = a.mode;
+          if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor;
+          else c = a.createDecryptor, this._minBufferSize = 1;
+          this._mode = c.call(a,
+              this, b && b.words)
+      },
+      _doProcessBlock: function(a, b) {
+          this._mode.processBlock(a, b)
+      },
+      _doFinalize: function() {
+          var a = this.cfg.padding;
+          if (this._xformMode == this._ENC_XFORM_MODE) {
+              a.pad(this._data, this.blockSize);
+              var b = this._process(!0)
+          } else b = this._process(!0), a.unpad(b);
+          return b
+      },
+      blockSize: 4
+  });
+  var n = d.CipherParams = l.extend({
+          init: function(a) {
+              this.mixIn(a)
+          },
+          toString: function(a) {
+              return (a || this.formatter).stringify(this)
+          }
+      }),
+      b = (p.format = {}).OpenSSL = {
+          stringify: function(a) {
+              var b = a.ciphertext;
+              a = a.salt;
+              return (a ? s.create([1398893684,
+                  1701076831
+              ]).concat(a).concat(b) : b).toString(r)
+          },
+          parse: function(a) {
+              a = r.parse(a);
+              var b = a.words;
+              if (1398893684 == b[0] && 1701076831 == b[1]) {
+                  var c = s.create(b.slice(2, 4));
+                  b.splice(0, 4);
+                  a.sigBytes -= 16
+              }
+              return n.create({
+                  ciphertext: a,
+                  salt: c
+              })
+          }
+      },
+      a = d.SerializableCipher = l.extend({
+          cfg: l.extend({
+              format: b
+          }),
+          encrypt: function(a, b, c, d) {
+              d = this.cfg.extend(d);
+              var l = a.createEncryptor(c, d);
+              b = l.finalize(b);
+              l = l.cfg;
+              return n.create({
+                  ciphertext: b,
+                  key: c,
+                  iv: l.iv,
+                  algorithm: a,
+                  mode: l.mode,
+                  padding: l.padding,
+                  blockSize: a.blockSize,
+                  formatter: d.format
+              })
+          },
+          decrypt: function(a, b, c, d) {
+              d = this.cfg.extend(d);
+              b = this._parse(b, d.format);
+              return a.createDecryptor(c, d).finalize(b.ciphertext)
+          },
+          _parse: function(a, b) {
+              return "string" == typeof a ? b.parse(a, this) : a
+          }
+      }),
+      p = (p.kdf = {}).OpenSSL = {
+          execute: function(a, b, c, d) {
+              d || (d = s.random(8));
+              a = w.create({
+                  keySize: b + c
+              }).compute(a, d);
+              c = s.create(a.words.slice(b), 4 * c);
+              a.sigBytes = 4 * b;
+              return n.create({
+                  key: a,
+                  iv: c,
+                  salt: d
+              })
+          }
+      },
+      c = d.PasswordBasedCipher = a.extend({
+          cfg: a.cfg.extend({
+              kdf: p
+          }),
+          encrypt: function(b, c, d, l) {
+              l = this.cfg.extend(l);
+              d = l.kdf.execute(d,
+                  b.keySize, b.ivSize);
+              l.iv = d.iv;
+              b = a.encrypt.call(this, b, c, d.key, l);
+              b.mixIn(d);
+              return b
+          },
+          decrypt: function(b, c, d, l) {
+              l = this.cfg.extend(l);
+              c = this._parse(c, l.format);
+              d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt);
+              l.iv = d.iv;
+              return a.decrypt.call(this, b, c, d.key, l)
+          }
+      })
+}();
+(function() {
+  for (var u = CryptoJS, p = u.lib.BlockCipher, d = u.algo, l = [], s = [], t = [], r = [], w = [], v = [], b = [], x = [], q = [], n = [], a = [], c = 0; 256 > c; c++) a[c] = 128 > c ? c << 1 : c << 1 ^ 283;
+  for (var e = 0, j = 0, c = 0; 256 > c; c++) {
+      var k = j ^ j << 1 ^ j << 2 ^ j << 3 ^ j << 4,
+          k = k >>> 8 ^ k & 255 ^ 99;
+      l[e] = k;
+      s[k] = e;
+      var z = a[e],
+          F = a[z],
+          G = a[F],
+          y = 257 * a[k] ^ 16843008 * k;
+      t[e] = y << 24 | y >>> 8;
+      r[e] = y << 16 | y >>> 16;
+      w[e] = y << 8 | y >>> 24;
+      v[e] = y;
+      y = 16843009 * G ^ 65537 * F ^ 257 * z ^ 16843008 * e;
+      b[k] = y << 24 | y >>> 8;
+      x[k] = y << 16 | y >>> 16;
+      q[k] = y << 8 | y >>> 24;
+      n[k] = y;
+      e ? (e = z ^ a[a[a[G ^ z]]], j ^= a[a[j]]) : e = j = 1
+  }
+  var H = [0, 1, 2, 4, 8,
+          16, 32, 64, 128, 27, 54
+      ],
+      d = d.AES = p.extend({
+          _doReset: function() {
+              for (var a = this._key, c = a.words, d = a.sigBytes / 4, a = 4 * ((this._nRounds = d + 6) + 1), e = this._keySchedule = [], j = 0; j < a; j++)
+                  if (j < d) e[j] = c[j];
+                  else {
+                      var k = e[j - 1];
+                      j % d ? 6 < d && 4 == j % d && (k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255]) : (k = k << 8 | k >>> 24, k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255], k ^= H[j / d | 0] << 24);
+                      e[j] = e[j - d] ^ k
+                  }
+              c = this._invKeySchedule = [];
+              for (d = 0; d < a; d++) j = a - d, k = d % 4 ? e[j] : e[j - 4], c[d] = 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[k >>> 16 & 255]] ^ q[l[k >>>
+                  8 & 255]] ^ n[l[k & 255]]
+          },
+          encryptBlock: function(a, b) {
+              this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l)
+          },
+          decryptBlock: function(a, c) {
+              var d = a[c + 1];
+              a[c + 1] = a[c + 3];
+              a[c + 3] = d;
+              this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s);
+              d = a[c + 1];
+              a[c + 1] = a[c + 3];
+              a[c + 3] = d
+          },
+          _doCryptBlock: function(a, b, c, d, e, j, l, f) {
+              for (var m = this._nRounds, g = a[b] ^ c[0], h = a[b + 1] ^ c[1], k = a[b + 2] ^ c[2], n = a[b + 3] ^ c[3], p = 4, r = 1; r < m; r++) var q = d[g >>> 24] ^ e[h >>> 16 & 255] ^ j[k >>> 8 & 255] ^ l[n & 255] ^ c[p++],
+                  s = d[h >>> 24] ^ e[k >>> 16 & 255] ^ j[n >>> 8 & 255] ^ l[g & 255] ^ c[p++],
+                  t =
+                  d[k >>> 24] ^ e[n >>> 16 & 255] ^ j[g >>> 8 & 255] ^ l[h & 255] ^ c[p++],
+                  n = d[n >>> 24] ^ e[g >>> 16 & 255] ^ j[h >>> 8 & 255] ^ l[k & 255] ^ c[p++],
+                  g = q,
+                  h = s,
+                  k = t;
+              q = (f[g >>> 24] << 24 | f[h >>> 16 & 255] << 16 | f[k >>> 8 & 255] << 8 | f[n & 255]) ^ c[p++];
+              s = (f[h >>> 24] << 24 | f[k >>> 16 & 255] << 16 | f[n >>> 8 & 255] << 8 | f[g & 255]) ^ c[p++];
+              t = (f[k >>> 24] << 24 | f[n >>> 16 & 255] << 16 | f[g >>> 8 & 255] << 8 | f[h & 255]) ^ c[p++];
+              n = (f[n >>> 24] << 24 | f[g >>> 16 & 255] << 16 | f[h >>> 8 & 255] << 8 | f[k & 255]) ^ c[p++];
+              a[b] = q;
+              a[b + 1] = s;
+              a[b + 2] = t;
+              a[b + 3] = n
+          },
+          keySize: 8
+      });
+  u.AES = p._createHelper(d)
+})();
+
+module.exports = CryptoJS

+ 9 - 0
assets/Scripts/mk/util/encrypt/aes.js.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "javascript",
+  "imported": true,
+  "uuid": "19ca9d95-a3ef-402f-bcf8-12ab6e90ab7b",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 123 - 0
assets/Scripts/mk/util/encrypt/base64.ts

@@ -0,0 +1,123 @@
+/**
+*
+*  Base64 encode / decode
+*
+*  @author haitao.tu
+*  @date   2010-04-26
+*  @email  tuhaitao@foxmail.com
+*
+*/
+
+export default class Base64 {
+	private static instance: Base64 = null
+	static get Instance(): Base64 {
+		if (!this.instance) {
+			this.instance = new Base64()
+		}
+		return this.instance
+	}
+
+	// private property
+	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+
+	// public method for encoding
+	encode(inputw) {
+		var output = "";
+		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+		var i = 0;
+		var input = this._utf8_encode(inputw);
+		while (i < input.length) {
+			chr1 = input.charCodeAt(i++);
+			chr2 = input.charCodeAt(i++);
+			chr3 = input.charCodeAt(i++);
+			enc1 = chr1 >> 2;
+			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+			enc4 = chr3 & 63;
+			if (isNaN(chr2)) {
+				enc3 = enc4 = 64;
+			} else if (isNaN(chr3)) {
+				enc4 = 64;
+			}
+			output = output +
+				this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+				this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
+		}
+		return output;
+	}
+
+	// public method for decoding
+	decode(inputw) {
+		var output = "";
+		var chr1, chr2, chr3;
+		var enc1, enc2, enc3, enc4;
+		var i = 0;
+		var input = inputw.replace(/[^A-Za-z0-9\+\/\=]/g, "");
+		while (i < input.length) {
+			enc1 = this._keyStr.indexOf(input.charAt(i++));
+			enc2 = this._keyStr.indexOf(input.charAt(i++));
+			enc3 = this._keyStr.indexOf(input.charAt(i++));
+			enc4 = this._keyStr.indexOf(input.charAt(i++));
+			chr1 = (enc1 << 2) | (enc2 >> 4);
+			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+			chr3 = ((enc3 & 3) << 6) | enc4;
+			output = output + String.fromCharCode(chr1);
+			if (enc3 != 64) {
+				output = output + String.fromCharCode(chr2);
+			}
+			if (enc4 != 64) {
+				output = output + String.fromCharCode(chr3);
+			}
+		}
+		output = this._utf8_decode(output);
+		return output;
+	}
+
+	// private method for UTF-8 encoding
+	_utf8_encode = function (string) {
+		string = string.replace(/\r\n/g, "\n");
+		var utftext = "";
+		for (var n = 0; n < string.length; n++) {
+			var c = string.charCodeAt(n);
+			if (c < 128) {
+				utftext += String.fromCharCode(c);
+			} else if ((c > 127) && (c < 2048)) {
+				utftext += String.fromCharCode((c >> 6) | 192);
+				utftext += String.fromCharCode((c & 63) | 128);
+			} else {
+				utftext += String.fromCharCode((c >> 12) | 224);
+				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+				utftext += String.fromCharCode((c & 63) | 128);
+			}
+
+		}
+		return utftext;
+	}
+
+	// private method for UTF-8 decoding
+	_utf8_decode = function (utftext) {
+		var string = "";
+		var i = 0;
+		var c = 0;
+		var c1 = 0;
+		var c2 = 0;
+		var c3 = 0;
+		while (i < utftext.length) {
+			c = utftext.charCodeAt(i);
+			if (c < 128) {
+				string += String.fromCharCode(c);
+				i++;
+			} else if ((c > 191) && (c < 224)) {
+				c2 = utftext.charCodeAt(i + 1);
+				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+				i += 2;
+			} else {
+				c2 = utftext.charCodeAt(i + 1);
+				c3 = utftext.charCodeAt(i + 2);
+				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+				i += 3;
+			}
+		}
+		return string;
+	}
+}

+ 9 - 0
assets/Scripts/mk/util/encrypt/base64.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "46dbaff8-2676-4bf0-ba81-ccc6215bd94f",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 325 - 0
assets/Scripts/mk/util/encrypt/hmacSha256.ts

@@ -0,0 +1,325 @@
+/*
+ * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
+ * in FIPS 180-2
+ * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009.
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for details.
+ * Also http://anmar.eu.org/projects/jssha2/
+ */
+
+/*
+ * Configurable variables. You may need to tweak these to be compatible with
+ * the server-side, but the defaults work in most cases.
+ */
+
+export class hmacSha256 {
+      constructor() {
+
+      }
+
+      private static instance: hmacSha256 = null
+      static get Instance(): hmacSha256 {
+            if (!this.instance) {
+                  this.instance = new hmacSha256()
+            }
+            return this.instance
+      }
+
+      private hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase    */
+      private b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance  */
+
+      /*
+       * These are the functions you'll usually want to call
+       * They take string arguments and return either hex or base-64 encoded strings
+       */
+      hex_sha256(s) { return this.rstr2hex(this.rstr_sha256(this.str2rstr_utf8(s))); }
+      b64_sha256(s) { return this.rstr2b64(this.rstr_sha256(this.str2rstr_utf8(s))); }
+      any_sha256(s, e) { return this.rstr2any(this.rstr_sha256(this.str2rstr_utf8(s)), e); }
+      hex_hmac_sha256(k, d) { return this.rstr2hex(this.rstr_hmac_sha256(this.str2rstr_utf8(k), this.str2rstr_utf8(d))); }
+      b64_hmac_sha256(k, d) { return this.rstr2b64(this.rstr_hmac_sha256(this.str2rstr_utf8(k), this.str2rstr_utf8(d))); }
+      any_hmac_sha256(k, d, e) { return this.rstr2any(this.rstr_hmac_sha256(this.str2rstr_utf8(k), this.str2rstr_utf8(d)), e); }
+
+      /*
+       * Perform a simple self-test to see if the VM is working
+       */
+      sha256_vm_test() {
+            return this.hex_sha256("abc").toLowerCase() ==
+                  "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
+      }
+
+      /*
+       * Calculate the sha256 of a raw string
+       */
+      rstr_sha256(s) {
+            return this.binb2rstr(this.binb_sha256(this.rstr2binb(s), s.length * 8));
+      }
+
+      /*
+       * Calculate the HMAC-sha256 of a key and some data (raw strings)
+       */
+      rstr_hmac_sha256(key, data) {
+            var bkey = this.rstr2binb(key);
+            if (bkey.length > 16) bkey = this.binb_sha256(bkey, key.length * 8);
+
+            var ipad = Array(16), opad = Array(16);
+            for (var i = 0; i < 16; i++) {
+                  ipad[i] = bkey[i] ^ 0x36363636;
+                  opad[i] = bkey[i] ^ 0x5C5C5C5C;
+            }
+
+            var hash = this.binb_sha256(ipad.concat(this.rstr2binb(data)), 512 + data.length * 8);
+            return this.binb2rstr(this.binb_sha256(opad.concat(hash), 512 + 256));
+      }
+
+      /*
+       * Convert a raw string to a hex string
+       */
+      rstr2hex(input) {
+            try { this.hexcase } catch (e) { this.hexcase = 0; }
+            var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+            var output = "";
+            var x;
+            for (var i = 0; i < input.length; i++) {
+                  x = input.charCodeAt(i);
+                  output += hex_tab.charAt((x >>> 4) & 0x0F)
+                        + hex_tab.charAt(x & 0x0F);
+            }
+            return output;
+      }
+
+      /*
+       * Convert a raw string to a base-64 string
+       */
+      rstr2b64(input) {
+            try { this.b64pad } catch (e) { this.b64pad = ''; }
+            var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+            var output = "";
+            var len = input.length;
+            for (var i = 0; i < len; i += 3) {
+                  var triplet = (input.charCodeAt(i) << 16)
+                        | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0)
+                        | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
+                  for (var j = 0; j < 4; j++) {
+                        if (i * 8 + j * 6 > input.length * 8) output += this.b64pad;
+                        else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
+                  }
+            }
+            return output;
+      }
+
+      /*
+       * Convert a raw string to an arbitrary string encoding
+       */
+      rstr2any(input, encoding) {
+            var divisor = encoding.length;
+            var remainders = Array();
+            var i, q, x, quotient;
+
+            /* Convert to an array of 16-bit big-endian values, forming the dividend */
+            var dividend = Array(Math.ceil(input.length / 2));
+            for (i = 0; i < dividend.length; i++) {
+                  dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
+            }
+
+            /*
+             * Repeatedly perform a long division. The binary array forms the dividend,
+             * the length of the encoding is the divisor. Once computed, the quotient
+             * forms the dividend for the next step. We stop when the dividend is zero.
+             * All remainders are stored for later use.
+             */
+            while (dividend.length > 0) {
+                  quotient = Array();
+                  x = 0;
+                  for (i = 0; i < dividend.length; i++) {
+                        x = (x << 16) + dividend[i];
+                        q = Math.floor(x / divisor);
+                        x -= q * divisor;
+                        if (quotient.length > 0 || q > 0)
+                              quotient[quotient.length] = q;
+                  }
+                  remainders[remainders.length] = x;
+                  dividend = quotient;
+            }
+
+            /* Convert the remainders to the output string */
+            var output = "";
+            for (i = remainders.length - 1; i >= 0; i--)
+                  output += encoding.charAt(remainders[i]);
+
+            /* Append leading zero equivalents */
+            var full_length = Math.ceil(input.length * 8 /
+                  (Math.log(encoding.length) / Math.log(2)))
+            for (i = output.length; i < full_length; i++)
+                  output = encoding[0] + output;
+
+            return output;
+      }
+
+      /*
+       * Encode a string as utf-8.
+       * For efficiency, this assumes the input is valid utf-16.
+       */
+      str2rstr_utf8(input) {
+            var output = "";
+            var i = -1;
+            var x, y;
+
+            while (++i < input.length) {
+                  /* Decode utf-16 surrogate pairs */
+                  x = input.charCodeAt(i);
+                  y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
+                  if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) {
+                        x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
+                        i++;
+                  }
+
+                  /* Encode output as utf-8 */
+                  if (x <= 0x7F)
+                        output += String.fromCharCode(x);
+                  else if (x <= 0x7FF)
+                        output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F),
+                              0x80 | (x & 0x3F));
+                  else if (x <= 0xFFFF)
+                        output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
+                              0x80 | ((x >>> 6) & 0x3F),
+                              0x80 | (x & 0x3F));
+                  else if (x <= 0x1FFFFF)
+                        output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
+                              0x80 | ((x >>> 12) & 0x3F),
+                              0x80 | ((x >>> 6) & 0x3F),
+                              0x80 | (x & 0x3F));
+            }
+            return output;
+      }
+
+      /*
+       * Encode a string as utf-16
+       */
+      str2rstr_utf16le(input) {
+            var output = "";
+            for (var i = 0; i < input.length; i++)
+                  output += String.fromCharCode(input.charCodeAt(i) & 0xFF,
+                        (input.charCodeAt(i) >>> 8) & 0xFF);
+            return output;
+      }
+
+      str2rstr_utf16be(input) {
+            var output = "";
+            for (var i = 0; i < input.length; i++)
+                  output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
+                        input.charCodeAt(i) & 0xFF);
+            return output;
+      }
+
+      /*
+       * Convert a raw string to an array of big-endian words
+       * Characters >255 have their high-byte silently ignored.
+       */
+      rstr2binb(input) {
+            var output = Array(input.length >> 2);
+            for (var i = 0; i < output.length; i++)
+                  output[i] = 0;
+            for (var i = 0; i < input.length * 8; i += 8)
+                  output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
+            return output;
+      }
+
+      /*
+       * Convert an array of big-endian words to a string
+       */
+      binb2rstr(input) {
+            var output = "";
+            for (var i = 0; i < input.length * 32; i += 8)
+                  output += String.fromCharCode((input[i >> 5] >>> (24 - i % 32)) & 0xFF);
+            return output;
+      }
+
+      /*
+       * Main sha256 function, with its support functions
+       */
+      sha256_S(X, n) { return (X >>> n) | (X << (32 - n)); }
+      sha256_R(X, n) { return (X >>> n); }
+      sha256_Ch(x, y, z) { return ((x & y) ^ ((~x) & z)); }
+      sha256_Maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)); }
+      sha256_Sigma0256(x) { return (this.sha256_S(x, 2) ^ this.sha256_S(x, 13) ^ this.sha256_S(x, 22)); }
+      sha256_Sigma1256(x) { return (this.sha256_S(x, 6) ^ this.sha256_S(x, 11) ^ this.sha256_S(x, 25)); }
+      sha256_Gamma0256(x) { return (this.sha256_S(x, 7) ^ this.sha256_S(x, 18) ^ this.sha256_R(x, 3)); }
+      sha256_Gamma1256(x) { return (this.sha256_S(x, 17) ^ this.sha256_S(x, 19) ^ this.sha256_R(x, 10)); }
+      sha256_Sigma0512(x) { return (this.sha256_S(x, 28) ^ this.sha256_S(x, 34) ^ this.sha256_S(x, 39)); }
+      sha256_Sigma1512(x) { return (this.sha256_S(x, 14) ^ this.sha256_S(x, 18) ^ this.sha256_S(x, 41)); }
+      sha256_Gamma0512(x) { return (this.sha256_S(x, 1) ^ this.sha256_S(x, 8) ^ this.sha256_R(x, 7)); }
+      sha256_Gamma1512(x) { return (this.sha256_S(x, 19) ^ this.sha256_S(x, 61) ^ this.sha256_R(x, 6)); }
+
+      private sha256_K = new Array
+            (
+                  1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993,
+                  -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987,
+                  1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522,
+                  264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986,
+                  -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585,
+                  113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291,
+                  1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885,
+                  -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344,
+                  430227734, 506948616, 659060556, 883997877, 958139571, 1322822218,
+                  1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872,
+                  -1866530822, -1538233109, -1090935817, -965641998
+            );
+
+      binb_sha256(m, l) {
+            var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534,
+                  1359893119, -1694144372, 528734635, 1541459225);
+            var W = new Array(64);
+            var a, b, c, d, e, f, g, h;
+            var i, j, T1, T2;
+
+            /* append padding */
+            m[l >> 5] |= 0x80 << (24 - l % 32);
+            m[((l + 64 >> 9) << 4) + 15] = l;
+
+            for (i = 0; i < m.length; i += 16) {
+                  a = HASH[0];
+                  b = HASH[1];
+                  c = HASH[2];
+                  d = HASH[3];
+                  e = HASH[4];
+                  f = HASH[5];
+                  g = HASH[6];
+                  h = HASH[7];
+
+                  for (j = 0; j < 64; j++) {
+                        if (j < 16) W[j] = m[j + i];
+                        else W[j] = this.safe_add(this.safe_add(this.safe_add(this.sha256_Gamma1256(W[j - 2]), W[j - 7]),
+                              this.sha256_Gamma0256(W[j - 15])), W[j - 16]);
+
+                        T1 = this.safe_add(this.safe_add(this.safe_add(this.safe_add(h, this.sha256_Sigma1256(e)), this.sha256_Ch(e, f, g)),
+                              this.sha256_K[j]), W[j]);
+                        T2 = this.safe_add(this.sha256_Sigma0256(a), this.sha256_Maj(a, b, c));
+                        h = g;
+                        g = f;
+                        f = e;
+                        e = this.safe_add(d, T1);
+                        d = c;
+                        c = b;
+                        b = a;
+                        a = this.safe_add(T1, T2);
+                  }
+
+                  HASH[0] = this.safe_add(a, HASH[0]);
+                  HASH[1] = this.safe_add(b, HASH[1]);
+                  HASH[2] = this.safe_add(c, HASH[2]);
+                  HASH[3] = this.safe_add(d, HASH[3]);
+                  HASH[4] = this.safe_add(e, HASH[4]);
+                  HASH[5] = this.safe_add(f, HASH[5]);
+                  HASH[6] = this.safe_add(g, HASH[6]);
+                  HASH[7] = this.safe_add(h, HASH[7]);
+            }
+            return HASH;
+      }
+
+      safe_add(x, y) {
+            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+            return (msw << 16) | (lsw & 0xFFFF);
+      }
+}

+ 9 - 0
assets/Scripts/mk/util/encrypt/hmacSha256.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "ab38a1a8-ab8f-48ae-af63-ce2b715b4677",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 260 - 0
assets/Scripts/mk/util/encrypt/md5.js

@@ -0,0 +1,260 @@
+/*
+ * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
+ * Digest Algorithm, as defined in RFC 1321.
+ * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for more info.
+ */
+
+/*
+ * Configurable variables. You may need to tweak these to be compatible with
+ * the server-side, but the defaults work in most cases.
+ */
+var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
+var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
+var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
+
+/*
+ * These are the functions you'll usually want to call
+ * They take string arguments and return either hex or base-64 encoded strings
+ */
+function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
+function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
+function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
+function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
+function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
+function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
+
+/*
+ * Perform a simple self-test to see if the VM is working
+ */
+function md5_vm_test()
+{
+  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
+}
+
+/*
+ * Calculate the MD5 of an array of little-endian words, and a bit length
+ */
+function core_md5(x, len)
+{
+  /* append padding */
+  x[len >> 5] |= 0x80 << ((len) % 32);
+  x[(((len + 64) >>> 9) << 4) + 14] = len;
+
+  var a =  1732584193;
+  var b = -271733879;
+  var c = -1732584194;
+  var d =  271733878;
+
+  for(var i = 0; i < x.length; i += 16)
+  {
+    var olda = a;
+    var oldb = b;
+    var oldc = c;
+    var oldd = d;
+
+    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
+    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
+    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
+    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
+    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
+    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
+    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
+    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
+    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
+    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
+    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
+    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
+    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
+    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
+    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
+    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
+
+    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
+    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
+    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
+    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
+    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
+    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
+    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
+    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
+    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
+    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
+    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
+    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
+    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
+    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
+    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
+    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
+
+    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
+    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
+    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
+    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
+    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
+    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
+    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
+    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
+    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
+    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
+    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
+    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
+    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
+    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
+    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
+    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
+
+    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
+    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
+    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
+    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
+    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
+    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
+    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
+    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
+    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
+    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
+    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
+    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
+    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
+    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
+    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
+    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
+
+    a = safe_add(a, olda);
+    b = safe_add(b, oldb);
+    c = safe_add(c, oldc);
+    d = safe_add(d, oldd);
+  }
+  return Array(a, b, c, d);
+
+}
+
+/*
+ * These functions implement the four basic operations the algorithm uses.
+ */
+function md5_cmn(q, a, b, x, s, t)
+{
+  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
+}
+function md5_ff(a, b, c, d, x, s, t)
+{
+  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
+}
+function md5_gg(a, b, c, d, x, s, t)
+{
+  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
+}
+function md5_hh(a, b, c, d, x, s, t)
+{
+  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
+}
+function md5_ii(a, b, c, d, x, s, t)
+{
+  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
+}
+
+/*
+ * Calculate the HMAC-MD5, of a key and some data
+ */
+function core_hmac_md5(key, data)
+{
+  var bkey = str2binl(key);
+  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
+
+  var ipad = Array(16), opad = Array(16);
+  for(var i = 0; i < 16; i++)
+  {
+    ipad[i] = bkey[i] ^ 0x36363636;
+    opad[i] = bkey[i] ^ 0x5C5C5C5C;
+  }
+
+  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
+  return core_md5(opad.concat(hash), 512 + 128);
+}
+
+/*
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
+ * to work around bugs in some JS interpreters.
+ */
+function safe_add(x, y)
+{
+  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+  return (msw << 16) | (lsw & 0xFFFF);
+}
+
+/*
+ * Bitwise rotate a 32-bit number to the left.
+ */
+function bit_rol(num, cnt)
+{
+  return (num << cnt) | (num >>> (32 - cnt));
+}
+
+/*
+ * Convert a string to an array of little-endian words
+ * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
+ */
+function str2binl(str)
+{
+  var bin = Array();
+  var mask = (1 << chrsz) - 1;
+  for(var i = 0; i < str.length * chrsz; i += chrsz)
+    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
+  return bin;
+}
+
+/*
+ * Convert an array of little-endian words to a string
+ */
+function binl2str(bin)
+{
+  var str = "";
+  var mask = (1 << chrsz) - 1;
+  for(var i = 0; i < bin.length * 32; i += chrsz)
+    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
+  return str;
+}
+
+/*
+ * Convert an array of little-endian words to a hex string.
+ */
+function binl2hex(binarray)
+{
+  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+  var str = "";
+  for(var i = 0; i < binarray.length * 4; i++)
+  {
+    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
+           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
+  }
+  return str;
+}
+
+/*
+ * Convert an array of little-endian words to a base-64 string
+ */
+function binl2b64(binarray)
+{
+  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+  var str = "";
+  for(var i = 0; i < binarray.length * 4; i += 3)
+  {
+    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
+                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
+                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
+    for(var j = 0; j < 4; j++)
+    {
+      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
+      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
+    }
+  }
+  return str;
+}
+
+module.exports = {
+  hex_md5: hex_md5
+}

+ 9 - 0
assets/Scripts/mk/util/encrypt/md5.js.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "javascript",
+  "imported": true,
+  "uuid": "45a9c7ca-ed94-46b1-bd3a-b7f138fa68c2",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 12 - 0
assets/Scripts/mk/util/encrypt/rsa.meta

@@ -0,0 +1,12 @@
+{
+  "ver": "1.1.0",
+  "importer": "directory",
+  "imported": true,
+  "uuid": "13d5fe20-eb44-4a50-a2e8-62cf4089750a",
+  "files": [],
+  "subMetas": {},
+  "userData": {
+    "compressionType": {},
+    "isRemoteBundle": {}
+  }
+}

+ 87 - 0
assets/Scripts/mk/util/encrypt/rsa/jsencrypt.d.ts

@@ -0,0 +1,87 @@
+declare class JSEncrypt{
+
+  constructor(options?);
+  /**
+   * Method to set the rsa key parameter (one method is enough to set both the public
+   * and the private key, since the private key contains the public key paramenters)
+   * Log a warning if logs are enabled
+   * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
+   * @public
+   */
+  setKey(key: string);
+  /**
+   * Proxy method for setKey, for api compatibility
+   * @see setKey
+   * @public
+   */
+  setPrivateKey(privkey: string);
+  /**
+   * Proxy method for setKey, for api compatibility
+   * @see setKey
+   * @public
+   */
+  setPublicKey(pubkey: string);
+
+  /**
+   * Proxy method for RSAKey object's decrypt, decrypt the string using the private
+   * components of the rsa key object. Note that if the object was not set will be created
+   * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
+   * @param {string} string base64 encoded crypted string to decrypt
+   * @return {string} the decrypted string
+   * @public
+   */
+  decrypt(string): string|false;
+
+/**
+ * Proxy method for RSAKey object's encrypt, encrypt the string using the public
+ * components of the rsa key object. Note that if the object was not set will be created
+ * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
+ * @param {string} string the string to encrypt
+ * @return {string} the encrypted string encoded in base64
+ * @public
+ */
+  encrypt(string) :string|false;
+
+/**
+ * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
+ * will be created and returned
+ * @param {callback} [cb] the callback to be called if we want the key to be generated
+ * in an async fashion
+ * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
+ * @public
+ */
+getKey(cb);
+
+/**
+ * Returns the pem encoded representation of the private key
+ * If the key doesn't exists a new key will be created
+ * @returns {string} pem encoded representation of the private key WITH header and footer
+ * @public
+ */
+getPrivateKey();
+
+/**
+ * Returns the pem encoded representation of the private key
+ * If the key doesn't exists a new key will be created
+ * @returns {string} pem encoded representation of the private key WITHOUT header and footer
+ * @public
+ */
+getPrivateKeyB64();
+
+/**
+ * Returns the pem encoded representation of the public key
+ * If the key doesn't exists a new key will be created
+ * @returns {string} pem encoded representation of the public key WITH header and footer
+ * @public
+ */
+getPublicKey();
+
+/**
+ * Returns the pem encoded representation of the public key
+ * If the key doesn't exists a new key will be created
+ * @returns {string} pem encoded representation of the public key WITHOUT header and footer
+ * @public
+ */
+getPublicKeyB64();
+
+}

+ 9 - 0
assets/Scripts/mk/util/encrypt/rsa/jsencrypt.d.ts.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "typescript",
+  "imported": true,
+  "uuid": "1b3ea26c-37e7-4b10-85ff-258565c822cc",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 5481 - 0
assets/Scripts/mk/util/encrypt/rsa/jsencrypt.js

@@ -0,0 +1,5481 @@
+(function (global, factory) {
+	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+	typeof define === 'function' && define.amd ? define(['exports'], factory) :
+	(factory((global.JSEncrypt = {})));
+}(this, (function (exports) { 'use strict';
+
+var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
+function int2char(n) {
+    return BI_RM.charAt(n);
+}
+//#region BIT_OPERATIONS
+// (public) this & a
+function op_and(x, y) {
+    return x & y;
+}
+// (public) this | a
+function op_or(x, y) {
+    return x | y;
+}
+// (public) this ^ a
+function op_xor(x, y) {
+    return x ^ y;
+}
+// (public) this & ~a
+function op_andnot(x, y) {
+    return x & ~y;
+}
+// return index of lowest 1-bit in x, x < 2^31
+function lbit(x) {
+    if (x == 0) {
+        return -1;
+    }
+    var r = 0;
+    if ((x & 0xffff) == 0) {
+        x >>= 16;
+        r += 16;
+    }
+    if ((x & 0xff) == 0) {
+        x >>= 8;
+        r += 8;
+    }
+    if ((x & 0xf) == 0) {
+        x >>= 4;
+        r += 4;
+    }
+    if ((x & 3) == 0) {
+        x >>= 2;
+        r += 2;
+    }
+    if ((x & 1) == 0) {
+        ++r;
+    }
+    return r;
+}
+// return number of 1 bits in x
+function cbit(x) {
+    var r = 0;
+    while (x != 0) {
+        x &= x - 1;
+        ++r;
+    }
+    return r;
+}
+//#endregion BIT_OPERATIONS
+
+var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+var b64pad = "=";
+function hex2b64(h) {
+    var i;
+    var c;
+    var ret = "";
+    for (i = 0; i + 3 <= h.length; i += 3) {
+        c = parseInt(h.substring(i, i + 3), 16);
+        ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
+    }
+    if (i + 1 == h.length) {
+        c = parseInt(h.substring(i, i + 1), 16);
+        ret += b64map.charAt(c << 2);
+    }
+    else if (i + 2 == h.length) {
+        c = parseInt(h.substring(i, i + 2), 16);
+        ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
+    }
+    while ((ret.length & 3) > 0) {
+        ret += b64pad;
+    }
+    return ret;
+}
+// convert a base64 string to hex
+function b64tohex(s) {
+    var ret = "";
+    var i;
+    var k = 0; // b64 state, 0-3
+    var slop = 0;
+    for (i = 0; i < s.length; ++i) {
+        if (s.charAt(i) == b64pad) {
+            break;
+        }
+        var v = b64map.indexOf(s.charAt(i));
+        if (v < 0) {
+            continue;
+        }
+        if (k == 0) {
+            ret += int2char(v >> 2);
+            slop = v & 3;
+            k = 1;
+        }
+        else if (k == 1) {
+            ret += int2char((slop << 2) | (v >> 4));
+            slop = v & 0xf;
+            k = 2;
+        }
+        else if (k == 2) {
+            ret += int2char(slop);
+            ret += int2char(v >> 2);
+            slop = v & 3;
+            k = 3;
+        }
+        else {
+            ret += int2char((slop << 2) | (v >> 4));
+            ret += int2char(v & 0xf);
+            k = 0;
+        }
+    }
+    if (k == 1) {
+        ret += int2char(slop << 2);
+    }
+    return ret;
+}
+
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+var extendStatics = function(d, b) {
+    extendStatics = Object.setPrototypeOf ||
+        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+    return extendStatics(d, b);
+};
+
+function __extends(d, b) {
+    extendStatics(d, b);
+    function __() { this.constructor = d; }
+    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+
+// Hex JavaScript decoder
+// Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
+var decoder;
+var Hex = {
+    decode: function (a) {
+        var i;
+        if (decoder === undefined) {
+            var hex = "0123456789ABCDEF";
+            var ignore = " \f\n\r\t\u00A0\u2028\u2029";
+            decoder = {};
+            for (i = 0; i < 16; ++i) {
+                decoder[hex.charAt(i)] = i;
+            }
+            hex = hex.toLowerCase();
+            for (i = 10; i < 16; ++i) {
+                decoder[hex.charAt(i)] = i;
+            }
+            for (i = 0; i < ignore.length; ++i) {
+                decoder[ignore.charAt(i)] = -1;
+            }
+        }
+        var out = [];
+        var bits = 0;
+        var char_count = 0;
+        for (i = 0; i < a.length; ++i) {
+            var c = a.charAt(i);
+            if (c == "=") {
+                break;
+            }
+            c = decoder[c];
+            if (c == -1) {
+                continue;
+            }
+            if (c === undefined) {
+                throw new Error("Illegal character at offset " + i);
+            }
+            bits |= c;
+            if (++char_count >= 2) {
+                out[out.length] = bits;
+                bits = 0;
+                char_count = 0;
+            }
+            else {
+                bits <<= 4;
+            }
+        }
+        if (char_count) {
+            throw new Error("Hex encoding incomplete: 4 bits missing");
+        }
+        return out;
+    }
+};
+
+// Base64 JavaScript decoder
+// Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
+var decoder$1;
+var Base64 = {
+    decode: function (a) {
+        var i;
+        if (decoder$1 === undefined) {
+            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+            var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
+            decoder$1 = Object.create(null);
+            for (i = 0; i < 64; ++i) {
+                decoder$1[b64.charAt(i)] = i;
+            }
+            for (i = 0; i < ignore.length; ++i) {
+                decoder$1[ignore.charAt(i)] = -1;
+            }
+        }
+        var out = [];
+        var bits = 0;
+        var char_count = 0;
+        for (i = 0; i < a.length; ++i) {
+            var c = a.charAt(i);
+            if (c == "=") {
+                break;
+            }
+            c = decoder$1[c];
+            if (c == -1) {
+                continue;
+            }
+            if (c === undefined) {
+                throw new Error("Illegal character at offset " + i);
+            }
+            bits |= c;
+            if (++char_count >= 4) {
+                out[out.length] = (bits >> 16);
+                out[out.length] = (bits >> 8) & 0xFF;
+                out[out.length] = bits & 0xFF;
+                bits = 0;
+                char_count = 0;
+            }
+            else {
+                bits <<= 6;
+            }
+        }
+        switch (char_count) {
+            case 1:
+                throw new Error("Base64 encoding incomplete: at least 2 bits missing");
+            case 2:
+                out[out.length] = (bits >> 10);
+                break;
+            case 3:
+                out[out.length] = (bits >> 16);
+                out[out.length] = (bits >> 8) & 0xFF;
+                break;
+        }
+        return out;
+    },
+    re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
+    unarmor: function (a) {
+        var m = Base64.re.exec(a);
+        if (m) {
+            if (m[1]) {
+                a = m[1];
+            }
+            else if (m[2]) {
+                a = m[2];
+            }
+            else {
+                throw new Error("RegExp out of sync");
+            }
+        }
+        return Base64.decode(a);
+    }
+};
+
+// Big integer base-10 printing library
+// Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
+var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
+var Int10 = /** @class */ (function () {
+    function Int10(value) {
+        this.buf = [+value || 0];
+    }
+    Int10.prototype.mulAdd = function (m, c) {
+        // assert(m <= 256)
+        var b = this.buf;
+        var l = b.length;
+        var i;
+        var t;
+        for (i = 0; i < l; ++i) {
+            t = b[i] * m + c;
+            if (t < max) {
+                c = 0;
+            }
+            else {
+                c = 0 | (t / max);
+                t -= c * max;
+            }
+            b[i] = t;
+        }
+        if (c > 0) {
+            b[i] = c;
+        }
+    };
+    Int10.prototype.sub = function (c) {
+        // assert(m <= 256)
+        var b = this.buf;
+        var l = b.length;
+        var i;
+        var t;
+        for (i = 0; i < l; ++i) {
+            t = b[i] - c;
+            if (t < 0) {
+                t += max;
+                c = 1;
+            }
+            else {
+                c = 0;
+            }
+            b[i] = t;
+        }
+        while (b[b.length - 1] === 0) {
+            b.pop();
+        }
+    };
+    Int10.prototype.toString = function (base) {
+        if ((base || 10) != 10) {
+            throw new Error("only base 10 is supported");
+        }
+        var b = this.buf;
+        var s = b[b.length - 1].toString();
+        for (var i = b.length - 2; i >= 0; --i) {
+            s += (max + b[i]).toString().substring(1);
+        }
+        return s;
+    };
+    Int10.prototype.valueOf = function () {
+        var b = this.buf;
+        var v = 0;
+        for (var i = b.length - 1; i >= 0; --i) {
+            v = v * max + b[i];
+        }
+        return v;
+    };
+    Int10.prototype.simplify = function () {
+        var b = this.buf;
+        return (b.length == 1) ? b[0] : this;
+    };
+    return Int10;
+}());
+
+// ASN.1 JavaScript decoder
+var ellipsis = "\u2026";
+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)?)?$/;
+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)?)?$/;
+function stringCut(str, len) {
+    if (str.length > len) {
+        str = str.substring(0, len) + ellipsis;
+    }
+    return str;
+}
+var Stream = /** @class */ (function () {
+    function Stream(enc, pos) {
+        this.hexDigits = "0123456789ABCDEF";
+        if (enc instanceof Stream) {
+            this.enc = enc.enc;
+            this.pos = enc.pos;
+        }
+        else {
+            // enc should be an array or a binary string
+            this.enc = enc;
+            this.pos = pos;
+        }
+    }
+    Stream.prototype.get = function (pos) {
+        if (pos === undefined) {
+            pos = this.pos++;
+        }
+        if (pos >= this.enc.length) {
+            throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
+        }
+        return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
+    };
+    Stream.prototype.hexByte = function (b) {
+        return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
+    };
+    Stream.prototype.hexDump = function (start, end, raw) {
+        var s = "";
+        for (var i = start; i < end; ++i) {
+            s += this.hexByte(this.get(i));
+            if (raw !== true) {
+                switch (i & 0xF) {
+                    case 0x7:
+                        s += "  ";
+                        break;
+                    case 0xF:
+                        s += "\n";
+                        break;
+                    default:
+                        s += " ";
+                }
+            }
+        }
+        return s;
+    };
+    Stream.prototype.isASCII = function (start, end) {
+        for (var i = start; i < end; ++i) {
+            var c = this.get(i);
+            if (c < 32 || c > 176) {
+                return false;
+            }
+        }
+        return true;
+    };
+    Stream.prototype.parseStringISO = function (start, end) {
+        var s = "";
+        for (var i = start; i < end; ++i) {
+            s += String.fromCharCode(this.get(i));
+        }
+        return s;
+    };
+    Stream.prototype.parseStringUTF = function (start, end) {
+        var s = "";
+        for (var i = start; i < end;) {
+            var c = this.get(i++);
+            if (c < 128) {
+                s += String.fromCharCode(c);
+            }
+            else if ((c > 191) && (c < 224)) {
+                s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
+            }
+            else {
+                s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
+            }
+        }
+        return s;
+    };
+    Stream.prototype.parseStringBMP = function (start, end) {
+        var str = "";
+        var hi;
+        var lo;
+        for (var i = start; i < end;) {
+            hi = this.get(i++);
+            lo = this.get(i++);
+            str += String.fromCharCode((hi << 8) | lo);
+        }
+        return str;
+    };
+    Stream.prototype.parseTime = function (start, end, shortYear) {
+        var s = this.parseStringISO(start, end);
+        var m = (shortYear ? reTimeS : reTimeL).exec(s);
+        if (!m) {
+            return "Unrecognized time: " + s;
+        }
+        if (shortYear) {
+            // to avoid querying the timer, use the fixed range [1970, 2069]
+            // it will conform with ITU X.400 [-10, +40] sliding window until 2030
+            m[1] = +m[1];
+            m[1] += (+m[1] < 70) ? 2000 : 1900;
+        }
+        s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
+        if (m[5]) {
+            s += ":" + m[5];
+            if (m[6]) {
+                s += ":" + m[6];
+                if (m[7]) {
+                    s += "." + m[7];
+                }
+            }
+        }
+        if (m[8]) {
+            s += " UTC";
+            if (m[8] != "Z") {
+                s += m[8];
+                if (m[9]) {
+                    s += ":" + m[9];
+                }
+            }
+        }
+        return s;
+    };
+    Stream.prototype.parseInteger = function (start, end) {
+        var v = this.get(start);
+        var neg = (v > 127);
+        var pad = neg ? 255 : 0;
+        var len;
+        var s = "";
+        // skip unuseful bits (not allowed in DER)
+        while (v == pad && ++start < end) {
+            v = this.get(start);
+        }
+        len = end - start;
+        if (len === 0) {
+            return neg ? -1 : 0;
+        }
+        // show bit length of huge integers
+        if (len > 4) {
+            s = v;
+            len <<= 3;
+            while (((+s ^ pad) & 0x80) == 0) {
+                s = +s << 1;
+                --len;
+            }
+            s = "(" + len + " bit)\n";
+        }
+        // decode the integer
+        if (neg) {
+            v = v - 256;
+        }
+        var n = new Int10(v);
+        for (var i = start + 1; i < end; ++i) {
+            n.mulAdd(256, this.get(i));
+        }
+        return s + n.toString();
+    };
+    Stream.prototype.parseBitString = function (start, end, maxLength) {
+        var unusedBit = this.get(start);
+        var lenBit = ((end - start - 1) << 3) - unusedBit;
+        var intro = "(" + lenBit + " bit)\n";
+        var s = "";
+        for (var i = start + 1; i < end; ++i) {
+            var b = this.get(i);
+            var skip = (i == end - 1) ? unusedBit : 0;
+            for (var j = 7; j >= skip; --j) {
+                s += (b >> j) & 1 ? "1" : "0";
+            }
+            if (s.length > maxLength) {
+                return intro + stringCut(s, maxLength);
+            }
+        }
+        return intro + s;
+    };
+    Stream.prototype.parseOctetString = function (start, end, maxLength) {
+        if (this.isASCII(start, end)) {
+            return stringCut(this.parseStringISO(start, end), maxLength);
+        }
+        var len = end - start;
+        var s = "(" + len + " byte)\n";
+        maxLength /= 2; // we work in bytes
+        if (len > maxLength) {
+            end = start + maxLength;
+        }
+        for (var i = start; i < end; ++i) {
+            s += this.hexByte(this.get(i));
+        }
+        if (len > maxLength) {
+            s += ellipsis;
+        }
+        return s;
+    };
+    Stream.prototype.parseOID = function (start, end, maxLength) {
+        var s = "";
+        var n = new Int10();
+        var bits = 0;
+        for (var i = start; i < end; ++i) {
+            var v = this.get(i);
+            n.mulAdd(128, v & 0x7F);
+            bits += 7;
+            if (!(v & 0x80)) { // finished
+                if (s === "") {
+                    n = n.simplify();
+                    if (n instanceof Int10) {
+                        n.sub(80);
+                        s = "2." + n.toString();
+                    }
+                    else {
+                        var m = n < 80 ? n < 40 ? 0 : 1 : 2;
+                        s = m + "." + (n - m * 40);
+                    }
+                }
+                else {
+                    s += "." + n.toString();
+                }
+                if (s.length > maxLength) {
+                    return stringCut(s, maxLength);
+                }
+                n = new Int10();
+                bits = 0;
+            }
+        }
+        if (bits > 0) {
+            s += ".incomplete";
+        }
+        return s;
+    };
+    return Stream;
+}());
+var ASN1 = /** @class */ (function () {
+    function ASN1(stream, header, length, tag, sub) {
+        if (!(tag instanceof ASN1Tag)) {
+            throw new Error("Invalid tag value.");
+        }
+        this.stream = stream;
+        this.header = header;
+        this.length = length;
+        this.tag = tag;
+        this.sub = sub;
+    }
+    ASN1.prototype.typeName = function () {
+        switch (this.tag.tagClass) {
+            case 0: // universal
+                switch (this.tag.tagNumber) {
+                    case 0x00:
+                        return "EOC";
+                    case 0x01:
+                        return "BOOLEAN";
+                    case 0x02:
+                        return "INTEGER";
+                    case 0x03:
+                        return "BIT_STRING";
+                    case 0x04:
+                        return "OCTET_STRING";
+                    case 0x05:
+                        return "NULL";
+                    case 0x06:
+                        return "OBJECT_IDENTIFIER";
+                    case 0x07:
+                        return "ObjectDescriptor";
+                    case 0x08:
+                        return "EXTERNAL";
+                    case 0x09:
+                        return "REAL";
+                    case 0x0A:
+                        return "ENUMERATED";
+                    case 0x0B:
+                        return "EMBEDDED_PDV";
+                    case 0x0C:
+                        return "UTF8String";
+                    case 0x10:
+                        return "SEQUENCE";
+                    case 0x11:
+                        return "SET";
+                    case 0x12:
+                        return "NumericString";
+                    case 0x13:
+                        return "PrintableString"; // ASCII subset
+                    case 0x14:
+                        return "TeletexString"; // aka T61String
+                    case 0x15:
+                        return "VideotexString";
+                    case 0x16:
+                        return "IA5String"; // ASCII
+                    case 0x17:
+                        return "UTCTime";
+                    case 0x18:
+                        return "GeneralizedTime";
+                    case 0x19:
+                        return "GraphicString";
+                    case 0x1A:
+                        return "VisibleString"; // ASCII subset
+                    case 0x1B:
+                        return "GeneralString";
+                    case 0x1C:
+                        return "UniversalString";
+                    case 0x1E:
+                        return "BMPString";
+                }
+                return "Universal_" + this.tag.tagNumber.toString();
+            case 1:
+                return "Application_" + this.tag.tagNumber.toString();
+            case 2:
+                return "[" + this.tag.tagNumber.toString() + "]"; // Context
+            case 3:
+                return "Private_" + this.tag.tagNumber.toString();
+        }
+    };
+    ASN1.prototype.content = function (maxLength) {
+        if (this.tag === undefined) {
+            return null;
+        }
+        if (maxLength === undefined) {
+            maxLength = Infinity;
+        }
+        var content = this.posContent();
+        var len = Math.abs(this.length);
+        if (!this.tag.isUniversal()) {
+            if (this.sub !== null) {
+                return "(" + this.sub.length + " elem)";
+            }
+            return this.stream.parseOctetString(content, content + len, maxLength);
+        }
+        switch (this.tag.tagNumber) {
+            case 0x01: // BOOLEAN
+                return (this.stream.get(content) === 0) ? "false" : "true";
+            case 0x02: // INTEGER
+                return this.stream.parseInteger(content, content + len);
+            case 0x03: // BIT_STRING
+                return this.sub ? "(" + this.sub.length + " elem)" :
+                    this.stream.parseBitString(content, content + len, maxLength);
+            case 0x04: // OCTET_STRING
+                return this.sub ? "(" + this.sub.length + " elem)" :
+                    this.stream.parseOctetString(content, content + len, maxLength);
+            // case 0x05: // NULL
+            case 0x06: // OBJECT_IDENTIFIER
+                return this.stream.parseOID(content, content + len, maxLength);
+            // case 0x07: // ObjectDescriptor
+            // case 0x08: // EXTERNAL
+            // case 0x09: // REAL
+            // case 0x0A: // ENUMERATED
+            // case 0x0B: // EMBEDDED_PDV
+            case 0x10: // SEQUENCE
+            case 0x11: // SET
+                if (this.sub !== null) {
+                    return "(" + this.sub.length + " elem)";
+                }
+                else {
+                    return "(no elem)";
+                }
+            case 0x0C: // UTF8String
+                return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
+            case 0x12: // NumericString
+            case 0x13: // PrintableString
+            case 0x14: // TeletexString
+            case 0x15: // VideotexString
+            case 0x16: // IA5String
+            // case 0x19: // GraphicString
+            case 0x1A: // VisibleString
+                // case 0x1B: // GeneralString
+                // case 0x1C: // UniversalString
+                return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
+            case 0x1E: // BMPString
+                return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
+            case 0x17: // UTCTime
+            case 0x18: // GeneralizedTime
+                return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
+        }
+        return null;
+    };
+    ASN1.prototype.toString = function () {
+        return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
+    };
+    ASN1.prototype.toPrettyString = function (indent) {
+        if (indent === undefined) {
+            indent = "";
+        }
+        var s = indent + this.typeName() + " @" + this.stream.pos;
+        if (this.length >= 0) {
+            s += "+";
+        }
+        s += this.length;
+        if (this.tag.tagConstructed) {
+            s += " (constructed)";
+        }
+        else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
+            s += " (encapsulates)";
+        }
+        s += "\n";
+        if (this.sub !== null) {
+            indent += "  ";
+            for (var i = 0, max = this.sub.length; i < max; ++i) {
+                s += this.sub[i].toPrettyString(indent);
+            }
+        }
+        return s;
+    };
+    ASN1.prototype.posStart = function () {
+        return this.stream.pos;
+    };
+    ASN1.prototype.posContent = function () {
+        return this.stream.pos + this.header;
+    };
+    ASN1.prototype.posEnd = function () {
+        return this.stream.pos + this.header + Math.abs(this.length);
+    };
+    ASN1.prototype.toHexString = function () {
+        return this.stream.hexDump(this.posStart(), this.posEnd(), true);
+    };
+    ASN1.decodeLength = function (stream) {
+        var buf = stream.get();
+        var len = buf & 0x7F;
+        if (len == buf) {
+            return len;
+        }
+        // no reason to use Int10, as it would be a huge buffer anyways
+        if (len > 6) {
+            throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
+        }
+        if (len === 0) {
+            return null;
+        } // undefined
+        buf = 0;
+        for (var i = 0; i < len; ++i) {
+            buf = (buf * 256) + stream.get();
+        }
+        return buf;
+    };
+    /**
+     * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
+     * @returns {string}
+     * @public
+     */
+    ASN1.prototype.getHexStringValue = function () {
+        var hexString = this.toHexString();
+        var offset = this.header * 2;
+        var length = this.length * 2;
+        return hexString.substr(offset, length);
+    };
+    ASN1.decode = function (str) {
+        var stream;
+        if (!(str instanceof Stream)) {
+            stream = new Stream(str, 0);
+        }
+        else {
+            stream = str;
+        }
+        var streamStart = new Stream(stream);
+        var tag = new ASN1Tag(stream);
+        var len = ASN1.decodeLength(stream);
+        var start = stream.pos;
+        var header = start - streamStart.pos;
+        var sub = null;
+        var getSub = function () {
+            var ret = [];
+            if (len !== null) {
+                // definite length
+                var end = start + len;
+                while (stream.pos < end) {
+                    ret[ret.length] = ASN1.decode(stream);
+                }
+                if (stream.pos != end) {
+                    throw new Error("Content size is not correct for container starting at offset " + start);
+                }
+            }
+            else {
+                // undefined length
+                try {
+                    for (;;) {
+                        var s = ASN1.decode(stream);
+                        if (s.tag.isEOC()) {
+                            break;
+                        }
+                        ret[ret.length] = s;
+                    }
+                    len = start - stream.pos; // undefined lengths are represented as negative values
+                }
+                catch (e) {
+                    throw new Error("Exception while decoding undefined length content: " + e);
+                }
+            }
+            return ret;
+        };
+        if (tag.tagConstructed) {
+            // must have valid content
+            sub = getSub();
+        }
+        else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
+            // sometimes BitString and OctetString are used to encapsulate ASN.1
+            try {
+                if (tag.tagNumber == 0x03) {
+                    if (stream.get() != 0) {
+                        throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
+                    }
+                }
+                sub = getSub();
+                for (var i = 0; i < sub.length; ++i) {
+                    if (sub[i].tag.isEOC()) {
+                        throw new Error("EOC is not supposed to be actual content.");
+                    }
+                }
+            }
+            catch (e) {
+                // but silently ignore when they don't
+                sub = null;
+            }
+        }
+        if (sub === null) {
+            if (len === null) {
+                throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
+            }
+            stream.pos = start + Math.abs(len);
+        }
+        return new ASN1(streamStart, header, len, tag, sub);
+    };
+    return ASN1;
+}());
+var ASN1Tag = /** @class */ (function () {
+    function ASN1Tag(stream) {
+        var buf = stream.get();
+        this.tagClass = buf >> 6;
+        this.tagConstructed = ((buf & 0x20) !== 0);
+        this.tagNumber = buf & 0x1F;
+        if (this.tagNumber == 0x1F) { // long tag
+            var n = new Int10();
+            do {
+                buf = stream.get();
+                n.mulAdd(128, buf & 0x7F);
+            } while (buf & 0x80);
+            this.tagNumber = n.simplify();
+        }
+    }
+    ASN1Tag.prototype.isUniversal = function () {
+        return this.tagClass === 0x00;
+    };
+    ASN1Tag.prototype.isEOC = function () {
+        return this.tagClass === 0x00 && this.tagNumber === 0x00;
+    };
+    return ASN1Tag;
+}());
+
+// Copyright (c) 2005  Tom Wu
+// Bits per digit
+var dbits;
+// JavaScript engine analysis
+var canary = 0xdeadbeefcafe;
+var j_lm = ((canary & 0xffffff) == 0xefcafe);
+//#region
+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];
+var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
+//#endregion
+// (public) Constructor
+var BigInteger = /** @class */ (function () {
+    function BigInteger(a, b, c) {
+        if (a != null) {
+            if ("number" == typeof a) {
+                this.fromNumber(a, b, c);
+            }
+            else if (b == null && "string" != typeof a) {
+                this.fromString(a, 256);
+            }
+            else {
+                this.fromString(a, b);
+            }
+        }
+    }
+    //#region PUBLIC
+    // BigInteger.prototype.toString = bnToString;
+    // (public) return string representation in given radix
+    BigInteger.prototype.toString = function (b) {
+        if (this.s < 0) {
+            return "-" + this.negate().toString(b);
+        }
+        var k;
+        if (b == 16) {
+            k = 4;
+        }
+        else if (b == 8) {
+            k = 3;
+        }
+        else if (b == 2) {
+            k = 1;
+        }
+        else if (b == 32) {
+            k = 5;
+        }
+        else if (b == 4) {
+            k = 2;
+        }
+        else {
+            return this.toRadix(b);
+        }
+        var km = (1 << k) - 1;
+        var d;
+        var m = false;
+        var r = "";
+        var i = this.t;
+        var p = this.DB - (i * this.DB) % k;
+        if (i-- > 0) {
+            if (p < this.DB && (d = this[i] >> p) > 0) {
+                m = true;
+                r = int2char(d);
+            }
+            while (i >= 0) {
+                if (p < k) {
+                    d = (this[i] & ((1 << p) - 1)) << (k - p);
+                    d |= this[--i] >> (p += this.DB - k);
+                }
+                else {
+                    d = (this[i] >> (p -= k)) & km;
+                    if (p <= 0) {
+                        p += this.DB;
+                        --i;
+                    }
+                }
+                if (d > 0) {
+                    m = true;
+                }
+                if (m) {
+                    r += int2char(d);
+                }
+            }
+        }
+        return m ? r : "0";
+    };
+    // BigInteger.prototype.negate = bnNegate;
+    // (public) -this
+    BigInteger.prototype.negate = function () {
+        var r = nbi();
+        BigInteger.ZERO.subTo(this, r);
+        return r;
+    };
+    // BigInteger.prototype.abs = bnAbs;
+    // (public) |this|
+    BigInteger.prototype.abs = function () {
+        return (this.s < 0) ? this.negate() : this;
+    };
+    // BigInteger.prototype.compareTo = bnCompareTo;
+    // (public) return + if this > a, - if this < a, 0 if equal
+    BigInteger.prototype.compareTo = function (a) {
+        var r = this.s - a.s;
+        if (r != 0) {
+            return r;
+        }
+        var i = this.t;
+        r = i - a.t;
+        if (r != 0) {
+            return (this.s < 0) ? -r : r;
+        }
+        while (--i >= 0) {
+            if ((r = this[i] - a[i]) != 0) {
+                return r;
+            }
+        }
+        return 0;
+    };
+    // BigInteger.prototype.bitLength = bnBitLength;
+    // (public) return the number of bits in "this"
+    BigInteger.prototype.bitLength = function () {
+        if (this.t <= 0) {
+            return 0;
+        }
+        return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
+    };
+    // BigInteger.prototype.mod = bnMod;
+    // (public) this mod a
+    BigInteger.prototype.mod = function (a) {
+        var r = nbi();
+        this.abs().divRemTo(a, null, r);
+        if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
+            a.subTo(r, r);
+        }
+        return r;
+    };
+    // BigInteger.prototype.modPowInt = bnModPowInt;
+    // (public) this^e % m, 0 <= e < 2^32
+    BigInteger.prototype.modPowInt = function (e, m) {
+        var z;
+        if (e < 256 || m.isEven()) {
+            z = new Classic(m);
+        }
+        else {
+            z = new Montgomery(m);
+        }
+        return this.exp(e, z);
+    };
+    // BigInteger.prototype.clone = bnClone;
+    // (public)
+    BigInteger.prototype.clone = function () {
+        var r = nbi();
+        this.copyTo(r);
+        return r;
+    };
+    // BigInteger.prototype.intValue = bnIntValue;
+    // (public) return value as integer
+    BigInteger.prototype.intValue = function () {
+        if (this.s < 0) {
+            if (this.t == 1) {
+                return this[0] - this.DV;
+            }
+            else if (this.t == 0) {
+                return -1;
+            }
+        }
+        else if (this.t == 1) {
+            return this[0];
+        }
+        else if (this.t == 0) {
+            return 0;
+        }
+        // assumes 16 < DB < 32
+        return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
+    };
+    // BigInteger.prototype.byteValue = bnByteValue;
+    // (public) return value as byte
+    BigInteger.prototype.byteValue = function () {
+        return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
+    };
+    // BigInteger.prototype.shortValue = bnShortValue;
+    // (public) return value as short (assumes DB>=16)
+    BigInteger.prototype.shortValue = function () {
+        return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
+    };
+    // BigInteger.prototype.signum = bnSigNum;
+    // (public) 0 if this == 0, 1 if this > 0
+    BigInteger.prototype.signum = function () {
+        if (this.s < 0) {
+            return -1;
+        }
+        else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
+            return 0;
+        }
+        else {
+            return 1;
+        }
+    };
+    // BigInteger.prototype.toByteArray = bnToByteArray;
+    // (public) convert to bigendian byte array
+    BigInteger.prototype.toByteArray = function () {
+        var i = this.t;
+        var r = [];
+        r[0] = this.s;
+        var p = this.DB - (i * this.DB) % 8;
+        var d;
+        var k = 0;
+        if (i-- > 0) {
+            if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
+                r[k++] = d | (this.s << (this.DB - p));
+            }
+            while (i >= 0) {
+                if (p < 8) {
+                    d = (this[i] & ((1 << p) - 1)) << (8 - p);
+                    d |= this[--i] >> (p += this.DB - 8);
+                }
+                else {
+                    d = (this[i] >> (p -= 8)) & 0xff;
+                    if (p <= 0) {
+                        p += this.DB;
+                        --i;
+                    }
+                }
+                if ((d & 0x80) != 0) {
+                    d |= -256;
+                }
+                if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
+                    ++k;
+                }
+                if (k > 0 || d != this.s) {
+                    r[k++] = d;
+                }
+            }
+        }
+        return r;
+    };
+    // BigInteger.prototype.equals = bnEquals;
+    BigInteger.prototype.equals = function (a) {
+        return (this.compareTo(a) == 0);
+    };
+    // BigInteger.prototype.min = bnMin;
+    BigInteger.prototype.min = function (a) {
+        return (this.compareTo(a) < 0) ? this : a;
+    };
+    // BigInteger.prototype.max = bnMax;
+    BigInteger.prototype.max = function (a) {
+        return (this.compareTo(a) > 0) ? this : a;
+    };
+    // BigInteger.prototype.and = bnAnd;
+    BigInteger.prototype.and = function (a) {
+        var r = nbi();
+        this.bitwiseTo(a, op_and, r);
+        return r;
+    };
+    // BigInteger.prototype.or = bnOr;
+    BigInteger.prototype.or = function (a) {
+        var r = nbi();
+        this.bitwiseTo(a, op_or, r);
+        return r;
+    };
+    // BigInteger.prototype.xor = bnXor;
+    BigInteger.prototype.xor = function (a) {
+        var r = nbi();
+        this.bitwiseTo(a, op_xor, r);
+        return r;
+    };
+    // BigInteger.prototype.andNot = bnAndNot;
+    BigInteger.prototype.andNot = function (a) {
+        var r = nbi();
+        this.bitwiseTo(a, op_andnot, r);
+        return r;
+    };
+    // BigInteger.prototype.not = bnNot;
+    // (public) ~this
+    BigInteger.prototype.not = function () {
+        var r = nbi();
+        for (var i = 0; i < this.t; ++i) {
+            r[i] = this.DM & ~this[i];
+        }
+        r.t = this.t;
+        r.s = ~this.s;
+        return r;
+    };
+    // BigInteger.prototype.shiftLeft = bnShiftLeft;
+    // (public) this << n
+    BigInteger.prototype.shiftLeft = function (n) {
+        var r = nbi();
+        if (n < 0) {
+            this.rShiftTo(-n, r);
+        }
+        else {
+            this.lShiftTo(n, r);
+        }
+        return r;
+    };
+    // BigInteger.prototype.shiftRight = bnShiftRight;
+    // (public) this >> n
+    BigInteger.prototype.shiftRight = function (n) {
+        var r = nbi();
+        if (n < 0) {
+            this.lShiftTo(-n, r);
+        }
+        else {
+            this.rShiftTo(n, r);
+        }
+        return r;
+    };
+    // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
+    // (public) returns index of lowest 1-bit (or -1 if none)
+    BigInteger.prototype.getLowestSetBit = function () {
+        for (var i = 0; i < this.t; ++i) {
+            if (this[i] != 0) {
+                return i * this.DB + lbit(this[i]);
+            }
+        }
+        if (this.s < 0) {
+            return this.t * this.DB;
+        }
+        return -1;
+    };
+    // BigInteger.prototype.bitCount = bnBitCount;
+    // (public) return number of set bits
+    BigInteger.prototype.bitCount = function () {
+        var r = 0;
+        var x = this.s & this.DM;
+        for (var i = 0; i < this.t; ++i) {
+            r += cbit(this[i] ^ x);
+        }
+        return r;
+    };
+    // BigInteger.prototype.testBit = bnTestBit;
+    // (public) true iff nth bit is set
+    BigInteger.prototype.testBit = function (n) {
+        var j = Math.floor(n / this.DB);
+        if (j >= this.t) {
+            return (this.s != 0);
+        }
+        return ((this[j] & (1 << (n % this.DB))) != 0);
+    };
+    // BigInteger.prototype.setBit = bnSetBit;
+    // (public) this | (1<<n)
+    BigInteger.prototype.setBit = function (n) {
+        return this.changeBit(n, op_or);
+    };
+    // BigInteger.prototype.clearBit = bnClearBit;
+    // (public) this & ~(1<<n)
+    BigInteger.prototype.clearBit = function (n) {
+        return this.changeBit(n, op_andnot);
+    };
+    // BigInteger.prototype.flipBit = bnFlipBit;
+    // (public) this ^ (1<<n)
+    BigInteger.prototype.flipBit = function (n) {
+        return this.changeBit(n, op_xor);
+    };
+    // BigInteger.prototype.add = bnAdd;
+    // (public) this + a
+    BigInteger.prototype.add = function (a) {
+        var r = nbi();
+        this.addTo(a, r);
+        return r;
+    };
+    // BigInteger.prototype.subtract = bnSubtract;
+    // (public) this - a
+    BigInteger.prototype.subtract = function (a) {
+        var r = nbi();
+        this.subTo(a, r);
+        return r;
+    };
+    // BigInteger.prototype.multiply = bnMultiply;
+    // (public) this * a
+    BigInteger.prototype.multiply = function (a) {
+        var r = nbi();
+        this.multiplyTo(a, r);
+        return r;
+    };
+    // BigInteger.prototype.divide = bnDivide;
+    // (public) this / a
+    BigInteger.prototype.divide = function (a) {
+        var r = nbi();
+        this.divRemTo(a, r, null);
+        return r;
+    };
+    // BigInteger.prototype.remainder = bnRemainder;
+    // (public) this % a
+    BigInteger.prototype.remainder = function (a) {
+        var r = nbi();
+        this.divRemTo(a, null, r);
+        return r;
+    };
+    // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
+    // (public) [this/a,this%a]
+    BigInteger.prototype.divideAndRemainder = function (a) {
+        var q = nbi();
+        var r = nbi();
+        this.divRemTo(a, q, r);
+        return [q, r];
+    };
+    // BigInteger.prototype.modPow = bnModPow;
+    // (public) this^e % m (HAC 14.85)
+    BigInteger.prototype.modPow = function (e, m) {
+        var i = e.bitLength();
+        var k;
+        var r = nbv(1);
+        var z;
+        if (i <= 0) {
+            return r;
+        }
+        else if (i < 18) {
+            k = 1;
+        }
+        else if (i < 48) {
+            k = 3;
+        }
+        else if (i < 144) {
+            k = 4;
+        }
+        else if (i < 768) {
+            k = 5;
+        }
+        else {
+            k = 6;
+        }
+        if (i < 8) {
+            z = new Classic(m);
+        }
+        else if (m.isEven()) {
+            z = new Barrett(m);
+        }
+        else {
+            z = new Montgomery(m);
+        }
+        // precomputation
+        var g = [];
+        var n = 3;
+        var k1 = k - 1;
+        var km = (1 << k) - 1;
+        g[1] = z.convert(this);
+        if (k > 1) {
+            var g2 = nbi();
+            z.sqrTo(g[1], g2);
+            while (n <= km) {
+                g[n] = nbi();
+                z.mulTo(g2, g[n - 2], g[n]);
+                n += 2;
+            }
+        }
+        var j = e.t - 1;
+        var w;
+        var is1 = true;
+        var r2 = nbi();
+        var t;
+        i = nbits(e[j]) - 1;
+        while (j >= 0) {
+            if (i >= k1) {
+                w = (e[j] >> (i - k1)) & km;
+            }
+            else {
+                w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
+                if (j > 0) {
+                    w |= e[j - 1] >> (this.DB + i - k1);
+                }
+            }
+            n = k;
+            while ((w & 1) == 0) {
+                w >>= 1;
+                --n;
+            }
+            if ((i -= n) < 0) {
+                i += this.DB;
+                --j;
+            }
+            if (is1) { // ret == 1, don't bother squaring or multiplying it
+                g[w].copyTo(r);
+                is1 = false;
+            }
+            else {
+                while (n > 1) {
+                    z.sqrTo(r, r2);
+                    z.sqrTo(r2, r);
+                    n -= 2;
+                }
+                if (n > 0) {
+                    z.sqrTo(r, r2);
+                }
+                else {
+                    t = r;
+                    r = r2;
+                    r2 = t;
+                }
+                z.mulTo(r2, g[w], r);
+            }
+            while (j >= 0 && (e[j] & (1 << i)) == 0) {
+                z.sqrTo(r, r2);
+                t = r;
+                r = r2;
+                r2 = t;
+                if (--i < 0) {
+                    i = this.DB - 1;
+                    --j;
+                }
+            }
+        }
+        return z.revert(r);
+    };
+    // BigInteger.prototype.modInverse = bnModInverse;
+    // (public) 1/this % m (HAC 14.61)
+    BigInteger.prototype.modInverse = function (m) {
+        var ac = m.isEven();
+        if ((this.isEven() && ac) || m.signum() == 0) {
+            return BigInteger.ZERO;
+        }
+        var u = m.clone();
+        var v = this.clone();
+        var a = nbv(1);
+        var b = nbv(0);
+        var c = nbv(0);
+        var d = nbv(1);
+        while (u.signum() != 0) {
+            while (u.isEven()) {
+                u.rShiftTo(1, u);
+                if (ac) {
+                    if (!a.isEven() || !b.isEven()) {
+                        a.addTo(this, a);
+                        b.subTo(m, b);
+                    }
+                    a.rShiftTo(1, a);
+                }
+                else if (!b.isEven()) {
+                    b.subTo(m, b);
+                }
+                b.rShiftTo(1, b);
+            }
+            while (v.isEven()) {
+                v.rShiftTo(1, v);
+                if (ac) {
+                    if (!c.isEven() || !d.isEven()) {
+                        c.addTo(this, c);
+                        d.subTo(m, d);
+                    }
+                    c.rShiftTo(1, c);
+                }
+                else if (!d.isEven()) {
+                    d.subTo(m, d);
+                }
+                d.rShiftTo(1, d);
+            }
+            if (u.compareTo(v) >= 0) {
+                u.subTo(v, u);
+                if (ac) {
+                    a.subTo(c, a);
+                }
+                b.subTo(d, b);
+            }
+            else {
+                v.subTo(u, v);
+                if (ac) {
+                    c.subTo(a, c);
+                }
+                d.subTo(b, d);
+            }
+        }
+        if (v.compareTo(BigInteger.ONE) != 0) {
+            return BigInteger.ZERO;
+        }
+        if (d.compareTo(m) >= 0) {
+            return d.subtract(m);
+        }
+        if (d.signum() < 0) {
+            d.addTo(m, d);
+        }
+        else {
+            return d;
+        }
+        if (d.signum() < 0) {
+            return d.add(m);
+        }
+        else {
+            return d;
+        }
+    };
+    // BigInteger.prototype.pow = bnPow;
+    // (public) this^e
+    BigInteger.prototype.pow = function (e) {
+        return this.exp(e, new NullExp());
+    };
+    // BigInteger.prototype.gcd = bnGCD;
+    // (public) gcd(this,a) (HAC 14.54)
+    BigInteger.prototype.gcd = function (a) {
+        var x = (this.s < 0) ? this.negate() : this.clone();
+        var y = (a.s < 0) ? a.negate() : a.clone();
+        if (x.compareTo(y) < 0) {
+            var t = x;
+            x = y;
+            y = t;
+        }
+        var i = x.getLowestSetBit();
+        var g = y.getLowestSetBit();
+        if (g < 0) {
+            return x;
+        }
+        if (i < g) {
+            g = i;
+        }
+        if (g > 0) {
+            x.rShiftTo(g, x);
+            y.rShiftTo(g, y);
+        }
+        while (x.signum() > 0) {
+            if ((i = x.getLowestSetBit()) > 0) {
+                x.rShiftTo(i, x);
+            }
+            if ((i = y.getLowestSetBit()) > 0) {
+                y.rShiftTo(i, y);
+            }
+            if (x.compareTo(y) >= 0) {
+                x.subTo(y, x);
+                x.rShiftTo(1, x);
+            }
+            else {
+                y.subTo(x, y);
+                y.rShiftTo(1, y);
+            }
+        }
+        if (g > 0) {
+            y.lShiftTo(g, y);
+        }
+        return y;
+    };
+    // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
+    // (public) test primality with certainty >= 1-.5^t
+    BigInteger.prototype.isProbablePrime = function (t) {
+        var i;
+        var x = this.abs();
+        if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
+            for (i = 0; i < lowprimes.length; ++i) {
+                if (x[0] == lowprimes[i]) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        if (x.isEven()) {
+            return false;
+        }
+        i = 1;
+        while (i < lowprimes.length) {
+            var m = lowprimes[i];
+            var j = i + 1;
+            while (j < lowprimes.length && m < lplim) {
+                m *= lowprimes[j++];
+            }
+            m = x.modInt(m);
+            while (i < j) {
+                if (m % lowprimes[i++] == 0) {
+                    return false;
+                }
+            }
+        }
+        return x.millerRabin(t);
+    };
+    //#endregion PUBLIC
+    //#region PROTECTED
+    // BigInteger.prototype.copyTo = bnpCopyTo;
+    // (protected) copy this to r
+    BigInteger.prototype.copyTo = function (r) {
+        for (var i = this.t - 1; i >= 0; --i) {
+            r[i] = this[i];
+        }
+        r.t = this.t;
+        r.s = this.s;
+    };
+    // BigInteger.prototype.fromInt = bnpFromInt;
+    // (protected) set from integer value x, -DV <= x < DV
+    BigInteger.prototype.fromInt = function (x) {
+        this.t = 1;
+        this.s = (x < 0) ? -1 : 0;
+        if (x > 0) {
+            this[0] = x;
+        }
+        else if (x < -1) {
+            this[0] = x + this.DV;
+        }
+        else {
+            this.t = 0;
+        }
+    };
+    // BigInteger.prototype.fromString = bnpFromString;
+    // (protected) set from string and radix
+    BigInteger.prototype.fromString = function (s, b) {
+        var k;
+        if (b == 16) {
+            k = 4;
+        }
+        else if (b == 8) {
+            k = 3;
+        }
+        else if (b == 256) {
+            k = 8;
+            /* byte array */
+        }
+        else if (b == 2) {
+            k = 1;
+        }
+        else if (b == 32) {
+            k = 5;
+        }
+        else if (b == 4) {
+            k = 2;
+        }
+        else {
+            this.fromRadix(s, b);
+            return;
+        }
+        this.t = 0;
+        this.s = 0;
+        var i = s.length;
+        var mi = false;
+        var sh = 0;
+        while (--i >= 0) {
+            var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
+            if (x < 0) {
+                if (s.charAt(i) == "-") {
+                    mi = true;
+                }
+                continue;
+            }
+            mi = false;
+            if (sh == 0) {
+                this[this.t++] = x;
+            }
+            else if (sh + k > this.DB) {
+                this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
+                this[this.t++] = (x >> (this.DB - sh));
+            }
+            else {
+                this[this.t - 1] |= x << sh;
+            }
+            sh += k;
+            if (sh >= this.DB) {
+                sh -= this.DB;
+            }
+        }
+        if (k == 8 && ((+s[0]) & 0x80) != 0) {
+            this.s = -1;
+            if (sh > 0) {
+                this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
+            }
+        }
+        this.clamp();
+        if (mi) {
+            BigInteger.ZERO.subTo(this, this);
+        }
+    };
+    // BigInteger.prototype.clamp = bnpClamp;
+    // (protected) clamp off excess high words
+    BigInteger.prototype.clamp = function () {
+        var c = this.s & this.DM;
+        while (this.t > 0 && this[this.t - 1] == c) {
+            --this.t;
+        }
+    };
+    // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
+    // (protected) r = this << n*DB
+    BigInteger.prototype.dlShiftTo = function (n, r) {
+        var i;
+        for (i = this.t - 1; i >= 0; --i) {
+            r[i + n] = this[i];
+        }
+        for (i = n - 1; i >= 0; --i) {
+            r[i] = 0;
+        }
+        r.t = this.t + n;
+        r.s = this.s;
+    };
+    // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
+    // (protected) r = this >> n*DB
+    BigInteger.prototype.drShiftTo = function (n, r) {
+        for (var i = n; i < this.t; ++i) {
+            r[i - n] = this[i];
+        }
+        r.t = Math.max(this.t - n, 0);
+        r.s = this.s;
+    };
+    // BigInteger.prototype.lShiftTo = bnpLShiftTo;
+    // (protected) r = this << n
+    BigInteger.prototype.lShiftTo = function (n, r) {
+        var bs = n % this.DB;
+        var cbs = this.DB - bs;
+        var bm = (1 << cbs) - 1;
+        var ds = Math.floor(n / this.DB);
+        var c = (this.s << bs) & this.DM;
+        for (var i = this.t - 1; i >= 0; --i) {
+            r[i + ds + 1] = (this[i] >> cbs) | c;
+            c = (this[i] & bm) << bs;
+        }
+        for (var i = ds - 1; i >= 0; --i) {
+            r[i] = 0;
+        }
+        r[ds] = c;
+        r.t = this.t + ds + 1;
+        r.s = this.s;
+        r.clamp();
+    };
+    // BigInteger.prototype.rShiftTo = bnpRShiftTo;
+    // (protected) r = this >> n
+    BigInteger.prototype.rShiftTo = function (n, r) {
+        r.s = this.s;
+        var ds = Math.floor(n / this.DB);
+        if (ds >= this.t) {
+            r.t = 0;
+            return;
+        }
+        var bs = n % this.DB;
+        var cbs = this.DB - bs;
+        var bm = (1 << bs) - 1;
+        r[0] = this[ds] >> bs;
+        for (var i = ds + 1; i < this.t; ++i) {
+            r[i - ds - 1] |= (this[i] & bm) << cbs;
+            r[i - ds] = this[i] >> bs;
+        }
+        if (bs > 0) {
+            r[this.t - ds - 1] |= (this.s & bm) << cbs;
+        }
+        r.t = this.t - ds;
+        r.clamp();
+    };
+    // BigInteger.prototype.subTo = bnpSubTo;
+    // (protected) r = this - a
+    BigInteger.prototype.subTo = function (a, r) {
+        var i = 0;
+        var c = 0;
+        var m = Math.min(a.t, this.t);
+        while (i < m) {
+            c += this[i] - a[i];
+            r[i++] = c & this.DM;
+            c >>= this.DB;
+        }
+        if (a.t < this.t) {
+            c -= a.s;
+            while (i < this.t) {
+                c += this[i];
+                r[i++] = c & this.DM;
+                c >>= this.DB;
+            }
+            c += this.s;
+        }
+        else {
+            c += this.s;
+            while (i < a.t) {
+                c -= a[i];
+                r[i++] = c & this.DM;
+                c >>= this.DB;
+            }
+            c -= a.s;
+        }
+        r.s = (c < 0) ? -1 : 0;
+        if (c < -1) {
+            r[i++] = this.DV + c;
+        }
+        else if (c > 0) {
+            r[i++] = c;
+        }
+        r.t = i;
+        r.clamp();
+    };
+    // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
+    // (protected) r = this * a, r != this,a (HAC 14.12)
+    // "this" should be the larger one if appropriate.
+    BigInteger.prototype.multiplyTo = function (a, r) {
+        var x = this.abs();
+        var y = a.abs();
+        var i = x.t;
+        r.t = i + y.t;
+        while (--i >= 0) {
+            r[i] = 0;
+        }
+        for (i = 0; i < y.t; ++i) {
+            r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
+        }
+        r.s = 0;
+        r.clamp();
+        if (this.s != a.s) {
+            BigInteger.ZERO.subTo(r, r);
+        }
+    };
+    // BigInteger.prototype.squareTo = bnpSquareTo;
+    // (protected) r = this^2, r != this (HAC 14.16)
+    BigInteger.prototype.squareTo = function (r) {
+        var x = this.abs();
+        var i = r.t = 2 * x.t;
+        while (--i >= 0) {
+            r[i] = 0;
+        }
+        for (i = 0; i < x.t - 1; ++i) {
+            var c = x.am(i, x[i], r, 2 * i, 0, 1);
+            if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
+                r[i + x.t] -= x.DV;
+                r[i + x.t + 1] = 1;
+            }
+        }
+        if (r.t > 0) {
+            r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
+        }
+        r.s = 0;
+        r.clamp();
+    };
+    // BigInteger.prototype.divRemTo = bnpDivRemTo;
+    // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
+    // r != q, this != m.  q or r may be null.
+    BigInteger.prototype.divRemTo = function (m, q, r) {
+        var pm = m.abs();
+        if (pm.t <= 0) {
+            return;
+        }
+        var pt = this.abs();
+        if (pt.t < pm.t) {
+            if (q != null) {
+                q.fromInt(0);
+            }
+            if (r != null) {
+                this.copyTo(r);
+            }
+            return;
+        }
+        if (r == null) {
+            r = nbi();
+        }
+        var y = nbi();
+        var ts = this.s;
+        var ms = m.s;
+        var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
+        if (nsh > 0) {
+            pm.lShiftTo(nsh, y);
+            pt.lShiftTo(nsh, r);
+        }
+        else {
+            pm.copyTo(y);
+            pt.copyTo(r);
+        }
+        var ys = y.t;
+        var y0 = y[ys - 1];
+        if (y0 == 0) {
+            return;
+        }
+        var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
+        var d1 = this.FV / yt;
+        var d2 = (1 << this.F1) / yt;
+        var e = 1 << this.F2;
+        var i = r.t;
+        var j = i - ys;
+        var t = (q == null) ? nbi() : q;
+        y.dlShiftTo(j, t);
+        if (r.compareTo(t) >= 0) {
+            r[r.t++] = 1;
+            r.subTo(t, r);
+        }
+        BigInteger.ONE.dlShiftTo(ys, t);
+        t.subTo(y, y); // "negative" y so we can replace sub with am later
+        while (y.t < ys) {
+            y[y.t++] = 0;
+        }
+        while (--j >= 0) {
+            // Estimate quotient digit
+            var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
+            if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
+                y.dlShiftTo(j, t);
+                r.subTo(t, r);
+                while (r[i] < --qd) {
+                    r.subTo(t, r);
+                }
+            }
+        }
+        if (q != null) {
+            r.drShiftTo(ys, q);
+            if (ts != ms) {
+                BigInteger.ZERO.subTo(q, q);
+            }
+        }
+        r.t = ys;
+        r.clamp();
+        if (nsh > 0) {
+            r.rShiftTo(nsh, r);
+        } // Denormalize remainder
+        if (ts < 0) {
+            BigInteger.ZERO.subTo(r, r);
+        }
+    };
+    // BigInteger.prototype.invDigit = bnpInvDigit;
+    // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
+    // justification:
+    //         xy == 1 (mod m)
+    //         xy =  1+km
+    //   xy(2-xy) = (1+km)(1-km)
+    // x[y(2-xy)] = 1-k^2m^2
+    // x[y(2-xy)] == 1 (mod m^2)
+    // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
+    // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
+    // JS multiply "overflows" differently from C/C++, so care is needed here.
+    BigInteger.prototype.invDigit = function () {
+        if (this.t < 1) {
+            return 0;
+        }
+        var x = this[0];
+        if ((x & 1) == 0) {
+            return 0;
+        }
+        var y = x & 3; // y == 1/x mod 2^2
+        y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
+        y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
+        y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
+        // last step - calculate inverse mod DV directly;
+        // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
+        y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
+        // we really want the negative inverse, and -DV < y < DV
+        return (y > 0) ? this.DV - y : -y;
+    };
+    // BigInteger.prototype.isEven = bnpIsEven;
+    // (protected) true iff this is even
+    BigInteger.prototype.isEven = function () {
+        return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
+    };
+    // BigInteger.prototype.exp = bnpExp;
+    // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
+    BigInteger.prototype.exp = function (e, z) {
+        if (e > 0xffffffff || e < 1) {
+            return BigInteger.ONE;
+        }
+        var r = nbi();
+        var r2 = nbi();
+        var g = z.convert(this);
+        var i = nbits(e) - 1;
+        g.copyTo(r);
+        while (--i >= 0) {
+            z.sqrTo(r, r2);
+            if ((e & (1 << i)) > 0) {
+                z.mulTo(r2, g, r);
+            }
+            else {
+                var t = r;
+                r = r2;
+                r2 = t;
+            }
+        }
+        return z.revert(r);
+    };
+    // BigInteger.prototype.chunkSize = bnpChunkSize;
+    // (protected) return x s.t. r^x < DV
+    BigInteger.prototype.chunkSize = function (r) {
+        return Math.floor(Math.LN2 * this.DB / Math.log(r));
+    };
+    // BigInteger.prototype.toRadix = bnpToRadix;
+    // (protected) convert to radix string
+    BigInteger.prototype.toRadix = function (b) {
+        if (b == null) {
+            b = 10;
+        }
+        if (this.signum() == 0 || b < 2 || b > 36) {
+            return "0";
+        }
+        var cs = this.chunkSize(b);
+        var a = Math.pow(b, cs);
+        var d = nbv(a);
+        var y = nbi();
+        var z = nbi();
+        var r = "";
+        this.divRemTo(d, y, z);
+        while (y.signum() > 0) {
+            r = (a + z.intValue()).toString(b).substr(1) + r;
+            y.divRemTo(d, y, z);
+        }
+        return z.intValue().toString(b) + r;
+    };
+    // BigInteger.prototype.fromRadix = bnpFromRadix;
+    // (protected) convert from radix string
+    BigInteger.prototype.fromRadix = function (s, b) {
+        this.fromInt(0);
+        if (b == null) {
+            b = 10;
+        }
+        var cs = this.chunkSize(b);
+        var d = Math.pow(b, cs);
+        var mi = false;
+        var j = 0;
+        var w = 0;
+        for (var i = 0; i < s.length; ++i) {
+            var x = intAt(s, i);
+            if (x < 0) {
+                if (s.charAt(i) == "-" && this.signum() == 0) {
+                    mi = true;
+                }
+                continue;
+            }
+            w = b * w + x;
+            if (++j >= cs) {
+                this.dMultiply(d);
+                this.dAddOffset(w, 0);
+                j = 0;
+                w = 0;
+            }
+        }
+        if (j > 0) {
+            this.dMultiply(Math.pow(b, j));
+            this.dAddOffset(w, 0);
+        }
+        if (mi) {
+            BigInteger.ZERO.subTo(this, this);
+        }
+    };
+    // BigInteger.prototype.fromNumber = bnpFromNumber;
+    // (protected) alternate constructor
+    BigInteger.prototype.fromNumber = function (a, b, c) {
+        if ("number" == typeof b) {
+            // new BigInteger(int,int,RNG)
+            if (a < 2) {
+                this.fromInt(1);
+            }
+            else {
+                this.fromNumber(a, c);
+                if (!this.testBit(a - 1)) {
+                    // force MSB set
+                    this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
+                }
+                if (this.isEven()) {
+                    this.dAddOffset(1, 0);
+                } // force odd
+                while (!this.isProbablePrime(b)) {
+                    this.dAddOffset(2, 0);
+                    if (this.bitLength() > a) {
+                        this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
+                    }
+                }
+            }
+        }
+        else {
+            // new BigInteger(int,RNG)
+            var x = [];
+            var t = a & 7;
+            x.length = (a >> 3) + 1;
+            b.nextBytes(x);
+            if (t > 0) {
+                x[0] &= ((1 << t) - 1);
+            }
+            else {
+                x[0] = 0;
+            }
+            this.fromString(x, 256);
+        }
+    };
+    // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
+    // (protected) r = this op a (bitwise)
+    BigInteger.prototype.bitwiseTo = function (a, op, r) {
+        var i;
+        var f;
+        var m = Math.min(a.t, this.t);
+        for (i = 0; i < m; ++i) {
+            r[i] = op(this[i], a[i]);
+        }
+        if (a.t < this.t) {
+            f = a.s & this.DM;
+            for (i = m; i < this.t; ++i) {
+                r[i] = op(this[i], f);
+            }
+            r.t = this.t;
+        }
+        else {
+            f = this.s & this.DM;
+            for (i = m; i < a.t; ++i) {
+                r[i] = op(f, a[i]);
+            }
+            r.t = a.t;
+        }
+        r.s = op(this.s, a.s);
+        r.clamp();
+    };
+    // BigInteger.prototype.changeBit = bnpChangeBit;
+    // (protected) this op (1<<n)
+    BigInteger.prototype.changeBit = function (n, op) {
+        var r = BigInteger.ONE.shiftLeft(n);
+        this.bitwiseTo(r, op, r);
+        return r;
+    };
+    // BigInteger.prototype.addTo = bnpAddTo;
+    // (protected) r = this + a
+    BigInteger.prototype.addTo = function (a, r) {
+        var i = 0;
+        var c = 0;
+        var m = Math.min(a.t, this.t);
+        while (i < m) {
+            c += this[i] + a[i];
+            r[i++] = c & this.DM;
+            c >>= this.DB;
+        }
+        if (a.t < this.t) {
+            c += a.s;
+            while (i < this.t) {
+                c += this[i];
+                r[i++] = c & this.DM;
+                c >>= this.DB;
+            }
+            c += this.s;
+        }
+        else {
+            c += this.s;
+            while (i < a.t) {
+                c += a[i];
+                r[i++] = c & this.DM;
+                c >>= this.DB;
+            }
+            c += a.s;
+        }
+        r.s = (c < 0) ? -1 : 0;
+        if (c > 0) {
+            r[i++] = c;
+        }
+        else if (c < -1) {
+            r[i++] = this.DV + c;
+        }
+        r.t = i;
+        r.clamp();
+    };
+    // BigInteger.prototype.dMultiply = bnpDMultiply;
+    // (protected) this *= n, this >= 0, 1 < n < DV
+    BigInteger.prototype.dMultiply = function (n) {
+        this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
+        ++this.t;
+        this.clamp();
+    };
+    // BigInteger.prototype.dAddOffset = bnpDAddOffset;
+    // (protected) this += n << w words, this >= 0
+    BigInteger.prototype.dAddOffset = function (n, w) {
+        if (n == 0) {
+            return;
+        }
+        while (this.t <= w) {
+            this[this.t++] = 0;
+        }
+        this[w] += n;
+        while (this[w] >= this.DV) {
+            this[w] -= this.DV;
+            if (++w >= this.t) {
+                this[this.t++] = 0;
+            }
+            ++this[w];
+        }
+    };
+    // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
+    // (protected) r = lower n words of "this * a", a.t <= n
+    // "this" should be the larger one if appropriate.
+    BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
+        var i = Math.min(this.t + a.t, n);
+        r.s = 0; // assumes a,this >= 0
+        r.t = i;
+        while (i > 0) {
+            r[--i] = 0;
+        }
+        for (var j = r.t - this.t; i < j; ++i) {
+            r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
+        }
+        for (var j = Math.min(a.t, n); i < j; ++i) {
+            this.am(0, a[i], r, i, 0, n - i);
+        }
+        r.clamp();
+    };
+    // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
+    // (protected) r = "this * a" without lower n words, n > 0
+    // "this" should be the larger one if appropriate.
+    BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
+        --n;
+        var i = r.t = this.t + a.t - n;
+        r.s = 0; // assumes a,this >= 0
+        while (--i >= 0) {
+            r[i] = 0;
+        }
+        for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
+            r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
+        }
+        r.clamp();
+        r.drShiftTo(1, r);
+    };
+    // BigInteger.prototype.modInt = bnpModInt;
+    // (protected) this % n, n < 2^26
+    BigInteger.prototype.modInt = function (n) {
+        if (n <= 0) {
+            return 0;
+        }
+        var d = this.DV % n;
+        var r = (this.s < 0) ? n - 1 : 0;
+        if (this.t > 0) {
+            if (d == 0) {
+                r = this[0] % n;
+            }
+            else {
+                for (var i = this.t - 1; i >= 0; --i) {
+                    r = (d * r + this[i]) % n;
+                }
+            }
+        }
+        return r;
+    };
+    // BigInteger.prototype.millerRabin = bnpMillerRabin;
+    // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
+    BigInteger.prototype.millerRabin = function (t) {
+        var n1 = this.subtract(BigInteger.ONE);
+        var k = n1.getLowestSetBit();
+        if (k <= 0) {
+            return false;
+        }
+        var r = n1.shiftRight(k);
+        t = (t + 1) >> 1;
+        if (t > lowprimes.length) {
+            t = lowprimes.length;
+        }
+        var a = nbi();
+        for (var i = 0; i < t; ++i) {
+            // Pick bases at random, instead of starting at 2
+            a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
+            var y = a.modPow(r, this);
+            if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
+                var j = 1;
+                while (j++ < k && y.compareTo(n1) != 0) {
+                    y = y.modPowInt(2, this);
+                    if (y.compareTo(BigInteger.ONE) == 0) {
+                        return false;
+                    }
+                }
+                if (y.compareTo(n1) != 0) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    };
+    // BigInteger.prototype.square = bnSquare;
+    // (public) this^2
+    BigInteger.prototype.square = function () {
+        var r = nbi();
+        this.squareTo(r);
+        return r;
+    };
+    //#region ASYNC
+    // Public API method
+    BigInteger.prototype.gcda = function (a, callback) {
+        var x = (this.s < 0) ? this.negate() : this.clone();
+        var y = (a.s < 0) ? a.negate() : a.clone();
+        if (x.compareTo(y) < 0) {
+            var t = x;
+            x = y;
+            y = t;
+        }
+        var i = x.getLowestSetBit();
+        var g = y.getLowestSetBit();
+        if (g < 0) {
+            callback(x);
+            return;
+        }
+        if (i < g) {
+            g = i;
+        }
+        if (g > 0) {
+            x.rShiftTo(g, x);
+            y.rShiftTo(g, y);
+        }
+        // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
+        var gcda1 = function () {
+            if ((i = x.getLowestSetBit()) > 0) {
+                x.rShiftTo(i, x);
+            }
+            if ((i = y.getLowestSetBit()) > 0) {
+                y.rShiftTo(i, y);
+            }
+            if (x.compareTo(y) >= 0) {
+                x.subTo(y, x);
+                x.rShiftTo(1, x);
+            }
+            else {
+                y.subTo(x, y);
+                y.rShiftTo(1, y);
+            }
+            if (!(x.signum() > 0)) {
+                if (g > 0) {
+                    y.lShiftTo(g, y);
+                }
+                setTimeout(function () { callback(y); }, 0); // escape
+            }
+            else {
+                setTimeout(gcda1, 0);
+            }
+        };
+        setTimeout(gcda1, 10);
+    };
+    // (protected) alternate constructor
+    BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
+        if ("number" == typeof b) {
+            if (a < 2) {
+                this.fromInt(1);
+            }
+            else {
+                this.fromNumber(a, c);
+                if (!this.testBit(a - 1)) {
+                    this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
+                }
+                if (this.isEven()) {
+                    this.dAddOffset(1, 0);
+                }
+                var bnp_1 = this;
+                var bnpfn1_1 = function () {
+                    bnp_1.dAddOffset(2, 0);
+                    if (bnp_1.bitLength() > a) {
+                        bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
+                    }
+                    if (bnp_1.isProbablePrime(b)) {
+                        setTimeout(function () { callback(); }, 0); // escape
+                    }
+                    else {
+                        setTimeout(bnpfn1_1, 0);
+                    }
+                };
+                setTimeout(bnpfn1_1, 0);
+            }
+        }
+        else {
+            var x = [];
+            var t = a & 7;
+            x.length = (a >> 3) + 1;
+            b.nextBytes(x);
+            if (t > 0) {
+                x[0] &= ((1 << t) - 1);
+            }
+            else {
+                x[0] = 0;
+            }
+            this.fromString(x, 256);
+        }
+    };
+    return BigInteger;
+}());
+//#region REDUCERS
+//#region NullExp
+var NullExp = /** @class */ (function () {
+    function NullExp() {
+    }
+    // NullExp.prototype.convert = nNop;
+    NullExp.prototype.convert = function (x) {
+        return x;
+    };
+    // NullExp.prototype.revert = nNop;
+    NullExp.prototype.revert = function (x) {
+        return x;
+    };
+    // NullExp.prototype.mulTo = nMulTo;
+    NullExp.prototype.mulTo = function (x, y, r) {
+        x.multiplyTo(y, r);
+    };
+    // NullExp.prototype.sqrTo = nSqrTo;
+    NullExp.prototype.sqrTo = function (x, r) {
+        x.squareTo(r);
+    };
+    return NullExp;
+}());
+// Modular reduction using "classic" algorithm
+var Classic = /** @class */ (function () {
+    function Classic(m) {
+        this.m = m;
+    }
+    // Classic.prototype.convert = cConvert;
+    Classic.prototype.convert = function (x) {
+        if (x.s < 0 || x.compareTo(this.m) >= 0) {
+            return x.mod(this.m);
+        }
+        else {
+            return x;
+        }
+    };
+    // Classic.prototype.revert = cRevert;
+    Classic.prototype.revert = function (x) {
+        return x;
+    };
+    // Classic.prototype.reduce = cReduce;
+    Classic.prototype.reduce = function (x) {
+        x.divRemTo(this.m, null, x);
+    };
+    // Classic.prototype.mulTo = cMulTo;
+    Classic.prototype.mulTo = function (x, y, r) {
+        x.multiplyTo(y, r);
+        this.reduce(r);
+    };
+    // Classic.prototype.sqrTo = cSqrTo;
+    Classic.prototype.sqrTo = function (x, r) {
+        x.squareTo(r);
+        this.reduce(r);
+    };
+    return Classic;
+}());
+//#endregion
+//#region Montgomery
+// Montgomery reduction
+var Montgomery = /** @class */ (function () {
+    function Montgomery(m) {
+        this.m = m;
+        this.mp = m.invDigit();
+        this.mpl = this.mp & 0x7fff;
+        this.mph = this.mp >> 15;
+        this.um = (1 << (m.DB - 15)) - 1;
+        this.mt2 = 2 * m.t;
+    }
+    // Montgomery.prototype.convert = montConvert;
+    // xR mod m
+    Montgomery.prototype.convert = function (x) {
+        var r = nbi();
+        x.abs().dlShiftTo(this.m.t, r);
+        r.divRemTo(this.m, null, r);
+        if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
+            this.m.subTo(r, r);
+        }
+        return r;
+    };
+    // Montgomery.prototype.revert = montRevert;
+    // x/R mod m
+    Montgomery.prototype.revert = function (x) {
+        var r = nbi();
+        x.copyTo(r);
+        this.reduce(r);
+        return r;
+    };
+    // Montgomery.prototype.reduce = montReduce;
+    // x = x/R mod m (HAC 14.32)
+    Montgomery.prototype.reduce = function (x) {
+        while (x.t <= this.mt2) {
+            // pad x so am has enough room later
+            x[x.t++] = 0;
+        }
+        for (var i = 0; i < this.m.t; ++i) {
+            // faster way of calculating u0 = x[i]*mp mod DV
+            var j = x[i] & 0x7fff;
+            var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
+            // use am to combine the multiply-shift-add into one call
+            j = i + this.m.t;
+            x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
+            // propagate carry
+            while (x[j] >= x.DV) {
+                x[j] -= x.DV;
+                x[++j]++;
+            }
+        }
+        x.clamp();
+        x.drShiftTo(this.m.t, x);
+        if (x.compareTo(this.m) >= 0) {
+            x.subTo(this.m, x);
+        }
+    };
+    // Montgomery.prototype.mulTo = montMulTo;
+    // r = "xy/R mod m"; x,y != r
+    Montgomery.prototype.mulTo = function (x, y, r) {
+        x.multiplyTo(y, r);
+        this.reduce(r);
+    };
+    // Montgomery.prototype.sqrTo = montSqrTo;
+    // r = "x^2/R mod m"; x != r
+    Montgomery.prototype.sqrTo = function (x, r) {
+        x.squareTo(r);
+        this.reduce(r);
+    };
+    return Montgomery;
+}());
+//#endregion Montgomery
+//#region Barrett
+// Barrett modular reduction
+var Barrett = /** @class */ (function () {
+    function Barrett(m) {
+        this.m = m;
+        // setup Barrett
+        this.r2 = nbi();
+        this.q3 = nbi();
+        BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
+        this.mu = this.r2.divide(m);
+    }
+    // Barrett.prototype.convert = barrettConvert;
+    Barrett.prototype.convert = function (x) {
+        if (x.s < 0 || x.t > 2 * this.m.t) {
+            return x.mod(this.m);
+        }
+        else if (x.compareTo(this.m) < 0) {
+            return x;
+        }
+        else {
+            var r = nbi();
+            x.copyTo(r);
+            this.reduce(r);
+            return r;
+        }
+    };
+    // Barrett.prototype.revert = barrettRevert;
+    Barrett.prototype.revert = function (x) {
+        return x;
+    };
+    // Barrett.prototype.reduce = barrettReduce;
+    // x = x mod m (HAC 14.42)
+    Barrett.prototype.reduce = function (x) {
+        x.drShiftTo(this.m.t - 1, this.r2);
+        if (x.t > this.m.t + 1) {
+            x.t = this.m.t + 1;
+            x.clamp();
+        }
+        this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
+        this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
+        while (x.compareTo(this.r2) < 0) {
+            x.dAddOffset(1, this.m.t + 1);
+        }
+        x.subTo(this.r2, x);
+        while (x.compareTo(this.m) >= 0) {
+            x.subTo(this.m, x);
+        }
+    };
+    // Barrett.prototype.mulTo = barrettMulTo;
+    // r = x*y mod m; x,y != r
+    Barrett.prototype.mulTo = function (x, y, r) {
+        x.multiplyTo(y, r);
+        this.reduce(r);
+    };
+    // Barrett.prototype.sqrTo = barrettSqrTo;
+    // r = x^2 mod m; x != r
+    Barrett.prototype.sqrTo = function (x, r) {
+        x.squareTo(r);
+        this.reduce(r);
+    };
+    return Barrett;
+}());
+//#endregion
+//#endregion REDUCERS
+// return new, unset BigInteger
+function nbi() { return new BigInteger(null); }
+function parseBigInt(str, r) {
+    return new BigInteger(str, r);
+}
+// am: Compute w_j += (x*this_i), propagate carries,
+// c is initial carry, returns final carry.
+// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
+// We need to select the fastest one that works in this environment.
+// am1: use a single mult and divide to get the high bits,
+// max digit bits should be 26 because
+// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
+function am1(i, x, w, j, c, n) {
+    while (--n >= 0) {
+        var v = x * this[i++] + w[j] + c;
+        c = Math.floor(v / 0x4000000);
+        w[j++] = v & 0x3ffffff;
+    }
+    return c;
+}
+// am2 avoids a big mult-and-extract completely.
+// Max digit bits should be <= 30 because we do bitwise ops
+// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
+function am2(i, x, w, j, c, n) {
+    var xl = x & 0x7fff;
+    var xh = x >> 15;
+    while (--n >= 0) {
+        var l = this[i] & 0x7fff;
+        var h = this[i++] >> 15;
+        var m = xh * l + h * xl;
+        l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
+        c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
+        w[j++] = l & 0x3fffffff;
+    }
+    return c;
+}
+// Alternately, set max digit bits to 28 since some
+// browsers slow down when dealing with 32-bit numbers.
+function am3(i, x, w, j, c, n) {
+    var xl = x & 0x3fff;
+    var xh = x >> 14;
+    while (--n >= 0) {
+        var l = this[i] & 0x3fff;
+        var h = this[i++] >> 14;
+        var m = xh * l + h * xl;
+        l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
+        c = (l >> 28) + (m >> 14) + xh * h;
+        w[j++] = l & 0xfffffff;
+    }
+    return c;
+}
+if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
+    BigInteger.prototype.am = am2;
+    dbits = 30;
+}
+else if (j_lm && (navigator.appName != "Netscape")) {
+    BigInteger.prototype.am = am1;
+    dbits = 26;
+}
+else { // Mozilla/Netscape seems to prefer am3
+    BigInteger.prototype.am = am3;
+    dbits = 28;
+}
+BigInteger.prototype.DB = dbits;
+BigInteger.prototype.DM = ((1 << dbits) - 1);
+BigInteger.prototype.DV = (1 << dbits);
+var BI_FP = 52;
+BigInteger.prototype.FV = Math.pow(2, BI_FP);
+BigInteger.prototype.F1 = BI_FP - dbits;
+BigInteger.prototype.F2 = 2 * dbits - BI_FP;
+// Digit conversions
+var BI_RC = [];
+var rr;
+var vv;
+rr = "0".charCodeAt(0);
+for (vv = 0; vv <= 9; ++vv) {
+    BI_RC[rr++] = vv;
+}
+rr = "a".charCodeAt(0);
+for (vv = 10; vv < 36; ++vv) {
+    BI_RC[rr++] = vv;
+}
+rr = "A".charCodeAt(0);
+for (vv = 10; vv < 36; ++vv) {
+    BI_RC[rr++] = vv;
+}
+function intAt(s, i) {
+    var c = BI_RC[s.charCodeAt(i)];
+    return (c == null) ? -1 : c;
+}
+// return bigint initialized to value
+function nbv(i) {
+    var r = nbi();
+    r.fromInt(i);
+    return r;
+}
+// returns bit length of the integer x
+function nbits(x) {
+    var r = 1;
+    var t;
+    if ((t = x >>> 16) != 0) {
+        x = t;
+        r += 16;
+    }
+    if ((t = x >> 8) != 0) {
+        x = t;
+        r += 8;
+    }
+    if ((t = x >> 4) != 0) {
+        x = t;
+        r += 4;
+    }
+    if ((t = x >> 2) != 0) {
+        x = t;
+        r += 2;
+    }
+    if ((t = x >> 1) != 0) {
+        x = t;
+        r += 1;
+    }
+    return r;
+}
+// "constants"
+BigInteger.ZERO = nbv(0);
+BigInteger.ONE = nbv(1);
+
+// prng4.js - uses Arcfour as a PRNG
+var Arcfour = /** @class */ (function () {
+    function Arcfour() {
+        this.i = 0;
+        this.j = 0;
+        this.S = [];
+    }
+    // Arcfour.prototype.init = ARC4init;
+    // Initialize arcfour context from key, an array of ints, each from [0..255]
+    Arcfour.prototype.init = function (key) {
+        var i;
+        var j;
+        var t;
+        for (i = 0; i < 256; ++i) {
+            this.S[i] = i;
+        }
+        j = 0;
+        for (i = 0; i < 256; ++i) {
+            j = (j + this.S[i] + key[i % key.length]) & 255;
+            t = this.S[i];
+            this.S[i] = this.S[j];
+            this.S[j] = t;
+        }
+        this.i = 0;
+        this.j = 0;
+    };
+    // Arcfour.prototype.next = ARC4next;
+    Arcfour.prototype.next = function () {
+        var t;
+        this.i = (this.i + 1) & 255;
+        this.j = (this.j + this.S[this.i]) & 255;
+        t = this.S[this.i];
+        this.S[this.i] = this.S[this.j];
+        this.S[this.j] = t;
+        return this.S[(t + this.S[this.i]) & 255];
+    };
+    return Arcfour;
+}());
+// Plug in your RNG constructor here
+function prng_newstate() {
+    return new Arcfour();
+}
+// Pool size must be a multiple of 4 and greater than 32.
+// An array of bytes the size of the pool will be passed to init()
+var rng_psize = 256;
+
+// Random number generator - requires a PRNG backend, e.g. prng4.js
+var rng_state;
+var rng_pool = null;
+var rng_pptr;
+// Initialize the pool with junk if needed.
+if (rng_pool == null) {
+    rng_pool = [];
+    rng_pptr = 0;
+    var t = void 0;
+    if (window.crypto && window.crypto.getRandomValues) {
+        // Extract entropy (2048 bits) from RNG if available
+        var z = new Uint32Array(256);
+        window.crypto.getRandomValues(z);
+        for (t = 0; t < z.length; ++t) {
+            rng_pool[rng_pptr++] = z[t] & 255;
+        }
+    }
+    // Use mouse events for entropy, if we do not have enough entropy by the time
+    // we need it, entropy will be generated by Math.random.
+    var onMouseMoveListener_1 = function (ev) {
+        this.count = this.count || 0;
+        if (this.count >= 256 || rng_pptr >= rng_psize) {
+            if (window.removeEventListener) {
+                window.removeEventListener("mousemove", onMouseMoveListener_1, false);
+            }
+            else if (window.detachEvent) {
+                window.detachEvent("onmousemove", onMouseMoveListener_1);
+            }
+            return;
+        }
+        try {
+            var mouseCoordinates = ev.x + ev.y;
+            rng_pool[rng_pptr++] = mouseCoordinates & 255;
+            this.count += 1;
+        }
+        catch (e) {
+            // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
+        }
+    };
+    if (window.addEventListener) {
+        window.addEventListener("mousemove", onMouseMoveListener_1, false);
+    }
+    else if (window.attachEvent) {
+        window.attachEvent("onmousemove", onMouseMoveListener_1);
+    }
+}
+function rng_get_byte() {
+    if (rng_state == null) {
+        rng_state = prng_newstate();
+        // At this point, we may not have collected enough entropy.  If not, fall back to Math.random
+        while (rng_pptr < rng_psize) {
+            var random = Math.floor(65536 * Math.random());
+            rng_pool[rng_pptr++] = random & 255;
+        }
+        rng_state.init(rng_pool);
+        for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
+            rng_pool[rng_pptr] = 0;
+        }
+        rng_pptr = 0;
+    }
+    // TODO: allow reseeding after first request
+    return rng_state.next();
+}
+var SecureRandom = /** @class */ (function () {
+    function SecureRandom() {
+    }
+    SecureRandom.prototype.nextBytes = function (ba) {
+        for (var i = 0; i < ba.length; ++i) {
+            ba[i] = rng_get_byte();
+        }
+    };
+    return SecureRandom;
+}());
+
+// Depends on jsbn.js and rng.js
+// function linebrk(s,n) {
+//   var ret = "";
+//   var i = 0;
+//   while(i + n < s.length) {
+//     ret += s.substring(i,i+n) + "\n";
+//     i += n;
+//   }
+//   return ret + s.substring(i,s.length);
+// }
+// function byte2Hex(b) {
+//   if(b < 0x10)
+//     return "0" + b.toString(16);
+//   else
+//     return b.toString(16);
+// }
+function pkcs1pad1(s, n) {
+    if (n < s.length + 22) {
+        console.error("Message too long for RSA");
+        return null;
+    }
+    var len = n - s.length - 6;
+    var filler = "";
+    for (var f = 0; f < len; f += 2) {
+        filler += "ff";
+    }
+    var m = "0001" + filler + "00" + s;
+    return parseBigInt(m, 16);
+}
+// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
+function pkcs1pad2(s, n) {
+    if (n < s.length + 11) {
+        // TODO: fix for utf-8
+        console.error("Message too long for RSA");
+        return null;
+    }
+    var ba = [];
+    var i = s.length - 1;
+    while (i >= 0 && n > 0) {
+        var c = s.charCodeAt(i--);
+        if (c < 128) {
+            // encode using utf-8
+            ba[--n] = c;
+        }
+        else if (c > 127 && c < 2048) {
+            ba[--n] = (c & 63) | 128;
+            ba[--n] = (c >> 6) | 192;
+        }
+        else {
+            ba[--n] = (c & 63) | 128;
+            ba[--n] = ((c >> 6) & 63) | 128;
+            ba[--n] = (c >> 12) | 224;
+        }
+    }
+    ba[--n] = 0;
+    var rng = new SecureRandom();
+    var x = [];
+    while (n > 2) {
+        // random non-zero pad
+        x[0] = 0;
+        while (x[0] == 0) {
+            rng.nextBytes(x);
+        }
+        ba[--n] = x[0];
+    }
+    ba[--n] = 2;
+    ba[--n] = 0;
+    return new BigInteger(ba);
+}
+// "empty" RSA key constructor
+var RSAKey = /** @class */ (function () {
+    function RSAKey() {
+        this.n = null;
+        this.e = 0;
+        this.d = null;
+        this.p = null;
+        this.q = null;
+        this.dmp1 = null;
+        this.dmq1 = null;
+        this.coeff = null;
+    }
+    //#region PROTECTED
+    // protected
+    // RSAKey.prototype.doPublic = RSADoPublic;
+    // Perform raw public operation on "x": return x^e (mod n)
+    RSAKey.prototype.doPublic = function (x) {
+        return x.modPowInt(this.e, this.n);
+    };
+    // RSAKey.prototype.doPrivate = RSADoPrivate;
+    // Perform raw private operation on "x": return x^d (mod n)
+    RSAKey.prototype.doPrivate = function (x) {
+        if (this.p == null || this.q == null) {
+            return x.modPow(this.d, this.n);
+        }
+        // TODO: re-calculate any missing CRT params
+        var xp = x.mod(this.p).modPow(this.dmp1, this.p);
+        var xq = x.mod(this.q).modPow(this.dmq1, this.q);
+        while (xp.compareTo(xq) < 0) {
+            xp = xp.add(this.p);
+        }
+        return xp
+            .subtract(xq)
+            .multiply(this.coeff)
+            .mod(this.p)
+            .multiply(this.q)
+            .add(xq);
+    };
+    //#endregion PROTECTED
+    //#region PUBLIC
+    // RSAKey.prototype.setPublic = RSASetPublic;
+    // Set the public key fields N and e from hex strings
+    RSAKey.prototype.setPublic = function (N, E) {
+        if (N != null && E != null && N.length > 0 && E.length > 0) {
+            this.n = parseBigInt(N, 16);
+            this.e = parseInt(E, 16);
+        }
+        else {
+            console.error("Invalid RSA public key");
+        }
+    };
+    // RSAKey.prototype.encrypt = RSAEncrypt;
+    // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
+    RSAKey.prototype.encrypt = function (text) {
+        var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
+        if (m == null) {
+            return null;
+        }
+        var c = this.doPublic(m);
+        if (c == null) {
+            return null;
+        }
+        var h = c.toString(16);
+        if ((h.length & 1) == 0) {
+            return h;
+        }
+        else {
+            return "0" + h;
+        }
+    };
+    /**
+     * 长文本加密
+     * @param {string} string 待加密长文本
+     * @returns {string} 加密后的base64编码
+     */
+    RSAKey.prototype.encryptLong = function (text) {
+        var _this = this;
+        var maxLength = ((this.n.bitLength() + 7) >> 3) - 11;
+        try {
+            var ct_1 = "";
+            if (text.length > maxLength) {
+                var lt = text.match(/.{1,117}/g);
+                lt.forEach(function (entry) {
+                    var t1 = _this.encrypt(entry);
+                    ct_1 += t1;
+                });
+                return hex2b64(ct_1);
+            }
+            var t = this.encrypt(text);
+            var y = hex2b64(t);
+            return y;
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * 长文本解密
+     * @param {string} string 加密后的base64编码
+     * @returns {string} 解密后的原文
+     */
+    RSAKey.prototype.decryptLong = function (text) {
+        var _this = this;
+        var maxLength = (this.n.bitLength() + 7) >> 3;
+        text = b64tohex(text);
+        try {
+            if (text.length > maxLength) {
+                var ct_2 = "";
+                var lt = text.match(/.{1,256}/g); // 128位解密。取256位
+                lt.forEach(function (entry) {
+                    var t1 = _this.decrypt(entry);
+                    ct_2 += t1;
+                });
+                return ct_2;
+            }
+            var y = this.decrypt(text);
+            return y;
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    // RSAKey.prototype.setPrivate = RSASetPrivate;
+    // Set the private key fields N, e, and d from hex strings
+    RSAKey.prototype.setPrivate = function (N, E, D) {
+        if (N != null && E != null && N.length > 0 && E.length > 0) {
+            this.n = parseBigInt(N, 16);
+            this.e = parseInt(E, 16);
+            this.d = parseBigInt(D, 16);
+        }
+        else {
+            console.error("Invalid RSA private key");
+        }
+    };
+    // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
+    // Set the private key fields N, e, d and CRT params from hex strings
+    RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
+        if (N != null && E != null && N.length > 0 && E.length > 0) {
+            this.n = parseBigInt(N, 16);
+            this.e = parseInt(E, 16);
+            this.d = parseBigInt(D, 16);
+            this.p = parseBigInt(P, 16);
+            this.q = parseBigInt(Q, 16);
+            this.dmp1 = parseBigInt(DP, 16);
+            this.dmq1 = parseBigInt(DQ, 16);
+            this.coeff = parseBigInt(C, 16);
+        }
+        else {
+            console.error("Invalid RSA private key");
+        }
+    };
+    // RSAKey.prototype.generate = RSAGenerate;
+    // Generate a new random private key B bits long, using public expt E
+    RSAKey.prototype.generate = function (B, E) {
+        var rng = new SecureRandom();
+        var qs = B >> 1;
+        this.e = parseInt(E, 16);
+        var ee = new BigInteger(E, 16);
+        for (;;) {
+            for (;;) {
+                this.p = new BigInteger(B - qs, 1, rng);
+                if (this.p
+                    .subtract(BigInteger.ONE)
+                    .gcd(ee)
+                    .compareTo(BigInteger.ONE) == 0 &&
+                    this.p.isProbablePrime(10)) {
+                    break;
+                }
+            }
+            for (;;) {
+                this.q = new BigInteger(qs, 1, rng);
+                if (this.q
+                    .subtract(BigInteger.ONE)
+                    .gcd(ee)
+                    .compareTo(BigInteger.ONE) == 0 &&
+                    this.q.isProbablePrime(10)) {
+                    break;
+                }
+            }
+            if (this.p.compareTo(this.q) <= 0) {
+                var t = this.p;
+                this.p = this.q;
+                this.q = t;
+            }
+            var p1 = this.p.subtract(BigInteger.ONE);
+            var q1 = this.q.subtract(BigInteger.ONE);
+            var phi = p1.multiply(q1);
+            if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
+                this.n = this.p.multiply(this.q);
+                this.d = ee.modInverse(phi);
+                this.dmp1 = this.d.mod(p1);
+                this.dmq1 = this.d.mod(q1);
+                this.coeff = this.q.modInverse(this.p);
+                break;
+            }
+        }
+    };
+    // RSAKey.prototype.decrypt = RSADecrypt;
+    // Return the PKCS#1 RSA decryption of "ctext".
+    // "ctext" is an even-length hex string and the output is a plain string.
+    RSAKey.prototype.decrypt = function (ctext) {
+        var c = parseBigInt(ctext, 16);
+        var m = this.doPrivate(c);
+        if (m == null) {
+            return null;
+        }
+        return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
+    };
+    // Generate a new random private key B bits long, using public expt E
+    RSAKey.prototype.generateAsync = function (B, E, callback) {
+        var rng = new SecureRandom();
+        var qs = B >> 1;
+        this.e = parseInt(E, 16);
+        var ee = new BigInteger(E, 16);
+        var rsa = this;
+        // These functions have non-descript names because they were originally for(;;) loops.
+        // I don't know about cryptography to give them better names than loop1-4.
+        var loop1 = function () {
+            var loop4 = function () {
+                if (rsa.p.compareTo(rsa.q) <= 0) {
+                    var t = rsa.p;
+                    rsa.p = rsa.q;
+                    rsa.q = t;
+                }
+                var p1 = rsa.p.subtract(BigInteger.ONE);
+                var q1 = rsa.q.subtract(BigInteger.ONE);
+                var phi = p1.multiply(q1);
+                if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
+                    rsa.n = rsa.p.multiply(rsa.q);
+                    rsa.d = ee.modInverse(phi);
+                    rsa.dmp1 = rsa.d.mod(p1);
+                    rsa.dmq1 = rsa.d.mod(q1);
+                    rsa.coeff = rsa.q.modInverse(rsa.p);
+                    setTimeout(function () {
+                        callback();
+                    }, 0); // escape
+                }
+                else {
+                    setTimeout(loop1, 0);
+                }
+            };
+            var loop3 = function () {
+                rsa.q = nbi();
+                rsa.q.fromNumberAsync(qs, 1, rng, function () {
+                    rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
+                        if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
+                            setTimeout(loop4, 0);
+                        }
+                        else {
+                            setTimeout(loop3, 0);
+                        }
+                    });
+                });
+            };
+            var loop2 = function () {
+                rsa.p = nbi();
+                rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
+                    rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
+                        if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
+                            setTimeout(loop3, 0);
+                        }
+                        else {
+                            setTimeout(loop2, 0);
+                        }
+                    });
+                });
+            };
+            setTimeout(loop2, 0);
+        };
+        setTimeout(loop1, 0);
+    };
+    RSAKey.prototype.sign = function (text, digestMethod, digestName) {
+        var header = getDigestHeader(digestName);
+        var digest = header + digestMethod(text).toString();
+        var m = pkcs1pad1(digest, this.n.bitLength() / 4);
+        if (m == null) {
+            return null;
+        }
+        var c = this.doPrivate(m);
+        if (c == null) {
+            return null;
+        }
+        var h = c.toString(16);
+        if ((h.length & 1) == 0) {
+            return h;
+        }
+        else {
+            return "0" + h;
+        }
+    };
+    RSAKey.prototype.verify = function (text, signature, digestMethod) {
+        var c = parseBigInt(signature, 16);
+        var m = this.doPublic(c);
+        if (m == null) {
+            return null;
+        }
+        var unpadded = m.toString(16).replace(/^1f+00/, "");
+        var digest = removeDigestHeader(unpadded);
+        return digest == digestMethod(text).toString();
+    };
+    return RSAKey;
+}());
+// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
+function pkcs1unpad2(d, n) {
+    var b = d.toByteArray();
+    var i = 0;
+    while (i < b.length && b[i] == 0) {
+        ++i;
+    }
+    if (b.length - i != n - 1 || b[i] != 2) {
+        return null;
+    }
+    ++i;
+    while (b[i] != 0) {
+        if (++i >= b.length) {
+            return null;
+        }
+    }
+    var ret = "";
+    while (++i < b.length) {
+        var c = b[i] & 255;
+        if (c < 128) {
+            // utf-8 decode
+            ret += String.fromCharCode(c);
+        }
+        else if (c > 191 && c < 224) {
+            ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
+            ++i;
+        }
+        else {
+            ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
+            i += 2;
+        }
+    }
+    return ret;
+}
+// https://tools.ietf.org/html/rfc3447#page-43
+var DIGEST_HEADERS = {
+    md2: "3020300c06082a864886f70d020205000410",
+    md5: "3020300c06082a864886f70d020505000410",
+    sha1: "3021300906052b0e03021a05000414",
+    sha224: "302d300d06096086480165030402040500041c",
+    sha256: "3031300d060960864801650304020105000420",
+    sha384: "3041300d060960864801650304020205000430",
+    sha512: "3051300d060960864801650304020305000440",
+    ripemd160: "3021300906052b2403020105000414"
+};
+function getDigestHeader(name) {
+    return DIGEST_HEADERS[name] || "";
+}
+function removeDigestHeader(str) {
+    for (var name_1 in DIGEST_HEADERS) {
+        if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
+            var header = DIGEST_HEADERS[name_1];
+            var len = header.length;
+            if (str.substr(0, len) == header) {
+                return str.substr(len);
+            }
+        }
+    }
+    return str;
+}
+// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
+// function RSAEncryptB64(text) {
+//  var h = this.encrypt(text);
+//  if(h) return hex2b64(h); else return null;
+// }
+// public
+// RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
+
+/*!
+Copyright (c) 2011, Yahoo! Inc. All rights reserved.
+Code licensed under the BSD License:
+http://developer.yahoo.com/yui/license.html
+version: 2.9.0
+*/
+var YAHOO = {};
+YAHOO.lang = {
+    /**
+     * Utility to set up the prototype, constructor and superclass properties to
+     * support an inheritance strategy that can chain constructors and methods.
+     * Static members will not be inherited.
+     *
+     * @method extend
+     * @static
+     * @param {Function} subc   the object to modify
+     * @param {Function} superc the object to inherit
+     * @param {Object} overrides  additional properties/methods to add to the
+     *                              subclass prototype.  These will override the
+     *                              matching items obtained from the superclass
+     *                              if present.
+     */
+    extend: function(subc, superc, overrides) {
+        if (! superc || ! subc) {
+            throw new Error("YAHOO.lang.extend failed, please check that " +
+                "all dependencies are included.");
+        }
+
+        var F = function() {};
+        F.prototype = superc.prototype;
+        subc.prototype = new F();
+        subc.prototype.constructor = subc;
+        subc.superclass = superc.prototype;
+
+        if (superc.prototype.constructor == Object.prototype.constructor) {
+            superc.prototype.constructor = superc;
+        }
+
+        if (overrides) {
+            var i;
+            for (i in overrides) {
+                subc.prototype[i] = overrides[i];
+            }
+
+            /*
+             * IE will not enumerate native functions in a derived object even if the
+             * function was overridden.  This is a workaround for specific functions
+             * we care about on the Object prototype.
+             * @property _IEEnumFix
+             * @param {Function} r  the object to receive the augmentation
+             * @param {Function} s  the object that supplies the properties to augment
+             * @static
+             * @private
+             */
+            var _IEEnumFix = function() {},
+                ADD = ["toString", "valueOf"];
+            try {
+                if (/MSIE/.test(navigator.userAgent)) {
+                    _IEEnumFix = function(r, s) {
+                        for (i = 0; i < ADD.length; i = i + 1) {
+                            var fname = ADD[i], f = s[fname];
+                            if (typeof f === 'function' && f != Object.prototype[fname]) {
+                                r[fname] = f;
+                            }
+                        }
+                    };
+                }
+            } catch (ex) {}            _IEEnumFix(subc.prototype, overrides);
+        }
+    }
+};
+
+/* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
+ */
+
+/**
+ * @fileOverview
+ * @name asn1-1.0.js
+ * @author Kenji Urushima kenji.urushima@gmail.com
+ * @version asn1 1.0.13 (2017-Jun-02)
+ * @since jsrsasign 2.1
+ * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
+ */
+
+/**
+ * kjur's class library name space
+ * <p>
+ * This name space provides following name spaces:
+ * <ul>
+ * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
+ * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
+ * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
+ * class and utilities</li>
+ * </ul>
+ * </p>
+ * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
+ * @name KJUR
+ * @namespace kjur's class library name space
+ */
+var KJUR = {};
+
+/**
+ * kjur's ASN.1 class library name space
+ * <p>
+ * This is ITU-T X.690 ASN.1 DER encoder class library and
+ * class structure and methods is very similar to
+ * org.bouncycastle.asn1 package of
+ * well known BouncyCaslte Cryptography Library.
+ * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
+ * Here are ASN.1 DER primitive classes.
+ * <ul>
+ * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
+ * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
+ * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
+ * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
+ * <li>0x05 {@link KJUR.asn1.DERNull}</li>
+ * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
+ * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
+ * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
+ * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
+ * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
+ * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
+ * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
+ * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
+ * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
+ * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
+ * <li>0x31 {@link KJUR.asn1.DERSet}</li>
+ * </ul>
+ * <h4>OTHER ASN.1 CLASSES</h4>
+ * <ul>
+ * <li>{@link KJUR.asn1.ASN1Object}</li>
+ * <li>{@link KJUR.asn1.DERAbstractString}</li>
+ * <li>{@link KJUR.asn1.DERAbstractTime}</li>
+ * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
+ * <li>{@link KJUR.asn1.DERTaggedObject}</li>
+ * </ul>
+ * <h4>SUB NAME SPACES</h4>
+ * <ul>
+ * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
+ * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
+ * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
+ * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
+ * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
+ * </ul>
+ * </p>
+ * NOTE: Please ignore method summary and document of this namespace.
+ * This caused by a bug of jsdoc2.
+ * @name KJUR.asn1
+ * @namespace
+ */
+if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
+
+/**
+ * ASN1 utilities class
+ * @name KJUR.asn1.ASN1Util
+ * @class ASN1 utilities class
+ * @since asn1 1.0.2
+ */
+KJUR.asn1.ASN1Util = new function() {
+    this.integerToByteHex = function(i) {
+        var h = i.toString(16);
+        if ((h.length % 2) == 1) h = '0' + h;
+        return h;
+    };
+    this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
+        var h = bigIntegerValue.toString(16);
+        if (h.substr(0, 1) != '-') {
+            if (h.length % 2 == 1) {
+                h = '0' + h;
+            } else {
+                if (! h.match(/^[0-7]/)) {
+                    h = '00' + h;
+                }
+            }
+        } else {
+            var hPos = h.substr(1);
+            var xorLen = hPos.length;
+            if (xorLen % 2 == 1) {
+                xorLen += 1;
+            } else {
+                if (! h.match(/^[0-7]/)) {
+                    xorLen += 2;
+                }
+            }
+            var hMask = '';
+            for (var i = 0; i < xorLen; i++) {
+                hMask += 'f';
+            }
+            var biMask = new BigInteger(hMask, 16);
+            var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
+            h = biNeg.toString(16).replace(/^-/, '');
+        }
+        return h;
+    };
+    /**
+     * get PEM string from hexadecimal data and header string
+     * @name getPEMStringFromHex
+     * @memberOf KJUR.asn1.ASN1Util
+     * @function
+     * @param {String} dataHex hexadecimal string of PEM body
+     * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
+     * @return {String} PEM formatted string of input data
+     * @description
+     * This method converts a hexadecimal string to a PEM string with
+     * a specified header. Its line break will be CRLF("\r\n").
+     * @example
+     * var pem  = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
+     * // value of pem will be:
+     * -----BEGIN PRIVATE KEY-----
+     * YWFh
+     * -----END PRIVATE KEY-----
+     */
+    this.getPEMStringFromHex = function(dataHex, pemHeader) {
+        return hextopem(dataHex, pemHeader);
+    };
+
+    /**
+     * generate ASN1Object specifed by JSON parameters
+     * @name newObject
+     * @memberOf KJUR.asn1.ASN1Util
+     * @function
+     * @param {Array} param JSON parameter to generate ASN1Object
+     * @return {KJUR.asn1.ASN1Object} generated object
+     * @since asn1 1.0.3
+     * @description
+     * generate any ASN1Object specified by JSON param
+     * including ASN.1 primitive or structured.
+     * Generally 'param' can be described as follows:
+     * <blockquote>
+     * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
+     * </blockquote>
+     * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
+     * <ul>
+     * <li>'bool' - DERBoolean</li>
+     * <li>'int' - DERInteger</li>
+     * <li>'bitstr' - DERBitString</li>
+     * <li>'octstr' - DEROctetString</li>
+     * <li>'null' - DERNull</li>
+     * <li>'oid' - DERObjectIdentifier</li>
+     * <li>'enum' - DEREnumerated</li>
+     * <li>'utf8str' - DERUTF8String</li>
+     * <li>'numstr' - DERNumericString</li>
+     * <li>'prnstr' - DERPrintableString</li>
+     * <li>'telstr' - DERTeletexString</li>
+     * <li>'ia5str' - DERIA5String</li>
+     * <li>'utctime' - DERUTCTime</li>
+     * <li>'gentime' - DERGeneralizedTime</li>
+     * <li>'seq' - DERSequence</li>
+     * <li>'set' - DERSet</li>
+     * <li>'tag' - DERTaggedObject</li>
+     * </ul>
+     * @example
+     * newObject({'prnstr': 'aaa'});
+     * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
+     * // ASN.1 Tagged Object
+     * newObject({'tag': {'tag': 'a1',
+     *                    'explicit': true,
+     *                    'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
+     * // more simple representation of ASN.1 Tagged Object
+     * newObject({'tag': ['a1',
+     *                    true,
+     *                    {'seq': [
+     *                      {'int': 3},
+     *                      {'prnstr': 'aaa'}]}
+     *                   ]});
+     */
+    this.newObject = function(param) {
+        var _KJUR = KJUR,
+            _KJUR_asn1 = _KJUR.asn1,
+            _DERBoolean = _KJUR_asn1.DERBoolean,
+            _DERInteger = _KJUR_asn1.DERInteger,
+            _DERBitString = _KJUR_asn1.DERBitString,
+            _DEROctetString = _KJUR_asn1.DEROctetString,
+            _DERNull = _KJUR_asn1.DERNull,
+            _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
+            _DEREnumerated = _KJUR_asn1.DEREnumerated,
+            _DERUTF8String = _KJUR_asn1.DERUTF8String,
+            _DERNumericString = _KJUR_asn1.DERNumericString,
+            _DERPrintableString = _KJUR_asn1.DERPrintableString,
+            _DERTeletexString = _KJUR_asn1.DERTeletexString,
+            _DERIA5String = _KJUR_asn1.DERIA5String,
+            _DERUTCTime = _KJUR_asn1.DERUTCTime,
+            _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
+            _DERSequence = _KJUR_asn1.DERSequence,
+            _DERSet = _KJUR_asn1.DERSet,
+            _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
+            _newObject = _KJUR_asn1.ASN1Util.newObject;
+
+        var keys = Object.keys(param);
+        if (keys.length != 1)
+            throw "key of param shall be only one.";
+        var key = keys[0];
+
+        if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
+            throw "undefined key: " + key;
+
+        if (key == "bool")    return new _DERBoolean(param[key]);
+        if (key == "int")     return new _DERInteger(param[key]);
+        if (key == "bitstr")  return new _DERBitString(param[key]);
+        if (key == "octstr")  return new _DEROctetString(param[key]);
+        if (key == "null")    return new _DERNull(param[key]);
+        if (key == "oid")     return new _DERObjectIdentifier(param[key]);
+        if (key == "enum")    return new _DEREnumerated(param[key]);
+        if (key == "utf8str") return new _DERUTF8String(param[key]);
+        if (key == "numstr")  return new _DERNumericString(param[key]);
+        if (key == "prnstr")  return new _DERPrintableString(param[key]);
+        if (key == "telstr")  return new _DERTeletexString(param[key]);
+        if (key == "ia5str")  return new _DERIA5String(param[key]);
+        if (key == "utctime") return new _DERUTCTime(param[key]);
+        if (key == "gentime") return new _DERGeneralizedTime(param[key]);
+
+        if (key == "seq") {
+            var paramList = param[key];
+            var a = [];
+            for (var i = 0; i < paramList.length; i++) {
+                var asn1Obj = _newObject(paramList[i]);
+                a.push(asn1Obj);
+            }
+            return new _DERSequence({'array': a});
+        }
+
+        if (key == "set") {
+            var paramList = param[key];
+            var a = [];
+            for (var i = 0; i < paramList.length; i++) {
+                var asn1Obj = _newObject(paramList[i]);
+                a.push(asn1Obj);
+            }
+            return new _DERSet({'array': a});
+        }
+
+        if (key == "tag") {
+            var tagParam = param[key];
+            if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
+                tagParam.length == 3) {
+                var obj = _newObject(tagParam[2]);
+                return new _DERTaggedObject({tag: tagParam[0],
+                    explicit: tagParam[1],
+                    obj: obj});
+            } else {
+                var newParam = {};
+                if (tagParam.explicit !== undefined)
+                    newParam.explicit = tagParam.explicit;
+                if (tagParam.tag !== undefined)
+                    newParam.tag = tagParam.tag;
+                if (tagParam.obj === undefined)
+                    throw "obj shall be specified for 'tag'.";
+                newParam.obj = _newObject(tagParam.obj);
+                return new _DERTaggedObject(newParam);
+            }
+        }
+    };
+
+    /**
+     * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
+     * @name jsonToASN1HEX
+     * @memberOf KJUR.asn1.ASN1Util
+     * @function
+     * @param {Array} param JSON parameter to generate ASN1Object
+     * @return hexadecimal string of ASN1Object
+     * @since asn1 1.0.4
+     * @description
+     * As for ASN.1 object representation of JSON object,
+     * please see {@link newObject}.
+     * @example
+     * jsonToASN1HEX({'prnstr': 'aaa'});
+     */
+    this.jsonToASN1HEX = function(param) {
+        var asn1Obj = this.newObject(param);
+        return asn1Obj.getEncodedHex();
+    };
+};
+
+/**
+ * get dot noted oid number string from hexadecimal value of OID
+ * @name oidHexToInt
+ * @memberOf KJUR.asn1.ASN1Util
+ * @function
+ * @param {String} hex hexadecimal value of object identifier
+ * @return {String} dot noted string of object identifier
+ * @since jsrsasign 4.8.3 asn1 1.0.7
+ * @description
+ * This static method converts from hexadecimal string representation of
+ * ASN.1 value of object identifier to oid number string.
+ * @example
+ * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6"
+ */
+KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
+    var s = "";
+    var i01 = parseInt(hex.substr(0, 2), 16);
+    var i0 = Math.floor(i01 / 40);
+    var i1 = i01 % 40;
+    var s = i0 + "." + i1;
+
+    var binbuf = "";
+    for (var i = 2; i < hex.length; i += 2) {
+        var value = parseInt(hex.substr(i, 2), 16);
+        var bin = ("00000000" + value.toString(2)).slice(- 8);
+        binbuf = binbuf + bin.substr(1, 7);
+        if (bin.substr(0, 1) == "0") {
+            var bi = new BigInteger(binbuf, 2);
+            s = s + "." + bi.toString(10);
+            binbuf = "";
+        }
+    }
+    return s;
+};
+
+/**
+ * get hexadecimal value of object identifier from dot noted oid value
+ * @name oidIntToHex
+ * @memberOf KJUR.asn1.ASN1Util
+ * @function
+ * @param {String} oidString dot noted string of object identifier
+ * @return {String} hexadecimal value of object identifier
+ * @since jsrsasign 4.8.3 asn1 1.0.7
+ * @description
+ * This static method converts from object identifier value string.
+ * to hexadecimal string representation of it.
+ * @example
+ * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406"
+ */
+KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
+    var itox = function(i) {
+        var h = i.toString(16);
+        if (h.length == 1) h = '0' + h;
+        return h;
+    };
+
+    var roidtox = function(roid) {
+        var h = '';
+        var bi = new BigInteger(roid, 10);
+        var b = bi.toString(2);
+        var padLen = 7 - b.length % 7;
+        if (padLen == 7) padLen = 0;
+        var bPad = '';
+        for (var i = 0; i < padLen; i++) bPad += '0';
+        b = bPad + b;
+        for (var i = 0; i < b.length - 1; i += 7) {
+            var b8 = b.substr(i, 7);
+            if (i != b.length - 7) b8 = '1' + b8;
+            h += itox(parseInt(b8, 2));
+        }
+        return h;
+    };
+
+    if (! oidString.match(/^[0-9.]+$/)) {
+        throw "malformed oid string: " + oidString;
+    }
+    var h = '';
+    var a = oidString.split('.');
+    var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
+    h += itox(i0);
+    a.splice(0, 2);
+    for (var i = 0; i < a.length; i++) {
+        h += roidtox(a[i]);
+    }
+    return h;
+};
+
+
+// ********************************************************************
+//  Abstract ASN.1 Classes
+// ********************************************************************
+
+// ********************************************************************
+
+/**
+ * base class for ASN.1 DER encoder object
+ * @name KJUR.asn1.ASN1Object
+ * @class base class for ASN.1 DER encoder object
+ * @property {Boolean} isModified flag whether internal data was changed
+ * @property {String} hTLV hexadecimal string of ASN.1 TLV
+ * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
+ * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
+ * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
+ * @description
+ */
+KJUR.asn1.ASN1Object = function() {
+    var hV = '';
+
+    /**
+     * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
+     * @name getLengthHexFromValue
+     * @memberOf KJUR.asn1.ASN1Object#
+     * @function
+     * @return {String} hexadecimal string of ASN.1 TLV length(L)
+     */
+    this.getLengthHexFromValue = function() {
+        if (typeof this.hV == "undefined" || this.hV == null) {
+            throw "this.hV is null or undefined.";
+        }
+        if (this.hV.length % 2 == 1) {
+            throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
+        }
+        var n = this.hV.length / 2;
+        var hN = n.toString(16);
+        if (hN.length % 2 == 1) {
+            hN = "0" + hN;
+        }
+        if (n < 128) {
+            return hN;
+        } else {
+            var hNlen = hN.length / 2;
+            if (hNlen > 15) {
+                throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
+            }
+            var head = 128 + hNlen;
+            return head.toString(16) + hN;
+        }
+    };
+
+    /**
+     * get hexadecimal string of ASN.1 TLV bytes
+     * @name getEncodedHex
+     * @memberOf KJUR.asn1.ASN1Object#
+     * @function
+     * @return {String} hexadecimal string of ASN.1 TLV
+     */
+    this.getEncodedHex = function() {
+        if (this.hTLV == null || this.isModified) {
+            this.hV = this.getFreshValueHex();
+            this.hL = this.getLengthHexFromValue();
+            this.hTLV = this.hT + this.hL + this.hV;
+            this.isModified = false;
+            //alert("first time: " + this.hTLV);
+        }
+        return this.hTLV;
+    };
+
+    /**
+     * get hexadecimal string of ASN.1 TLV value(V) bytes
+     * @name getValueHex
+     * @memberOf KJUR.asn1.ASN1Object#
+     * @function
+     * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
+     */
+    this.getValueHex = function() {
+        this.getEncodedHex();
+        return this.hV;
+    };
+
+    this.getFreshValueHex = function() {
+        return '';
+    };
+};
+
+// == BEGIN DERAbstractString ================================================
+/**
+ * base class for ASN.1 DER string classes
+ * @name KJUR.asn1.DERAbstractString
+ * @class base class for ASN.1 DER string classes
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @property {String} s internal string of value
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>str - specify initial ASN.1 value(V) by a string</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERAbstractString = function(params) {
+    KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
+
+    /**
+     * get string value of this string object
+     * @name getString
+     * @memberOf KJUR.asn1.DERAbstractString#
+     * @function
+     * @return {String} string value of this string object
+     */
+    this.getString = function() {
+        return this.s;
+    };
+
+    /**
+     * set value by a string
+     * @name setString
+     * @memberOf KJUR.asn1.DERAbstractString#
+     * @function
+     * @param {String} newS value by a string to set
+     */
+    this.setString = function(newS) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.s = newS;
+        this.hV = stohex(this.s);
+    };
+
+    /**
+     * set value by a hexadecimal string
+     * @name setStringHex
+     * @memberOf KJUR.asn1.DERAbstractString#
+     * @function
+     * @param {String} newHexString value by a hexadecimal string to set
+     */
+    this.setStringHex = function(newHexString) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.s = null;
+        this.hV = newHexString;
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params == "string") {
+            this.setString(params);
+        } else if (typeof params['str'] != "undefined") {
+            this.setString(params['str']);
+        } else if (typeof params['hex'] != "undefined") {
+            this.setStringHex(params['hex']);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
+// == END   DERAbstractString ================================================
+
+// == BEGIN DERAbstractTime ==================================================
+/**
+ * base class for ASN.1 DER Generalized/UTCTime class
+ * @name KJUR.asn1.DERAbstractTime
+ * @class base class for ASN.1 DER Generalized/UTCTime class
+ * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * @see KJUR.asn1.ASN1Object - superclass
+ */
+KJUR.asn1.DERAbstractTime = function(params) {
+    KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
+
+    // --- PRIVATE METHODS --------------------
+    this.localDateToUTC = function(d) {
+        utc = d.getTime() + (d.getTimezoneOffset() * 60000);
+        var utcDate = new Date(utc);
+        return utcDate;
+    };
+
+    /*
+     * format date string by Data object
+     * @name formatDate
+     * @memberOf KJUR.asn1.AbstractTime;
+     * @param {Date} dateObject
+     * @param {string} type 'utc' or 'gen'
+     * @param {boolean} withMillis flag for with millisections or not
+     * @description
+     * 'withMillis' flag is supported from asn1 1.0.6.
+     */
+    this.formatDate = function(dateObject, type, withMillis) {
+        var pad = this.zeroPadding;
+        var d = this.localDateToUTC(dateObject);
+        var year = String(d.getFullYear());
+        if (type == 'utc') year = year.substr(2, 2);
+        var month = pad(String(d.getMonth() + 1), 2);
+        var day = pad(String(d.getDate()), 2);
+        var hour = pad(String(d.getHours()), 2);
+        var min = pad(String(d.getMinutes()), 2);
+        var sec = pad(String(d.getSeconds()), 2);
+        var s = year + month + day + hour + min + sec;
+        if (withMillis === true) {
+            var millis = d.getMilliseconds();
+            if (millis != 0) {
+                var sMillis = pad(String(millis), 3);
+                sMillis = sMillis.replace(/[0]+$/, "");
+                s = s + "." + sMillis;
+            }
+        }
+        return s + "Z";
+    };
+
+    this.zeroPadding = function(s, len) {
+        if (s.length >= len) return s;
+        return new Array(len - s.length + 1).join('0') + s;
+    };
+
+    // --- PUBLIC METHODS --------------------
+    /**
+     * get string value of this string object
+     * @name getString
+     * @memberOf KJUR.asn1.DERAbstractTime#
+     * @function
+     * @return {String} string value of this time object
+     */
+    this.getString = function() {
+        return this.s;
+    };
+
+    /**
+     * set value by a string
+     * @name setString
+     * @memberOf KJUR.asn1.DERAbstractTime#
+     * @function
+     * @param {String} newS value by a string to set such like "130430235959Z"
+     */
+    this.setString = function(newS) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.s = newS;
+        this.hV = stohex(newS);
+    };
+
+    /**
+     * set value by a Date object
+     * @name setByDateValue
+     * @memberOf KJUR.asn1.DERAbstractTime#
+     * @function
+     * @param {Integer} year year of date (ex. 2013)
+     * @param {Integer} month month of date between 1 and 12 (ex. 12)
+     * @param {Integer} day day of month
+     * @param {Integer} hour hours of date
+     * @param {Integer} min minutes of date
+     * @param {Integer} sec seconds of date
+     */
+    this.setByDateValue = function(year, month, day, hour, min, sec) {
+        var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
+        this.setByDate(dateObject);
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+};
+YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
+// == END   DERAbstractTime ==================================================
+
+// == BEGIN DERAbstractStructured ============================================
+/**
+ * base class for ASN.1 DER structured class
+ * @name KJUR.asn1.DERAbstractStructured
+ * @class base class for ASN.1 DER structured class
+ * @property {Array} asn1Array internal array of ASN1Object
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * @see KJUR.asn1.ASN1Object - superclass
+ */
+KJUR.asn1.DERAbstractStructured = function(params) {
+    KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
+
+    /**
+     * set value by array of ASN1Object
+     * @name setByASN1ObjectArray
+     * @memberOf KJUR.asn1.DERAbstractStructured#
+     * @function
+     * @param {array} asn1ObjectArray array of ASN1Object to set
+     */
+    this.setByASN1ObjectArray = function(asn1ObjectArray) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.asn1Array = asn1ObjectArray;
+    };
+
+    /**
+     * append an ASN1Object to internal array
+     * @name appendASN1Object
+     * @memberOf KJUR.asn1.DERAbstractStructured#
+     * @function
+     * @param {ASN1Object} asn1Object to add
+     */
+    this.appendASN1Object = function(asn1Object) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.asn1Array.push(asn1Object);
+    };
+
+    this.asn1Array = new Array();
+    if (typeof params != "undefined") {
+        if (typeof params['array'] != "undefined") {
+            this.asn1Array = params['array'];
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
+
+
+// ********************************************************************
+//  ASN.1 Object Classes
+// ********************************************************************
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Boolean
+ * @name KJUR.asn1.DERBoolean
+ * @class class for ASN.1 DER Boolean
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * @see KJUR.asn1.ASN1Object - superclass
+ */
+KJUR.asn1.DERBoolean = function() {
+    KJUR.asn1.DERBoolean.superclass.constructor.call(this);
+    this.hT = "01";
+    this.hTLV = "0101ff";
+};
+YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Integer
+ * @name KJUR.asn1.DERInteger
+ * @class class for ASN.1 DER Integer
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>int - specify initial ASN.1 value(V) by integer value</li>
+ * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERInteger = function(params) {
+    KJUR.asn1.DERInteger.superclass.constructor.call(this);
+    this.hT = "02";
+
+    /**
+     * set value by Tom Wu's BigInteger object
+     * @name setByBigInteger
+     * @memberOf KJUR.asn1.DERInteger#
+     * @function
+     * @param {BigInteger} bigIntegerValue to set
+     */
+    this.setByBigInteger = function(bigIntegerValue) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
+    };
+
+    /**
+     * set value by integer value
+     * @name setByInteger
+     * @memberOf KJUR.asn1.DERInteger
+     * @function
+     * @param {Integer} integer value to set
+     */
+    this.setByInteger = function(intValue) {
+        var bi = new BigInteger(String(intValue), 10);
+        this.setByBigInteger(bi);
+    };
+
+    /**
+     * set value by integer value
+     * @name setValueHex
+     * @memberOf KJUR.asn1.DERInteger#
+     * @function
+     * @param {String} hexadecimal string of integer value
+     * @description
+     * <br/>
+     * NOTE: Value shall be represented by minimum octet length of
+     * two's complement representation.
+     * @example
+     * new KJUR.asn1.DERInteger(123);
+     * new KJUR.asn1.DERInteger({'int': 123});
+     * new KJUR.asn1.DERInteger({'hex': '1fad'});
+     */
+    this.setValueHex = function(newHexString) {
+        this.hV = newHexString;
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params['bigint'] != "undefined") {
+            this.setByBigInteger(params['bigint']);
+        } else if (typeof params['int'] != "undefined") {
+            this.setByInteger(params['int']);
+        } else if (typeof params == "number") {
+            this.setByInteger(params);
+        } else if (typeof params['hex'] != "undefined") {
+            this.setValueHex(params['hex']);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER encoded BitString primitive
+ * @name KJUR.asn1.DERBitString
+ * @class class for ASN.1 DER encoded BitString primitive
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>bin - specify binary string (ex. '10111')</li>
+ * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
+ * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
+ * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
+ * argument for "BitString encapsulates" structure.</li>
+ * </ul>
+ * NOTE1: 'params' can be omitted.<br/>
+ * NOTE2: 'obj' parameter have been supported since
+ * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
+ * @example
+ * // default constructor
+ * o = new KJUR.asn1.DERBitString();
+ * // initialize with binary string
+ * o = new KJUR.asn1.DERBitString({bin: "1011"});
+ * // initialize with boolean array
+ * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
+ * // initialize with hexadecimal string (04 is unused bits)
+ * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
+ * // initialize with ASN1Util.newObject argument for encapsulated
+ * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
+ * // above generates a ASN.1 data like this:
+ * // BIT STRING, encapsulates {
+ * //   SEQUENCE {
+ * //     INTEGER 3
+ * //     PrintableString 'aaa'
+ * //     }
+ * //   }
+ */
+KJUR.asn1.DERBitString = function(params) {
+    if (params !== undefined && typeof params.obj !== "undefined") {
+        var o = KJUR.asn1.ASN1Util.newObject(params.obj);
+        params.hex = "00" + o.getEncodedHex();
+    }
+    KJUR.asn1.DERBitString.superclass.constructor.call(this);
+    this.hT = "03";
+
+    /**
+     * set ASN.1 value(V) by a hexadecimal string including unused bits
+     * @name setHexValueIncludingUnusedBits
+     * @memberOf KJUR.asn1.DERBitString#
+     * @function
+     * @param {String} newHexStringIncludingUnusedBits
+     */
+    this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.hV = newHexStringIncludingUnusedBits;
+    };
+
+    /**
+     * set ASN.1 value(V) by unused bit and hexadecimal string of value
+     * @name setUnusedBitsAndHexValue
+     * @memberOf KJUR.asn1.DERBitString#
+     * @function
+     * @param {Integer} unusedBits
+     * @param {String} hValue
+     */
+    this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
+        if (unusedBits < 0 || 7 < unusedBits) {
+            throw "unused bits shall be from 0 to 7: u = " + unusedBits;
+        }
+        var hUnusedBits = "0" + unusedBits;
+        this.hTLV = null;
+        this.isModified = true;
+        this.hV = hUnusedBits + hValue;
+    };
+
+    /**
+     * set ASN.1 DER BitString by binary string<br/>
+     * @name setByBinaryString
+     * @memberOf KJUR.asn1.DERBitString#
+     * @function
+     * @param {String} binaryString binary value string (i.e. '10111')
+     * @description
+     * Its unused bits will be calculated automatically by length of
+     * 'binaryValue'. <br/>
+     * NOTE: Trailing zeros '0' will be ignored.
+     * @example
+     * o = new KJUR.asn1.DERBitString();
+     * o.setByBooleanArray("01011");
+     */
+    this.setByBinaryString = function(binaryString) {
+        binaryString = binaryString.replace(/0+$/, '');
+        var unusedBits = 8 - binaryString.length % 8;
+        if (unusedBits == 8) unusedBits = 0;
+        for (var i = 0; i <= unusedBits; i++) {
+            binaryString += '0';
+        }
+        var h = '';
+        for (var i = 0; i < binaryString.length - 1; i += 8) {
+            var b = binaryString.substr(i, 8);
+            var x = parseInt(b, 2).toString(16);
+            if (x.length == 1) x = '0' + x;
+            h += x;
+        }
+        this.hTLV = null;
+        this.isModified = true;
+        this.hV = '0' + unusedBits + h;
+    };
+
+    /**
+     * set ASN.1 TLV value(V) by an array of boolean<br/>
+     * @name setByBooleanArray
+     * @memberOf KJUR.asn1.DERBitString#
+     * @function
+     * @param {array} booleanArray array of boolean (ex. [true, false, true])
+     * @description
+     * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
+     * @example
+     * o = new KJUR.asn1.DERBitString();
+     * o.setByBooleanArray([false, true, false, true, true]);
+     */
+    this.setByBooleanArray = function(booleanArray) {
+        var s = '';
+        for (var i = 0; i < booleanArray.length; i++) {
+            if (booleanArray[i] == true) {
+                s += '1';
+            } else {
+                s += '0';
+            }
+        }
+        this.setByBinaryString(s);
+    };
+
+    /**
+     * generate an array of falses with specified length<br/>
+     * @name newFalseArray
+     * @memberOf KJUR.asn1.DERBitString
+     * @function
+     * @param {Integer} nLength length of array to generate
+     * @return {array} array of boolean falses
+     * @description
+     * This static method may be useful to initialize boolean array.
+     * @example
+     * o = new KJUR.asn1.DERBitString();
+     * o.newFalseArray(3) &rarr; [false, false, false]
+     */
+    this.newFalseArray = function(nLength) {
+        var a = new Array(nLength);
+        for (var i = 0; i < nLength; i++) {
+            a[i] = false;
+        }
+        return a;
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
+            this.setHexValueIncludingUnusedBits(params);
+        } else if (typeof params['hex'] != "undefined") {
+            this.setHexValueIncludingUnusedBits(params['hex']);
+        } else if (typeof params['bin'] != "undefined") {
+            this.setByBinaryString(params['bin']);
+        } else if (typeof params['array'] != "undefined") {
+            this.setByBooleanArray(params['array']);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER OctetString<br/>
+ * @name KJUR.asn1.DEROctetString
+ * @class class for ASN.1 DER OctetString
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * This class provides ASN.1 OctetString simple type.<br/>
+ * Supported "params" attributes are:
+ * <ul>
+ * <li>str - to set a string as a value</li>
+ * <li>hex - to set a hexadecimal string as a value</li>
+ * <li>obj - to set a encapsulated ASN.1 value by JSON object
+ * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
+ * </ul>
+ * NOTE: A parameter 'obj' have been supported
+ * for "OCTET STRING, encapsulates" structure.
+ * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
+ * @see KJUR.asn1.DERAbstractString - superclass
+ * @example
+ * // default constructor
+ * o = new KJUR.asn1.DEROctetString();
+ * // initialize with string
+ * o = new KJUR.asn1.DEROctetString({str: "aaa"});
+ * // initialize with hexadecimal string
+ * o = new KJUR.asn1.DEROctetString({hex: "616161"});
+ * // initialize with ASN1Util.newObject argument
+ * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
+ * // above generates a ASN.1 data like this:
+ * // OCTET STRING, encapsulates {
+ * //   SEQUENCE {
+ * //     INTEGER 3
+ * //     PrintableString 'aaa'
+ * //     }
+ * //   }
+ */
+KJUR.asn1.DEROctetString = function(params) {
+    if (params !== undefined && typeof params.obj !== "undefined") {
+        var o = KJUR.asn1.ASN1Util.newObject(params.obj);
+        params.hex = o.getEncodedHex();
+    }
+    KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
+    this.hT = "04";
+};
+YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Null
+ * @name KJUR.asn1.DERNull
+ * @class class for ASN.1 DER Null
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * @see KJUR.asn1.ASN1Object - superclass
+ */
+KJUR.asn1.DERNull = function() {
+    KJUR.asn1.DERNull.superclass.constructor.call(this);
+    this.hT = "05";
+    this.hTLV = "0500";
+};
+YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER ObjectIdentifier
+ * @name KJUR.asn1.DERObjectIdentifier
+ * @class class for ASN.1 DER ObjectIdentifier
+ * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERObjectIdentifier = function(params) {
+    var itox = function(i) {
+        var h = i.toString(16);
+        if (h.length == 1) h = '0' + h;
+        return h;
+    };
+    var roidtox = function(roid) {
+        var h = '';
+        var bi = new BigInteger(roid, 10);
+        var b = bi.toString(2);
+        var padLen = 7 - b.length % 7;
+        if (padLen == 7) padLen = 0;
+        var bPad = '';
+        for (var i = 0; i < padLen; i++) bPad += '0';
+        b = bPad + b;
+        for (var i = 0; i < b.length - 1; i += 7) {
+            var b8 = b.substr(i, 7);
+            if (i != b.length - 7) b8 = '1' + b8;
+            h += itox(parseInt(b8, 2));
+        }
+        return h;
+    };
+
+    KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
+    this.hT = "06";
+
+    /**
+     * set value by a hexadecimal string
+     * @name setValueHex
+     * @memberOf KJUR.asn1.DERObjectIdentifier#
+     * @function
+     * @param {String} newHexString hexadecimal value of OID bytes
+     */
+    this.setValueHex = function(newHexString) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.s = null;
+        this.hV = newHexString;
+    };
+
+    /**
+     * set value by a OID string<br/>
+     * @name setValueOidString
+     * @memberOf KJUR.asn1.DERObjectIdentifier#
+     * @function
+     * @param {String} oidString OID string (ex. 2.5.4.13)
+     * @example
+     * o = new KJUR.asn1.DERObjectIdentifier();
+     * o.setValueOidString("2.5.4.13");
+     */
+    this.setValueOidString = function(oidString) {
+        if (! oidString.match(/^[0-9.]+$/)) {
+            throw "malformed oid string: " + oidString;
+        }
+        var h = '';
+        var a = oidString.split('.');
+        var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
+        h += itox(i0);
+        a.splice(0, 2);
+        for (var i = 0; i < a.length; i++) {
+            h += roidtox(a[i]);
+        }
+        this.hTLV = null;
+        this.isModified = true;
+        this.s = null;
+        this.hV = h;
+    };
+
+    /**
+     * set value by a OID name
+     * @name setValueName
+     * @memberOf KJUR.asn1.DERObjectIdentifier#
+     * @function
+     * @param {String} oidName OID name (ex. 'serverAuth')
+     * @since 1.0.1
+     * @description
+     * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
+     * Otherwise raise error.
+     * @example
+     * o = new KJUR.asn1.DERObjectIdentifier();
+     * o.setValueName("serverAuth");
+     */
+    this.setValueName = function(oidName) {
+        var oid = KJUR.asn1.x509.OID.name2oid(oidName);
+        if (oid !== '') {
+            this.setValueOidString(oid);
+        } else {
+            throw "DERObjectIdentifier oidName undefined: " + oidName;
+        }
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (params !== undefined) {
+        if (typeof params === "string") {
+            if (params.match(/^[0-2].[0-9.]+$/)) {
+                this.setValueOidString(params);
+            } else {
+                this.setValueName(params);
+            }
+        } else if (params.oid !== undefined) {
+            this.setValueOidString(params.oid);
+        } else if (params.hex !== undefined) {
+            this.setValueHex(params.hex);
+        } else if (params.name !== undefined) {
+            this.setValueName(params.name);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Enumerated
+ * @name KJUR.asn1.DEREnumerated
+ * @class class for ASN.1 DER Enumerated
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>int - specify initial ASN.1 value(V) by integer value</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ * @example
+ * new KJUR.asn1.DEREnumerated(123);
+ * new KJUR.asn1.DEREnumerated({int: 123});
+ * new KJUR.asn1.DEREnumerated({hex: '1fad'});
+ */
+KJUR.asn1.DEREnumerated = function(params) {
+    KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
+    this.hT = "0a";
+
+    /**
+     * set value by Tom Wu's BigInteger object
+     * @name setByBigInteger
+     * @memberOf KJUR.asn1.DEREnumerated#
+     * @function
+     * @param {BigInteger} bigIntegerValue to set
+     */
+    this.setByBigInteger = function(bigIntegerValue) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
+    };
+
+    /**
+     * set value by integer value
+     * @name setByInteger
+     * @memberOf KJUR.asn1.DEREnumerated#
+     * @function
+     * @param {Integer} integer value to set
+     */
+    this.setByInteger = function(intValue) {
+        var bi = new BigInteger(String(intValue), 10);
+        this.setByBigInteger(bi);
+    };
+
+    /**
+     * set value by integer value
+     * @name setValueHex
+     * @memberOf KJUR.asn1.DEREnumerated#
+     * @function
+     * @param {String} hexadecimal string of integer value
+     * @description
+     * <br/>
+     * NOTE: Value shall be represented by minimum octet length of
+     * two's complement representation.
+     */
+    this.setValueHex = function(newHexString) {
+        this.hV = newHexString;
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params['int'] != "undefined") {
+            this.setByInteger(params['int']);
+        } else if (typeof params == "number") {
+            this.setByInteger(params);
+        } else if (typeof params['hex'] != "undefined") {
+            this.setValueHex(params['hex']);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER UTF8String
+ * @name KJUR.asn1.DERUTF8String
+ * @class class for ASN.1 DER UTF8String
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DERUTF8String = function(params) {
+    KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
+    this.hT = "0c";
+};
+YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER NumericString
+ * @name KJUR.asn1.DERNumericString
+ * @class class for ASN.1 DER NumericString
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DERNumericString = function(params) {
+    KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
+    this.hT = "12";
+};
+YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER PrintableString
+ * @name KJUR.asn1.DERPrintableString
+ * @class class for ASN.1 DER PrintableString
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DERPrintableString = function(params) {
+    KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
+    this.hT = "13";
+};
+YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER TeletexString
+ * @name KJUR.asn1.DERTeletexString
+ * @class class for ASN.1 DER TeletexString
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DERTeletexString = function(params) {
+    KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
+    this.hT = "14";
+};
+YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER IA5String
+ * @name KJUR.asn1.DERIA5String
+ * @class class for ASN.1 DER IA5String
+ * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
+ * @extends KJUR.asn1.DERAbstractString
+ * @description
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DERIA5String = function(params) {
+    KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
+    this.hT = "16";
+};
+YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER UTCTime
+ * @name KJUR.asn1.DERUTCTime
+ * @class class for ASN.1 DER UTCTime
+ * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
+ * @extends KJUR.asn1.DERAbstractTime
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * <li>date - specify Date object.</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ * <h4>EXAMPLES</h4>
+ * @example
+ * d1 = new KJUR.asn1.DERUTCTime();
+ * d1.setString('130430125959Z');
+ *
+ * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
+ * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
+ * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
+ */
+KJUR.asn1.DERUTCTime = function(params) {
+    KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
+    this.hT = "17";
+
+    /**
+     * set value by a Date object<br/>
+     * @name setByDate
+     * @memberOf KJUR.asn1.DERUTCTime#
+     * @function
+     * @param {Date} dateObject Date object to set ASN.1 value(V)
+     * @example
+     * o = new KJUR.asn1.DERUTCTime();
+     * o.setByDate(new Date("2016/12/31"));
+     */
+    this.setByDate = function(dateObject) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.date = dateObject;
+        this.s = this.formatDate(this.date, 'utc');
+        this.hV = stohex(this.s);
+    };
+
+    this.getFreshValueHex = function() {
+        if (typeof this.date == "undefined" && typeof this.s == "undefined") {
+            this.date = new Date();
+            this.s = this.formatDate(this.date, 'utc');
+            this.hV = stohex(this.s);
+        }
+        return this.hV;
+    };
+
+    if (params !== undefined) {
+        if (params.str !== undefined) {
+            this.setString(params.str);
+        } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
+            this.setString(params);
+        } else if (params.hex !== undefined) {
+            this.setStringHex(params.hex);
+        } else if (params.date !== undefined) {
+            this.setByDate(params.date);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER GeneralizedTime
+ * @name KJUR.asn1.DERGeneralizedTime
+ * @class class for ASN.1 DER GeneralizedTime
+ * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
+ * @property {Boolean} withMillis flag to show milliseconds or not
+ * @extends KJUR.asn1.DERAbstractTime
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
+ * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
+ * <li>date - specify Date object.</li>
+ * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
+ * </ul>
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
+ */
+KJUR.asn1.DERGeneralizedTime = function(params) {
+    KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
+    this.hT = "18";
+    this.withMillis = false;
+
+    /**
+     * set value by a Date object
+     * @name setByDate
+     * @memberOf KJUR.asn1.DERGeneralizedTime#
+     * @function
+     * @param {Date} dateObject Date object to set ASN.1 value(V)
+     * @example
+     * When you specify UTC time, use 'Date.UTC' method like this:<br/>
+     * o1 = new DERUTCTime();
+     * o1.setByDate(date);
+     *
+     * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
+     */
+    this.setByDate = function(dateObject) {
+        this.hTLV = null;
+        this.isModified = true;
+        this.date = dateObject;
+        this.s = this.formatDate(this.date, 'gen', this.withMillis);
+        this.hV = stohex(this.s);
+    };
+
+    this.getFreshValueHex = function() {
+        if (this.date === undefined && this.s === undefined) {
+            this.date = new Date();
+            this.s = this.formatDate(this.date, 'gen', this.withMillis);
+            this.hV = stohex(this.s);
+        }
+        return this.hV;
+    };
+
+    if (params !== undefined) {
+        if (params.str !== undefined) {
+            this.setString(params.str);
+        } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
+            this.setString(params);
+        } else if (params.hex !== undefined) {
+            this.setStringHex(params.hex);
+        } else if (params.date !== undefined) {
+            this.setByDate(params.date);
+        }
+        if (params.millis === true) {
+            this.withMillis = true;
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Sequence
+ * @name KJUR.asn1.DERSequence
+ * @class class for ASN.1 DER Sequence
+ * @extends KJUR.asn1.DERAbstractStructured
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>array - specify array of ASN1Object to set elements of content</li>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERSequence = function(params) {
+    KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
+    this.hT = "30";
+    this.getFreshValueHex = function() {
+        var h = '';
+        for (var i = 0; i < this.asn1Array.length; i++) {
+            var asn1Obj = this.asn1Array[i];
+            h += asn1Obj.getEncodedHex();
+        }
+        this.hV = h;
+        return this.hV;
+    };
+};
+YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER Set
+ * @name KJUR.asn1.DERSet
+ * @class class for ASN.1 DER Set
+ * @extends KJUR.asn1.DERAbstractStructured
+ * @description
+ * <br/>
+ * As for argument 'params' for constructor, you can specify one of
+ * following properties:
+ * <ul>
+ * <li>array - specify array of ASN1Object to set elements of content</li>
+ * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
+ * </ul>
+ * NOTE1: 'params' can be omitted.<br/>
+ * NOTE2: sortflag is supported since 1.0.5.
+ */
+KJUR.asn1.DERSet = function(params) {
+    KJUR.asn1.DERSet.superclass.constructor.call(this, params);
+    this.hT = "31";
+    this.sortFlag = true; // item shall be sorted only in ASN.1 DER
+    this.getFreshValueHex = function() {
+        var a = new Array();
+        for (var i = 0; i < this.asn1Array.length; i++) {
+            var asn1Obj = this.asn1Array[i];
+            a.push(asn1Obj.getEncodedHex());
+        }
+        if (this.sortFlag == true) a.sort();
+        this.hV = a.join('');
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params.sortflag != "undefined" &&
+            params.sortflag == false)
+            this.sortFlag = false;
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER TaggedObject
+ * @name KJUR.asn1.DERTaggedObject
+ * @class class for ASN.1 DER TaggedObject
+ * @extends KJUR.asn1.ASN1Object
+ * @description
+ * <br/>
+ * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
+ * For example, if you find '[1]' tag in a ASN.1 dump,
+ * 'tagNoHex' will be 'a1'.
+ * <br/>
+ * As for optional argument 'params' for constructor, you can specify *ANY* of
+ * following properties:
+ * <ul>
+ * <li>explicit - specify true if this is explicit tag otherwise false
+ *     (default is 'true').</li>
+ * <li>tag - specify tag (default is 'a0' which means [0])</li>
+ * <li>obj - specify ASN1Object which is tagged</li>
+ * </ul>
+ * @example
+ * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
+ * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
+ * hex = d2.getEncodedHex();
+ */
+KJUR.asn1.DERTaggedObject = function(params) {
+    KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
+    this.hT = "a0";
+    this.hV = '';
+    this.isExplicit = true;
+    this.asn1Object = null;
+
+    /**
+     * set value by an ASN1Object
+     * @name setString
+     * @memberOf KJUR.asn1.DERTaggedObject#
+     * @function
+     * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
+     * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
+     * @param {ASN1Object} asn1Object ASN.1 to encapsulate
+     */
+    this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
+        this.hT = tagNoHex;
+        this.isExplicit = isExplicitFlag;
+        this.asn1Object = asn1Object;
+        if (this.isExplicit) {
+            this.hV = this.asn1Object.getEncodedHex();
+            this.hTLV = null;
+            this.isModified = true;
+        } else {
+            this.hV = null;
+            this.hTLV = asn1Object.getEncodedHex();
+            this.hTLV = this.hTLV.replace(/^../, tagNoHex);
+            this.isModified = false;
+        }
+    };
+
+    this.getFreshValueHex = function() {
+        return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+        if (typeof params['tag'] != "undefined") {
+            this.hT = params['tag'];
+        }
+        if (typeof params['explicit'] != "undefined") {
+            this.isExplicit = params['explicit'];
+        }
+        if (typeof params['obj'] != "undefined") {
+            this.asn1Object = params['obj'];
+            this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
+        }
+    }
+};
+YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
+
+/**
+ * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
+ * This object is just a decorator for parsing the key parameter
+ * @param {string|Object} key - The key in string format, or an object containing
+ * the parameters needed to build a RSAKey object.
+ * @constructor
+ */
+var JSEncryptRSAKey = /** @class */ (function (_super) {
+    __extends(JSEncryptRSAKey, _super);
+    function JSEncryptRSAKey(key) {
+        var _this = _super.call(this) || this;
+        // Call the super constructor.
+        //  RSAKey.call(this);
+        // If a key key was provided.
+        if (key) {
+            // If this is a string...
+            if (typeof key === "string") {
+                _this.parseKey(key);
+            }
+            else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
+                JSEncryptRSAKey.hasPublicKeyProperty(key)) {
+                // Set the values for the key.
+                _this.parsePropertiesFrom(key);
+            }
+        }
+        return _this;
+    }
+    /**
+     * Method to parse a pem encoded string containing both a public or private key.
+     * The method will translate the pem encoded string in a der encoded string and
+     * will parse private key and public key parameters. This method accepts public key
+     * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
+     *
+     * @todo Check how many rsa formats use the same format of pkcs #1.
+     *
+     * The format is defined as:
+     * PublicKeyInfo ::= SEQUENCE {
+     *   algorithm       AlgorithmIdentifier,
+     *   PublicKey       BIT STRING
+     * }
+     * Where AlgorithmIdentifier is:
+     * AlgorithmIdentifier ::= SEQUENCE {
+     *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
+     *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
+     * }
+     * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
+     * RSAPublicKey ::= SEQUENCE {
+     *   modulus           INTEGER,  -- n
+     *   publicExponent    INTEGER   -- e
+     * }
+     * it's possible to examine the structure of the keys obtained from openssl using
+     * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
+     * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
+     * @private
+     */
+    JSEncryptRSAKey.prototype.parseKey = function (pem) {
+        try {
+            var modulus = 0;
+            var public_exponent = 0;
+            var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
+            var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
+            var asn1 = ASN1.decode(der);
+            // Fixes a bug with OpenSSL 1.0+ private keys
+            if (asn1.sub.length === 3) {
+                asn1 = asn1.sub[2].sub[0];
+            }
+            if (asn1.sub.length === 9) {
+                // Parse the private key.
+                modulus = asn1.sub[1].getHexStringValue(); // bigint
+                this.n = parseBigInt(modulus, 16);
+                public_exponent = asn1.sub[2].getHexStringValue(); // int
+                this.e = parseInt(public_exponent, 16);
+                var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
+                this.d = parseBigInt(private_exponent, 16);
+                var prime1 = asn1.sub[4].getHexStringValue(); // bigint
+                this.p = parseBigInt(prime1, 16);
+                var prime2 = asn1.sub[5].getHexStringValue(); // bigint
+                this.q = parseBigInt(prime2, 16);
+                var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
+                this.dmp1 = parseBigInt(exponent1, 16);
+                var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
+                this.dmq1 = parseBigInt(exponent2, 16);
+                var coefficient = asn1.sub[8].getHexStringValue(); // bigint
+                this.coeff = parseBigInt(coefficient, 16);
+            }
+            else if (asn1.sub.length === 2) {
+                // Parse the public key.
+                var bit_string = asn1.sub[1];
+                var sequence = bit_string.sub[0];
+                modulus = sequence.sub[0].getHexStringValue();
+                this.n = parseBigInt(modulus, 16);
+                public_exponent = sequence.sub[1].getHexStringValue();
+                this.e = parseInt(public_exponent, 16);
+            }
+            else {
+                return false;
+            }
+            return true;
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * Translate rsa parameters in a hex encoded string representing the rsa key.
+     *
+     * The translation follow the ASN.1 notation :
+     * RSAPrivateKey ::= SEQUENCE {
+     *   version           Version,
+     *   modulus           INTEGER,  -- n
+     *   publicExponent    INTEGER,  -- e
+     *   privateExponent   INTEGER,  -- d
+     *   prime1            INTEGER,  -- p
+     *   prime2            INTEGER,  -- q
+     *   exponent1         INTEGER,  -- d mod (p1)
+     *   exponent2         INTEGER,  -- d mod (q-1)
+     *   coefficient       INTEGER,  -- (inverse of q) mod p
+     * }
+     * @returns {string}  DER Encoded String representing the rsa private key
+     * @private
+     */
+    JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
+        var options = {
+            array: [
+                new KJUR.asn1.DERInteger({ int: 0 }),
+                new KJUR.asn1.DERInteger({ bigint: this.n }),
+                new KJUR.asn1.DERInteger({ int: this.e }),
+                new KJUR.asn1.DERInteger({ bigint: this.d }),
+                new KJUR.asn1.DERInteger({ bigint: this.p }),
+                new KJUR.asn1.DERInteger({ bigint: this.q }),
+                new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
+                new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
+                new KJUR.asn1.DERInteger({ bigint: this.coeff })
+            ]
+        };
+        var seq = new KJUR.asn1.DERSequence(options);
+        return seq.getEncodedHex();
+    };
+    /**
+     * base64 (pem) encoded version of the DER encoded representation
+     * @returns {string} pem encoded representation without header and footer
+     * @public
+     */
+    JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
+        return hex2b64(this.getPrivateBaseKey());
+    };
+    /**
+     * Translate rsa parameters in a hex encoded string representing the rsa public key.
+     * The representation follow the ASN.1 notation :
+     * PublicKeyInfo ::= SEQUENCE {
+     *   algorithm       AlgorithmIdentifier,
+     *   PublicKey       BIT STRING
+     * }
+     * Where AlgorithmIdentifier is:
+     * AlgorithmIdentifier ::= SEQUENCE {
+     *   algorithm       OBJECT IDENTIFIER,     the OID of the enc algorithm
+     *   parameters      ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
+     * }
+     * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
+     * RSAPublicKey ::= SEQUENCE {
+     *   modulus           INTEGER,  -- n
+     *   publicExponent    INTEGER   -- e
+     * }
+     * @returns {string} DER Encoded String representing the rsa public key
+     * @private
+     */
+    JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
+        var first_sequence = new KJUR.asn1.DERSequence({
+            array: [
+                new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
+                new KJUR.asn1.DERNull()
+            ]
+        });
+        var second_sequence = new KJUR.asn1.DERSequence({
+            array: [
+                new KJUR.asn1.DERInteger({ bigint: this.n }),
+                new KJUR.asn1.DERInteger({ int: this.e })
+            ]
+        });
+        var bit_string = new KJUR.asn1.DERBitString({
+            hex: "00" + second_sequence.getEncodedHex()
+        });
+        var seq = new KJUR.asn1.DERSequence({
+            array: [first_sequence, bit_string]
+        });
+        return seq.getEncodedHex();
+    };
+    /**
+     * base64 (pem) encoded version of the DER encoded representation
+     * @returns {string} pem encoded representation without header and footer
+     * @public
+     */
+    JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
+        return hex2b64(this.getPublicBaseKey());
+    };
+    /**
+     * wrap the string in block of width chars. The default value for rsa keys is 64
+     * characters.
+     * @param {string} str the pem encoded string without header and footer
+     * @param {Number} [width=64] - the length the string has to be wrapped at
+     * @returns {string}
+     * @private
+     */
+    JSEncryptRSAKey.wordwrap = function (str, width) {
+        width = width || 64;
+        if (!str) {
+            return str;
+        }
+        var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
+        return str.match(RegExp(regex, "g")).join("\n");
+    };
+    /**
+     * Retrieve the pem encoded private key
+     * @returns {string} the pem encoded private key with header/footer
+     * @public
+     */
+    JSEncryptRSAKey.prototype.getPrivateKey = function () {
+        var key = "-----BEGIN RSA PRIVATE KEY-----\n";
+        key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
+        key += "-----END RSA PRIVATE KEY-----";
+        return key;
+    };
+    /**
+     * Retrieve the pem encoded public key
+     * @returns {string} the pem encoded public key with header/footer
+     * @public
+     */
+    JSEncryptRSAKey.prototype.getPublicKey = function () {
+        var key = "-----BEGIN PUBLIC KEY-----\n";
+        key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
+        key += "-----END PUBLIC KEY-----";
+        return key;
+    };
+    /**
+     * Check if the object contains the necessary parameters to populate the rsa modulus
+     * and public exponent parameters.
+     * @param {Object} [obj={}] - An object that may contain the two public key
+     * parameters
+     * @returns {boolean} true if the object contains both the modulus and the public exponent
+     * properties (n and e)
+     * @todo check for types of n and e. N should be a parseable bigInt object, E should
+     * be a parseable integer number
+     * @private
+     */
+    JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
+        obj = obj || {};
+        return obj.hasOwnProperty("n") && obj.hasOwnProperty("e");
+    };
+    /**
+     * Check if the object contains ALL the parameters of an RSA key.
+     * @param {Object} [obj={}] - An object that may contain nine rsa key
+     * parameters
+     * @returns {boolean} true if the object contains all the parameters needed
+     * @todo check for types of the parameters all the parameters but the public exponent
+     * should be parseable bigint objects, the public exponent should be a parseable integer number
+     * @private
+     */
+    JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
+        obj = obj || {};
+        return (obj.hasOwnProperty("n") &&
+            obj.hasOwnProperty("e") &&
+            obj.hasOwnProperty("d") &&
+            obj.hasOwnProperty("p") &&
+            obj.hasOwnProperty("q") &&
+            obj.hasOwnProperty("dmp1") &&
+            obj.hasOwnProperty("dmq1") &&
+            obj.hasOwnProperty("coeff"));
+    };
+    /**
+     * Parse the properties of obj in the current rsa object. Obj should AT LEAST
+     * include the modulus and public exponent (n, e) parameters.
+     * @param {Object} obj - the object containing rsa parameters
+     * @private
+     */
+    JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
+        this.n = obj.n;
+        this.e = obj.e;
+        if (obj.hasOwnProperty("d")) {
+            this.d = obj.d;
+            this.p = obj.p;
+            this.q = obj.q;
+            this.dmp1 = obj.dmp1;
+            this.dmq1 = obj.dmq1;
+            this.coeff = obj.coeff;
+        }
+    };
+    return JSEncryptRSAKey;
+}(RSAKey));
+
+/**
+ *
+ * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
+ * possible parameters are:
+ * - default_key_size        {number}  default: 1024 the key size in bit
+ * - default_public_exponent {string}  default: '010001' the hexadecimal representation of the public exponent
+ * - log                     {boolean} default: false whether log warn/error or not
+ * @constructor
+ */
+var JSEncrypt = /** @class */ (function () {
+    function JSEncrypt(options) {
+        options = options || {};
+        this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
+        this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
+        this.log = options.log || false;
+        // The private and public key.
+        this.key = null;
+    }
+    /**
+     * Method to set the rsa key parameter (one method is enough to set both the public
+     * and the private key, since the private key contains the public key paramenters)
+     * Log a warning if logs are enabled
+     * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
+     * @public
+     */
+    JSEncrypt.prototype.setKey = function (key) {
+        if (this.log && this.key) {
+            console.warn("A key was already set, overriding existing.");
+        }
+        this.key = new JSEncryptRSAKey(key);
+    };
+    /**
+     * Proxy method for setKey, for api compatibility
+     * @see setKey
+     * @public
+     */
+    JSEncrypt.prototype.setPrivateKey = function (privkey) {
+        // Create the key.
+        this.setKey(privkey);
+    };
+    /**
+     * Proxy method for setKey, for api compatibility
+     * @see setKey
+     * @public
+     */
+    JSEncrypt.prototype.setPublicKey = function (pubkey) {
+        // Sets the public key.
+        this.setKey(pubkey);
+    };
+    /**
+     * Proxy method for RSAKey object's decrypt, decrypt the string using the private
+     * components of the rsa key object. Note that if the object was not set will be created
+     * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
+     * @param {string} str base64 encoded crypted string to decrypt
+     * @return {string} the decrypted string
+     * @public
+     */
+    JSEncrypt.prototype.decrypt = function (str) {
+        // Return the decrypted string.
+        try {
+            return this.getKey().decrypt(b64tohex(str));
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * Proxy method for RSAKey object's encrypt, encrypt the string using the public
+     * components of the rsa key object. Note that if the object was not set will be created
+     * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
+     * @param {string} str the string to encrypt
+     * @return {string} the encrypted string encoded in base64
+     * @public
+     */
+    JSEncrypt.prototype.encrypt = function (str) {
+        // Return the encrypted string.
+        try {
+            return hex2b64(this.getKey().encrypt(str));
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * 分段加密长字符串
+     * @param {string} str the string to encrypt
+     * @return {string} the encrypted string encoded in base64
+     * @public
+     */
+    JSEncrypt.prototype.encryptLong = function (str) {
+        try {
+            var encrypted = this.getKey().encryptLong(str) || "";
+            var uncrypted = this.getKey().decryptLong(encrypted) || "";
+            var count = 0;
+            var reg = /null$/g;
+            while (reg.test(uncrypted)) {
+                // 如果加密出错,重新加密
+                count++;
+                encrypted = this.getKey().encryptLong(str) || "";
+                uncrypted = this.getKey().decryptLong(encrypted) || "";
+                // console.log('加密出错次数', count)
+                if (count > 10) {
+                    // 重复加密不能大于10次
+                    // console.log('加密次数过多')
+                    break;
+                }
+            }
+            return encrypted;
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * 分段解密长字符串
+     * @param {string} str base64 encoded crypted string to decrypt
+     * @return {string} the decrypted string
+     * @public
+     */
+    JSEncrypt.prototype.decryptLong = function (str) {
+        try {
+            return this.getKey().decryptLong(str);
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * Proxy method for RSAKey object's sign.
+     * @param {string} str the string to sign
+     * @param {function} digestMethod hash method
+     * @param {string} digestName the name of the hash algorithm
+     * @return {string} the signature encoded in base64
+     * @public
+     */
+    JSEncrypt.prototype.sign = function (str, digestMethod, digestName) {
+        // return the RSA signature of 'str' in 'hex' format.
+        try {
+            return hex2b64(this.getKey().sign(str, digestMethod, digestName));
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * Proxy method for RSAKey object's verify.
+     * @param {string} str the string to verify
+     * @param {string} signature the signature encoded in base64 to compare the string to
+     * @param {function} digestMethod hash method
+     * @return {boolean} whether the data and signature match
+     * @public
+     */
+    JSEncrypt.prototype.verify = function (str, signature, digestMethod) {
+        // Return the decrypted 'digest' of the signature.
+        try {
+            return this.getKey().verify(str, b64tohex(signature), digestMethod);
+        }
+        catch (ex) {
+            return false;
+        }
+    };
+    /**
+     * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
+     * will be created and returned
+     * @param {callback} [cb] the callback to be called if we want the key to be generated
+     * in an async fashion
+     * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
+     * @public
+     */
+    JSEncrypt.prototype.getKey = function (cb) {
+        // Only create new if it does not exist.
+        if (!this.key) {
+            // Get a new private key.
+            this.key = new JSEncryptRSAKey();
+            if (cb && {}.toString.call(cb) === "[object Function]") {
+                this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
+                return;
+            }
+            // Generate the key.
+            this.key.generate(this.default_key_size, this.default_public_exponent);
+        }
+        return this.key;
+    };
+    /**
+     * Returns the pem encoded representation of the private key
+     * If the key doesn't exists a new key will be created
+     * @returns {string} pem encoded representation of the private key WITH header and footer
+     * @public
+     */
+    JSEncrypt.prototype.getPrivateKey = function () {
+        // Return the private representation of this key.
+        return this.getKey().getPrivateKey();
+    };
+    /**
+     * Returns the pem encoded representation of the private key
+     * If the key doesn't exists a new key will be created
+     * @returns {string} pem encoded representation of the private key WITHOUT header and footer
+     * @public
+     */
+    JSEncrypt.prototype.getPrivateKeyB64 = function () {
+        // Return the private representation of this key.
+        return this.getKey().getPrivateBaseKeyB64();
+    };
+    /**
+     * Returns the pem encoded representation of the public key
+     * If the key doesn't exists a new key will be created
+     * @returns {string} pem encoded representation of the public key WITH header and footer
+     * @public
+     */
+    JSEncrypt.prototype.getPublicKey = function () {
+        // Return the private representation of this key.
+        return this.getKey().getPublicKey();
+    };
+    /**
+     * Returns the pem encoded representation of the public key
+     * If the key doesn't exists a new key will be created
+     * @returns {string} pem encoded representation of the public key WITHOUT header and footer
+     * @public
+     */
+    JSEncrypt.prototype.getPublicKeyB64 = function () {
+        // Return the private representation of this key.
+        return this.getKey().getPublicBaseKeyB64();
+    };
+    JSEncrypt.version = "3.1.4";
+    return JSEncrypt;
+}());
+
+window.JSEncrypt = JSEncrypt;
+
+exports.JSEncrypt = JSEncrypt;
+exports.default = JSEncrypt;
+
+Object.defineProperty(exports, '__esModule', { value: true });
+
+})));

+ 9 - 0
assets/Scripts/mk/util/encrypt/rsa/jsencrypt.js.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "javascript",
+  "imported": true,
+  "uuid": "a9b1dc9d-74a4-4d83-ad64-bf9ac566c968",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}

+ 201 - 0
assets/Scripts/mk/util/encrypt/sha1.js

@@ -0,0 +1,201 @@
+/*   
+ *   A   JavaScript   implementation   of   the   Secure   Hash   Algorithm,   SHA-1,   as   defined   
+ *   in   FIPS   PUB   180-1   
+ *   Version   2.1-BETA   Copyright   Paul   Johnston   2000   -   2002.   
+ *   Other   contributors:   Greg   Holt,   Andrew   Kepert,   Ydnar,   Lostinet   
+ *   Distributed   under   the   BSD   License   
+ *   See   http://pajhome.org.uk/crypt/md5   for   details.   
+ */
+/*   
+ *   Configurable   variables.   You   may   need   to   tweak   these   to   be   compatible   with   
+ *   the   server-side,   but   the   defaults   work   in   most   cases.   
+ */
+var hexcase = 0; /*   hex   output   format.   0   -   lowercase;   1   -   uppercase                 */
+var b64pad = ""; /*   base-64   pad   character.   "="   for   strict   RFC   compliance       */
+var chrsz = 8; /*   bits   per   input   character.   8   -   ASCII;   16   -   Unicode             */
+
+/*   
+ *   These   are   the   functions   you'll   usually   want   to   call   
+ *   They   take   string   arguments   and   return   either   hex   or   base-64   encoded   strings   
+ */
+function hex_sha1(s) {
+    return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
+}
+
+function b64_sha1(s) {
+    return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
+}
+
+function str_sha1(s) {
+    return binb2str(core_sha1(str2binb(s), s.length * chrsz));
+}
+
+function hex_hmac_sha1(key, data) {
+    return binb2hex(core_hmac_sha1(key, data));
+}
+
+function b64_hmac_sha1(key, data) {
+    return binb2b64(core_hmac_sha1(key, data));
+}
+
+function str_hmac_sha1(key, data) {
+    return binb2str(core_hmac_sha1(key, data));
+}
+
+/*   
+ *   Perform   a   simple   self-test   to   see   if   the   VM   is   working   
+ */
+function sha1_vm_test() {
+    return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
+}
+
+/*   
+ *   Calculate   the   SHA-1   of   an   array   of   big-endian   words,   and   a   bit   length   
+ */
+function core_sha1(x, len) {
+    /*   append   padding   */
+    x[len >> 5] |= 0x80 << (24 - len % 32);
+    x[((len + 64 >> 9) << 4) + 15] = len;
+
+    var w = Array(80);
+    var a = 1732584193;
+    var b = -271733879;
+    var c = -1732584194;
+    var d = 271733878;
+    var e = -1009589776;
+
+    for (var i = 0; i < x.length; i += 16) {
+        var olda = a;
+        var oldb = b;
+        var oldc = c;
+        var oldd = d;
+        var olde = e;
+
+        for (var j = 0; j < 80; j++) {
+            if (j < 16) w[j] = x[i + j];
+            else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
+            var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
+            e = d;
+            d = c;
+            c = rol(b, 30);
+            b = a;
+            a = t;
+        }
+
+        a = safe_add(a, olda);
+        b = safe_add(b, oldb);
+        c = safe_add(c, oldc);
+        d = safe_add(d, oldd);
+        e = safe_add(e, olde);
+    }
+    return Array(a, b, c, d, e);
+
+}
+
+/*   
+ *   Perform   the   appropriate   triplet   combination   function   for   the   current   
+ *   iteration   
+ */
+function sha1_ft(t, b, c, d) {
+    if (t < 20) return (b & c) | ((~b) & d);
+    if (t < 40) return b ^ c ^ d;
+    if (t < 60) return (b & c) | (b & d) | (c & d);
+    return b ^ c ^ d;
+}
+
+/*   
+ *   Determine   the   appropriate   additive   constant   for   the   current   iteration   
+ */
+function sha1_kt(t) {
+    return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
+}
+
+/*   
+ *   Calculate   the   HMAC-SHA1   of   a   key   and   some   data   
+ */
+function core_hmac_sha1(key, data) {
+    var bkey = str2binb(key);
+    if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
+
+    var ipad = Array(16),
+        opad = Array(16);
+    for (var i = 0; i < 16; i++) {
+        ipad[i] = bkey[i] ^ 0x36363636;
+        opad[i] = bkey[i] ^ 0x5C5C5C5C;
+    }
+
+    var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
+    return core_sha1(opad.concat(hash), 512 + 160);
+}
+
+/*   
+ *   Add   integers,   wrapping   at   2^32.   This   uses   16-bit   operations   internally   
+ *   to   work   around   bugs   in   some   JS   interpreters.   
+ */
+function safe_add(x, y) {
+    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+    return (msw << 16) | (lsw & 0xFFFF);
+}
+
+/*   
+ *   Bitwise   rotate   a   32-bit   number   to   the   left.   
+ */
+function rol(num, cnt) {
+    return (num << cnt) | (num >>> (32 - cnt));
+}
+
+/*   
+ *   Convert   an   8-bit   or   16-bit   string   to   an   array   of   big-endian   words   
+ *   In   8-bit   function,   characters   >255   have   their   hi-byte   silently   ignored.   
+ */
+function str2binb(str) {
+    var bin = Array();
+    var mask = (1 << chrsz) - 1;
+    for (var i = 0; i < str.length * chrsz; i += chrsz)
+    bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
+    return bin;
+}
+
+/*   
+ *   Convert   an   array   of   big-endian   words   to   a   string   
+ */
+function binb2str(bin) {
+    var str = "";
+    var mask = (1 << chrsz) - 1;
+    for (var i = 0; i < bin.length * 32; i += chrsz)
+    str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
+    return str;
+}
+
+/*   
+ *   Convert   an   array   of   big-endian   words   to   a   hex   string.   
+ */
+function binb2hex(binarray) {
+    var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+    var str = "";
+    for (var i = 0; i < binarray.length * 4; i++) {
+        str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
+    }
+    return str;
+}
+
+/*   
+ *   Convert   an   array   of   big-endian   words   to   a   base-64   string   
+ */
+function binb2b64(binarray) {
+    var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    var str = "";
+    for (var i = 0; i < binarray.length * 4; i += 3) {
+        var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
+        for (var j = 0; j < 4; j++) {
+            if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
+            else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
+        }
+    }
+    return str;
+}
+
+module.exports = {
+  hex_sha1: hex_sha1
+}

+ 9 - 0
assets/Scripts/mk/util/encrypt/sha1.js.meta

@@ -0,0 +1,9 @@
+{
+  "ver": "4.0.21",
+  "importer": "javascript",
+  "imported": true,
+  "uuid": "7bba95a1-1226-48e5-a692-20f084d7f360",
+  "files": [],
+  "subMetas": {},
+  "userData": {}
+}