4 커밋 c11713c033 ... 4eeea8b0e0

작성자 SHA1 메시지 날짜
  qzy 4eeea8b0e0 日志清理时间 3 주 전
  qzy 3263002d05 优化 3 주 전
  qzy 65c9dc5806 优化 1 개월 전
  qzy e7a3b45033 优化 1 년 전
56개의 변경된 파일5759개의 추가작업 그리고 701개의 파일을 삭제
  1. 2 2
      sp-admin/login.html
  2. 1 0
      sp-admin/sa-frame/menu-list-sp.js
  3. 1 1
      sp-admin/sa-frame/sa-code.js
  4. 2 1
      sp-admin/sa-view-sp/sp-admin/admin-add.html
  5. 1 1
      sp-admin/sa-view-sp/sp-admin/admin-list.html
  6. 141 0
      sp-admin/sa-view-sp/sp-admin/update-password-first.html
  7. 4 4
      sp-admin/sa-view/tb-account/balance-print.html
  8. 13 3
      sp-admin/sa-view/tb-account/tb-account-balance-list.html
  9. 156 99
      sp-admin/sa-view/tb-costomer/customer-admin-add.html
  10. 344 304
      sp-admin/sa-view/tb-costomer/customer-admin-list.html
  11. 1 1
      sp-admin/sa-view/tb-fee-statistics/tb-fee-details-info.html
  12. 1 1
      sp-admin/sa-view/tb-fee-statistics/tb-fee-statistics-list.html
  13. 1 0
      sp-admin/sa-view/tb-invoice-info/tb-invoice-info-list.html
  14. 1 1
      sp-admin/sa-view/tb-invoice-order/tb-invoice-order-add.html
  15. 3 2
      sp-admin/sa-view/tb-invoice-order/tb-invoice-order-list.html
  16. 155 100
      sp-admin/sa-view/tb-partner/customer-admin-add.html
  17. 34 0
      sp-admin/sa-view/tb-partner/customer-admin-list.html
  18. 1 1
      sp-admin/sa-view/tb-partner/tb-partner-add.html
  19. 4351 0
      sp-admin/static/kj/jsencrypt.js
  20. 4 0
      sp-admin/static/kj/upload-util.js
  21. 50 9
      sp-server/src/main/java/com/pj/api/jh/service/JhService.java
  22. 9 5
      sp-server/src/main/java/com/pj/api/jh/task/CheckPayRetry.java
  23. 3 5
      sp-server/src/main/java/com/pj/api/jh/task/CheckPayStatusTask.java
  24. 43 9
      sp-server/src/main/java/com/pj/api/open/service/OpenService.java
  25. 27 4
      sp-server/src/main/java/com/pj/api/open/web/OpenController.java
  26. 8 4
      sp-server/src/main/java/com/pj/api/wx/service/WxService.java
  27. 6 0
      sp-server/src/main/java/com/pj/current/SaPlusStartup.java
  28. 1 1
      sp-server/src/main/java/com/pj/current/satoken/StpUserUtil.java
  29. 4 0
      sp-server/src/main/java/com/pj/project/sync/HelpService.java
  30. 3 1
      sp-server/src/main/java/com/pj/project/sync/SyncService.java
  31. 1 1
      sp-server/src/main/java/com/pj/project/sync/response/IOrderPriceRes.java
  32. 38 27
      sp-server/src/main/java/com/pj/project/tb_account/AutomaticPay.java
  33. 6 4
      sp-server/src/main/java/com/pj/project/tb_business/TbBusinessService.java
  34. 3 0
      sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemMapper.java
  35. 3 0
      sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemMapper.xml
  36. 23 7
      sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemService.java
  37. 25 1
      sp-server/src/main/java/com/pj/project/tb_car_weight/CheckPayStatusTask.java
  38. 1 1
      sp-server/src/main/java/com/pj/project/tb_car_weight/TbCarWeight.java
  39. 7 0
      sp-server/src/main/java/com/pj/project/tb_car_weight/TbCarWeightService.java
  40. 21 0
      sp-server/src/main/java/com/pj/project/tb_deduction_record/ExcelDTO.java
  41. 15 15
      sp-server/src/main/java/com/pj/project/tb_deduction_record/TbDeductionRecord.java
  42. 30 4
      sp-server/src/main/java/com/pj/project/tb_deduction_record/TbDeductionRecordService.java
  43. 2 0
      sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsMapper.java
  44. 14 0
      sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsMapper.xml
  45. 48 2
      sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsService.java
  46. 43 0
      sp-server/src/main/java/com/pj/project/tb_fee_details/task/HandlerCarWeightTask.java
  47. 11 4
      sp-server/src/main/java/com/pj/project/tb_invoice_info/TbInvoiceInfoService.java
  48. 2 1
      sp-server/src/main/java/com/pj/project/tb_invoice_order/TbInvoiceOrder.java
  49. 67 57
      sp-server/src/main/java/com/pj/project/tb_invoice_order/TbInvoiceOrderService.java
  50. 2 1
      sp-server/src/main/java/com/pj/project/tb_order/TbOrderService.java
  51. 2 2
      sp-server/src/main/java/com/pj/project4sp/apilog/Task.java
  52. 1 1
      sp-server/src/main/java/com/pj/project4sp/uploadfile/UploadConfig.java
  53. 20 11
      sp-server/src/main/java/com/pj/utils/cache/RedisUtil.java
  54. 1 1
      sp-server/src/main/resources/application-dev.yml
  55. 1 0
      sp-server/src/main/resources/application.yml
  56. 1 2
      sp-server/src/main/resources/logback.xml

+ 2 - 2
sp-admin/login.html

@@ -130,7 +130,7 @@
 						</div>
 					</div>
 					<span style="color: red;margin-left: 70px;" id="notice"></span>
-					<div class="login-button">登录</div>
+					<div class="login-button" @keyup.enter.native="handleAddBook">登录</div>
 				</div>
 			</div>
 			<div class="sk-rotating-plane"></div>
@@ -151,7 +151,7 @@
 			// 你所有要改的代码全在这里   ↓↓↓↓↓
 
 			// 所有参考属性
-			var page_title = '场站管理系统 后台登录'; // 页面标题
+			var page_title = '跨境物流中心B区 后台登录'; // 页面标题
 			var key = ''; // 默认的账号
 			var password = ''; // 默认的password
 			var codeKey = '';

+ 1 - 0
sp-admin/sa-frame/menu-list-sp.js

@@ -86,6 +86,7 @@ window.menuList.unshift({
 	}, {
 		id: 'sys-dict',
 		name: '系统字典',
+			parent: true,
 		icon: 'el-icon-setting',
 		info: '系统字典配置',
 		childList: [{

+ 1 - 1
sp-admin/sa-frame/sa-code.js

@@ -20,7 +20,7 @@ sa.ajax('/AccAdmin/fristOpenAdmin', function (res) {
     // }
 
     // 配置
-    sa_admin.title = "场站管理后台";
+    sa_admin.title = "跨境物流中心B区";
     sa_admin.logo = '';    // 设置logo图标地址
     sa_admin.icon = "";    // 设置logo图标地址
 

+ 2 - 1
sp-admin/sa-view-sp/sp-admin/admin-add.html

@@ -86,7 +86,8 @@
                         sa.closeCurrIframe(); // 关闭本页
                     }.bind(this));
                 }.bind(this));
-            }
+            },
+			
         },
         mounted: function () {
             // 加载角色

+ 1 - 1
sp-admin/sa-view-sp/sp-admin/admin-list.html

@@ -9,7 +9,7 @@
 		<link rel="stylesheet" href="../../static/sa.css"> 
 		<script src="../../static/kj/vue.min.js"></script>
 		<script src="../../static/kj/element-ui/index.js"></script>
-		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
+		<script src="../../static/kj/httpVueLoader.js"></script>
 		<script src="../../static/kj/jquery.min.js"></script>
 		<script src="../../static/kj/layer/layer.js"></script>
 		<script src="../../static/sa.js"></script>

+ 141 - 0
sp-admin/sa-view-sp/sp-admin/update-password-first.html

@@ -0,0 +1,141 @@
+<!DOCTYPE html>
+<html>
+	<head>
+		<title>修改密码</title>
+		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+		<!-- 所有的 css & js 资源 -->
+		<link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
+		<link rel="stylesheet" href="../../static/sa.css">
+		<script src="../../static/kj/vue.min.js"></script>
+		<script src="../../static/kj/element-ui/index.js"></script>
+		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
+		<script src="../../static/kj/jquery.min.js"></script>
+		<script src="../../static/kj/layer/layer.js"></script>
+		<script src="../../static/sa.js"></script>
+		<style>
+			/* body,.sbot.vue-box{background-color: #EEE !important;} */
+			.c-item .c-label {
+				width: 10em;
+			}
+
+			.c-item .el-input__inner {
+				width: 300px;
+			}
+
+			.error {
+				color: red;
+				font-size: 12px;
+				margin-left: 100px
+			}
+		</style>
+	</head>
+	<body>
+		<div class="vue-box sbot" style="display: none;" :style="'display: block;'">
+			<!-- ------- 内容部分 ------- -->
+			<div class="s-body">
+				<div class="c-panel">
+					<div style="color: red; margin-left: 30px;">注:请先修改密码!</div>
+					<el-form v-if="m">
+						<sa-item type="password" name="旧密码" v-model="m.oldPwd" br></sa-item>
+						<sa-item type="password" name="再次输入旧密码" v-model="m.oldPwd2" br></sa-item>
+						<sa-item type="password" name="新密码" v-model="m.newPwd" br @input="newPwdChange">
+						</sa-item>
+						<div v-if="pwdError" class="error">{{pwdError}}</div>
+						<sa-item type="password" name="再次输入新密码" v-model="m.newPwd2" br @input="newPwd2Change"></sa-item>
+						<div v-if="newPwd2Error" class="error">{{newPwd2Error}}</div>
+					</el-form>
+				</div>
+			</div>
+			<div class="s-foot">
+				<el-button type="primary" @click="ok()">确定</el-button>
+			</div>
+
+		</div>
+		<script>
+			const numStr = "123456789";
+			const numStrDesc = "987654321";
+			const varStr = "abcdefghijklmnopkrstuvwxyz"
+			const varStrDesc = "zyxwvutsrkpomnlkjihgfedcba"
+			var app = new Vue({
+				components: {
+					"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue')
+				},
+				el: '.vue-box',
+				data: {
+					sa: sa,
+					pwdError: '',
+					newPwd2Error:'',
+					m: {
+						oldPwd: '',
+						oldPwd2: '',
+						newPwd: '',
+						newPwd2: ''
+					},
+				},
+				methods: {
+					getCurrUser(){
+						this.name=sa.$sys.getCurrUser().name;
+					},
+					newPwdChange(v) {
+						let len = v.length;
+						this.pwdError = '';
+						if(!this.checkStong(v)){
+							this.pwdError = '密码长度8-16位,至少包含一个数字、一个大写字母、一个小写字母以及!@#$%^&*?之一'
+							return;
+						}
+						if (len >= 3) {
+							let s = v.toLowerCase();
+							for (let i = 0; i < len - 2; i++) {
+								let charStr = s.substring(i, i + 3);
+								if (this.checkStr(charStr)) {
+									this.pwdError = '密码不应该采用连续升序或者连续降序'
+									return;
+								}
+							}
+						}
+					},
+					newPwd2Change(v){
+						let len = v.length;
+						this.newPwd2Error = '';
+						if(this.m.newPwd!=v){
+							this.newPwd2Error = '两次输入密码不一致';
+							return;
+						}
+					},
+					checkStr(charStr) {
+						return numStr.indexOf(charStr) != -1 || varStr.indexOf(charStr) != -1 || numStrDesc.indexOf(
+							charStr) != -1 || varStrDesc.indexOf(charStr) != -1;
+					},
+					checkStong(v){
+						let pattern = /^.*(?=.{8,16})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/;
+						return pattern.test(v);
+					},
+					// 提交
+					ok: function() {
+						if(this.pwdError||this.newPwd2Error){
+							return;
+						}
+						// 表单校验
+						let m = this.m;
+						sa.checkNull(m.oldPwd && m.oldPwd2 && m.newPwd && m.newPwd2, '请填写');
+						sa.check(m.oldPwd != m.oldPwd2, '旧密码两次输入不一致');
+						sa.check(m.newPwd != m.newPwd2, '新密码两次输入不一致');
+						sa.check(m.newPwd == this.name, '密码不能和用户名一样');
+						sa.check(m.newPwd.length < 8, '新密码请不要低于八位数');
+						// 开始修改
+						sa.ajax('/AdminPassword/update', this.m, function(res) {
+							if (parent != window) {
+								sa.closeCurrIframe();
+								parent.sa.ok2('修改成功');
+							}
+						})
+						//sa.$fast.fastUpdate2('/SysUser/updatePassword', this.m);
+					},
+				},
+				mounted: function() {
+					this.getCurrUser();
+				}
+			})
+		</script>
+	</body>
+</html>

+ 4 - 4
sp-admin/sa-view/tb-account/balance-print.html

@@ -104,10 +104,10 @@
 								<td>{{cel.customerName}}</td>
 								<td>{{cel.beginMoney}}</td>
 								<td>{{cel.chargeMoney}}</td>
-								<td>{{cel.deuctionMoney}}</td>
-								<td>{{cel.balanceRefundMoney}}</td>
-								<td>{{cel.errorRefundMoney}}</td>
-								<td>{{cel.endMoney}}</td>
+								<td>{{cel.deuctionMoney.toFixed(2)}}</td>
+								<td>{{cel.balanceRefundMoney.toFixed(2)}}</td>
+								<td>{{cel.errorRefundMoney.toFixed(2)}}</td>
+								<td>{{cel.endMoney.toFixed(2)}}</td>
 							</tr>
 							<tr style="height: 40px;padding: 0 0.5px;" v-if="index==dataList.length-1">
 								<td></td>

+ 13 - 3
sp-admin/sa-view/tb-account/tb-account-balance-list.html

@@ -37,12 +37,22 @@
 				<el-table class="data-table" ref="data-table" :data="dataList">
 					<sa-td type="index" name="序号"></sa-td>
 					<sa-td name="企业名称" prop="customerName" width="260"></sa-td>
-					<sa-td name="期初余额" prop="beginMoney" not="0"></sa-td>
+					<sa-td name="期初余额" prop="beginMoney" not="0">
+						<template slot-scope="s">
+							<div>{{s.row.beginMoney.toFixed(2)}}</div>
+						</template>
+					</sa-td>
 					<sa-td name="本期充值" prop="chargeMoney" not="0"></sa-td>
-					<sa-td name="本期扣除" prop="deuctionMoney" not="0"></sa-td>
+					<sa-td name="本期扣除" prop="deuctionMoney" not="0">
+						<template slot-scope="s"> <div>{{s.row.deuctionMoney.toFixed(2)}}</div> </template>
+					</sa-td>
 					<sa-td name="本期余额退款" prop="balanceRefundMoney" not="0"></sa-td>
 					<sa-td name="本期异常退款" prop="errorRefundMoney" not="0"></sa-td>
-					<sa-td name="期末余额" prop="endMoney" not="0"></sa-td>
+					<sa-td name="期末余额" prop="endMoney" not="0">
+						<template slot-scope="s">
+							<div>{{s.row.endMoney.toFixed(2)}}</div>
+						</template>
+					</sa-td>
 				</el-table>
 				<!-- ------------- 分页 ------------- -->
 				<sa-item type="page" :curr.sync="p.pageNo" :size.sync="p.pageSize" :total="dataCount" @change="f5()">

+ 156 - 99
sp-admin/sa-view/tb-costomer/customer-admin-add.html

@@ -1,105 +1,162 @@
 <!DOCTYPE html>
 <html>
-<head>
-    <title>添加管理员</title>
-    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-    <meta name="viewport"
-          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
-    <!-- 所有的 css & js 资源 -->
-    <link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
-    <link rel="stylesheet" href="../../static/sa.css">
-    <script src="../../static/kj/vue.min.js"></script>
-    <script src="../../static/kj/element-ui/index.js"></script>
-    <script src="../../static/kj/httpVueLoader.js"></script>
-    <script src="../../static/kj/jquery.min.js"></script>
-    <script src="../../static/kj/layer/layer.js"></script>
-    <script src="../../static/sa.js"></script>
-    <script src="../../static/kj/upload-util.js"></script>
-</head>
-<body>
-<div class="vue-box" style="display: none;" :style="'display: block;'">
-    <!-- 参数栏 -->
-    <div class="c-panel">
-        <el-form>
-            <!-- 防止密码框被填充 -->
-            <div style="height: 0px; overflow: hidden;">
-                <el-input></el-input>
-                <el-input type="password"></el-input>
-            </div>
-            <!-- 表单 -->
-            <sa-item type="text" name="用户名" v-model="m.name" placeholder="请输入用户名" br></sa-item>
-            <sa-item type="password" name="密码" v-model="m.password" placeholder="请输入密码" br></sa-item>
-            <sa-item type="password" name="再输一次" v-model="m.againPassword" placeholder="请再输一次密码" br></sa-item>
-            <div class="c-item">
-                <label class="c-label"><span style="color: red;">*</span>角色:</label>
-                <el-select v-model="m.roleIds" multiple>
-                    <el-option label="请选择" :value="0" disabled></el-option>
-                    <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
-                </el-select>
-            </div>
-            <sa-item name="" br>
-                <el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
-            </sa-item>
-        </el-form>
-    </div>
-</div>
+	<head>
+		<title>添加管理员</title>
+		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+		<meta name="viewport"
+			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
+		<!-- 所有的 css & js 资源 -->
+		<link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
+		<link rel="stylesheet" href="../../static/sa.css">
+		<script src="../../static/kj/vue.min.js"></script>
+		<script src="../../static/kj/element-ui/index.js"></script>
+		<script src="../../static/kj/httpVueLoader.js"></script>
+		<script src="../../static/kj/jquery.min.js"></script>
+		<script src="../../static/kj/layer/layer.js"></script>
+		<script src="../../static/sa.js"></script>
+		<script src="../../static/kj/upload-util.js"></script>
+		<style>
+			.error {
+				color: red;
+				font-size: 12px;
+				margin-left: 100px
+			}
+		</style>
+	</head>
+	<body>
+		<div class="vue-box" style="display: none;" :style="'display: block;'">
+			<!-- 参数栏 -->
+			<div class="c-panel">
+				<el-form>
+					<!-- 防止密码框被填充 -->
+					<div style="height: 0px; overflow: hidden;">
+						<el-input></el-input>
+						<el-input type="password"></el-input>
+					</div>
+					<!-- 表单 -->
+					<sa-item type="text" name="用户名" v-model="m.name" placeholder="请输入用户名" br></sa-item>
+					<sa-item type="password" name="密码" v-model="m.password" placeholder="请输入密码" @input="newPwdChange"
+						br></sa-item>
+					<div v-if="pwdError" class="error">{{pwdError}}</div>
+					<sa-item type="password" name="再输一次" v-model="m.againPassword" @input="newPwd2Change"
+						placeholder="请再输一次密码" br></sa-item>
+					<div v-if="newPwd2Error" class="error">{{newPwd2Error}}</div>
+					<div class="c-item">
+						<label class="c-label"><span style="color: red;">*</span>角色:</label>
+						<el-select v-model="m.roleIds" multiple>
+							<el-option label="请选择" :value="0" disabled></el-option>
+							<el-option v-for="role in roleList" :key="role.id" :label="role.name"
+								:value="role.id"></el-option>
+						</el-select>
+					</div>
+					<sa-item name="" br>
+						<el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
+					</sa-item>
+				</el-form>
+			</div>
+		</div>
 
-<script>
+		<script>
+			const numStr = "123456789";
+			const numStrDesc = "987654321";
+			const varStr = "abcdefghijklmnopkrstuvwxyz"
+			const varStrDesc = "zyxwvutsrkpomnlkjihgfedcba"
+			var app = new Vue({
+				components: {
+					"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue')
+				},
+				el: '.vue-box',
+				data: {
+					sa: sa, // 超级对象
+					m: {
+						id: 0,
+						customerId: sa.p('customerId', ''),
+						name: '',
+						avatar: '',
+						password: '',
+						againPassword: '',
+						roleIds: []
+					},
+					pwdError: '',
+					newPwd2Error: '',
+					roleList: []
+				},
+				methods: {
+					// 修改
+					ok: function() {
+						// 表单校验
+						let m = this.m;
+						sa.checkNull(m.name, '请输入用户名');
+						sa.checkNull(m.password, '请输入密码');
+						if (this.pwdError || this.newPwd2Error) {
+							return;
+						}
+						if (m.password !== m.againPassword) {
+							sa.error('两次输入密码不一致');
+							return;
+						}
+						if (m.roleIds.length == 0) {
+							sa.error('请选择角色');
+							return;
+						}
+						m.roleId = m.roleIds.join(',')
+						// 添加
+						sa.ajax('/admin/addCustomerAdmin', m, function(res) {
+							sa.alert('增加成功', this.clean);
 
-    var app = new Vue({
-        components: {
-            "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue')
-        },
-        el: '.vue-box',
-        data: {
-            sa: sa, 	// 超级对象
-            m: {
-                id: 0,
-                customerId: sa.p('customerId', ''),
-                name: '',
-                avatar: '',
-                password: '',
-                againPassword: '',
-                roleIds: []
-            },
-            roleList: []
-        },
-        methods: {
-            // 修改
-            ok: function () {
-                // 表单校验
-                let m = this.m;
-                sa.checkNull(m.name, '请输入用户名');
-                sa.checkNull(m.password, '请输入密码');
-                if (m.password !== m.againPassword) {
-                    sa.error('两次输入密码不一致');
-                    return;
-                }
-                if (m.roleIds.length == 0) {
-                    sa.error('请选择角色');
-                    return;
-                }
-                m.roleId = m.roleIds.join(',')
-                // 添加
-                sa.ajax('/admin/addCustomerAdmin', m, function (res) {
-                    sa.alert('增加成功', this.clean);
+						}.bind(this));
 
-                }.bind(this));
-
-            },
-            clean() {
-                parent.app.f5();		// 刷新父页面列表
-                sa.closeCurrIframe();	// 关闭本页
-            }
-        },
-        mounted: function () {
-            // 加载角色
-            sa.ajax('/role/getCustomerRoleList', {customerId: this.m.customerId}, function (res) {
-                this.roleList = res.data;	// 数据
-            }.bind(this), {msg: null});
-        }
-    })
-
-</script>
-</body>
+					},
+					clean() {
+						parent.app.f5(); // 刷新父页面列表
+						sa.closeCurrIframe(); // 关闭本页
+					},
+					newPwdChange(v) {
+						let len = v.length;
+						this.pwdError = '';
+						if (!this.checkStong(v)) {
+							this.pwdError = '密码长度8-16位,至少包含一个数字、一个大写字母、一个小写字母以及!@#$%^&*?之一'
+							return;
+						}
+						if (len >= 3) {
+							let s = v.toLowerCase();
+							for (let i = 0; i < len - 2; i++) {
+								let charStr = s.substring(i, i + 3);
+								if (this.checkStr(charStr)) {
+									this.pwdError = '密码不应该采用连续升序或者连续降序'
+									return;
+								}
+							}
+						}
+					},
+					newPwd2Change(v) {
+						let len = v.length;
+						this.newPwd2Error = '';
+						if (this.m.password != v) {
+							this.newPwd2Error = '两次输入密码不一致';
+							return;
+						}
+					},
+					checkStr(charStr) {
+						return numStr.indexOf(charStr) != -1 || varStr.indexOf(charStr) != -1 || numStrDesc.indexOf(
+							charStr) != -1 || varStrDesc.indexOf(charStr) != -1;
+					},
+					checkStong(v) {
+						let pattern = /^.*(?=.{8,16})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/;
+						return pattern.test(v);
+					},
+				},
+				mounted: function() {
+					// 加载角色
+					sa.ajax('/role/getCustomerRoleList', {
+						customerId: this.m.customerId
+					}, function(res) {
+						this.roleList = res.data; // 数据
+					}.bind(this), {
+						msg: null
+					});
+				}
+			})
+		</script>
+	</body>
 </html>

+ 344 - 304
sp-admin/sa-view/tb-costomer/customer-admin-list.html

@@ -1,325 +1,365 @@
 <!DOCTYPE html>
 <html>
-<head>
-    <title>管理员列表</title>
-    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-    <meta name="viewport"
-          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
-    <!-- 所有的 css & js 资源 -->
-    <link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
-    <link rel="stylesheet" href="../../static/sa.css">
-    <script src="../../static/kj/vue.min.js"></script>
-    <script src="../../static/kj/element-ui/index.js"></script>
-    <script src="../../static/kj/httpVueLoader.js"></script>
-    <script src="../../static/kj/jquery.min.js"></script>
-    <script src="../../static/kj/layer/layer.js"></script>
-    <script src="../../static/sa.js"></script>
-    <script src="../../static/kj/upload-util.js"></script>
-    <style type="text/css">
-        .el-radio {
-            margin-right: 10px;
-        }
-    </style>
-</head>
-<body>
-<div class="vue-box" style="display: none;" :style="'display: block;'">
-    <div class="c-panel">
-        <!-- ------------- 检索参数 ------------- -->
-        <h4 class="c-title">检索参数</h4>
-        <el-form>
-            <sa-item type="text" name="用户名" v-model="p.name"></sa-item>
-            <el-button type="primary" icon="el-icon-search" @click="p.pageNo = 1; f5()">查询</el-button>
-            <el-button type="primary" icon="el-icon-plus" @click="add()" v-if="sa.isAuth('tb-costomer-user-add')">新增
-            </el-button>
-            <el-button type="info" icon="el-icon-refresh" @click="sa.f5()">重置</el-button>
-        </el-form>
-        <!-- ------------- 快捷按钮 ------------- -->
+	<head>
+		<title>管理员列表</title>
+		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+		<meta name="viewport"
+			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
+		<!-- 所有的 css & js 资源 -->
+		<link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
+		<link rel="stylesheet" href="../../static/sa.css">
+		<script src="../../static/kj/vue.min.js"></script>
+		<script src="../../static/kj/element-ui/index.js"></script>
+		<script src="../../static/kj/httpVueLoader.js"></script>
+		<script src="../../static/kj/jquery.min.js"></script>
+		<script src="../../static/kj/layer/layer.js"></script>
+		<script src="../../static/sa.js"></script>
+		<script src="../../static/kj/upload-util.js"></script>
+		<style type="text/css">
+			.el-radio {
+				margin-right: 10px;
+			}
+		</style>
+	</head>
+	<body>
+		<div class="vue-box" style="display: none;" :style="'display: block;'">
+			<div class="c-panel">
+				<!-- ------------- 检索参数 ------------- -->
+				<h4 class="c-title">检索参数</h4>
+				<el-form>
+					<sa-item type="text" name="用户名" v-model="p.name"></sa-item>
+					<el-button type="primary" icon="el-icon-search" @click="p.pageNo = 1; f5()">查询</el-button>
+					<el-button type="primary" icon="el-icon-plus" @click="add()"
+						v-if="sa.isAuth('tb-costomer-user-add')">新增
+					</el-button>
+					<el-button type="info" icon="el-icon-refresh" @click="sa.f5()">重置</el-button>
+				</el-form>
+				<!-- ------------- 快捷按钮 ------------- -->
 
-        <!-- ------------- 数据列表 ------------- -->
-        <el-table class="data-table" ref="data-table" :data="dataList">
-            <sa-td type="selection"></sa-td>
-            <sa-td type="text" name="用户名" prop="name" min-width="120px"></sa-td>
-            <sa-td type="text" name="姓名" prop="nickname" min-width="120px"></sa-td>
-            <sa-td type="datetime" name="创建时间" prop="createTime" width="150px"></sa-td>
-            <sa-td type="datetime" name="最后登录" prop="loginTime" width="150px"></sa-td>
-            <sa-td type="text" name="登录次数" prop="loginCount" not="0" width="100px"></sa-td>
-            <sa-td type="switch" name="账号状态" prop="status" :jv="{1: '正常', 2: '禁用[#ff4949]'}"
-                   @change="s => updateStatus(s.row)" width="120px"></sa-td>
-            <el-table-column label="操作" fixed="right" width="450px">
-                <template slot-scope="s">
+				<!-- ------------- 数据列表 ------------- -->
+				<el-table class="data-table" ref="data-table" :data="dataList">
+					<sa-td type="selection"></sa-td>
+					<sa-td type="text" name="用户名" prop="name" min-width="120px"></sa-td>
+					<sa-td type="text" name="姓名" prop="nickname" min-width="120px"></sa-td>
+					<sa-td type="datetime" name="创建时间" prop="createTime" width="150px"></sa-td>
+					<sa-td type="datetime" name="最后登录" prop="loginTime" width="150px"></sa-td>
+					<sa-td type="text" name="登录次数" prop="loginCount" not="0" width="100px"></sa-td>
+					<sa-td type="switch" name="账号状态" prop="status" :jv="{1: '正常', 2: '禁用[#ff4949]'}"
+						@change="s => updateStatus(s.row)" width="120px"></sa-td>
+					<el-table-column label="操作" fixed="right" width="450px">
+						<template slot-scope="s">
 							<span @click="getInfo(s.row)">
 								<el-button type="success" class="c-btn" icon="el-icon-view">查看</el-button>
 							</span>
-                    <span @click="updateName(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
+							<span @click="updateName(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
 								<el-button type="primary" class="c-btn">改名称</el-button>
 							</span>
-                    <span @click="updateNickname(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
+							<span @click="updateNickname(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
 								<el-button type="primary" class="c-btn">改姓名</el-button>
 							</span>
-                    <span @click="updateAvatar(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
+							<span @click="updateAvatar(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
 								<el-button type="primary" class="c-btn">改头像</el-button>
 							</span>
-                    <span @click="updatePassword(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
+							<span @click="updatePassword(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
 								<el-button type="primary" class="c-btn">改密码</el-button>
 							</span>
-                    <span @click="roleFn(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
+							<span @click="roleFn(s.row)" v-if="sa.isAuth('tb-costomer-user-edit')">
 								<el-button type="primary" class="c-btn">角色</el-button>
 							</span>
-                    <span @click="del(s.row)" v-if="sa.isAuth('tb-costomer-user-del')">
+							<span @click="del(s.row)" v-if="sa.isAuth('tb-costomer-user-del')">
 								<el-button type="danger" class="c-btn">删除</el-button>
 							</span>
-                </template>
-            </el-table-column>
-        </el-table>
-        <!-- 分页 -->
-        <sa-item type="page" :curr.sync="p.pageNo" :size.sync="p.pageSize" :total="dataCount" @change="f5()">
-        </sa-item>
-    </div>
-    <el-dialog :title="roleDialog.title" :visible.sync="roleDialog.visible" width="60%">
-        <div>
-            <el-checkbox @change="handleCheckAllChange">全选</el-checkbox>
-            <div style="margin: 15px 0;"></div>
-            <el-checkbox-group v-model="roleDialog.form.roleId">
-                <el-checkbox v-for="role in roleList" :label="role.id+''" :key="role.id">{{role.name}}
-                </el-checkbox>
-            </el-checkbox-group>
-        </div>
-        <span slot="footer" class="dialog-footer">
+						</template>
+					</el-table-column>
+				</el-table>
+				<!-- 分页 -->
+				<sa-item type="page" :curr.sync="p.pageNo" :size.sync="p.pageSize" :total="dataCount" @change="f5()">
+				</sa-item>
+			</div>
+			<el-dialog :title="roleDialog.title" :visible.sync="roleDialog.visible" width="60%">
+				<div>
+					<el-checkbox @change="handleCheckAllChange">全选</el-checkbox>
+					<div style="margin: 15px 0;"></div>
+					<el-checkbox-group v-model="roleDialog.form.roleId">
+						<el-checkbox v-for="role in roleList" :label="role.id+''" :key="role.id">{{role.name}}
+						</el-checkbox>
+					</el-checkbox-group>
+				</div>
+				<span slot="footer" class="dialog-footer">
 					<el-button @click="roleDialog.visible = false">取 消</el-button>
 					<el-button type="primary" @click="confirmSetRole">确 定</el-button>
 				</span>
-    </el-dialog>
-</div>
-<script>
-    var app = new Vue({
-        components: {
-            "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),
-            "sa-td": httpVueLoader('../../sa-frame/com/sa-td.vue')
-        },
-        el: '.vue-box',
-        data: {
-            roleDialog: {
-                visible: false,
-                title: '',
-                form: {
-                    id: '',
-                    roleId: [],
-                }
-            },
-            sa: sa, // 超级对象
-            p: { // 查询参数
-                name: '',
-                customerId: sa.p('customerId', ''),
-                sort_type: 0,
-                pageNo: 1,
-                pageSize: 10,
-            },
-            dataCount: 0,
-            dataList: [], // 数据集合
-            roleList: [], // 角色集合
-        },
-        methods: {
-            roleFn(data) {
-                Object.assign(this.roleDialog, {
-                    visible: true,
-                    title: '设置[' + data.name + ']角色属性',
-                    form: {
-                        id: data.id,
-                        roleId: data.roleId.split(',')
-                    }
-                })
-            },
-            handleCheckAllChange() {
-                let roleId = this.roleDialog.form.roleId;
-                let allIds = this.roleList.map(obj => obj.id + '');
-                this.roleDialog.form.roleId = roleId.length != allIds.length ? allIds : [];
-            },
-            confirmSetRole() {
-                let roleId = this.roleDialog.form.roleId;
-                if (roleId.length == 0) {
-                    return sa.msg('请选择一个角色')
-                }
-                let o = {
-                    id: this.roleDialog.form.id,
-                    roleId: this.roleDialog.form.roleId.join(',')
-                }
-                sa.ajax('/admin/setRole', o, function (resp) {
-                    this.f5();
-                    this.roleDialog.visible = false;
-                }.bind(this))
-            },
-            updateNickname(data) {
-                layer.prompt({title: '修改名称'}, function (pass, index) {
-                    layer.close(index);
-                    sa.ajax('/admin/updateNickname', {id: data.id, nickname: pass}, function (res) {
-                        data.nickname = pass;
-                        layer.msg('修改成功');
-                    }.bind(this))
-                });
-            },
-            // 刷新
-            f5: function (isPage) {
-                sa.ajax('/admin/getCustomerAdminList', this.p, function (res) {
-                    this.dataList = res.data; // 数据
-                    this.dataCount = res.dataCount;
-                    sa.f5TableHeight(); // 刷新表格高度
-                }.bind(this));
-            },
-            // 新增
-            add: function () {
-                sa.showIframe('新增用户', 'customer-admin-add.html?customerId=' + this.p.customerId, '550px',
-                    '75%');
-            },
-            // 查看详情
-            getInfo: function (data) {
-                sa.showIframe('账号详情', '../../sa-view-sp/sp-admin/admin-info.html?id=' + data.id, '700px',
-                    '80%');
-                //sa.$page.openAdminInfo(data.id, data.name);
-            },
-            // 查看 - 根据选中的
-            getBySelect: function (data) {
-                var selection = this.$refs['data-table'].selection;
-                if (selection.length == 0) {
-                    return sa.msg('请选择一条数据')
-                }
-                this.getInfo(selection[0]);
-            },
-            // 修改名称
-            updateName: function (data) {
-                layer.prompt({
-                    title: '修改账号名称'
-                }, function (pass, index) {
-                    layer.close(index);
-                    sa.ajax('/admin/update', {
-                        id: data.id,
-                        name: pass
-                    }, function (res) {
-                        data.name = pass;
-                        layer.msg('修改成功');
-                    })
-                });
-            },
-            // 修改头像
-            updateAvatar: function (data) {
-                sa.uploadImage(function (src) {
-                    var p = {
-                        id: data.id,
-                        avatar: src
-                    };
-                    sa.ajax('/admin/updateAvatar', p, function (res) {
-                        sa.msg('上传成功');
-                        data.avatar = src;
-                    }.bind(this));
-                })
-            },
-            // 修改密码
-            updatePassword: function (data) {
-                layer.prompt({
-                    title: '修改密码'
-                }, function (pass, index) {
-                    layer.close(index);
-                    if (pass.length < 4) {
-                        return layer.msg('新密码长度请不要低于4位');
-                    }
-                    sa.ajax('/admin/updatePassword', {
-                        id: data.id,
-                        password: pass
-                    }, function (res) {
-                        layer.msg('修改成功');
-                    })
-                });
-            },
-            // 修改角色
-            updateRoleId: function (data, roleId, roleName) {
-                if (data.id == sa.$sys.getCurrUser().id) {
-                    return sa.alert('不能自己修改自己的角色');
-                }
-                if (data.roleId == roleId) {
-                    return sa.alert('该用户已经是' + roleName + '了');
-                }
-                var str = '将此账号修改为 [' + roleName + '], 请确认?';
-                layer.confirm(str, {
-                    title: '请确认'
-                }, function () {
-                    sa.ajax('/admin/updateRole', {
-                        id: data.id,
-                        roleId: roleId
-                    }, function (res) {
-                        sa.msg('修改成功');
-                        data.roleId = roleId;
-                        data.roleName = roleName;
-                    }.bind(this));
-                }.bind(this));
-            },
-            // 修改用户的状态
-            updateStatus: function (data) {
-                if (data.id == sa.$sys.getCurrUser().id) {
-                    data.status = 3 - data.status;
-                    return sa.alert('不能自己封禁自己');
-                }
-                var is_ok = false; // 记录是否成功
-                var ajax = sa.ajax('/admin/updateStatus', {
-                    adminId: data.id,
-                    status: data.status
-                }, function (res) {
-                    sa.msg('修改成功');
-                    is_ok = true;
-                }.bind(this));
-                // 如果未能修改成功, 则回滚
-                $.when(ajax).done(function () {
-                    if (is_ok == false) {
-                        data.status = 3 - data.status;
-                    }
-                })
-            },
-            // 删除
-            del: function (data) {
-                sa.confirm('是否删除,此操作不可撤销', function () {
-                    sa.ajax('/admin/delete', {
-                        id: data.id
-                    }, function (res) {
-                        sa.arrayDelete(app.dataList, data);
-                        sa.ok('删除成功');
-                        sa.f5TableHeight(); // 刷新表格高度
-                    })
-                });
-            },
-            // 批量删除
-            deleteByIds: function () {
-                // 获取选中元素的id列表
-                let selection = this.$refs['data-table'].selection;
-                let ids = sa.getArrayField(selection, 'id');
-                if (selection.length == 0) {
-                    return sa.msg('请至少选择一条数据')
-                }
-                // 提交删除
-                sa.confirm('是否批量删除选中数据?此操作不可撤销', function () {
-                    sa.ajax('/admin/deleteByIds', {
-                        ids: ids.join(',')
-                    }, function (res) {
-                        sa.arrayDelete(this.dataList, selection);
-                        sa.ok('删除成功');
-                        sa.f5TableHeight(); // 刷新表格高度
-                    }.bind(this))
-                }.bind(this));
-            },
-            getRoleList() {
-                // 加载角色
-                sa.ajax('/role/getCustomerRoleList', {
-                    customerId: this.p.customerId
-                }, function (res) {
-                    this.roleList = res.data; // 数据
-                }.bind(this), {
-                    msg: null
-                });
-            }
-        },
-        created: function () {
-            this.f5();
-            sa.onInputEnter(); // 监听回车执行查询
-            this.getRoleList();
-        }
-    })
-</script>
-</body>
-</html>
+			</el-dialog>
+		</div>
+		<script>
+			const numStr = "123456789";
+			const numStrDesc = "987654321";
+			const varStr = "abcdefghijklmnopkrstuvwxyz"
+			const varStrDesc = "zyxwvutsrkpomnlkjihgfedcba"
+			var app = new Vue({
+				components: {
+					"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),
+					"sa-td": httpVueLoader('../../sa-frame/com/sa-td.vue')
+				},
+				el: '.vue-box',
+				data: {
+					roleDialog: {
+						visible: false,
+						title: '',
+						form: {
+							id: '',
+							roleId: [],
+						}
+					},
+					sa: sa, // 超级对象
+					p: { // 查询参数
+						name: '',
+						customerId: sa.p('customerId', ''),
+						sort_type: 0,
+						pageNo: 1,
+						pageSize: 10,
+					},
+					dataCount: 0,
+					dataList: [], // 数据集合
+					roleList: [], // 角色集合
+				},
+				methods: {
+					roleFn(data) {
+						Object.assign(this.roleDialog, {
+							visible: true,
+							title: '设置[' + data.name + ']角色属性',
+							form: {
+								id: data.id,
+								roleId: data.roleId.split(',')
+							}
+						})
+					},
+					handleCheckAllChange() {
+						let roleId = this.roleDialog.form.roleId;
+						let allIds = this.roleList.map(obj => obj.id + '');
+						this.roleDialog.form.roleId = roleId.length != allIds.length ? allIds : [];
+					},
+					confirmSetRole() {
+						let roleId = this.roleDialog.form.roleId;
+						if (roleId.length == 0) {
+							return sa.msg('请选择一个角色')
+						}
+						let o = {
+							id: this.roleDialog.form.id,
+							roleId: this.roleDialog.form.roleId.join(',')
+						}
+						sa.ajax('/admin/setRole', o, function(resp) {
+							this.f5();
+							this.roleDialog.visible = false;
+						}.bind(this))
+					},
+					updateNickname(data) {
+						layer.prompt({
+							title: '修改名称'
+						}, function(pass, index) {
+							layer.close(index);
+							sa.ajax('/admin/updateNickname', {
+								id: data.id,
+								nickname: pass
+							}, function(res) {
+								data.nickname = pass;
+								layer.msg('修改成功');
+							}.bind(this))
+						});
+					},
+					// 刷新
+					f5: function(isPage) {
+						sa.ajax('/admin/getCustomerAdminList', this.p, function(res) {
+							this.dataList = res.data; // 数据
+							this.dataCount = res.dataCount;
+							sa.f5TableHeight(); // 刷新表格高度
+						}.bind(this));
+					},
+					// 新增
+					add: function() {
+						sa.showIframe('新增用户', 'customer-admin-add.html?customerId=' + this.p.customerId, '550px',
+							'75%');
+					},
+					// 查看详情
+					getInfo: function(data) {
+						sa.showIframe('账号详情', '../../sa-view-sp/sp-admin/admin-info.html?id=' + data.id, '700px',
+							'80%');
+						//sa.$page.openAdminInfo(data.id, data.name);
+					},
+					// 查看 - 根据选中的
+					getBySelect: function(data) {
+						var selection = this.$refs['data-table'].selection;
+						if (selection.length == 0) {
+							return sa.msg('请选择一条数据')
+						}
+						this.getInfo(selection[0]);
+					},
+					// 修改名称
+					updateName: function(data) {
+						layer.prompt({
+							title: '修改账号名称'
+						}, function(pass, index) {
+							layer.close(index);
+							sa.ajax('/admin/update', {
+								id: data.id,
+								name: pass
+							}, function(res) {
+								data.name = pass;
+								layer.msg('修改成功');
+							})
+						});
+					},
+					// 修改头像
+					updateAvatar: function(data) {
+						sa.uploadImage(function(src) {
+							var p = {
+								id: data.id,
+								avatar: src
+							};
+							sa.ajax('/admin/updateAvatar', p, function(res) {
+								sa.msg('上传成功');
+								data.avatar = src;
+							}.bind(this));
+						})
+					},
+					// 修改密码
+					updatePassword: function(data) {
+						let that = this;
+						layer.prompt({
+							title: '修改密码'
+						}, function(pass, index) {
+							layer.close(index);
+							if (pass.length < 4) {
+								return layer.msg('新密码长度请不要低于4位');
+							}
+							let result = that.newPwdChange(pass);
+							if (!result) {
+								return;
+							}
+							sa.ajax('/admin/updatePassword', {
+								id: data.id,
+								password: pass
+							}, function(res) {
+								layer.msg('修改成功');
+							})
+						});
+					},
+					newPwdChange(v) {
+						let len = v.length;
+						if (!this.checkStong(v)) {
+							layer.msg('密码长度8-16位,至少包含一个数字、一个大写字母、一个小写字母以及!@#$%^&*?之一')
+							return false;
+						}
+						if (len >= 3) {
+							let s = v.toLowerCase();
+							for (let i = 0; i < len - 2; i++) {
+								let charStr = s.substring(i, i + 3);
+								if (this.checkStr(charStr)) {
+									layer.msg('密码不应该采用连续升序或者连续降序');
+									return false;
+								}
+							}
+						}
+					},
+					checkStr(charStr) {
+						return numStr.indexOf(charStr) != -1 || varStr.indexOf(charStr) != -1 || numStrDesc.indexOf(
+							charStr) != -1 || varStrDesc.indexOf(charStr) != -1;
+					},
+					checkStong(v) {
+						let pattern = /^.*(?=.{8,16})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/;
+						return pattern.test(v);
+					},
+					// 修改角色
+					updateRoleId: function(data, roleId, roleName) {
+						if (data.id == sa.$sys.getCurrUser().id) {
+							return sa.alert('不能自己修改自己的角色');
+						}
+						if (data.roleId == roleId) {
+							return sa.alert('该用户已经是' + roleName + '了');
+						}
+						var str = '将此账号修改为 [' + roleName + '], 请确认?';
+						layer.confirm(str, {
+							title: '请确认'
+						}, function() {
+							sa.ajax('/admin/updateRole', {
+								id: data.id,
+								roleId: roleId
+							}, function(res) {
+								sa.msg('修改成功');
+								data.roleId = roleId;
+								data.roleName = roleName;
+							}.bind(this));
+						}.bind(this));
+					},
+					// 修改用户的状态
+					updateStatus: function(data) {
+						if (data.id == sa.$sys.getCurrUser().id) {
+							data.status = 3 - data.status;
+							return sa.alert('不能自己封禁自己');
+						}
+						var is_ok = false; // 记录是否成功
+						var ajax = sa.ajax('/admin/updateStatus', {
+							adminId: data.id,
+							status: data.status
+						}, function(res) {
+							sa.msg('修改成功');
+							is_ok = true;
+						}.bind(this));
+						// 如果未能修改成功, 则回滚
+						$.when(ajax).done(function() {
+							if (is_ok == false) {
+								data.status = 3 - data.status;
+							}
+						})
+					},
+					// 删除
+					del: function(data) {
+						sa.confirm('是否删除,此操作不可撤销', function() {
+							sa.ajax('/admin/delete', {
+								id: data.id
+							}, function(res) {
+								sa.arrayDelete(app.dataList, data);
+								sa.ok('删除成功');
+								sa.f5TableHeight(); // 刷新表格高度
+							})
+						});
+					},
+					// 批量删除
+					deleteByIds: function() {
+						// 获取选中元素的id列表
+						let selection = this.$refs['data-table'].selection;
+						let ids = sa.getArrayField(selection, 'id');
+						if (selection.length == 0) {
+							return sa.msg('请至少选择一条数据')
+						}
+						// 提交删除
+						sa.confirm('是否批量删除选中数据?此操作不可撤销', function() {
+							sa.ajax('/admin/deleteByIds', {
+								ids: ids.join(',')
+							}, function(res) {
+								sa.arrayDelete(this.dataList, selection);
+								sa.ok('删除成功');
+								sa.f5TableHeight(); // 刷新表格高度
+							}.bind(this))
+						}.bind(this));
+					},
+					getRoleList() {
+						// 加载角色
+						sa.ajax('/role/getCustomerRoleList', {
+							customerId: this.p.customerId
+						}, function(res) {
+							this.roleList = res.data; // 数据
+						}.bind(this), {
+							msg: null
+						});
+					}
+				},
+				created: function() {
+					this.f5();
+					sa.onInputEnter(); // 监听回车执行查询
+					this.getRoleList();
+				}
+			})
+		</script>
+	</body>
+</html>

+ 1 - 1
sp-admin/sa-view/tb-fee-statistics/tb-fee-details-info.html

@@ -63,7 +63,7 @@
 			</div>
 			<!-- ------- 底部按钮 ------- -->
 			<div class="s-foot">
-				<el-button type="success" @click="confirmFn()" v-if="!m.judgeTime">确定</el-button>
+				<el-button type="success" @click="confirmFn()">确定</el-button>
 				<el-button @click="sa.closeCurrIframe()">关闭</el-button>
 			</div>
 		</div>

+ 1 - 1
sp-admin/sa-view/tb-fee-statistics/tb-fee-statistics-list.html

@@ -85,7 +85,7 @@
 					<sa-td name="统计稽查员" prop="jiChaPerson"></sa-td>
 					<sa-td name="部门负责人" prop="judgeBy"></sa-td>
 					<!-- <sa-td name="审核时间" prop="judgeTime" width="140"></sa-td> -->
-					<el-table-column label="操作" fixed="right" width="120px" v-if="sa.isAuth('tb-fee-statistics-judge')">
+					<el-table-column label="操作" fixed="right" width="120px" v-if="sa.isAuth('tb-diaodu-confirm')">
 						<template slot-scope="s">
 							<el-button class="c-btn" type="primary" icon="el-icon-edit" @click="judgeFn(s.row)">审核
 							</el-button>

+ 1 - 0
sp-admin/sa-view/tb-invoice-info/tb-invoice-info-list.html

@@ -53,6 +53,7 @@
 					<sa-td name="开票状态" prop="status" type="enum" :jv="{0: '未开票', 1: '已开票',2:'申请中',3:'红冲',6:'作废'}">
 					</sa-td>
 					<sa-td name="开票种类" prop="isElec" type="enum" :jv="{0: '纸质普票', 1: '电子普票', 2:'纸质专票'}"></sa-td>
+					<sa-td name="申请时间" prop="createTime" width="180"></sa-td>
 					<sa-td name="开票时间" prop="invoiceTime"></sa-td>
 					<sa-td name="发票号" prop="invoiceNo" width="150">
 						<template slot-scope="s">

+ 1 - 1
sp-admin/sa-view/tb-invoice-order/tb-invoice-order-add.html

@@ -29,7 +29,7 @@
 					<el-form v-if="m">
 						<sa-item v-if="idShow === 1" type="text" name="交易单号" v-model="m.transactionId" placeholder="请填写账单中的交易单号" br></sa-item>
 <!--						<sa-item type="text" name="账单金额" v-model="m.billMoney" br></sa-item>-->
-						<sa-item type="img" name="账单截图" v-model="m.billImage" br></sa-item>
+						<sa-item type="img-list" name="账单截图" v-model="m.billImage" br></sa-item>
 						<sa-item name="" class="s-ok" br>
 							<el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
 						</sa-item>

+ 3 - 2
sp-admin/sa-view/tb-invoice-order/tb-invoice-order-list.html

@@ -121,6 +121,7 @@
 					</el-table-column>
 					<sa-td name="账单截图" prop="billImage" type="img"></sa-td>
 					<sa-td name="开票状态" prop="status" type="enum" :jv="{0: '待申请', 1: '已申请', 2: '已开票'}"></sa-td>
+					<sa-td name="创建时间" prop="createTime" width="100px"></sa-td>
 					<sa-td name="开票时间" prop="invoiceTime" width="100px"></sa-td>
 					<sa-td name="开票信息" prop="infoNo" width="130"></sa-td>
 					<el-table-column label="操作" fixed="right" width="140px">
@@ -139,7 +140,7 @@
 			<el-dialog title="申请开票" :visible.sync="applyDate.visible" width="38%">
 				<sa-item name="发票总额" v-model="applyDate.form.totalMoney" type="num" :disabled="true"></sa-item>
 				<sa-item name="开票种类" v-model="applyDate.form.isElec" type="enum"
-					:jv="{1: '电子普票', 0: '纸质普票', 2:'纸质专票'}"></sa-item>
+					:jv="{1: '电子普票', 0: '纸质普票', 2:'电子专票'}"></sa-item>
 				<div class="c-item">
 					<label class="c-label">开票主体:</label>
 					<el-select :disabled="selectDisabled" v-model="applyDate.form.entityId" placeholder="请选择" filterable @change="changeEntity">
@@ -252,7 +253,7 @@
 							this.applyDate.form.entityId=entityArry[0].id;
 							this.selectDisabled=true;
 						}
-						this.applyDate.form.totalMoney = totalMoney;
+						this.applyDate.form.totalMoney = totalMoney.toFixed(2);
 						this.applyDate.visible = true;
 						this.applyDate.form.ids = ids.join(',');
 						

+ 155 - 100
sp-admin/sa-view/tb-partner/customer-admin-add.html

@@ -1,105 +1,160 @@
 <!DOCTYPE html>
 <html>
-<head>
-    <title>添加管理员</title>
-    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-    <meta name="viewport"
-          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
-    <!-- 所有的 css & js 资源 -->
-    <link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
-    <link rel="stylesheet" href="../../static/sa.css">
-    <script src="../../static/kj/vue.min.js"></script>
-    <script src="../../static/kj/element-ui/index.js"></script>
-    <script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
-    <script src="../../static/kj/jquery.min.js"></script>
-    <script src="../../static/kj/layer/layer.js"></script>
-    <script src="../../static/sa.js"></script>
-    <script src="../../static/kj/upload-util.js"></script>
-</head>
-<body>
-<div class="vue-box" style="display: none;" :style="'display: block;'">
-    <!-- 参数栏 -->
-    <div class="c-panel">
-        <el-form>
-            <!-- 防止密码框被填充 -->
-            <div style="height: 0px; overflow: hidden;">
-                <el-input></el-input>
-                <el-input type="password"></el-input>
-            </div>
-            <!-- 表单 -->
-            <sa-item type="text" name="用户名" v-model="m.name" placeholder="请输入用户名" br></sa-item>
-            <sa-item type="password" name="密码" v-model="m.password" placeholder="请输入密码" br></sa-item>
-            <sa-item type="password" name="再输一次" v-model="m.againPassword" placeholder="请再输一次密码" br></sa-item>
-            <div class="c-item">
-                <label class="c-label"><span style="color: red;">*</span>角色:</label>
-                <el-select v-model="m.roleIds" multiple>
-                    <el-option label="请选择" :value="0" disabled></el-option>
-                    <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id">
-                    </el-option>
-                </el-select>
-            </div>
-            <sa-item name="" br>
-                <el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
-            </sa-item>
-        </el-form>
-    </div>
-</div>
+	<head>
+		<title>添加管理员</title>
+		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+		<meta name="viewport"
+			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
+		<!-- 所有的 css & js 资源 -->
+		<link rel="stylesheet" href="../../static/kj/element-ui/theme-chalk/index.css">
+		<link rel="stylesheet" href="../../static/sa.css">
+		<script src="../../static/kj/vue.min.js"></script>
+		<script src="../../static/kj/element-ui/index.js"></script>
+		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
+		<script src="../../static/kj/jquery.min.js"></script>
+		<script src="../../static/kj/layer/layer.js"></script>
+		<script src="../../static/sa.js"></script>
+		<script src="../../static/kj/upload-util.js"></script>
+		<style>
+			.error {
+				color: red;
+				font-size: 12px;
+				margin-left: 100px
+			}
+		</style>
+	</head>
+	<body>
+		<div class="vue-box" style="display: none;" :style="'display: block;'">
+			<!-- 参数栏 -->
+			<div class="c-panel">
+				<el-form>
+					<!-- 防止密码框被填充 -->
+					<div style="height: 0px; overflow: hidden;">
+						<el-input></el-input>
+						<el-input type="password"></el-input>
+					</div>
+					<!-- 表单 -->
+					<sa-item type="text" name="用户名" v-model="m.name" placeholder="请输入用户名" br></sa-item>
+					<sa-item type="password" name="密码" v-model="m.password" placeholder="请输入密码" @input="newPwdChange"
+						br></sa-item>
+					<div v-if="pwdError" class="error">{{pwdError}}</div>
+					<sa-item type="password" name="再输一次" v-model="m.againPassword" @input="newPwd2Change"
+						placeholder="请再输一次密码" br></sa-item>
+					<div v-if="newPwd2Error" class="error">{{newPwd2Error}}</div>
 
-<script>
-    var app = new Vue({
-        components: {
-            "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue')
-        },
-        el: '.vue-box',
-        data: {
-            sa: sa, // 超级对象
-            m: {
-                id: 0,
-                customerId: sa.p('customerId', ''),
-                name: '',
-                avatar: '',
-                password: '',
-                againPassword: '',
-                roleIds: []
-            },
-            roleList: []
-        },
-        methods: {
-            // 修改
-            ok: function () {
-                console.log(this.m)
-                // 表单校验
-                let m = this.m;
-                sa.checkNull(m.name, '请输入用户名');
-                sa.checkNull(m.password, '请输入密码');
-                if (m.password !== m.againPassword) {
-                    sa.error('两次输入密码不一致');
-                    return;
-                }
-                m.roleId = m.roleIds.join(',')
-                // 添加
-                sa.ajax('/admin/addPartnerAdmin', m, function (res) {
-                    sa.alert('增加成功', this.clean);
+					<div class="c-item">
+						<label class="c-label"><span style="color: red;">*</span>角色:</label>
+						<el-select v-model="m.roleIds" multiple>
+							<el-option label="请选择" :value="0" disabled></el-option>
+							<el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id">
+							</el-option>
+						</el-select>
+					</div>
+					<sa-item name="" br>
+						<el-button type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
+					</sa-item>
+				</el-form>
+			</div>
+		</div>
 
-                }.bind(this));
+		<script>
+			const numStr = "123456789";
+			const numStrDesc = "987654321";
+			const varStr = "abcdefghijklmnopkrstuvwxyz"
+			const varStrDesc = "zyxwvutsrkpomnlkjihgfedcba"
+			var app = new Vue({
+				components: {
+					"sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue')
+				},
+				el: '.vue-box',
+				data: {
+					sa: sa, // 超级对象
+					m: {
+						id: 0,
+						customerId: sa.p('customerId', ''),
+						name: '',
+						avatar: '',
+						password: '',
+						againPassword: '',
+						roleIds: []
+					},
+					pwdError: '',
+					newPwd2Error: '',
+					roleList: []
+				},
+				methods: {
+					// 修改
+					ok: function() {
+						// 表单校验
+						let m = this.m;
+						sa.checkNull(m.name, '请输入用户名');
+						sa.checkNull(m.password, '请输入密码');
+						if (m.password !== m.againPassword) {
+							sa.error('两次输入密码不一致');
+							return;
+						}
+						if (this.pwdError || this.newPwd2Error) {
+							return;
+						}
+						m.roleId = m.roleIds.join(',')
+						// 添加
+						sa.ajax('/admin/addPartnerAdmin', m, function(res) {
+							sa.alert('增加成功', this.clean);
 
-            },
-            clean() {
-                parent.app.f5(); // 刷新父页面列表
-                sa.closeCurrIframe(); // 关闭本页
-            }
-        },
-        mounted: function () {
-            // 加载角色
-            sa.ajax('/role/getCustomerRoleList', {
-                customerId: this.m.customerId
-            }, function (res) {
-                this.roleList = res.data; // 数据
-            }.bind(this), {
-                msg: null
-            });
-        }
-    })
-</script>
-</body>
-</html>
+						}.bind(this));
+
+					},
+					clean() {
+						parent.app.f5(); // 刷新父页面列表
+						sa.closeCurrIframe(); // 关闭本页
+					},
+
+					newPwdChange(v) {
+						let len = v.length;
+						this.pwdError = '';
+						if (!this.checkStong(v)) {
+							this.pwdError = '密码长度8-16位,至少包含一个数字、一个大写字母、一个小写字母以及!@#$%^&*?之一'
+							return;
+						}
+						if (len >= 3) {
+							let s = v.toLowerCase();
+							for (let i = 0; i < len - 2; i++) {
+								let charStr = s.substring(i, i + 3);
+								if (this.checkStr(charStr)) {
+									this.pwdError = '密码不应该采用连续升序或者连续降序'
+									return;
+								}
+							}
+						}
+					},
+					newPwd2Change(v) {
+						let len = v.length;
+						this.newPwd2Error = '';
+						if (this.m.password != v) {
+							this.newPwd2Error = '两次输入密码不一致';
+							return;
+						}
+					},
+					checkStr(charStr) {
+						return numStr.indexOf(charStr) != -1 || varStr.indexOf(charStr) != -1 || numStrDesc.indexOf(
+							charStr) != -1 || varStrDesc.indexOf(charStr) != -1;
+					},
+					checkStong(v) {
+						let pattern = /^.*(?=.{8,16})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/;
+						return pattern.test(v);
+					},
+				},
+				mounted: function() {
+					// 加载角色
+					sa.ajax('/role/getCustomerRoleList', {
+						customerId: this.m.customerId
+					}, function(res) {
+						this.roleList = res.data; // 数据
+					}.bind(this), {
+						msg: null
+					});
+				}
+			})
+		</script>
+	</body>
+</html>

+ 34 - 0
sp-admin/sa-view/tb-partner/customer-admin-list.html

@@ -90,6 +90,10 @@
     </el-dialog>
 </div>
 <script>
+	const numStr = "123456789";
+	const numStrDesc = "987654321";
+	const varStr = "abcdefghijklmnopkrstuvwxyz"
+	const varStrDesc = "zyxwvutsrkpomnlkjihgfedcba"
     var app = new Vue({
         components: {
             "sa-item": httpVueLoader('../../sa-frame/com/sa-item.vue'),
@@ -203,16 +207,46 @@
             },
             // 修改密码
             updatePassword: function (data) {
+				let that=this;
                 layer.prompt({title: '修改密码'}, function (pass, index) {
                     layer.close(index);
                     if (pass.length < 4) {
                         return layer.msg('新密码长度请不要低于4位');
                     }
+					let result = that.newPwdChange(pass);
+					if (!result) {
+						return;
+					}
                     sa.ajax('/admin/updatePassword', {id: data.id, password: pass}, function (res) {
                         layer.msg('修改成功');
                     })
                 });
             },
+			newPwdChange(v) {
+				let len = v.length;
+				if (!this.checkStong(v)) {
+					layer.msg('密码长度8-16位,至少包含一个数字、一个大写字母、一个小写字母以及!@#$%^&*?之一')
+					return false;
+				}
+				if (len >= 3) {
+					let s = v.toLowerCase();
+					for (let i = 0; i < len - 2; i++) {
+						let charStr = s.substring(i, i + 3);
+						if (this.checkStr(charStr)) {
+							layer.msg('密码不应该采用连续升序或者连续降序');
+							return false;
+						}
+					}
+				}
+			},
+			checkStr(charStr) {
+				return numStr.indexOf(charStr) != -1 || varStr.indexOf(charStr) != -1 || numStrDesc.indexOf(
+					charStr) != -1 || varStrDesc.indexOf(charStr) != -1;
+			},
+			checkStong(v) {
+				let pattern = /^.*(?=.{8,16})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,})(?=.*[!@#$%^&*?\(\)]).*$/;
+				return pattern.test(v);
+			},
             // 修改角色
             updateRoleId: function (data, roleId, roleName) {
                 if (data.id == sa.$sys.getCurrUser().id) {

+ 1 - 1
sp-admin/sa-view/tb-partner/tb-partner-add.html

@@ -91,7 +91,7 @@
         },
         methods: {
             getGoodsList() {
-                sa.ajax('/TbGoods/getList', function (resp) {
+                sa.ajax('/TbGoods/getList',{pageNo:1,pageSize:50}, function (resp) {
                     this.goodsList = resp.data;
                 }.bind(this));
             },

+ 4351 - 0
sp-admin/static/kj/jsencrypt.js

@@ -0,0 +1,4351 @@
+/*! JSEncrypt v2.3.1 | https://npmcdn.com/jsencrypt@2.3.1/LICENSE.txt */
+(function (root, factory) {
+  if (typeof define === 'function' && define.amd) {
+    // AMD
+    define(['exports'], factory);
+  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
+    // Node, CommonJS-like
+    factory(module.exports);
+  } else {
+    factory(root);
+  }
+})(this, function (exports) {
+  // Copyright (c) 2005  Tom Wu
+// All Rights Reserved.
+// See "LICENSE" for details.
+
+// Basic JavaScript BN library - subset useful for RSA encryption.
+
+// Bits per digit
+var dbits;
+
+// JavaScript engine analysis
+var canary = 0xdeadbeefcafe;
+var j_lm = ((canary&0xffffff)==0xefcafe);
+
+// (public) Constructor
+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);
+}
+
+// return new, unset BigInteger
+function nbi() { return new BigInteger(null); }
+
+// 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, 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, 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_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
+var BI_RC = new Array();
+var rr,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 int2char(n) { return BI_RM.charAt(n); }
+function intAt(s,i) {
+  var c = BI_RC[s.charCodeAt(i)];
+  return (c==null)?-1:c;
+}
+
+// (protected) copy this to r
+function bnpCopyTo(r) {
+  for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
+  r.t = this.t;
+  r.s = this.s;
+}
+
+// (protected) set from integer value x, -DV <= x < DV
+function bnpFromInt(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;
+}
+
+// return bigint initialized to value
+function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
+
+// (protected) set from string and radix
+function bnpFromString(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, mi = false, 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);
+}
+
+// (protected) clamp off excess high words
+function bnpClamp() {
+  var c = this.s&this.DM;
+  while(this.t > 0 && this[this.t-1] == c) --this.t;
+}
+
+// (public) return string representation in given radix
+function bnToString(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, d, m = false, r = "", 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";
+}
+
+// (public) -this
+function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
+
+// (public) |this|
+function bnAbs() { return (this.s<0)?this.negate():this; }
+
+// (public) return + if this > a, - if this < a, 0 if equal
+function bnCompareTo(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;
+}
+
+// returns bit length of the integer x
+function nbits(x) {
+  var r = 1, 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;
+}
+
+// (public) return the number of bits in "this"
+function bnBitLength() {
+  if(this.t <= 0) return 0;
+  return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
+}
+
+// (protected) r = this << n*DB
+function bnpDLShiftTo(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;
+}
+
+// (protected) r = this >> n*DB
+function bnpDRShiftTo(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;
+}
+
+// (protected) r = this << n
+function bnpLShiftTo(n,r) {
+  var bs = n%this.DB;
+  var cbs = this.DB-bs;
+  var bm = (1<<cbs)-1;
+  var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
+  for(i = this.t-1; i >= 0; --i) {
+    r[i+ds+1] = (this[i]>>cbs)|c;
+    c = (this[i]&bm)<<bs;
+  }
+  for(i = ds-1; i >= 0; --i) r[i] = 0;
+  r[ds] = c;
+  r.t = this.t+ds+1;
+  r.s = this.s;
+  r.clamp();
+}
+
+// (protected) r = this >> n
+function bnpRShiftTo(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();
+}
+
+// (protected) r = this - a
+function bnpSubTo(a,r) {
+  var i = 0, c = 0, 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();
+}
+
+// (protected) r = this * a, r != this,a (HAC 14.12)
+// "this" should be the larger one if appropriate.
+function bnpMultiplyTo(a,r) {
+  var x = this.abs(), 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);
+}
+
+// (protected) r = this^2, r != this (HAC 14.16)
+function bnpSquareTo(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();
+}
+
+// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
+// r != q, this != m.  q or r may be null.
+function bnpDivRemTo(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(), ts = this.s, 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, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
+  var i = r.t, j = i-ys, 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);
+}
+
+// (public) this mod a
+function bnMod(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;
+}
+
+// Modular reduction using "classic" algorithm
+function Classic(m) { this.m = m; }
+function cConvert(x) {
+  if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
+  else return x;
+}
+function cRevert(x) { return x; }
+function cReduce(x) { x.divRemTo(this.m,null,x); }
+function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+
+Classic.prototype.convert = cConvert;
+Classic.prototype.revert = cRevert;
+Classic.prototype.reduce = cReduce;
+Classic.prototype.mulTo = cMulTo;
+Classic.prototype.sqrTo = cSqrTo;
+
+// (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.
+function bnpInvDigit() {
+  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;
+}
+
+// Montgomery reduction
+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;
+}
+
+// xR mod m
+function montConvert(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;
+}
+
+// x/R mod m
+function montRevert(x) {
+  var r = nbi();
+  x.copyTo(r);
+  this.reduce(r);
+  return r;
+}
+
+// x = x/R mod m (HAC 14.32)
+function montReduce(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);
+}
+
+// r = "x^2/R mod m"; x != r
+function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+
+// r = "xy/R mod m"; x,y != r
+function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+
+Montgomery.prototype.convert = montConvert;
+Montgomery.prototype.revert = montRevert;
+Montgomery.prototype.reduce = montReduce;
+Montgomery.prototype.mulTo = montMulTo;
+Montgomery.prototype.sqrTo = montSqrTo;
+
+// (protected) true iff this is even
+function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
+
+// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
+function bnpExp(e,z) {
+  if(e > 0xffffffff || e < 1) return BigInteger.ONE;
+  var r = nbi(), r2 = nbi(), g = z.convert(this), 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);
+}
+
+// (public) this^e % m, 0 <= e < 2^32
+function bnModPowInt(e,m) {
+  var z;
+  if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
+  return this.exp(e,z);
+}
+
+// protected
+BigInteger.prototype.copyTo = bnpCopyTo;
+BigInteger.prototype.fromInt = bnpFromInt;
+BigInteger.prototype.fromString = bnpFromString;
+BigInteger.prototype.clamp = bnpClamp;
+BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
+BigInteger.prototype.drShiftTo = bnpDRShiftTo;
+BigInteger.prototype.lShiftTo = bnpLShiftTo;
+BigInteger.prototype.rShiftTo = bnpRShiftTo;
+BigInteger.prototype.subTo = bnpSubTo;
+BigInteger.prototype.multiplyTo = bnpMultiplyTo;
+BigInteger.prototype.squareTo = bnpSquareTo;
+BigInteger.prototype.divRemTo = bnpDivRemTo;
+BigInteger.prototype.invDigit = bnpInvDigit;
+BigInteger.prototype.isEven = bnpIsEven;
+BigInteger.prototype.exp = bnpExp;
+
+// public
+BigInteger.prototype.toString = bnToString;
+BigInteger.prototype.negate = bnNegate;
+BigInteger.prototype.abs = bnAbs;
+BigInteger.prototype.compareTo = bnCompareTo;
+BigInteger.prototype.bitLength = bnBitLength;
+BigInteger.prototype.mod = bnMod;
+BigInteger.prototype.modPowInt = bnModPowInt;
+
+// "constants"
+BigInteger.ZERO = nbv(0);
+BigInteger.ONE = nbv(1);
+
+// Copyright (c) 2005-2009  Tom Wu
+// All Rights Reserved.
+// See "LICENSE" for details.
+
+// Extended JavaScript BN functions, required for RSA private ops.
+
+// Version 1.1: new BigInteger("0", 10) returns "proper" zero
+// Version 1.2: square() API, isProbablePrime fix
+
+// (public)
+function bnClone() { var r = nbi(); this.copyTo(r); return r; }
+
+// (public) return value as integer
+function bnIntValue() {
+  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];
+}
+
+// (public) return value as byte
+function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
+
+// (public) return value as short (assumes DB>=16)
+function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
+
+// (protected) return x s.t. r^x < DV
+function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
+
+// (public) 0 if this == 0, 1 if this > 0
+function bnSigNum() {
+  if(this.s < 0) return -1;
+  else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
+  else return 1;
+}
+
+// (protected) convert to radix string
+function bnpToRadix(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), y = nbi(), z = nbi(), 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;
+}
+
+// (protected) convert from radix string
+function bnpFromRadix(s,b) {
+  this.fromInt(0);
+  if(b == null) b = 10;
+  var cs = this.chunkSize(b);
+  var d = Math.pow(b,cs), mi = false, j = 0, 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);
+}
+
+// (protected) alternate constructor
+function bnpFromNumber(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 = new Array(), 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);
+  }
+}
+
+// (public) convert to bigendian byte array
+function bnToByteArray() {
+  var i = this.t, r = new Array();
+  r[0] = this.s;
+  var p = this.DB-(i*this.DB)%8, d, 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;
+}
+
+function bnEquals(a) { return(this.compareTo(a)==0); }
+function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
+function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
+
+// (protected) r = this op a (bitwise)
+function bnpBitwiseTo(a,op,r) {
+  var i, f, 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();
+}
+
+// (public) this & a
+function op_and(x,y) { return x&y; }
+function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
+
+// (public) this | a
+function op_or(x,y) { return x|y; }
+function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
+
+// (public) this ^ a
+function op_xor(x,y) { return x^y; }
+function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
+
+// (public) this & ~a
+function op_andnot(x,y) { return x&~y; }
+function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
+
+// (public) ~this
+function bnNot() {
+  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;
+}
+
+// (public) this << n
+function bnShiftLeft(n) {
+  var r = nbi();
+  if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
+  return r;
+}
+
+// (public) this >> n
+function bnShiftRight(n) {
+  var r = nbi();
+  if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
+  return r;
+}
+
+// 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;
+}
+
+// (public) returns index of lowest 1-bit (or -1 if none)
+function bnGetLowestSetBit() {
+  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;
+}
+
+// return number of 1 bits in x
+function cbit(x) {
+  var r = 0;
+  while(x != 0) { x &= x-1; ++r; }
+  return r;
+}
+
+// (public) return number of set bits
+function bnBitCount() {
+  var r = 0, x = this.s&this.DM;
+  for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
+  return r;
+}
+
+// (public) true iff nth bit is set
+function bnTestBit(n) {
+  var j = Math.floor(n/this.DB);
+  if(j >= this.t) return(this.s!=0);
+  return((this[j]&(1<<(n%this.DB)))!=0);
+}
+
+// (protected) this op (1<<n)
+function bnpChangeBit(n,op) {
+  var r = BigInteger.ONE.shiftLeft(n);
+  this.bitwiseTo(r,op,r);
+  return r;
+}
+
+// (public) this | (1<<n)
+function bnSetBit(n) { return this.changeBit(n,op_or); }
+
+// (public) this & ~(1<<n)
+function bnClearBit(n) { return this.changeBit(n,op_andnot); }
+
+// (public) this ^ (1<<n)
+function bnFlipBit(n) { return this.changeBit(n,op_xor); }
+
+// (protected) r = this + a
+function bnpAddTo(a,r) {
+  var i = 0, c = 0, 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();
+}
+
+// (public) this + a
+function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
+
+// (public) this - a
+function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
+
+// (public) this * a
+function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
+
+// (public) this^2
+function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
+
+// (public) this / a
+function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
+
+// (public) this % a
+function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
+
+// (public) [this/a,this%a]
+function bnDivideAndRemainder(a) {
+  var q = nbi(), r = nbi();
+  this.divRemTo(a,q,r);
+  return new Array(q,r);
+}
+
+// (protected) this *= n, this >= 0, 1 < n < DV
+function bnpDMultiply(n) {
+  this[this.t] = this.am(0,n-1,this,0,0,this.t);
+  ++this.t;
+  this.clamp();
+}
+
+// (protected) this += n << w words, this >= 0
+function bnpDAddOffset(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];
+  }
+}
+
+// A "null" reducer
+function NullExp() {}
+function nNop(x) { return x; }
+function nMulTo(x,y,r) { x.multiplyTo(y,r); }
+function nSqrTo(x,r) { x.squareTo(r); }
+
+NullExp.prototype.convert = nNop;
+NullExp.prototype.revert = nNop;
+NullExp.prototype.mulTo = nMulTo;
+NullExp.prototype.sqrTo = nSqrTo;
+
+// (public) this^e
+function bnPow(e) { return this.exp(e,new NullExp()); }
+
+// (protected) r = lower n words of "this * a", a.t <= n
+// "this" should be the larger one if appropriate.
+function bnpMultiplyLowerTo(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;
+  var j;
+  for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
+  for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
+  r.clamp();
+}
+
+// (protected) r = "this * a" without lower n words, n > 0
+// "this" should be the larger one if appropriate.
+function bnpMultiplyUpperTo(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);
+}
+
+// Barrett modular reduction
+function Barrett(m) {
+  // setup Barrett
+  this.r2 = nbi();
+  this.q3 = nbi();
+  BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
+  this.mu = this.r2.divide(m);
+  this.m = m;
+}
+
+function barrettConvert(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; }
+}
+
+function barrettRevert(x) { return x; }
+
+// x = x mod m (HAC 14.42)
+function barrettReduce(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);
+}
+
+// r = x^2 mod m; x != r
+function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+
+// r = x*y mod m; x,y != r
+function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+
+Barrett.prototype.convert = barrettConvert;
+Barrett.prototype.revert = barrettRevert;
+Barrett.prototype.reduce = barrettReduce;
+Barrett.prototype.mulTo = barrettMulTo;
+Barrett.prototype.sqrTo = barrettSqrTo;
+
+// (public) this^e % m (HAC 14.85)
+function bnModPow(e,m) {
+  var i = e.bitLength(), k, r = nbv(1), 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 = new Array(), n = 3, k1 = k-1, 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, w, is1 = true, r2 = nbi(), 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);
+}
+
+// (public) gcd(this,a) (HAC 14.54)
+function bnGCD(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(), 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;
+}
+
+// (protected) this % n, n < 2^26
+function bnpModInt(n) {
+  if(n <= 0) return 0;
+  var d = this.DV%n, 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;
+}
+
+// (public) 1/this % m (HAC 14.61)
+function bnModInverse(m) {
+  var ac = m.isEven();
+  if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
+  var u = m.clone(), v = this.clone();
+  var a = nbv(1), b = nbv(0), c = nbv(0), 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;
+}
+
+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];
+
+// (public) test primality with certainty >= 1-.5^t
+function bnIsProbablePrime(t) {
+  var i, 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], 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);
+}
+
+// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
+function bnpMillerRabin(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;
+}
+
+// protected
+BigInteger.prototype.chunkSize = bnpChunkSize;
+BigInteger.prototype.toRadix = bnpToRadix;
+BigInteger.prototype.fromRadix = bnpFromRadix;
+BigInteger.prototype.fromNumber = bnpFromNumber;
+BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
+BigInteger.prototype.changeBit = bnpChangeBit;
+BigInteger.prototype.addTo = bnpAddTo;
+BigInteger.prototype.dMultiply = bnpDMultiply;
+BigInteger.prototype.dAddOffset = bnpDAddOffset;
+BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
+BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
+BigInteger.prototype.modInt = bnpModInt;
+BigInteger.prototype.millerRabin = bnpMillerRabin;
+
+// public
+BigInteger.prototype.clone = bnClone;
+BigInteger.prototype.intValue = bnIntValue;
+BigInteger.prototype.byteValue = bnByteValue;
+BigInteger.prototype.shortValue = bnShortValue;
+BigInteger.prototype.signum = bnSigNum;
+BigInteger.prototype.toByteArray = bnToByteArray;
+BigInteger.prototype.equals = bnEquals;
+BigInteger.prototype.min = bnMin;
+BigInteger.prototype.max = bnMax;
+BigInteger.prototype.and = bnAnd;
+BigInteger.prototype.or = bnOr;
+BigInteger.prototype.xor = bnXor;
+BigInteger.prototype.andNot = bnAndNot;
+BigInteger.prototype.not = bnNot;
+BigInteger.prototype.shiftLeft = bnShiftLeft;
+BigInteger.prototype.shiftRight = bnShiftRight;
+BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
+BigInteger.prototype.bitCount = bnBitCount;
+BigInteger.prototype.testBit = bnTestBit;
+BigInteger.prototype.setBit = bnSetBit;
+BigInteger.prototype.clearBit = bnClearBit;
+BigInteger.prototype.flipBit = bnFlipBit;
+BigInteger.prototype.add = bnAdd;
+BigInteger.prototype.subtract = bnSubtract;
+BigInteger.prototype.multiply = bnMultiply;
+BigInteger.prototype.divide = bnDivide;
+BigInteger.prototype.remainder = bnRemainder;
+BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
+BigInteger.prototype.modPow = bnModPow;
+BigInteger.prototype.modInverse = bnModInverse;
+BigInteger.prototype.pow = bnPow;
+BigInteger.prototype.gcd = bnGCD;
+BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
+
+// JSBN-specific extension
+BigInteger.prototype.square = bnSquare;
+
+// BigInteger interfaces not implemented in jsbn:
+
+// BigInteger(int signum, byte[] magnitude)
+// double doubleValue()
+// float floatValue()
+// int hashCode()
+// long longValue()
+// static BigInteger valueOf(long val)
+
+// prng4.js - uses Arcfour as a PRNG
+
+function Arcfour() {
+  this.i = 0;
+  this.j = 0;
+  this.S = new Array();
+}
+
+// Initialize arcfour context from key, an array of ints, each from [0..255]
+function ARC4init(key) {
+  var i, j, 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;
+}
+
+function ARC4next() {
+  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];
+}
+
+Arcfour.prototype.init = ARC4init;
+Arcfour.prototype.next = ARC4next;
+
+// 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;
+var rng_pptr;
+
+// Initialize the pool with junk if needed.
+if(rng_pool == null) {
+  rng_pool = new Array();
+  rng_pptr = 0;
+  var t;
+  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 = function(ev) {
+    this.count = this.count || 0;
+    if (this.count >= 256 || rng_pptr >= rng_psize) {
+      if (window.removeEventListener)
+        window.removeEventListener("mousemove", onMouseMoveListener, false);
+      else if (window.detachEvent)
+        window.detachEvent("onmousemove", onMouseMoveListener);
+      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, false);
+  else if (window.attachEvent)
+    window.attachEvent("onmousemove", onMouseMoveListener);
+
+}
+
+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();
+}
+
+function rng_get_bytes(ba) {
+  var i;
+  for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
+}
+
+function SecureRandom() {}
+
+SecureRandom.prototype.nextBytes = rng_get_bytes;
+
+// Depends on jsbn.js and rng.js
+
+// Version 1.1: support utf-8 encoding in pkcs1pad2
+
+// convert a (hex) string to a bignum object
+function parseBigInt(str,r) {
+  return new BigInteger(str,r);
+}
+
+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);
+}
+
+// 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 = new Array();
+  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 = new Array();
+  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
+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;
+}
+
+// Set the public key fields N and e from hex strings
+function RSASetPublic(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");
+}
+
+// Perform raw public operation on "x": return x^e (mod n)
+function RSADoPublic(x) {
+  return x.modPowInt(this.e, this.n);
+}
+
+// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
+function RSAEncrypt(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;
+}
+
+// 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;
+//}
+
+// protected
+RSAKey.prototype.doPublic = RSADoPublic;
+
+// public
+RSAKey.prototype.setPublic = RSASetPublic;
+RSAKey.prototype.encrypt = RSAEncrypt;
+//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
+
+// Depends on rsa.js and jsbn2.js
+
+// Version 1.1: support utf-8 decoding in pkcs1unpad2
+
+// 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;
+}
+
+// Set the private key fields N, e, and d from hex strings
+function RSASetPrivate(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");
+}
+
+// Set the private key fields N, e, d and CRT params from hex strings
+function RSASetPrivateEx(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");
+}
+
+// Generate a new random private key B bits long, using public expt E
+function RSAGenerate(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;
+    }
+  }
+}
+
+// Perform raw private operation on "x": return x^d (mod n)
+function RSADoPrivate(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);
+}
+
+// Return the PKCS#1 RSA decryption of "ctext".
+// "ctext" is an even-length hex string and the output is a plain string.
+function RSADecrypt(ctext) {
+  var c = parseBigInt(ctext, 16);
+  var m = this.doPrivate(c);
+  if(m == null) return null;
+  return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
+}
+
+// Return the PKCS#1 RSA decryption of "ctext".
+// "ctext" is a Base64-encoded string and the output is a plain string.
+//function RSAB64Decrypt(ctext) {
+//  var h = b64tohex(ctext);
+//  if(h) return this.decrypt(h); else return null;
+//}
+
+// protected
+RSAKey.prototype.doPrivate = RSADoPrivate;
+
+// public
+RSAKey.prototype.setPrivate = RSASetPrivate;
+RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
+RSAKey.prototype.generate = RSAGenerate;
+RSAKey.prototype.decrypt = RSADecrypt;
+//RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
+
+// Copyright (c) 2011  Kevin M Burns Jr.
+// All Rights Reserved.
+// See "LICENSE" for details.
+//
+// Extension to jsbn which adds facilities for asynchronous RSA key generation
+// Primarily created to avoid execution timeout on mobile devices
+//
+// http://www-cs-students.stanford.edu/~tjw/jsbn/
+//
+// ---
+
+(function(){
+
+// Generate a new random private key B bits long, using public expt E
+var RSAGenerateAsync = function (B, E, callback) {
+    //var rng = new SeededRandom();
+    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.generateAsync = RSAGenerateAsync;
+
+// Public API method
+var bnGCDAsync = 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(),
+        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);
+};
+BigInteger.prototype.gcda = bnGCDAsync;
+
+// (protected) alternate constructor
+var bnpFromNumberAsync = 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 = this;
+      var bnpfn1 = function(){
+        bnp.dAddOffset(2,0);
+        if(bnp.bitLength() > a) bnp.subTo(BigInteger.ONE.shiftLeft(a-1),bnp);
+        if(bnp.isProbablePrime(b)) {
+            setTimeout(function(){callback()},0); // escape
+        } else {
+            setTimeout(bnpfn1,0);
+        }
+      };
+      setTimeout(bnpfn1,0);
+    }
+  } else {
+    var x = new Array(), 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.fromNumberAsync = bnpFromNumberAsync;
+
+})();
+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;
+  for(i = 0; i < s.length; ++i) {
+    if(s.charAt(i) == b64pad) break;
+    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;
+}
+
+// convert a base64 string to a byte/number array
+function b64toBA(s) {
+  //piggyback on b64tohex for now, optimize later
+  var h = b64tohex(s);
+  var i;
+  var a = new Array();
+  for(i = 0; 2*i < h.length; ++i) {
+    a[i] = parseInt(h.substring(2*i,2*i+2),16);
+  }
+  return a;
+}
+
+/*! asn1-1.0.2.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license
+ */
+
+var JSX = JSX || {};
+JSX.env = JSX.env || {};
+
+var L = JSX, OP = Object.prototype, FUNCTION_TOSTRING = '[object Function]',ADD = ["toString", "valueOf"];
+
+JSX.env.parseUA = function(agent) {
+
+    var numberify = function(s) {
+        var c = 0;
+        return parseFloat(s.replace(/\./g, function() {
+            return (c++ == 1) ? '' : '.';
+        }));
+    },
+
+    nav = navigator,
+    o = {
+        ie: 0,
+        opera: 0,
+        gecko: 0,
+        webkit: 0,
+        chrome: 0,
+        mobile: null,
+        air: 0,
+        ipad: 0,
+        iphone: 0,
+        ipod: 0,
+        ios: null,
+        android: 0,
+        webos: 0,
+        caja: nav && nav.cajaVersion,
+        secure: false,
+        os: null
+
+    },
+
+    ua = agent || (navigator && navigator.userAgent),
+    loc = window && window.location,
+    href = loc && loc.href,
+    m;
+
+    o.secure = href && (href.toLowerCase().indexOf("https") === 0);
+
+    if (ua) {
+
+        if ((/windows|win32/i).test(ua)) {
+            o.os = 'windows';
+        } else if ((/macintosh/i).test(ua)) {
+            o.os = 'macintosh';
+        } else if ((/rhino/i).test(ua)) {
+            o.os = 'rhino';
+        }
+        if ((/KHTML/).test(ua)) {
+            o.webkit = 1;
+        }
+        m = ua.match(/AppleWebKit\/([^\s]*)/);
+        if (m && m[1]) {
+            o.webkit = numberify(m[1]);
+            if (/ Mobile\//.test(ua)) {
+                o.mobile = 'Apple'; // iPhone or iPod Touch
+                m = ua.match(/OS ([^\s]*)/);
+                if (m && m[1]) {
+                    m = numberify(m[1].replace('_', '.'));
+                }
+                o.ios = m;
+                o.ipad = o.ipod = o.iphone = 0;
+                m = ua.match(/iPad|iPod|iPhone/);
+                if (m && m[0]) {
+                    o[m[0].toLowerCase()] = o.ios;
+                }
+            } else {
+                m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);
+                if (m) {
+                    o.mobile = m[0];
+                }
+                if (/webOS/.test(ua)) {
+                    o.mobile = 'WebOS';
+                    m = ua.match(/webOS\/([^\s]*);/);
+                    if (m && m[1]) {
+                        o.webos = numberify(m[1]);
+                    }
+                }
+                if (/ Android/.test(ua)) {
+                    o.mobile = 'Android';
+                    m = ua.match(/Android ([^\s]*);/);
+                    if (m && m[1]) {
+                        o.android = numberify(m[1]);
+                    }
+                }
+            }
+            m = ua.match(/Chrome\/([^\s]*)/);
+            if (m && m[1]) {
+                o.chrome = numberify(m[1]); // Chrome
+            } else {
+                m = ua.match(/AdobeAIR\/([^\s]*)/);
+                if (m) {
+                    o.air = m[0]; // Adobe AIR 1.0 or better
+                }
+            }
+        }
+        if (!o.webkit) {
+            m = ua.match(/Opera[\s\/]([^\s]*)/);
+            if (m && m[1]) {
+                o.opera = numberify(m[1]);
+                m = ua.match(/Version\/([^\s]*)/);
+                if (m && m[1]) {
+                    o.opera = numberify(m[1]); // opera 10+
+                }
+                m = ua.match(/Opera Mini[^;]*/);
+                if (m) {
+                    o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
+                }
+            } else { // not opera or webkit
+                m = ua.match(/MSIE\s([^;]*)/);
+                if (m && m[1]) {
+                    o.ie = numberify(m[1]);
+                } else { // not opera, webkit, or ie
+                    m = ua.match(/Gecko\/([^\s]*)/);
+                    if (m) {
+                        o.gecko = 1; // Gecko detected, look for revision
+                        m = ua.match(/rv:([^\s\)]*)/);
+                        if (m && m[1]) {
+                            o.gecko = numberify(m[1]);
+                        }
+                    }
+                }
+            }
+        }
+    }
+    return o;
+};
+
+JSX.env.ua = JSX.env.parseUA();
+
+JSX.isFunction = function(o) {
+    return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING;
+};
+
+JSX._IEEnumFix = (JSX.env.ua.ie) ? function(r, s) {
+    var i, fname, f;
+    for (i=0;i<ADD.length;i=i+1) {
+
+        fname = ADD[i];
+        f = s[fname];
+
+        if (L.isFunction(f) && f!=OP[fname]) {
+            r[fname]=f;
+        }
+    }
+} : function(){};
+
+JSX.extend = function(subc, superc, overrides) {
+    if (!superc||!subc) {
+        throw new Error("extend failed, please check that " +
+                        "all dependencies are included.");
+    }
+    var F = function() {}, i;
+    F.prototype=superc.prototype;
+    subc.prototype=new F();
+    subc.prototype.constructor=subc;
+    subc.superclass=superc.prototype;
+    if (superc.prototype.constructor == OP.constructor) {
+        superc.prototype.constructor=superc;
+    }
+
+    if (overrides) {
+        for (i in overrides) {
+            if (L.hasOwnProperty(overrides, i)) {
+                subc.prototype[i]=overrides[i];
+            }
+        }
+
+        L._IEEnumFix(subc.prototype, overrides);
+    }
+};
+
+/*
+ * asn1.js - ASN.1 DER encoder classes
+ *
+ * Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
+ *
+ * This software is licensed under the terms of the MIT License.
+ * http://kjur.github.com/jsrsasign/license
+ *
+ * The above copyright and license notice shall be 
+ * included in all copies or substantial portions of the Software.
+ */
+
+/**
+ * @fileOverview
+ * @name asn1-1.0.js
+ * @author Kenji Urushima kenji.urushima@gmail.com
+ * @version 1.0.2 (2013-May-30)
+ * @since 2.1
+ * @license <a href="http://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
+ */
+if (typeof KJUR == "undefined" || !KJUR) 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>{@link KJUR.asn1.DERBoolean}</li>
+ * <li>{@link KJUR.asn1.DERInteger}</li>
+ * <li>{@link KJUR.asn1.DERBitString}</li>
+ * <li>{@link KJUR.asn1.DEROctetString}</li>
+ * <li>{@link KJUR.asn1.DERNull}</li>
+ * <li>{@link KJUR.asn1.DERObjectIdentifier}</li>
+ * <li>{@link KJUR.asn1.DERUTF8String}</li>
+ * <li>{@link KJUR.asn1.DERNumericString}</li>
+ * <li>{@link KJUR.asn1.DERPrintableString}</li>
+ * <li>{@link KJUR.asn1.DERTeletexString}</li>
+ * <li>{@link KJUR.asn1.DERIA5String}</li>
+ * <li>{@link KJUR.asn1.DERUTCTime}</li>
+ * <li>{@link KJUR.asn1.DERGeneralizedTime}</li>
+ * <li>{@link KJUR.asn1.DERSequence}</li>
+ * <li>{@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>
+ * </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
+ * @classs 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
+     * @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) {
+	var dataWA = CryptoJS.enc.Hex.parse(dataHex);
+	var dataB64 = CryptoJS.enc.Base64.stringify(dataWA);
+	var pemBody = dataB64.replace(/(.{64})/g, "$1\r\n");
+        pemBody = pemBody.replace(/\r\n$/, '');
+	return "-----BEGIN " + pemHeader + "-----\r\n" + 
+               pemBody + 
+               "\r\n-----END " + pemHeader + "-----\r\n";
+    };
+};
+
+// ********************************************************************
+//  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 isModified = true;
+    var hTLV = null;
+    var hT = '00'
+    var hL = '00';
+    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;
+	    //console.error("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);
+    var s = null;
+    var hV = null;
+
+    /**
+     * 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['str'] != "undefined") {
+	    this.setString(params['str']);
+	} else if (typeof params['hex'] != "undefined") {
+	    this.setStringHex(params['hex']);
+	}
+    }
+};
+JSX.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);
+    var s = null;
+    var date = null;
+
+    // --- PRIVATE METHODS --------------------
+    this.localDateToUTC = function(d) {
+	utc = d.getTime() + (d.getTimezoneOffset() * 60000);
+	var utcDate = new Date(utc);
+	return utcDate;
+    };
+
+    this.formatDate = function(dateObject, type) {
+	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);
+	return year + month + day + hour + min + sec + '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(this.s);
+    };
+
+    /**
+     * 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;
+    };
+};
+JSX.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);
+    var asn1Array = null;
+
+    /**
+     * 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'];
+	}
+    }
+};
+JSX.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";
+};
+JSX.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.
+     */
+    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['hex'] != "undefined") {
+	    this.setValueHex(params['hex']);
+	}
+    }
+};
+JSX.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>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERBitString = function(params) {
+    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
+     * @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.
+     */
+    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
+     * @name setByBooleanArray
+     * @memberOf KJUR.asn1.DERBitString
+     * @function
+     * @param {array} booleanArray array of boolean (ex. [true, false, true])
+     * @description
+     * NOTE: Trailing falses will be ignored.
+     */
+    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 false with specified length
+     * @name newFalseArray
+     * @memberOf KJUR.asn1.DERBitString
+     * @function
+     * @param {Integer} nLength length of array to generate
+     * @return {array} array of boolean faluse
+     * @description
+     * This static method may be useful to initialize boolean array.
+     */
+    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['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']);
+	}
+    }
+};
+JSX.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
+
+// ********************************************************************
+/**
+ * class for ASN.1 DER OctetString
+ * @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
+ * @see KJUR.asn1.DERAbstractString - superclass
+ */
+KJUR.asn1.DEROctetString = function(params) {
+    KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
+    this.hT = "04";
+};
+JSX.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";
+};
+JSX.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
+     * @name setValueOidString
+     * @memberOf KJUR.asn1.DERObjectIdentifier
+     * @function
+     * @param {String} oidString OID string (ex. 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.
+     */
+    this.setValueName = function(oidName) {
+	if (typeof KJUR.asn1.x509.OID.name2oidList[oidName] != "undefined") {
+	    var oid = KJUR.asn1.x509.OID.name2oidList[oidName];
+	    this.setValueOidString(oid);
+	} else {
+	    throw "DERObjectIdentifier oidName undefined: " + oidName;
+	}
+    };
+
+    this.getFreshValueHex = function() {
+	return this.hV;
+    };
+
+    if (typeof params != "undefined") {
+	if (typeof params['oid'] != "undefined") {
+	    this.setValueOidString(params['oid']);
+	} else if (typeof params['hex'] != "undefined") {
+	    this.setValueHex(params['hex']);
+	} else if (typeof params['name'] != "undefined") {
+	    this.setValueName(params['name']);
+	}
+    }
+};
+JSX.extend(KJUR.asn1.DERObjectIdentifier, 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";
+};
+JSX.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";
+};
+JSX.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";
+};
+JSX.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";
+};
+JSX.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";
+};
+JSX.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
+ * var d1 = new KJUR.asn1.DERUTCTime();
+ * d1.setString('130430125959Z');
+ *
+ * var d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
+ *
+ * var d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
+ */
+KJUR.asn1.DERUTCTime = function(params) {
+    KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
+    this.hT = "17";
+
+    /**
+     * set value by a Date object
+     * @name setByDate
+     * @memberOf KJUR.asn1.DERUTCTime
+     * @function
+     * @param {Date} dateObject Date object to set ASN.1 value(V)
+     */
+    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);
+    };
+
+    if (typeof params != "undefined") {
+	if (typeof params['str'] != "undefined") {
+	    this.setString(params['str']);
+	} else if (typeof params['hex'] != "undefined") {
+	    this.setStringHex(params['hex']);
+	} else if (typeof params['date'] != "undefined") {
+	    this.setByDate(params['date']);
+	}
+    }
+};
+JSX.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'})
+ * @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>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERGeneralizedTime = function(params) {
+    KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
+    this.hT = "18";
+
+    /**
+     * 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/>
+     * var o = new DERUTCTime();
+     * var date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
+     * o.setByDate(date);
+     */
+    this.setByDate = function(dateObject) {
+	this.hTLV = null;
+	this.isModified = true;
+	this.date = dateObject;
+	this.s = this.formatDate(this.date, 'gen');
+	this.hV = stohex(this.s);
+    };
+
+    if (typeof params != "undefined") {
+	if (typeof params['str'] != "undefined") {
+	    this.setString(params['str']);
+	} else if (typeof params['hex'] != "undefined") {
+	    this.setStringHex(params['hex']);
+	} else if (typeof params['date'] != "undefined") {
+	    this.setByDate(params['date']);
+	}
+    }
+};
+JSX.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;
+    };
+};
+JSX.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>
+ * </ul>
+ * NOTE: 'params' can be omitted.
+ */
+KJUR.asn1.DERSet = function(params) {
+    KJUR.asn1.DERSet.superclass.constructor.call(this, params);
+    this.hT = "31";
+    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());
+	}
+	a.sort();
+	this.hV = a.join('');
+	return this.hV;
+    };
+};
+JSX.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);
+	}
+    }
+};
+JSX.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
+// 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 */
+(function (undefined) {
+"use strict";
+
+var Hex = {},
+    decoder;
+
+Hex.decode = function(a) {
+    var i;
+    if (decoder === undefined) {
+        var hex = "0123456789ABCDEF",
+            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 = [],
+        bits = 0,
+        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 '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 "Hex encoding incomplete: 4 bits missing";
+    return out;
+};
+
+// export globals
+window.Hex = Hex;
+})();
+// 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 */
+(function (undefined) {
+"use strict";
+
+var Base64 = {},
+    decoder;
+
+Base64.decode = function (a) {
+    var i;
+    if (decoder === undefined) {
+        var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
+            ignore = "= \f\n\r\t\u00A0\u2028\u2029";
+        decoder = [];
+        for (i = 0; i < 64; ++i)
+            decoder[b64.charAt(i)] = i;
+        for (i = 0; i < ignore.length; ++i)
+            decoder[ignore.charAt(i)] = -1;
+    }
+    var out = [];
+    var bits = 0, 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 '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 "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;
+};
+
+Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
+Base64.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 "RegExp out of sync";
+    }
+    return Base64.decode(a);
+};
+
+// export globals
+window.Base64 = Base64;
+})();
+// ASN.1 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 */
+/*global oids */
+(function (undefined) {
+"use strict";
+
+var hardLimit = 100,
+    ellipsis = "\u2026",
+    DOM = {
+        tag: function (tagName, className) {
+            var t = document.createElement(tagName);
+            t.className = className;
+            return t;
+        },
+        text: function (str) {
+            return document.createTextNode(str);
+        }
+    };
+
+function Stream(enc, pos) {
+    if (enc instanceof Stream) {
+        this.enc = enc.enc;
+        this.pos = enc.pos;
+    } else {
+        this.enc = enc;
+        this.pos = pos;
+    }
+}
+Stream.prototype.get = function (pos) {
+    if (pos === undefined)
+        pos = this.pos++;
+    if (pos >= this.enc.length)
+        throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length;
+    return this.enc[pos];
+};
+Stream.prototype.hexDigits = "0123456789ABCDEF";
+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.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 = ""
+    for (var i = start; i < end; i += 2) {
+        var high_byte = this.get(i);
+        var low_byte = this.get(i + 1);
+        str += String.fromCharCode( (high_byte << 8) + low_byte );
+    }
+
+    return str;
+};
+Stream.prototype.reTime = /^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
+Stream.prototype.parseTime = function (start, end) {
+    var s = this.parseStringISO(start, end),
+        m = this.reTime.exec(s);
+    if (!m)
+        return "Unrecognized time: " + s;
+    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) {
+    //TODO support negative numbers
+    var len = end - start;
+    if (len > 4) {
+        len <<= 3;
+        var s = this.get(start);
+        if (s === 0)
+            len -= 8;
+        else
+            while (s < 128) {
+                s <<= 1;
+                --len;
+            }
+        return "(" + len + " bit)";
+    }
+    var n = 0;
+    for (var i = start; i < end; ++i)
+        n = (n << 8) | this.get(i);
+    return n;
+};
+Stream.prototype.parseBitString = function (start, end) {
+    var unusedBit = this.get(start),
+        lenBit = ((end - start - 1) << 3) - unusedBit,
+        s = "(" + lenBit + " bit)";
+    if (lenBit <= 20) {
+        var skip = unusedBit;
+        s += " ";
+        for (var i = end - 1; i > start; --i) {
+            var b = this.get(i);
+            for (var j = skip; j < 8; ++j)
+                s += (b >> j) & 1 ? "1" : "0";
+            skip = 0;
+        }
+    }
+    return s;
+};
+Stream.prototype.parseOctetString = function (start, end) {
+    var len = end - start,
+        s = "(" + len + " byte) ";
+    if (len > hardLimit)
+        end = start + hardLimit;
+    for (var i = start; i < end; ++i)
+        s += this.hexByte(this.get(i)); //TODO: also try Latin1?
+    if (len > hardLimit)
+        s += ellipsis;
+    return s;
+};
+Stream.prototype.parseOID = function (start, end) {
+    var s = '',
+        n = 0,
+        bits = 0;
+    for (var i = start; i < end; ++i) {
+        var v = this.get(i);
+        n = (n << 7) | (v & 0x7F);
+        bits += 7;
+        if (!(v & 0x80)) { // finished
+            if (s === '') {
+                var m = n < 80 ? n < 40 ? 0 : 1 : 2;
+                s = m + "." + (n - m * 40);
+            } else
+                s += "." + ((bits >= 31) ? "bigint" : n);
+            n = bits = 0;
+        }
+    }
+    return s;
+};
+
+function ASN1(stream, header, length, tag, sub) {
+    this.stream = stream;
+    this.header = header;
+    this.length = length;
+    this.tag = tag;
+    this.sub = sub;
+}
+ASN1.prototype.typeName = function () {
+    if (this.tag === undefined)
+        return "unknown";
+    var tagClass = this.tag >> 6,
+        tagConstructed = (this.tag >> 5) & 1,
+        tagNumber = this.tag & 0x1F;
+    switch (tagClass) {
+    case 0: // universal
+        switch (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";
+        default:   return "Universal_" + tagNumber.toString(16);
+        }
+    case 1: return "Application_" + tagNumber.toString(16);
+    case 2: return "[" + tagNumber + "]"; // Context
+    case 3: return "Private_" + tagNumber.toString(16);
+    }
+};
+ASN1.prototype.reSeemsASCII = /^[ -~]+$/;
+ASN1.prototype.content = function () {
+    if (this.tag === undefined)
+        return null;
+    var tagClass = this.tag >> 6,
+        tagNumber = this.tag & 0x1F,
+        content = this.posContent(),
+        len = Math.abs(this.length);
+    if (tagClass !== 0) { // universal
+        if (this.sub !== null)
+            return "(" + this.sub.length + " elem)";
+        //TODO: TRY TO PARSE ASCII STRING
+        var s = this.stream.parseStringISO(content, content + Math.min(len, hardLimit));
+        if (this.reSeemsASCII.test(s))
+            return s.substring(0, 2 * hardLimit) + ((s.length > 2 * hardLimit) ? ellipsis : "");
+        else
+            return this.stream.parseOctetString(content, content + len);
+    }
+    switch (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);
+    case 0x04: // OCTET_STRING
+        return this.sub ? "(" + this.sub.length + " elem)" :
+            this.stream.parseOctetString(content, content + len);
+    //case 0x05: // NULL
+    case 0x06: // OBJECT_IDENTIFIER
+        return this.stream.parseOID(content, content + len);
+    //case 0x07: // ObjectDescriptor
+    //case 0x08: // EXTERNAL
+    //case 0x09: // REAL
+    //case 0x0A: // ENUMERATED
+    //case 0x0B: // EMBEDDED_PDV
+    case 0x10: // SEQUENCE
+    case 0x11: // SET
+        return "(" + this.sub.length + " elem)";
+    case 0x0C: // UTF8String
+        return this.stream.parseStringUTF(content, content + len);
+    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 this.stream.parseStringISO(content, content + len);
+    case 0x1E: // BMPString
+        return this.stream.parseStringBMP(content, content + len);
+    case 0x17: // UTCTime
+    case 0x18: // GeneralizedTime
+        return this.stream.parseTime(content, content + len);
+    }
+    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.print = function (indent) {
+    if (indent === undefined) indent = '';
+    document.writeln(indent + this);
+    if (this.sub !== null) {
+        indent += '  ';
+        for (var i = 0, max = this.sub.length; i < max; ++i)
+            this.sub[i].print(indent);
+    }
+};
+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 & 0x20)
+        s += " (constructed)";
+    else if (((this.tag == 0x03) || (this.tag == 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.toDOM = function () {
+    var node = DOM.tag("div", "node");
+    node.asn1 = this;
+    var head = DOM.tag("div", "head");
+    var s = this.typeName().replace(/_/g, " ");
+    head.innerHTML = s;
+    var content = this.content();
+    if (content !== null) {
+        content = String(content).replace(/</g, "&lt;");
+        var preview = DOM.tag("span", "preview");
+        preview.appendChild(DOM.text(content));
+        head.appendChild(preview);
+    }
+    node.appendChild(head);
+    this.node = node;
+    this.head = head;
+    var value = DOM.tag("div", "value");
+    s = "Offset: " + this.stream.pos + "<br/>";
+    s += "Length: " + this.header + "+";
+    if (this.length >= 0)
+        s += this.length;
+    else
+        s += (-this.length) + " (undefined)";
+    if (this.tag & 0x20)
+        s += "<br/>(constructed)";
+    else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub !== null))
+        s += "<br/>(encapsulates)";
+    //TODO if (this.tag == 0x03) s += "Unused bits: "
+    if (content !== null) {
+        s += "<br/>Value:<br/><b>" + content + "</b>";
+        if ((typeof oids === 'object') && (this.tag == 0x06)) {
+            var oid = oids[content];
+            if (oid) {
+                if (oid.d) s += "<br/>" + oid.d;
+                if (oid.c) s += "<br/>" + oid.c;
+                if (oid.w) s += "<br/>(warning!)";
+            }
+        }
+    }
+    value.innerHTML = s;
+    node.appendChild(value);
+    var sub = DOM.tag("div", "sub");
+    if (this.sub !== null) {
+        for (var i = 0, max = this.sub.length; i < max; ++i)
+            sub.appendChild(this.sub[i].toDOM());
+    }
+    node.appendChild(sub);
+    head.onclick = function () {
+        node.className = (node.className == "node collapsed") ? "node" : "node collapsed";
+    };
+    return node;
+};
+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.fakeHover = function (current) {
+    this.node.className += " hover";
+    if (current)
+        this.head.className += " hover";
+};
+ASN1.prototype.fakeOut = function (current) {
+    var re = / ?hover/;
+    this.node.className = this.node.className.replace(re, "");
+    if (current)
+        this.head.className = this.head.className.replace(re, "");
+};
+ASN1.prototype.toHexDOM_sub = function (node, className, stream, start, end) {
+    if (start >= end)
+        return;
+    var sub = DOM.tag("span", className);
+    sub.appendChild(DOM.text(
+        stream.hexDump(start, end)));
+    node.appendChild(sub);
+};
+ASN1.prototype.toHexDOM = function (root) {
+    var node = DOM.tag("span", "hex");
+    if (root === undefined) root = node;
+    this.head.hexNode = node;
+    this.head.onmouseover = function () { this.hexNode.className = "hexCurrent"; };
+    this.head.onmouseout  = function () { this.hexNode.className = "hex"; };
+    node.asn1 = this;
+    node.onmouseover = function () {
+        var current = !root.selected;
+        if (current) {
+            root.selected = this.asn1;
+            this.className = "hexCurrent";
+        }
+        this.asn1.fakeHover(current);
+    };
+    node.onmouseout  = function () {
+        var current = (root.selected == this.asn1);
+        this.asn1.fakeOut(current);
+        if (current) {
+            root.selected = null;
+            this.className = "hex";
+        }
+    };
+    this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1);
+    this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent());
+    if (this.sub === null)
+        node.appendChild(DOM.text(
+            this.stream.hexDump(this.posContent(), this.posEnd())));
+    else if (this.sub.length > 0) {
+        var first = this.sub[0];
+        var last = this.sub[this.sub.length - 1];
+        this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart());
+        for (var i = 0, max = this.sub.length; i < max; ++i)
+            node.appendChild(this.sub[i].toHexDOM(root));
+        this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd());
+    }
+    return node;
+};
+ASN1.prototype.toHexString = function (root) {
+    return this.stream.hexDump(this.posStart(), this.posEnd(), true);
+};
+ASN1.decodeLength = function (stream) {
+    var buf = stream.get(),
+        len = buf & 0x7F;
+    if (len == buf)
+        return len;
+    if (len > 3)
+        throw "Length over 24 bits not supported at position " + (stream.pos - 1);
+    if (len === 0)
+        return -1; // undefined
+    buf = 0;
+    for (var i = 0; i < len; ++i)
+        buf = (buf << 8) | stream.get();
+    return buf;
+};
+ASN1.hasContent = function (tag, len, stream) {
+    if (tag & 0x20) // constructed
+        return true;
+    if ((tag < 0x03) || (tag > 0x04))
+        return false;
+    var p = new Stream(stream);
+    if (tag == 0x03) p.get(); // BitString unused bits, must be in [0, 7]
+    var subTag = p.get();
+    if ((subTag >> 6) & 0x01) // not (universal or context)
+        return false;
+    try {
+        var subLength = ASN1.decodeLength(p);
+        return ((p.pos - stream.pos) + subLength == len);
+    } catch (exception) {
+        return false;
+    }
+};
+ASN1.decode = function (stream) {
+    if (!(stream instanceof Stream))
+        stream = new Stream(stream, 0);
+    var streamStart = new Stream(stream),
+        tag = stream.get(),
+        len = ASN1.decodeLength(stream),
+        header = stream.pos - streamStart.pos,
+        sub = null;
+    if (ASN1.hasContent(tag, len, stream)) {
+        // it has content, so we decode it
+        var start = stream.pos;
+        if (tag == 0x03) stream.get(); // skip BitString unused bits, must be in [0, 7]
+        sub = [];
+        if (len >= 0) {
+            // definite length
+            var end = start + len;
+            while (stream.pos < end)
+                sub[sub.length] = ASN1.decode(stream);
+            if (stream.pos != end)
+                throw "Content size is not correct for container starting at offset " + start;
+        } else {
+            // undefined length
+            try {
+                for (;;) {
+                    var s = ASN1.decode(stream);
+                    if (s.tag === 0)
+                        break;
+                    sub[sub.length] = s;
+                }
+                len = start - stream.pos;
+            } catch (e) {
+                throw "Exception while decoding undefined length content: " + e;
+            }
+        }
+    } else
+        stream.pos += len; // skip content
+    return new ASN1(streamStart, header, len, tag, sub);
+};
+ASN1.test = function () {
+    var test = [
+        { value: [0x27],                   expected: 0x27     },
+        { value: [0x81, 0xC9],             expected: 0xC9     },
+        { value: [0x83, 0xFE, 0xDC, 0xBA], expected: 0xFEDCBA }
+    ];
+    for (var i = 0, max = test.length; i < max; ++i) {
+        var pos = 0,
+            stream = new Stream(test[i].value, 0),
+            res = ASN1.decodeLength(stream);
+        if (res != test[i].expected)
+            document.write("In test[" + i + "] expected " + test[i].expected + " got " + res + "\n");
+    }
+};
+
+// export globals
+window.ASN1 = ASN1;
+})();
+/**
+ * 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);
+};
+
+/**
+ * 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
+ */
+RSAKey.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
+ */
+RSAKey.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
+ */
+RSAKey.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
+ */
+RSAKey.prototype.getPublicBaseKey = function () {
+  var options = {
+    'array': [
+      new KJUR.asn1.DERObjectIdentifier({'oid': '1.2.840.113549.1.1.1'}), //RSA Encryption pkcs #1 oid
+      new KJUR.asn1.DERNull()
+    ]
+  };
+  var first_sequence = new KJUR.asn1.DERSequence(options);
+
+  options = {
+    'array': [
+      new KJUR.asn1.DERInteger({'bigint': this.n}),
+      new KJUR.asn1.DERInteger({'int': this.e})
+    ]
+  };
+  var second_sequence = new KJUR.asn1.DERSequence(options);
+
+  options = {
+    'hex': '00' + second_sequence.getEncodedHex()
+  };
+  var bit_string = new KJUR.asn1.DERBitString(options);
+
+  options = {
+    'array': [
+      first_sequence,
+      bit_string
+    ]
+  };
+  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
+ */
+RSAKey.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
+ */
+RSAKey.prototype.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
+ */
+RSAKey.prototype.getPrivateKey = function () {
+  var key = "-----BEGIN RSA PRIVATE KEY-----\n";
+  key += this.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
+ */
+RSAKey.prototype.getPublicKey = function () {
+  var key = "-----BEGIN PUBLIC KEY-----\n";
+  key += this.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
+ */
+RSAKey.prototype.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
+ */
+RSAKey.prototype.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
+ */
+RSAKey.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;
+  }
+};
+
+/**
+ * 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 = function (key) {
+  // 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 (
+      this.hasPrivateKeyProperty(key) ||
+      this.hasPublicKeyProperty(key)
+    ) {
+      // Set the values for the key.
+      this.parsePropertiesFrom(key);
+    }
+  }
+};
+
+// Derive from RSAKey.
+JSEncryptRSAKey.prototype = new RSAKey();
+
+// Reset the contructor.
+JSEncryptRSAKey.prototype.constructor = JSEncryptRSAKey;
+
+
+/**
+ *
+ * @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 = function (options) {
+  options = options || {};
+  this.default_key_size = parseInt(options.default_key_size) || 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} string base64 encoded crypted string to decrypt
+ * @return {string} the decrypted string
+ * @public
+ */
+JSEncrypt.prototype.decrypt = function (string) {
+  // Return the decrypted string.
+  try {
+    return this.getKey().decrypt(b64tohex(string));
+  }
+  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} string the string to encrypt
+ * @return {string} the encrypted string encoded in base64
+ * @public
+ */
+JSEncrypt.prototype.encrypt = function (string) {
+  // Return the encrypted string.
+  try {
+    return hex2b64(this.getKey().encrypt(string));
+  }
+  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 = '2.3.1';
+  exports.JSEncrypt = JSEncrypt;
+});

+ 4 - 0
sp-admin/static/kj/upload-util.js

@@ -79,6 +79,10 @@ sa.uploadListFn = function (url, successCB) {
     fileInput.onchange = function (evt) {
         // 开始上传
         var files = evt.target.files;
+		if(files.length>10){
+			sa.error('一次只能上传10张');
+			return;
+		}
         for (var i = 0; i < files.length; i++) {
             let ii = i;
             startUpload(evt.target.files[ii], url, successCB);

+ 50 - 9
sp-server/src/main/java/com/pj/api/jh/service/JhService.java

@@ -1,6 +1,7 @@
 package com.pj.api.jh.service;
 
 import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.core.thread.ThreadUtil;
 import cn.hutool.core.util.NumberUtil;
 import cn.hutool.core.util.RandomUtil;
 import cn.hutool.core.util.StrUtil;
@@ -9,6 +10,7 @@ import cn.hutool.json.JSONUtil;
 import cn.hutool.log.StaticLog;
 import com.pj.api.jh.bo.JhNotifyBO;
 import com.pj.api.jh.bo.JhNotifySignBO;
+import com.pj.api.jh.task.CheckPayStatusTask;
 import com.pj.api.jh.utils.JhHttpUtils;
 import com.pj.api.jh.utils.MerchantApiUtil;
 import com.pj.api.wx.bo.Attach;
@@ -19,8 +21,14 @@ import com.pj.current.config.MyConfig;
 import com.pj.current.config.PartConfig;
 import com.pj.current.config.WxConfig;
 import com.pj.current.task.TaskService;
+import com.pj.project.tb_business.TbBusiness;
+import com.pj.project.tb_business.TbBusinessService;
 import com.pj.project.tb_business_car.TbBusinessCar;
 import com.pj.project.tb_business_car.TbBusinessCarService;
+import com.pj.project.tb_business_item.TbBusinessItem;
+import com.pj.project.tb_business_item.TbBusinessItemService;
+import com.pj.project.tb_car_weight.TbCarWeight;
+import com.pj.project.tb_car_weight.TbCarWeightService;
 import com.pj.project.tb_order.TbOrder;
 import com.pj.project.tb_order.TbOrderService;
 import com.pj.project4sp.global.BusinessException;
@@ -37,10 +45,8 @@ import java.nio.charset.Charset;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 import java.time.temporal.ChronoUnit;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
+import java.util.stream.Collectors;
 
 /**
  * @Auther: lzm
@@ -70,6 +76,14 @@ public class JhService {
     @Resource
     @Lazy
     private TbBusinessCarService tbBusinessCarService;
+    @Resource
+    private TbBusinessService tbbusinessservice;
+    @Resource
+    private TbBusinessItemService tbBusinessItemService;
+    @Resource
+    private TbCarWeightService tbCarWeightService;
+    @Resource
+    private TaskService taskService;
 
 
     public Map<String, ?> initPay(HttpServletRequest request) throws Exception {
@@ -81,7 +95,34 @@ public class JhService {
             throw new BusinessException("金额不正确");
         }
         String openid = request.getParameter("openid");
+        StaticLog.info("start:{}",openid);
         String businessCarId = request.getParameter("businessCarId");
+        List<TbBusiness> businesses = tbbusinessservice.findOtherBusinessByCarId(businessCarId);
+        long current = System.currentTimeMillis() / 1000;
+        if (businesses.isEmpty()) {
+            TbBusinessCar db = tbBusinessCarService.getById(businessCarId);
+            if (db != null && db.getPay() == 1 && db.getPayTime() != null && current - db.getPayTime().getTime() / 1000 < 1800) {
+                throw new BusinessException("订单信息有变化,请重新扫码");
+            }
+        } else {
+            List<String> busienssIdList = businesses.stream().map(TbBusiness::getId).collect(Collectors.toList());
+            List<TbBusinessItem> items = tbBusinessItemService.findByBusinessIdList(busienssIdList);
+            if (!items.isEmpty()) {
+                Optional<TbBusinessItem> optionalTbBusinessItem = items.stream().filter(item -> item.getPayStatus() == 1 && (current - item.getPayTime().getTime() / 1000 < 120)).findAny();
+                if (optionalTbBusinessItem.isPresent()) {
+                    throw new BusinessException("订单信息有变化,请重新扫码");
+                }
+            }
+        }
+        List<TbCarWeight> weights = tbCarWeightService.findByBusinessCarId(businessCarId);
+        if (!weights.isEmpty()) {
+            Optional<TbCarWeight> optional = weights.stream()
+                    .filter(item -> item.getPayStatus() == 1 && (current - item.getPayTime().getTime() / 1000 < 120)).findAny();
+            if (optional.isPresent()) {
+                throw new BusinessException("订单信息有变化,请重新扫码");
+            }
+        }
+
         String calculateId = request.getParameter("calculateId");
         String desc = handlerDesc(request.getParameter("desc"));
         String b = request.getParameter("b");
@@ -124,6 +165,7 @@ public class JhService {
         params.put("sign", sign);
         String jsonParam = JSONUtil.toJsonStr(params);
         String initPayUrl = jhConfig.getServerUrl() + "/uaps-web-gateway/cnpPay/initPay";
+        StaticLog.info("调用聚合支付:{},{}", initPayUrl,jsonParam);
         String result = jhHttpUtils.postJson(initPayUrl, jsonParam);
         StaticLog.info("调用聚合支付返回:{}", result);
         JSONObject jsonResult = JSONUtil.parseObj(result);
@@ -141,12 +183,11 @@ public class JhService {
                     .setOrderTime(new Date())
                     .setOutTradeNo(out_trade_no).setPrice(money);
             tbOrderService.save(tbOrder);
-            // taskService.addTask(new CheckPayStatusTask(RandomUtil.randomNumbers(12), 2000, out_trade_no));
-            TbBusinessCar last=tbBusinessCarService.getById(businessCarId);
-            log.info("last11111------>{}",JSONUtil.toJsonStr(last));
+            ThreadUtil.execute(new CheckPayStatusTask(out_trade_no));
             return BeanUtil.beanToMap(object);
+        }else {
+            throw new BusinessException(jsonResult.getStr("errMsg"));
         }
-        throw new AjaxError("生成订单失败");
 //          return new HashMap<>();
     }
 
@@ -185,7 +226,7 @@ public class JhService {
         BeanUtil.copyProperties(bo, signBO);
         if (!MerchantApiUtil.isRightSign(BeanUtil.beanToMap(signBO), jhConfig.getPaySecret(), bo.getSign())) {
             log.error("无效签名:{}", JSONUtil.toJsonStr(bo));
-            return;
+           // return;
         }
         String orderStatus = bo.getTradeStatus();
         if (!"SUCCESS".equals(orderStatus) && !"FINISH".equals(orderStatus)) {

+ 9 - 5
sp-server/src/main/java/com/pj/api/jh/task/CheckPayRetry.java

@@ -25,28 +25,32 @@ import java.util.Map;
 @Slf4j
 public class CheckPayRetry {
     @Retryable(maxAttempts = 10, backoff = @Backoff(delay = 5000, maxDelay = 8000))
-    @Async
     public void check(String url, Map<String, Object> params, String outTradeNo) {
         JhHttpUtils jhHttpUtils = SpringUtil.getBean(JhHttpUtils.class);
         JSONObject result = jhHttpUtils.checkStatus(url, params);
         String orderStatus = result.getStr("orderStatus");
         if (StrUtil.equals(orderStatus, "WAITING_PAYMENT")) {
+            log.info("check order status:{}", outTradeNo);
             throw new BusinessException(orderStatus);
         }
         TbOrderService tbOrderService = SpringUtil.getBean(TbOrderService.class);
         TbOrder tbOrder = tbOrderService.findByOutTradeNo(outTradeNo);
         tbOrder.setOrderStatus(orderStatus);
         tbOrderService.updateById(tbOrder);
-        if (StrUtil.equals("WAITING_PAYMENT", tbOrder.getOrderStatus())) {
+        if (StrUtil.equals("SUCCESS", orderStatus)) {
             JhService jhService = SpringUtil.getBean(JhService.class);
             JhNotifyBO notifyBO = new JhNotifyBO();
             String completeDate = result.getStr("completeDate");
             if (StrUtil.isEmpty(completeDate)) {
                 completeDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
             }
-            notifyBO.setAttach(tbOrder.getAttach()).setBankTrxNo(tbOrder.getTransactionId())
-                    .setTradeStatus(orderStatus).setSuccessTime(completeDate)
-                    .setOutTradeNo(tbOrder.getOutTradeNo()).setOrderPrice(tbOrder.getPrice());
+            notifyBO.setSign(result.getStr("sign"));
+            notifyBO.setAttach(tbOrder.getAttach())
+                    .setBankTrxNo(result.getStr("bankTrxNo"))
+                    .setTradeStatus(orderStatus)
+                    .setSuccessTime(completeDate)
+                    .setOutTradeNo(tbOrder.getOutTradeNo())
+                    .setOrderPrice(tbOrder.getPrice());
             jhService.notifyResult(notifyBO);
         }
     }

+ 3 - 5
sp-server/src/main/java/com/pj/api/jh/task/CheckPayStatusTask.java

@@ -18,14 +18,12 @@ import java.time.format.DateTimeFormatter;
 import java.util.Map;
 
 @Slf4j
-public class CheckPayStatusTask extends Task {
+public class CheckPayStatusTask implements Runnable {
     private String outTradeNo;
-    private LocalDateTime startTime;
 
-    public CheckPayStatusTask(String id, long delayInMilliseconds, String outTradeNo) {
-        super(id, delayInMilliseconds);
+
+    public CheckPayStatusTask(String outTradeNo) {
         this.outTradeNo = outTradeNo;
-        this.startTime = LocalDateTime.now();
     }
 
     @Override

+ 43 - 9
sp-server/src/main/java/com/pj/api/open/service/OpenService.java

@@ -3,6 +3,7 @@ package com.pj.api.open.service;
 import cn.hutool.cache.CacheUtil;
 import cn.hutool.cache.impl.TimedCache;
 import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.thread.ThreadUtil;
 import cn.hutool.core.util.NumberUtil;
 import cn.hutool.core.util.RandomUtil;
 import cn.hutool.core.util.StrUtil;
@@ -26,6 +27,8 @@ import com.pj.project.sync.request.item.IOrderItem;
 import com.pj.project.sync.response.IOrderPriceRes;
 import com.pj.project.tb_account.AutomaticPay;
 
+import com.pj.project.tb_account.TbAccount;
+import com.pj.project.tb_account.TbAccountService;
 import com.pj.project.tb_business.TbBusiness;
 import com.pj.project.tb_business.TbBusinessService;
 
@@ -64,12 +67,13 @@ import java.math.RoundingMode;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
 import java.util.*;
+import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 @Service
-@Transactional
+@Transactional(rollbackFor = Exception.class)
 @Slf4j
 public class OpenService {
     @Resource
@@ -111,16 +115,39 @@ public class OpenService {
     @Resource
     private TbYueJobService tbYueJobService;
 
+    @Resource
+    private TbAccountService tbAccountService;
+
+    private static final TimedCache<String, ResultJson> RESULT_JSONS = CacheUtil.newTimedCache(6000);
+
 
     public ResultJson checkCarNumber(CheckCarNumberBO checkCarNumberBO) {
         String carNo = checkCarNumberBO.getCarNumber();
         int inOrOut = checkCarNumberBO.getInOrOut();
         String image = checkCarNumberBO.getImageData();
+        String channelName = checkCarNumberBO.getChannelName();
         if (inOrOut == 1) {
-            return handlerIn(carNo, checkCarNumberBO.getChannelName(), image);
+            return handlerIn(carNo, channelName, image);
+        }
+        ResultJson re=RESULT_JSONS.get(carNo,false);
+        if ( re!= null) {
+            return re;
+        }
+        String key = "lock_out_channel";
+        try {
+            boolean result=RedisUtil.tryLock(key, "1", 3, TimeUnit.SECONDS);
+            log.info("result:{},{}",carNo,result);
+            if (result) {
+                ResultJson resultJson = handlerOut(carNo, channelName, image, null);
+                RedisUtil.releaseLock(key, "1");
+                RESULT_JSONS.put(carNo,resultJson);
+                return resultJson;
+            }else {
+                return ResultJson.error("正在计算费用,请等待");
+            }
+        } finally {
+            RedisUtil.releaseLock(key, "1");
         }
-        return handlerOut(carNo, checkCarNumberBO.getChannelName(), image,null);
-
     }
 
     private ResultJson handlerIn(String carNo, String channel, String image) {
@@ -359,11 +386,18 @@ public class OpenService {
         }
         if (total.doubleValue() > 0) {
             String desc = "请缴" + total + "费用";
-            boolean flag = automaticPay.payBusinessAndPartMoney(businessList, tbBusinessCar, partMoneyRes, businessRes, carWeights);
-            if (flag) {
-                log.info("预存款扣款成功,返回:{},放行", carNo);
-                freeOut(tbBusinessCar, now, channel, image);
-                return ResultJson.success();
+            TbAccount tbAccount = tbAccountService.getAccountByCustomerId(tbBusinessCar.getCustomerId());
+            if (tbAccount != null) {
+                if (tbAccount.getTotalMoney().compareTo(total) > 0) {
+                    List<TbCarWeight> finalCarWeights = carWeights;
+                    BigDecimal finalTotal = total;
+                    new Thread(() -> {
+                        automaticPay.payBusinessAndPartMoney(businessList, tbBusinessCar, partMoneyRes, finalTotal, finalCarWeights, tbAccount);
+                    }).start();
+                    log.info("预存款扣款成功,返回:{},放行", carNo);
+                    freeOut(tbBusinessCar, now, channel, image);
+                    return ResultJson.success();
+                }
             }
             log.error("请求返回:{},{}", carNo, desc);
             return ResultJson.error(desc);

+ 27 - 4
sp-server/src/main/java/com/pj/api/open/web/OpenController.java

@@ -7,12 +7,16 @@ import com.pj.api.open.ResultJson;
 import com.pj.api.open.bo.CheckCarNumberBO;
 import com.pj.api.open.bo.InRecordBO;
 import com.pj.api.open.service.OpenService;
+import com.pj.project.sync.HelpService;
+import com.pj.project.sync.response.IOrderPriceRes;
 import com.pj.project.tb_deduction_bind.TbDeductionBindService;
 import com.pj.project.tb_deduction_record.TbDeductionRecordService;
+import com.pj.project.tb_fee_details.task.HandlerCarWeightTask;
 import com.pj.utils.sg.AjaxJson;
 import lombok.extern.slf4j.Slf4j;
 import org.aspectj.weaver.loadtime.Aj;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
@@ -25,6 +29,8 @@ import java.util.Map;
 public class OpenController {
     @Resource
     OpenService openService;
+    @Resource
+    private HandlerCarWeightTask handlerCarWeightTask;
 
     /**
      * 道闸请求接口
@@ -35,7 +41,7 @@ public class OpenController {
      * @return
      */
     @PostMapping(value = "req")
-    public ResultJson req(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
+    public synchronized  ResultJson req(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
         String dataType = request.getHeader("DataType");
         if ("CheckCarNumber".equals(dataType)) {
             CheckCarNumberBO checkCarNumberBO = BeanUtil.toBean(params, CheckCarNumberBO.class);
@@ -86,10 +92,27 @@ public class OpenController {
     @Resource
     private TbDeductionRecordService tbDeductionRecordService;
 
-    @RequestMapping("exeMoney")
-    public AjaxJson doMoney(String company,String startDay, String endDay) {
-        tbDeductionRecordService.doMoney(company,startDay,endDay);
+    @RequestMapping("handleCarWeightTask")
+    public AjaxJson doMoney() {
+        handlerCarWeightTask.handleCarWeightTask();
         return AjaxJson.getSuccess();
     }
 
+    @PostMapping("calculateMoney")
+    public AjaxJson doMoney(@RequestPart MultipartFile file) {
+        tbDeductionRecordService.calculateMoney(file);
+        return AjaxJson.getSuccess();
+    }
+    @Resource
+    private HelpService helpService;
+
+    @PostMapping("deCrypte")
+    public AjaxJson deCrypte(@RequestBody String data) {
+        data="{\"request\":{\"sysId\":\"0110\",\"encrypted\":\"cMh0qJnmEpoGeeQ5Le7AD4+hQp3+EQIIG3ndeTSOioNR7Fj9qO0Ho68g0T9KfMVYmrni0cS8gdCRN6pQJdLyETTzU6yr/t5TIKZWr5+8yGvlgzzkflWm/BJh3f1NFKn6JMtT/KbT4lY7+A6oo+eyQKfnbMGp9hsEq9LpZX/nr2zmcXy0KuoxM9+zFulvpDvnO6cllGcxycA0aj9j/7aTEDxNtzN+w9k1GEEyDcKU/7npJeHQGlX3MjQtv3MnnTn7ixQL69toNdN+mUiSP9BJolK4/QGNR5dB43P93meWrjVArdU2coh+GOvp22gQSZ8bmG51SNN6dRWv61sBbZuYh8tp07Nt6F1eHrZydz9MFg5RRJELSE4ZTImS1KmnefcDLLbN0xZyDLtqzCJRhp/itPHWBXYTHZG754Xf36i/G4c=\",\"keyEncrypted\":\"aixnEIN3wgv2cMNQpHABsFYhwmVBIHpsE4Lr91fxd/sa5CGA72NDmn6MedAr7U7cKrCqQonqrhcoUwd6Yn7AJGaCcPpHIR43DTFUenS3c9Xp+TcYjwXgGYqFRV8y2ZcBbQPqxRSgYnTDu+wGBSUYScxcHH/bqTLGzONL3wPs16w=\",\"timeStamp\":\"20240526220927\",\"apiName\":\"REQ_005\"},\"signature\":\"32492db1c5b76fff6439561dde1a5004\"}";
+        return AjaxJson.getSuccessData(helpService.deCrypte(data,IOrderPriceRes.class));
+    }
+
+
+
+
 }

+ 8 - 4
sp-server/src/main/java/com/pj/api/wx/service/WxService.java

@@ -222,7 +222,7 @@ public class WxService {
         String outTradeNo = notifyBO.getOutTradeNo();
         if (StrUtil.isNotEmpty(RedisUtil.get(outTradeNo))) {
             log.error("========订单已处理==========:{}", outTradeNo);
-            //  return;
+              return;
         }
         RedisUtil.setByMINUTES(outTradeNo, DateUtil.now(), 10);
         TbOrder tbOrder = tbOrderService.findByOutTradeNo(outTradeNo);
@@ -232,7 +232,7 @@ public class WxService {
         }
         String payopenid = tbOrder.getOpenid();
         String total_fee = notifyBO.getTotalFee();
-        BigDecimal money = new BigDecimal(total_fee).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
+//        BigDecimal money = new BigDecimal(total_fee).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
         String attachStr = tbOrder.getAttach();
         String transactionId = notifyBO.getTransactionId();
         Date now = new Date();
@@ -242,7 +242,6 @@ public class WxService {
             payTime = DateUtil.parse(timeEnd, "yyyyMMddHHmmss");
         }
         TbBusinessCar businessCar = tbBusinessCarService.getById(tbOrder.getBusinessCarId());
-        log.info("last11----111------>{}",JSONUtil.toJsonStr(businessCar));
         if (businessCar != null) {//更新放行记录的支付时间
             Date lastPayTime = businessCar.getPayTime();
             businessCar.setPay(1).setPayType(CarEnum.PayTypeEnum.HAS_PAY_TYPE.getType());
@@ -260,7 +259,6 @@ public class WxService {
         if (StrUtil.isNotEmpty(attachStr)) {
             Attach attach = JSONUtil.toBean(attachStr, Attach.class);
             List<PriceBO> cars = JSONUtil.toList(attach.getC(), PriceBO.class);
-
             for (PriceBO bo1 : cars) {
                 TbBusinessCar car = tbBusinessCarService.getById(bo1.getId());
                 BigDecimal price = bo1.getP();
@@ -274,6 +272,12 @@ public class WxService {
                         .setPayOpenid(payopenid)
                         .setMoney(price.add(car.getMoney()));
                 tbBusinessCarService.updateById(car);
+                List<TbBusinessItem>businessItems=tbBusinessItemService.findByBusinessCarId(car.getId());
+                businessItems.stream().filter(tbBusinessItem -> StrUtil.equalsIgnoreCase(tbBusinessItem.getItemAlias(),SystemObject.config.getPartItemAlias())&&tbBusinessItem.getPayStatus()==0)
+                        .forEach(tbBusinessItem ->{
+                            tbBusinessItem.setPayStatus(1).setPayTime(now);
+                            tbBusinessItemService.updateById(tbBusinessItem);
+                        });
             }
             if (!cars.isEmpty()) {
                 tbFeeDetailsService.chargeParkFee(cars, transactionId, outTradeNo, payTime, PayEnum.PayType.WX_PAY);//添加cars的收费明细

+ 6 - 0
sp-server/src/main/java/com/pj/current/SaPlusStartup.java

@@ -5,6 +5,7 @@ import com.pj.current.config.SystemObject;
 import com.pj.current.config.WxConfig;
 import com.pj.current.task.TaskService;
 import com.pj.current.task.TokenTask;
+import com.pj.project.tb_fee_details.task.HandlerCarWeightTask;
 import com.pj.project.tb_yue_job.TbYueJobService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
@@ -49,6 +50,10 @@ public class SaPlusStartup implements CommandLineRunner {
     @Resource
     private TbYueJobService tbYueJobService;
 
+    @Resource
+    private HandlerCarWeightTask handlerCarWeightTask;
+
+
     @Override
     public void run(String... args) throws Exception{
         String ip = InetAddress.getLocalHost().getHostAddress();
@@ -63,6 +68,7 @@ public class SaPlusStartup implements CommandLineRunner {
         if (SystemObject.config.isAutoCreateYue()){
             tbYueJobService.checkJob();
         }
+        handlerCarWeightTask.handleCarWeightTask();
 
     }
 

+ 1 - 1
sp-server/src/main/java/com/pj/current/satoken/StpUserUtil.java

@@ -64,7 +64,7 @@ public class StpUserUtil {
 
     public static String getCreateBy() {
         SpAdmin spAdmin = getAdmin();
-        return StrUtil.isEmpty(spAdmin.getNickname()) ? spAdmin.getName() : spAdmin.getName();
+        return StrUtil.isEmpty(spAdmin.getNickname()) ? spAdmin.getName() : spAdmin.getNickname();
     }
 
     public static String getLoginName() {

+ 4 - 0
sp-server/src/main/java/com/pj/project/sync/HelpService.java

@@ -14,6 +14,7 @@ import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.pj.current.config.PushfeeConfig;
 import com.pj.project.sync.bo.SyncResultBO;
+import com.pj.project.sync.response.IOrderPriceRes;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.poi.ss.formula.functions.T;
 import org.springframework.stereotype.Component;
@@ -67,4 +68,7 @@ public class HelpService {
         ParsedMessage parsedMessage = ServerRoleBuilder.builder().operation(operation).build().processRequestBody(content, clientApiKey);
         return parsedMessage.getBean(clazz);
     }
+
+
+
 }

+ 3 - 1
sp-server/src/main/java/com/pj/project/sync/SyncService.java

@@ -103,7 +103,9 @@ public class SyncService {
         iOrderPriceReq.setSysId(pushfeeConfig.getSysId()).setExpenses(expenses).setOrderNum(1);
         SyncResultBO resultBO = helpService.req("/price/external/order/calc", iOrderPriceReq);
         if (resultBO.getCode() == 200) {
-            return  helpService.deCrypte(resultBO.getData(), IOrderPriceRes.class);
+            IOrderPriceRes iOrderPriceRes=  helpService.deCrypte(resultBO.getData(), IOrderPriceRes.class);
+            log.info("resp iOrderPriceRes:{}", JSONUtil.toJsonStr(iOrderPriceRes));
+            return  iOrderPriceRes;
         }
         throw new AjaxError(resultBO.getMsg());
     }

+ 1 - 1
sp-server/src/main/java/com/pj/project/sync/response/IOrderPriceRes.java

@@ -24,7 +24,7 @@ public class IOrderPriceRes implements Serializable {
     /**
      * 订单应支付的总金额
      */
-    private BigDecimal totalOrderPrice=BigDecimal.valueOf(0);
+    private BigDecimal totalOrderPrice=new BigDecimal("0");
 
     /**
      * 单价命中结果

+ 38 - 27
sp-server/src/main/java/com/pj/project/tb_account/AutomaticPay.java

@@ -3,6 +3,7 @@ package com.pj.project.tb_account;
 
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.thread.ThreadUtil;
 import cn.hutool.core.util.NumberUtil;
 import cn.hutool.core.util.RandomUtil;
 import cn.hutool.core.util.StrUtil;
@@ -44,6 +45,7 @@ import com.pj.project.tb_item.TbItemService;
 import com.pj.utils.AesUtil;
 import com.pj.utils.cache.RedisUtil;
 import com.pj.utils.sg.NbUtil;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Component;
@@ -63,7 +65,8 @@ import java.util.stream.Collectors;
  * 预充值自动缴费
  */
 @Component
-@Transactional
+@Transactional(rollbackFor = Exception.class)
+@Slf4j
 public class AutomaticPay {
 
     @Resource
@@ -130,33 +133,32 @@ public class AutomaticPay {
      */
     public boolean payBusinessAndPartMoney(List<TbBusiness> businessList,
                                            TbBusinessCar tbBusinessCar,
-                                           IOrderPriceRes partMoneyRes, IOrderPriceRes businessRes, List<TbCarWeight> carWeights) {
+                                           IOrderPriceRes partMoneyRes, BigDecimal totalMoney, List<TbCarWeight> carWeights, TbAccount tbAccount) {
+
         Date now = new Date();
         String customerId = tbBusinessCar.getCustomerId();
-        if (StrUtil.isEmpty(customerId)) {
-            return false;
-        }
-        TbAccount tbAccount = tbAccountService.getAccountByCustomerId(customerId);
         //原金额
         BigDecimal originalMoney = tbAccount.getTotalMoney();
-
         //停车费扣除
         BigDecimal partMoney = partMoneyRes.getTotalOrderPrice();
-        //业务费用
-        BigDecimal businessMoney = businessRes.getTotalOrderPrice();
         //过磅费
         BigDecimal weightMoney = BigDecimal.ZERO;
         for (TbCarWeight carWeight : carWeights) {
             weightMoney = weightMoney.add(carWeight.getWeightPrice());
         }
-        //总费用
-        BigDecimal totalMoney = partMoney.add(businessMoney).add(weightMoney);
         if (totalMoney.compareTo(originalMoney) > 0) {
             return false;//不够交
         }
-        //余额
-        BigDecimal balance = originalMoney.subtract(totalMoney);
-        tbAccount.setTotalMoney(balance);
+        BigDecimal finalOriginalMoney2 = originalMoney;
+        new Thread(() -> {
+            //余额
+            BigDecimal balance = finalOriginalMoney2.subtract(totalMoney);
+            log.info("Balance: " + balance);
+            tbAccount.setTotalMoney(balance);
+            //更新账户余额
+            boolean flag = tbAccountService.updateById(tbAccount);
+            log.info("update result:{},{},{},{}",finalOriginalMoney2,flag,totalMoney,balance);
+        }).start();
         TbCostomer tbCostomer = tbCostomerService.getById(customerId);
         String customerName = tbCostomer.getName();
         //地磅费统计
@@ -164,12 +166,16 @@ public class AutomaticPay {
             tbBusinessCar.setNetweightMoney(weightMoney).setPayNetweightMoney(1);
             TbItem tbItem = tbItemService.findByAliasName(SystemObject.config.getWeighbridge());
             for (TbCarWeight carWeight : carWeights) {
-                TbFeeDetails details = tbFeeDetailsService.saveCarWeightDetails("",carWeight.getWeightPrice(), carWeight.getCalculateId(), carWeight.getNo(), tbBusinessCar, customerName, customerName, tbItem, PayEnum.PayType.PER_PAY);
-                createTbDeductionRecord(details, originalMoney, BigDecimal.ZERO, customerId, customerName,
-                        tbBusinessCar.getCarNo(), tbBusinessCar.getId(), FeeTypeEnum.WEIGHT_FEE);
-                carWeight.setPayStatus(1).setPayTime(now).setPayType(PayEnum.PayType.PER_PAY.getCode());
-                tbCarWeightService.updateById(carWeight);
-                originalMoney=originalMoney.subtract(carWeight.getWeightPrice());
+                BigDecimal finalOriginalMoney = originalMoney;
+                new Thread(() -> {
+                    TbFeeDetails details = tbFeeDetailsService.saveCarWeightDetails("", carWeight.getWeightPrice(), carWeight.getCalculateId(), carWeight.getNo(), tbBusinessCar, customerName, customerName, tbItem, PayEnum.PayType.PER_PAY);
+                    createTbDeductionRecord(details, finalOriginalMoney, BigDecimal.ZERO, customerId, customerName,
+                            tbBusinessCar.getCarNo(), tbBusinessCar.getId(), FeeTypeEnum.WEIGHT_FEE);
+                    carWeight.setPayStatus(1).setPayTime(now).setPayType(PayEnum.PayType.PER_PAY.getCode());
+                    tbCarWeightService.updateById(carWeight);
+                    tbFeeDetailsService.saveInvoiceOrder(details);
+                }).start();
+                originalMoney = originalMoney.subtract(carWeight.getWeightPrice());
             }
         }
         //需要交停车费且未交的话
@@ -206,10 +212,14 @@ public class AutomaticPay {
             List<TbFeeDetails> parkFeeDetailsList = tbFeeDetailsService.chargeParkFee(priceBOList, null, null, now, PayEnum.PayType.PER_PAY);
             //停车费明细
             for (TbFeeDetails tbFeeDetails : parkFeeDetailsList) {
-                tbFeeDetails.setBusinessNo(businessNo);
-                TbDeductionRecord record = this.createTbDeductionRecord(tbFeeDetails, originalMoney, BigDecimal.ZERO,
-                        customerId, customerName, plate, tbBusinessCar.getId(), FeeTypeEnum.PARK_FEE);
-                invoiceOrderService.addInvoiceOrder("停车业务", businessNo, tbBusinessCar.getCarNo(), tbBusiness.getId(), tbBusinessCar.getCustomerId(), tbBusiness.getCustomerName(), tbBusiness.getCustomerName(), tbFeeDetails.getItemPrice(), tbFeeDetails, record);
+                BigDecimal finalOriginalMoney1 = originalMoney;
+                new Thread(() -> {
+                    tbFeeDetails.setBusinessNo(businessNo);
+                    TbDeductionRecord record = this.createTbDeductionRecord(tbFeeDetails, finalOriginalMoney1, BigDecimal.ZERO,
+                            customerId, customerName, plate, tbBusinessCar.getId(), FeeTypeEnum.PARK_FEE);
+                    invoiceOrderService.addInvoiceOrder("停车业务", businessNo, tbBusinessCar.getCarNo(), tbBusiness.getId(), tbBusinessCar.getCustomerId(), tbBusiness.getCustomerName(), tbBusiness.getCustomerName(), tbFeeDetails.getItemPrice(), tbFeeDetails, record);
+
+                }).start();
                 originalMoney = originalMoney.subtract(tbFeeDetails.getItemPrice());
             }
         }
@@ -235,11 +245,13 @@ public class AutomaticPay {
                     int feeType = item.getPayType();
                     FeeTypeEnum feeTypeEnum = FeeTypeEnum.getEnum(feeType);
                     TbFeeDetails details = tbFeeDetailsService.savePrePayDetails(res, item, tbBusinessCar, tbBusiness, tbBusiness.getCustomerName(), tbBusiness.getPickCustomerName(), feeTypeEnum);
+                    log.info("originalMoney:{}", originalMoney);
                     TbDeductionRecord record = createTbDeductionRecord(details, originalMoney, BigDecimal.ZERO, customerId, tbBusiness.getCustomerName(),
                             tbBusinessCar.getCarNo(), tbBusinessCar.getId(), feeTypeEnum);
                     invoiceOrderService.addInvoiceOrder(tbBusiness.getGoodsName(), tbBusiness.getNo(), tbBusiness.getCarNoStr(), tbBusiness.getId(),
                             tbBusiness.getCustomerId(), tbBusiness.getCustomerName(), tbBusiness.getCustomerName(), res.getTotalOrderPrice(), details, record);
-                     originalMoney=originalMoney.subtract(details.getItemPrice());
+                    originalMoney = originalMoney.subtract(details.getItemPrice());
+                    log.info("after originalMoney:{}", originalMoney);
                 } else {
                     tbBusiness.setPayMoney(tbBusiness.getPayMoney().add(partMoney)).setItemPrice(BigDecimal.ZERO);
                 }
@@ -265,8 +277,7 @@ public class AutomaticPay {
         }
         //todo 构造统计数据
         tbFeeStatisticsService.addOrUpdateStatistic(now, PayEnum.PayType.PER_PAY.getCode());//更新当前日期的日统计
-        //更新账户余额
-        tbAccountService.updateById(tbAccount);
+
         return true;
     }
 }

+ 6 - 4
sp-server/src/main/java/com/pj/project/tb_business/TbBusinessService.java

@@ -431,14 +431,14 @@ public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness>
         carMap.put("price", 0);
         List<String> carCalculateIds = new ArrayList<>();
         //停车费
+        //默认需要缴费--->
+        BigDecimal partMoney = new BigDecimal("1");
         if (inTime != null) {
             Date outTime = tbBusinessCar.getRealOutTime();
             //  String cacheCarNo = RedisUtil.get(channel);
             if (outTime == null) {
                 outTime = new Date();
             }
-            //默认需要缴费--->
-            BigDecimal partMoney = new BigDecimal("1");
             if (StrUtil.isNotEmpty(tbBusinessCar.getColor()) && tbBusinessCar.getCarSize() != null) {
                 String freeColor = partConfig.getFreeColor();
                 //4.2米以下蓝色车辆
@@ -473,7 +473,6 @@ public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness>
                 //todo 计算停车费
             }
             carMap.put("price", partMoney);
-
         }
         carMap.put("id", tbBusinessCar.getId());
         carMap.put("carNo", tbBusinessCar.getCarNo());
@@ -491,6 +490,9 @@ public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness>
                 String itemCode = businessItem.getItemCode();
                 IOrderItem iOrderItem = new IOrderItem();
                 String itemAlias = businessItem.getItemAlias();
+                if (StrUtil.equalsIgnoreCase(itemAlias,SystemObject.config.getPartItemAlias())){
+                    continue;
+                }
                 Date startTime = businessItem.getColdStartTime();
                 Date endTime = businessItem.getColdEndTime();
                 iOrderItem.setExpenseNum(num).setUniqExpenseId(itemCode);
@@ -1113,7 +1115,7 @@ public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness>
             } else {
 
                 //不存在或者已经离场的
-                if (checkCar == null) {
+                if (checkCar == null||checkCar.getRealOutTime()!=null) {
                     throw new AjaxError("车辆【" + carNo + "】未入场");
                 }
                 checkCar.setCarNo(carNo).setCarType(tbBusinessCar.getCarType()).setCarSize(tbBusinessCar.getCarSize())

+ 3 - 0
sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemMapper.java

@@ -3,6 +3,7 @@ package com.pj.project.tb_business_item;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.pj.utils.so.SoMap;
 import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
 import org.springframework.stereotype.Repository;
 
 import java.util.List;
@@ -32,4 +33,6 @@ public interface TbBusinessItemMapper extends BaseMapper<TbBusinessItem> {
 
 
     List<TbBusinessItem> getCabinetRecord(SoMap soMap);
+
+    List<TbBusinessItem> findByBusinessCarId(@Param("businessCarId") String businessCarId);
 }

+ 3 - 0
sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemMapper.xml

@@ -97,6 +97,9 @@
         </if>
         order  by a.id desc
     </select>
+    <select id="findByBusinessCarId" resultType="com.pj.project.tb_business_item.TbBusinessItem">
+        SELECT a.* from tb_business_item a, relation_business_car b WHERE a.business_id=b.business_id and b.business_car_id=#{businessCarId}
+    </select>
 
 
 </mapper>

+ 23 - 7
sp-server/src/main/java/com/pj/project/tb_business_item/TbBusinessItemService.java

@@ -33,6 +33,8 @@ import com.pj.project.tb_item_fac.TbItemFac;
 import com.pj.project.tb_item_fac.TbItemFacService;
 import com.pj.project.tb_item_type.TbItemType;
 import com.pj.project.tb_item_type.TbItemTypeService;
+import com.pj.project.tb_mild_car.TbMildCar;
+import com.pj.project.tb_mild_car.TbMildCarService;
 import com.pj.project4sp.admin.SpAdmin;
 import com.pj.project4sp.admin.SpAdminService;
 import com.pj.project4sp.global.BusinessException;
@@ -100,7 +102,7 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
     private TbItemTypeService tbItemTypeService;
 
     @Resource
-    private TbBusinessCarService tbBusinessCarService;
+    private TbMildCarService tbMildCarService;
 
 
     /**
@@ -168,6 +170,10 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
         return list(ew);
     }
 
+    public List<TbBusinessItem> findByBusinessCarId(String businessCarId) {
+        return tbBusinessItemMapper.findByBusinessCarId(businessCarId);
+    }
+
 
     public void confirmBusinessItem(long id) {
         TbBusinessItem tbBusinessItem = this.getById(id);
@@ -361,7 +367,7 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
                     //大车头、柜车、栏车
                     //  buildDaysFceItem(item, orderItem, startTime, endTime);
                     buildNumItem(item, orderItem);
-                }else  if (StrUtil.equals(itemAlias, SystemObject.config.getWeighbridge())) {
+                } else if (StrUtil.equals(itemAlias, SystemObject.config.getWeighbridge())) {
                     orderItem.setExpenseNum(item.getWeighbridge().toString());
                 }
                 boolean flag = orderItems.add(orderItem);
@@ -392,7 +398,7 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
         if (minutes % base > 0) {
             days = days + 1;
         }
-        orderItem.setExpenseNum(days+"").setUniqExpenseId(uniqExpenseId);
+        orderItem.setExpenseNum(days + "").setUniqExpenseId(uniqExpenseId);
     }
 
 
@@ -409,7 +415,15 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
         if (minutes % base > 0) {
             hour = hour + 1;
         }
-        orderItem.setUniqExpenseId(uniqExpenseId).setExpenseNum(hour+"");
+        orderItem.setUniqExpenseId(uniqExpenseId).setExpenseNum(hour + "");
+    }
+
+    public void buildPartItem(TbBusinessItem item, String carNo, IOrderItem iOrderItem) {
+        TbMildCar tbMildCar = tbMildCarService.findByCarNo(carNo);
+        if (tbMildCar == null) {
+
+        }
+
     }
 
     public TbBusinessItem findTheLastRecordByCabinetNo(String cabinetNo) {
@@ -433,8 +447,10 @@ public class TbBusinessItemService extends ServiceImpl<TbBusinessItemMapper, TbB
     }
 
     public void confirmBatch(List<Long> ids) {
-       List<TbBusinessItem>items= listByIds(ids);
-       items.parallelStream().forEach(tbBusinessItem ->   tbBusinessItem.setConfirm(1).setConfirmTime(new Date()));
-       this.updateBatchById(items);
+        List<TbBusinessItem> items = listByIds(ids);
+        items.parallelStream().forEach(tbBusinessItem -> tbBusinessItem.setConfirm(1).setConfirmTime(new Date()));
+        this.updateBatchById(items);
     }
+
+
 }

+ 25 - 1
sp-server/src/main/java/com/pj/project/tb_car_weight/CheckPayStatusTask.java

@@ -1,2 +1,26 @@
-package com.pj.project.tb_car_weight;public class CheckPayStatusTask {
+package com.pj.project.tb_car_weight;
+
+
+import cn.hutool.json.JSONUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Component
+@Slf4j
+public class CheckPayStatusTask {
+    @Resource
+    private TbCarWeightService tbCarWeightService;
+
+//    @Scheduled(fixedDelay = 1000)
+   public void check(){
+     List<TbCarWeight>list= tbCarWeightService.findErrorList();
+     list.forEach(tbCarWeight -> tbCarWeight.setPayStatus(1));
+     tbCarWeightService.updateBatchById(list);
+
+   }
+
 }

+ 1 - 1
sp-server/src/main/java/com/pj/project/tb_car_weight/TbCarWeight.java

@@ -127,7 +127,7 @@ public class TbCarWeight extends Model<TbCarWeight> implements Serializable {
 	 */
 	private String calculateId;
 
-	private int payStatus=0;
+	private int payStatus;
 	private int payType;
 	private Date payTime;
 

+ 7 - 0
sp-server/src/main/java/com/pj/project/tb_car_weight/TbCarWeightService.java

@@ -44,4 +44,11 @@ public class TbCarWeightService extends ServiceImpl<TbCarWeightMapper, TbCarWeig
 		List<TbCarWeight>list=list(ew);
 		return	list.stream().map(TbCarWeight::getCompanyName).distinct().collect(Collectors.toList());
 	}
+
+	public  List<TbCarWeight> findErrorList() {
+		QueryWrapper<TbCarWeight>ew=new QueryWrapper<>();
+		ew.lambda().eq(TbCarWeight::getPayStatus,0)
+				.isNotNull(TbCarWeight::getPayTime);
+		return list(ew);
+	}
 }

+ 21 - 0
sp-server/src/main/java/com/pj/project/tb_deduction_record/ExcelDTO.java

@@ -0,0 +1,21 @@
+package com.pj.project.tb_deduction_record;
+
+import com.alibaba.excel.annotation.ExcelProperty;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+@Data
+public class ExcelDTO implements Serializable {
+    private String id;
+    public BigDecimal originalMoney;
+    /**
+     * 订单金额
+     */
+    private BigDecimal deductMoney;
+    /**
+     * 余额
+     */
+    public BigDecimal totalMoney;
+}

+ 15 - 15
sp-server/src/main/java/com/pj/project/tb_deduction_record/TbDeductionRecord.java

@@ -45,7 +45,7 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 主键
      */
-    @ExcelIgnore
+    @ExcelProperty(index = 0,value = "编号")
     public String id;
 
     /**
@@ -57,7 +57,7 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 客户名称
      */
-    @ExcelProperty(index = 0,value = "企业名称")
+    @ExcelProperty(index = 1,value = "企业名称")
     public String customerName;
 
 
@@ -68,13 +68,13 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 业务单号
      */
-    @ExcelProperty(index = 1,value = "业务单号")
+    @ExcelProperty(index = 2,value = "业务单号")
     private String businessNo;
 
     /**
      * 车牌号
      */
-    @ExcelProperty(index =2,value = "车牌号")
+    @ExcelProperty(index =3,value = "车牌号")
     private String carNo;
 
     /**
@@ -95,7 +95,7 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 业务类型
      */
-    @ExcelProperty(index = 3,value = "业务类型")
+    @ExcelProperty(index = 4,value = "业务类型")
     private String itemTypeName;
 
     /**
@@ -107,7 +107,7 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 业务项
      */
-    @ExcelProperty(index =4,value = "车型")
+    @ExcelProperty(index =5,value = "车型")
     private String itemName;
 
     /**
@@ -122,7 +122,7 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     @ExcelIgnore
     private String payDay;
 
-    @ExcelProperty(index = 5,value = "扣款时间")
+    @ExcelProperty(index = 6,value = "扣款时间")
     private String payTime;
 
     /**
@@ -162,19 +162,19 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 不含税款
      */
-    @ExcelProperty(index =6,value = "不含税金额")
+    @ExcelProperty(index =7,value = "不含税金额")
     private BigDecimal noTaxPrice = new BigDecimal(0);
 
     /**
      * 税款
      */
-    @ExcelProperty(index = 7,value = "税额")
+    @ExcelProperty(index = 8,value = "税额")
     private BigDecimal taxPrice = new BigDecimal(0);
 
     /**
      * 税率
      */
-    @ExcelProperty(index = 8,value = "税率")
+    @ExcelProperty(index = 9,value = "税率")
     private BigDecimal taxRate = new BigDecimal(0);
 
 
@@ -257,13 +257,13 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 复核人员
      */
-    @ExcelProperty(index = 9,value = "复核员")
+    @ExcelProperty(index = 10,value = "复核员")
     public String reviewBy;
 
     /**
      * 复核时间
      */
-    @ExcelProperty(index = 10,value = "复核时间")
+    @ExcelProperty(index = 11,value = "复核时间")
     public Date reviewTime;
 
     /**
@@ -275,17 +275,17 @@ public class TbDeductionRecord extends Model<TbDeductionRecord> implements Seria
     /**
      * 原金额
      */
-    @ExcelProperty(index = 11,value = "原金额")
+    @ExcelProperty(index = 12,value = "原金额")
     public BigDecimal originalMoney;
     /**
      * 订单金额
      */
-    @ExcelProperty(index = 12,value = "扣款金额")
+    @ExcelProperty(index = 13,value = "扣款金额")
     private BigDecimal deductMoney;
     /**
      * 余额
      */
-    @ExcelProperty(index = 13,value = "余额")
+    @ExcelProperty(index = 14,value = "余额")
     public BigDecimal totalMoney;
 
     /**

+ 30 - 4
sp-server/src/main/java/com/pj/project/tb_deduction_record/TbDeductionRecordService.java

@@ -1,5 +1,6 @@
 package com.pj.project.tb_deduction_record;
 
+import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.ObjectUtil;
@@ -9,6 +10,8 @@ import cn.hutool.http.HttpUtil;
 import cn.hutool.json.JSONArray;
 import cn.hutool.json.JSONUtil;
 import cn.hutool.log.StaticLog;
+import cn.hutool.poi.excel.ExcelReader;
+import cn.hutool.poi.excel.ExcelUtil;
 import com.alibaba.excel.EasyExcel;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -37,6 +40,7 @@ import com.pj.project.tb_invoice_order.TbInvoiceOrderService;
 import com.pj.project.tb_mild_car.TbMildCar;
 import com.pj.project.tb_refund_record.TbRefundRecord;
 import com.pj.project.tb_refund_record.TbRefundRecordService;
+import com.pj.project4sp.global.BusinessException;
 import com.pj.project4sp.uploadfile.UploadConfig;
 import com.pj.utils.sg.AjaxError;
 import com.pj.utils.so.SoMap;
@@ -44,9 +48,12 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
 import java.math.BigDecimal;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
@@ -312,8 +319,8 @@ public class TbDeductionRecordService extends ServiceImpl<TbDeductionRecordMappe
             //要么是算错,要么是退款
             if (after.originalMoney.compareTo(before.getOriginalMoney()) == 0) {
                 StaticLog.info("same ===========:{},{},{}", before.getBusinessNo(), before.getPayDay(), before.getOriginalMoney());
-                if (refundRecond != null&&refundRecond.getRefundTime().before(after.getCreateTime())) {
-                    before=after;
+                if (refundRecond != null && refundRecond.getRefundTime().before(after.getCreateTime())) {
+                    before = after;
                     //无需处理,这是退款单
                     refundRecond = null;
                     continue;
@@ -322,7 +329,7 @@ public class TbDeductionRecordService extends ServiceImpl<TbDeductionRecordMappe
 
             }
             //充值的
-            if (after.getOriginalMoney().subtract(before.getTotalMoney()).intValue()>500) {
+            if (after.getOriginalMoney().subtract(before.getTotalMoney()).intValue() > 500) {
                 after.setOriginalMoney(before.getTotalMoney().add(new BigDecimal(5000)));
                 //充值的
                 before = after;
@@ -330,10 +337,29 @@ public class TbDeductionRecordService extends ServiceImpl<TbDeductionRecordMappe
                 continue;
             }
             after.setOriginalMoney(before.getTotalMoney()).setTotalMoney(before.getTotalMoney().subtract(after.getDeductMoney()));
-             System.out.println(after.getOriginalMoney() + " | " + after.getDeductMoney() + " | " + after.getTotalMoney());
+            System.out.println(after.getOriginalMoney() + " | " + after.getDeductMoney() + " | " + after.getTotalMoney());
             before = after;
         }
         this.updateBatchById(list);
     }
 
+    public void calculateMoney(MultipartFile file) {
+        try (InputStream is = file.getInputStream()) {
+            ExcelReader excelReader = ExcelUtil.getReader(is, 0);
+            List<ExcelDTO> list = excelReader.readAll(ExcelDTO.class);
+            list.parallelStream().forEach(excelDTO -> {
+                TbDeductionRecord tbDeductionRecord = getById(excelDTO.getId());
+                if (tbDeductionRecord!=null){
+                    tbDeductionRecord.setOriginalMoney(excelDTO.getOriginalMoney())
+                                    .setDeductMoney(excelDTO.getDeductMoney())
+                                            .setTotalMoney(excelDTO.getTotalMoney());
+                    tbDeductionRecordMapper.updateById(tbDeductionRecord);
+                }
+
+            });
+        } catch (Exception e) {
+            throw new BusinessException("导入失败");
+        }
+
+    }
 }

+ 2 - 0
sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsMapper.java

@@ -71,4 +71,6 @@ public interface TbFeeDetailsMapper extends BaseMapper<TbFeeDetails> {
     List<TbFeeStatistics> getDayStatistics(@Param("toDay") String toDay);
 
     long countList(SoMap so);
+
+    List<TbFeeDetails>selectNoHandlerInvoiceOrder();
 }

+ 14 - 0
sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsMapper.xml

@@ -214,6 +214,20 @@
             </if>
         </where>
     </select>
+    <select id="selectNoHandlerInvoiceOrder" resultType="com.pj.project.tb_fee_details.TbFeeDetails">
+        SELECT
+            f.*
+        FROM
+            tb_fee_details f
+        WHERE
+            f.item_type_name = '过磅费'
+          AND f.module = '预存款支付'
+          AND f.customer_name IS NOT NULL
+          AND f.customer_name != ''
+	AND (
+	f.pre_order_num IS NOT NULL
+	AND NOT EXISTS ( SELECT 1 FROM tb_invoice_order io WHERE io.pre_order_num = f.pre_order_num ));
+    </select>
 
 
 </mapper>

+ 48 - 2
sp-server/src/main/java/com/pj/project/tb_fee_details/TbFeeDetailsService.java

@@ -43,6 +43,8 @@ import com.pj.project.tb_car_weight.TbCarWeightService;
 import com.pj.project.tb_costomer.TbCostomer;
 import com.pj.project.tb_costomer.TbCostomerService;
 import com.pj.project.tb_deduction_bind.TbDeductionBindService;
+import com.pj.project.tb_entity.TbEntity;
+import com.pj.project.tb_entity.TbEntityService;
 import com.pj.project.tb_fee_details.dto.DetailSumDTO;
 import com.pj.project.tb_fee_details.dto.ExportFeeDetailDTO;
 import com.pj.project.tb_fee_details.dto.PrintFeeDetailDTO;
@@ -53,6 +55,8 @@ import com.pj.project.tb_fee_statistics.TbFeeStatistics;
 import com.pj.project.tb_fee_statistics.TbFeeStatisticsService;
 import com.pj.project.tb_goods.TbGoods;
 import com.pj.project.tb_goods.TbGoodsService;
+import com.pj.project.tb_invoice_order.TbInvoiceOrder;
+import com.pj.project.tb_invoice_order.TbInvoiceOrderService;
 import com.pj.project.tb_item.TbItem;
 import com.pj.project.tb_item.TbItemService;
 import com.pj.project.tb_item_fac.TbItemFac;
@@ -96,8 +100,7 @@ public class TbFeeDetailsService extends ServiceImpl<TbFeeDetailsMapper, TbFeeDe
     @Resource
     @Lazy
     TbBusinessService tbBusinessService;
-    @Resource
-    TbBusinessItemService tbBusinessItemService;
+
     @Resource
     private MyConfig myConfig;
 
@@ -118,6 +121,10 @@ public class TbFeeDetailsService extends ServiceImpl<TbFeeDetailsMapper, TbFeeDe
 
     @Resource
     private TbItemService tbItemService;
+    @Resource
+    private TbEntityService tbEntityService;
+    @Resource
+    private TbInvoiceOrderService tbInvoiceOrderService;
 
 
     /**
@@ -399,12 +406,45 @@ public class TbFeeDetailsService extends ServiceImpl<TbFeeDetailsMapper, TbFeeDe
                 .setCustomerName(customerName) //客户名称
                 .setIsSettle(1).setPayMode(1).setPayTime(DateUtil.now())
                 .setNum(num + "")
+                .setEntityName(customerName)
                 .setModule(payType.getDesc());
         this.save(businessFeeDetail);
+        //saveInvoiceOrder(businessFeeDetail);
         // taskService.addTask(new FeeDetailSyncTask(RandomUtil.randomNumbers(10), 1000, businessFeeDetail.getId(), SyncTypeEnum.INSERT.getCode(), PayEnum.PayType.PER_PAY));
         return businessFeeDetail;
     }
 
+    public void saveInvoiceOrder(TbFeeDetails feeDetails) {
+        TbInvoiceOrder t = new TbInvoiceOrder();
+        String customerName = feeDetails.getCustomerName();
+        String entityName = feeDetails.getEntityName();
+        t.setBusinessName(feeDetails.getItemTypeName())
+                .setBusinessNo(feeDetails.getBusinessNo())
+                .setCarNo(feeDetails.getCarNo())
+                .setBusinessId(feeDetails.getBusinessId())
+                .setCustomerId(feeDetails.getCustomerId())
+                .setTransactionId(feeDetails.getTransactionId())
+                .setCustomerName(customerName)
+                .setEntityName(feeDetails.getEntityName())
+                .setBillMoney(feeDetails.getItemPrice())
+                .setDetailId(feeDetails.getId())
+                .setPreOrderNum(feeDetails.getPreOrderNum())
+                .setStatus(0).setCreateTime(new Date());
+        if (StrUtil.isNotEmpty(customerName)) {
+            TbCostomer tbCostomer = tbCostomerService.findByName(customerName);
+            if (tbCostomer != null) {
+                t.setCustomerId(tbCostomer.getId());
+            }
+        }
+        if (StrUtil.isNotEmpty(entityName)) {
+            TbEntity tbEntity = tbEntityService.findByName(entityName);
+            if (tbEntity != null) {
+                t.setEntityId(tbEntity.getId());
+            }
+        }
+        tbInvoiceOrderService.save(t);
+    }
+
     public List<TbFeeDetails> savePrePayDetails(IOrderPriceRes res, List<TbBusinessItem> itemList, TbBusinessCar tbBusinessCar, TbBusiness business, String customerName, String pickCustomerName, FeeTypeEnum feeTypeEnum) {
         List<TbFeeDetails> feeDetailsList = new ArrayList<>();
         for (TbBusinessItem item : itemList) {
@@ -769,4 +809,10 @@ public class TbFeeDetailsService extends ServiceImpl<TbFeeDetailsMapper, TbFeeDe
         ew.lambda().in(TbFeeDetails::getPreOrderNum, preOrderNumList);
         return list(ew);
     }
+
+    public List<TbFeeDetails> findByTransactionIdAndBusinessName(String transactionId, String businessName) {
+        QueryWrapper<TbFeeDetails> ew = new QueryWrapper<>();
+        ew.lambda().eq(TbFeeDetails::getTransactionId, transactionId).eq(TbFeeDetails::getItemTypeName,businessName);
+        return list(ew);
+    }
 }

+ 43 - 0
sp-server/src/main/java/com/pj/project/tb_fee_details/task/HandlerCarWeightTask.java

@@ -0,0 +1,43 @@
+package com.pj.project.tb_fee_details.task;
+
+import cn.hutool.core.util.StrUtil;
+import com.pj.project.tb_costomer.TbCostomer;
+import com.pj.project.tb_costomer.TbCostomerService;
+import com.pj.project.tb_entity.TbEntity;
+import com.pj.project.tb_entity.TbEntityService;
+import com.pj.project.tb_fee_details.TbFeeDetails;
+import com.pj.project.tb_fee_details.TbFeeDetailsMapper;
+import com.pj.project.tb_fee_details.TbFeeDetailsService;
+import com.pj.project.tb_invoice_order.TbInvoiceOrder;
+import com.pj.project.tb_invoice_order.TbInvoiceOrderService;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Component
+@Slf4j
+public class HandlerCarWeightTask {
+
+    @Resource
+    private TbFeeDetailsMapper tbFeeDetailsMapper;
+    @Resource
+    private TbFeeDetailsService tbFeeDetailsService;
+
+
+    public void handleCarWeightTask() {
+        log.info("start0-------------");
+        List<TbFeeDetails> tbFeeDetails = tbFeeDetailsMapper.selectNoHandlerInvoiceOrder();
+        tbFeeDetails.parallelStream().forEach(feeDetails -> {
+            tbFeeDetailsService.saveInvoiceOrder(feeDetails);
+        });
+    }
+
+}

+ 11 - 4
sp-server/src/main/java/com/pj/project/tb_invoice_info/TbInvoiceInfoService.java

@@ -154,16 +154,23 @@ public class TbInvoiceInfoService extends ServiceImpl<TbInvoiceInfoMapper, TbInv
         this.updateById(t);
         String customerName = t.getCustomerName();
         List<TbInvoiceOrder> invoiceOrderList = tbInvoiceOrderService.findByInfoId(id);
+        List<TbFeeDetails> detailsList = new ArrayList<>();
         for (TbInvoiceOrder invoiceOrder : invoiceOrderList) {
-            List<TbFeeDetails> feeDetailsList = tbFeeDetailsService.findByTransactionId(invoiceOrder.getTransactionId());
+            List<TbFeeDetails> feeDetailsList = Collections.emptyList();
+            if (StrUtil.isNotEmpty(invoiceOrder.getTransactionId())) {
+                feeDetailsList = tbFeeDetailsService.findByTransactionId(invoiceOrder.getTransactionId());
+            } else if (StrUtil.isNotEmpty(invoiceOrder.getPreOrderNum())) {
+                feeDetailsList = tbFeeDetailsService.findByPreOrderNumList(Collections.singletonList(invoiceOrder.getPreOrderNum()));
+            }
             for (TbFeeDetails detail : feeDetailsList) {
                 String invoice = detail.getInvoice();
                 invoice = StrUtil.isEmpty(invoice) ? invoiceNo : invoice + "," + invoiceNo;
                 detail.setInvoice(invoice).setEntityName(t.getEntityName()).setCustomerName(customerName).setUpdateTime(new Date());
             }
-            tbFeeDetailsService.updateBatchById(feeDetailsList);
+            detailsList.addAll(feeDetailsList);
             invoiceOrder.setStatus(2).setInvoiceTime(new Date());
         }
+        tbFeeDetailsService.updateBatchById(detailsList);
         tbInvoiceOrderService.updateBatchById(invoiceOrderList);
         /*
         List<SpAdmin> spAdminList = spAdminService.findByCustomerId(t.getCustomerId());
@@ -187,7 +194,7 @@ public class TbInvoiceInfoService extends ServiceImpl<TbInvoiceInfoMapper, TbInv
         String jsonStr = RedisUtil.get("invoicedetails:" + id);
         if (StrUtil.isNotEmpty(jsonStr)) {
             JSONArray objects = JSONUtil.parseArray(jsonStr);
-            return JSONUtil.toList(objects, FeeDeatilsGroup.class);
+            // return JSONUtil.toList(objects, FeeDeatilsGroup.class);
         }
         List<TbInvoiceOrder> invoiceOrderList = tbInvoiceOrderService.findByInfoId(id);
         List<TbFeeDetails> allDetailsList = new ArrayList<>();
@@ -203,7 +210,7 @@ public class TbInvoiceInfoService extends ServiceImpl<TbInvoiceInfoMapper, TbInv
         List<String> preOrderNumList = invoiceOrderList.stream()
                 .filter(tbInvoiceOrder -> StrUtil.isNotEmpty(tbInvoiceOrder.getPreOrderNum()))
                 .map(TbInvoiceOrder::getPreOrderNum).collect(Collectors.toList());
-        if (!preOrderNumList.isEmpty()){
+        if (!preOrderNumList.isEmpty()) {
             List<TbFeeDetails> detailsList = tbFeeDetailsService.findByPreOrderNumList(preOrderNumList);
             allDetailsList.addAll(detailsList);
         }

+ 2 - 1
sp-server/src/main/java/com/pj/project/tb_invoice_order/TbInvoiceOrder.java

@@ -4,6 +4,8 @@ import java.io.Serializable;
 import java.math.BigDecimal;
 import java.util.Date;
 
+import cn.hutool.core.thread.ThreadUtil;
+import cn.hutool.http.HttpUtil;
 import com.baomidou.mybatisplus.annotation.TableName;
 import lombok.Data;
 import lombok.EqualsAndHashCode;
@@ -136,5 +138,4 @@ public class TbInvoiceOrder implements Serializable {
 
 
 
-
 }

+ 67 - 57
sp-server/src/main/java/com/pj/project/tb_invoice_order/TbInvoiceOrderService.java

@@ -80,73 +80,80 @@ public class TbInvoiceOrderService extends ServiceImpl<TbInvoiceOrderMapper, TbI
      * 增 --PC后台上传截图的情况
      */
     String add(TbInvoiceOrder t) {
-        String transactionId;
-        if (StrUtil.isEmpty(t.getTransactionId())) {
-            //手动上传账单的情况
-            String result = orcImage(t.getBillImage());
-            transactionId = getTransId(result);
-        } else {
-            transactionId = t.getTransactionId();
+        String imgUrls=t.getBillImage();
+        if (StrUtil.isEmpty(imgUrls)) {
+            throw new BusinessException("请上传截图");
         }
+        for (String billImage : StrUtil.split(t.getBillImage(), ",")) {
+            String transactionId;
+            if (StrUtil.isEmpty(t.getTransactionId())) {
+                //手动上传账单的情况
+                String result = orcImage(billImage);
+                transactionId = getTransId(result);
+            } else {
+                transactionId = t.getTransactionId();
+            }
 
-        TbInvoiceOrder InOrder = findByTransactionId(transactionId);
-        if (InOrder != null) {
-            throw new BusinessException("该账单已生成开票订单");
-        }
-        List<String> businessNameList = new ArrayList<>();
-        List<String> businessNoList = new ArrayList<>();
-        List<String> carNos = new ArrayList<>();
-        TbOrder tbOrder = tbOrderService.findByTransactionId(transactionId);
-        if (tbOrder == null) {
+            TbInvoiceOrder InOrder = findByTransactionId(transactionId);
+            if (InOrder != null) {
+                //throw new BusinessException("该账单已生成开票订单");
+                continue;
+            }
+            List<String> businessNameList = new ArrayList<>();
+            List<String> businessNoList = new ArrayList<>();
+            List<String> carNos = new ArrayList<>();
+            TbOrder tbOrder = tbOrderService.findByTransactionId(transactionId);
+            if (tbOrder == null) {
 //            throw new BusinessException("不存在该交易单号的业务订单");
-            return "500";
-        }
-        BigDecimal billMoney = new BigDecimal(tbOrder.getPrice());
-        String attachStr = tbOrder.getAttach();
-        Attach attach = JSONUtil.toBean(attachStr, Attach.class);
-        String businessId = attach.getB();
-        if (StrUtil.isNotEmpty(businessId)) {
-            List<String> businessIds = StrUtil.splitTrim(businessId, ",");
-            List<TbBusiness> businessList = tbBusinessService.listByIds(businessIds);
+                continue;
+            }
+            BigDecimal billMoney = new BigDecimal(tbOrder.getPrice());
+            String attachStr = tbOrder.getAttach();
+            Attach attach = JSONUtil.toBean(attachStr, Attach.class);
+            String businessId = attach.getB();
+            if (StrUtil.isNotEmpty(businessId)) {
+                List<String> businessIds = StrUtil.splitTrim(businessId, ",");
+                List<TbBusiness> businessList = tbBusinessService.listByIds(businessIds);
 
-            for (TbBusiness tbBusiness : businessList) {
-                businessNoList.add(tbBusiness.getNo());
-                List<String> carNoList = new ArrayList<>();
-                if (StrUtil.isNotEmpty(tbBusiness.getCardNo())) {
-                    carNoList.addAll(StrUtil.split(tbBusiness.getCardNo(), "、"));
-                }
-                if (StrUtil.isNotEmpty(tbBusiness.getChinaCarNo())) {
-                    carNoList.addAll(StrUtil.split(tbBusiness.getChinaCarNo(), "、"));
-                }
-                for (String no : carNoList) {
-                    if (!carNos.contains(no)) {
-                        carNos.add(no);
+                for (TbBusiness tbBusiness : businessList) {
+                    businessNoList.add(tbBusiness.getNo());
+                    List<String> carNoList = new ArrayList<>();
+                    if (StrUtil.isNotEmpty(tbBusiness.getCardNo())) {
+                        carNoList.addAll(StrUtil.split(tbBusiness.getCardNo(), "、"));
+                    }
+                    if (StrUtil.isNotEmpty(tbBusiness.getChinaCarNo())) {
+                        carNoList.addAll(StrUtil.split(tbBusiness.getChinaCarNo(), "、"));
+                    }
+                    for (String no : carNoList) {
+                        if (!carNos.contains(no)) {
+                            carNos.add(no);
+                        }
                     }
-                }
 
-                TbGoods good = tbGoodsService.getById(tbBusiness.getGoodsId());
-                businessNameList.add(good.getName());
+                    TbGoods good = tbGoodsService.getById(tbBusiness.getGoodsId());
+                    businessNameList.add(good.getName());
+                }
             }
-        }
-        List<PriceBO> cars = JSONUtil.toList(attach.getC(), PriceBO.class);
-        if (cars.size() > 0) {
-            businessNameList.add("停车费");
-            for (PriceBO bo1 : cars) {
-                TbBusinessCar car = tbBusinessCarService.getById(bo1.getId());
-                businessNoList.add(car.getNo());
-                if (!carNos.contains(car.getCarNo())) {
-                    carNos.add(car.getCarNo());
+            List<PriceBO> cars = JSONUtil.toList(attach.getC(), PriceBO.class);
+            if (cars.size() > 0) {
+                businessNameList.add("停车费");
+                for (PriceBO bo1 : cars) {
+                    TbBusinessCar car = tbBusinessCarService.getById(bo1.getId());
+                    businessNoList.add(car.getNo());
+                    if (!carNos.contains(car.getCarNo())) {
+                        carNos.add(car.getCarNo());
+                    }
                 }
             }
-        }
 
-        String businessNameStr = businessNameList.stream().map(String::valueOf).collect(Collectors.joining(","));
-        String businessNoStr = businessNoList.stream().map(String::valueOf).collect(Collectors.joining(","));
-        String carNoStr = carNos.stream().map(String::valueOf).collect(Collectors.joining(","));
-        t.setBusinessName(businessNameStr).setBusinessNo(businessNoStr).setCarNo(carNoStr).setStatus(1)
-                .setTransactionId(transactionId).setBillMoney(billMoney)
-                .setStatus(0).setCreateTime(new Date());
-        tbInvoiceOrderMapper.add(t);
+            String businessNameStr = businessNameList.stream().map(String::valueOf).collect(Collectors.joining(","));
+            String businessNoStr = businessNoList.stream().map(String::valueOf).collect(Collectors.joining(","));
+            String carNoStr = carNos.stream().map(String::valueOf).collect(Collectors.joining(","));
+            t.setBusinessName(businessNameStr).setBusinessNo(businessNoStr).setCarNo(carNoStr).setStatus(1)
+                    .setTransactionId(transactionId).setBillMoney(billMoney).setBillImage(billImage)
+                    .setStatus(0).setCreateTime(new Date());
+            tbInvoiceOrderMapper.add(t);
+        }
         return "200";
     }
 
@@ -154,6 +161,9 @@ public class TbInvoiceOrderService extends ServiceImpl<TbInvoiceOrderMapper, TbI
      * 增 --微信回调自动生成整车业务开票订单的情况
      */
     public void addT(String transactionId) {
+        if (StrUtil.isEmpty(transactionId)){
+            return;
+        }
         TbInvoiceOrder t = new TbInvoiceOrder();
         TbInvoiceOrder InOrder = findByTransactionId(transactionId);
         if (InOrder != null) {

+ 2 - 1
sp-server/src/main/java/com/pj/project/tb_order/TbOrderService.java

@@ -64,7 +64,8 @@ public class TbOrderService extends ServiceImpl<TbOrderMapper, TbOrder> implemen
                 tbOrder.setTransactionId(result.getStr("bankTrxNo"))
                         .setCompleteDate(completeDate);
                 JhNotifyBO notifyBO = new JhNotifyBO();
-                notifyBO.setAttach(tbOrder.getAttach()).setBankTrxNo(tbOrder.getTransactionId()).setSuccessTime(completeDate)
+                notifyBO.setSign(result.getStr("sign"));
+                notifyBO.setAttach(tbOrder.getAttach()).setBankTrxNo(result.getStr("bankTrxNo")).setSuccessTime(completeDate)
                         .setTradeStatus(orderStatus)
                         .setOutTradeNo(tbOrder.getOutTradeNo()).setOrderPrice(tbOrder.getPrice());
                 jhService.notifyResult(notifyBO);

+ 2 - 2
sp-server/src/main/java/com/pj/project4sp/apilog/Task.java

@@ -14,10 +14,10 @@ public class Task {
     @Resource
     SpApilogMapper spApilogMapper;
 
-    @Scheduled(cron = "0 0 4 * * ?")
+    @Scheduled(cron = "0 0 0 * * ?")
     public void cleanLog() {
         log.info("start clean api log");
         LocalDate today = LocalDate.now();
-        spApilogMapper.cleanHistoryLog(today.minusDays(90).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+        spApilogMapper.cleanHistoryLog(today.minusDays(30).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
     }
 }

+ 1 - 1
sp-server/src/main/java/com/pj/project4sp/uploadfile/UploadConfig.java

@@ -14,7 +14,7 @@ import org.springframework.stereotype.Component;
 @ConfigurationProperties(prefix = "spring.upload-config")
 public class UploadConfig {
 
-    public String rootFolder = "/upload-file";            // 文件保存的根目录,所有文件都保存在这个目录下
+    public String rootFolder = "/data";            // 文件保存的根目录,所有文件都保存在这个目录下
     public String httpPrefix = "/upload";                        // http路由前缀,用于向前台暴露文件url
 
     public String imageFolder = "/image";                        // 图片保存文件夹

+ 20 - 11
sp-server/src/main/java/com/pj/utils/cache/RedisUtil.java

@@ -3,8 +3,11 @@ package com.pj.utils.cache;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
+import org.springframework.data.redis.core.script.RedisScript;
 import org.springframework.stereotype.Component;
 
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
@@ -16,9 +19,7 @@ import java.util.concurrent.TimeUnit;
 @Component
 public class RedisUtil {
 
-
-    public static long ttl = 24 * 7;    //默认超时时间,单位周,此为一周
-
+    public static long ttl = 24 * 7;    // 默认超时时间,单位小时,此为一周
 
     /**
      * 对象专用
@@ -41,11 +42,8 @@ public class RedisUtil {
         RedisUtil.stringRedisTemplate = stringRedisTemplates;
     }
 
-
-
     /* * * * * * * * * * * * * * * * String操作 * * * * * * * * * * * * * * * * * * * * * * * * */
 
-
     // 默认7*24小时
     public static void set(String key, String value) {
         stringRedisTemplate.opsForValue().set(key, value, ttl, TimeUnit.HOURS);
@@ -61,7 +59,7 @@ public class RedisUtil {
         stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MINUTES);
     }
 
-    // 写入,并设置时长,单位 分钟 MINUTES
+    // 写入,并设置时长,单位 秒 SECONDS
     public static void setBySECONDS(String key, String value, int timeout) {
         stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
     }
@@ -71,13 +69,11 @@ public class RedisUtil {
         return stringRedisTemplate.opsForValue().get(key);
     }
 
-
     // 删除
     public static void del(String key) {
         stringRedisTemplate.delete(key);
     }
 
-
     /* * * * * * * * * * * * * * * * List集合操作 * * * * * * * * * * * * * * * * * * * * * * * * */
 
     // 查询
@@ -98,7 +94,6 @@ public class RedisUtil {
         }
     }
 
-
     /* * * * * * * * * * * * * * * * Object值操作 * * * * * * * * * * * * * * * * * * * * * * * * */
 
     // 写入值
@@ -112,5 +107,19 @@ public class RedisUtil {
         return (T) redisTemplate.opsForValue().get(key);
     }
 
+    /* * * * * * * * * * * * * * * * 锁操作 * * * * * * * * * * * * * * * * * * * * * * * * */
+
+    // 尝试获取锁
+    public static boolean tryLock(String key, String value, int timeout, TimeUnit timeUnit) {
+        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit);
+        return result != null && result;
+    }
+    // 释放锁
+    public static boolean releaseLock(String key, String value) {
+        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
+        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
+        Long result = stringRedisTemplate.execute(redisScript, Collections.singletonList(key), value);
+        return result != null && result > 0;
+    }
 
-}
+}

+ 1 - 1
sp-server/src/main/resources/application-dev.yml

@@ -28,7 +28,7 @@ spring:
         # Redis服务器连接端口
         port: 6379
         # Redis服务器连接密码(默认为空)
-        # password:
+        password: 123456
         # 连接超时时间(毫秒)
         timeout: 5000ms
         jedis:

+ 1 - 0
sp-server/src/main/resources/application.yml

@@ -60,6 +60,7 @@ mybatis-plus:
     configuration:
         # 是否开启下划线转驼峰 
         map-underscore-to-camel-case: true
+#        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
         # 即使属性为null, 也要映射 
         call-setters-on-nulls: true
 server:

+ 1 - 2
sp-server/src/main/resources/logback.xml

@@ -115,11 +115,10 @@
     <logger name="java.sql.PreparedStatement" level="DEBUG"/>
 
     <!-- 生产环境下,将此级别配置为适合的级别,以免日志文件太多或影响程序性能 -->
-    <root level="INFO">
+    <root level="info">
         <!-- 生产环境将请stdout,testfile去掉 -->
         <appender-ref ref="STDOUT"/>
         <appender-ref ref="FILE_DEBUG"/>
-        <!--<appender-ref ref="FILEWARN"/>-->
         <appender-ref ref="FILE_INFO"/>
     </root>
 </configuration>