commit d46f96d2636b915c86217b89e45573201d95111c Author: fengachen <373943794@qq.com> Date: Wed Sep 15 09:58:01 2021 +0800 initital commit diff --git a/app.js b/app.js new file mode 100644 index 0000000..1ed57c4 --- /dev/null +++ b/app.js @@ -0,0 +1,19 @@ +// app.js +App({ + onLaunch() { + // 展示本地存储能力 + const logs = wx.getStorageSync('logs') || [] + logs.unshift(Date.now()) + wx.setStorageSync('logs', logs) + + // 登录 + wx.login({ + success: res => { + // 发送 res.code 到后台换取 openId, sessionKey, unionId + } + }) + }, + globalData: { + userInfo: null + } +}) diff --git a/app.json b/app.json new file mode 100644 index 0000000..9cf6286 --- /dev/null +++ b/app.json @@ -0,0 +1,49 @@ +{ + "pages":[ + "pages/notice/notice", + "pages/project/project", + "pages/meeting/meeting", + "pages/mine/mine", + "pages/index/index", + "pages/logs/logs" + ], + "window":{ + "backgroundTextStyle":"light", + "navigationBarBackgroundColor": "#fff", + "navigationBarTitleText": "Weixin", + "navigationBarTextStyle":"black" + }, + "tabBar": { + "selectedColor": "#08A09A", + "color": "#999", + "backgroundColor": "#fff", + "list": [ + { + "text": "消息", + "pagePath": "pages/notice/notice", + "iconPath": "./assets/images/notice.png", + "selectedIconPath": "./assets/images/notice-active.png" + }, + { + "text": "项目", + "pagePath": "pages/project/project", + "iconPath": "./assets/images/project.png", + "selectedIconPath": "./assets/images/project-active.png" + }, + { + "text": "会议", + "pagePath": "pages/meeting/meeting", + "iconPath": "./assets/images/meeting.png", + "selectedIconPath": "./assets/images/meeting-active.png" + }, + { + "text": "我的", + "pagePath": "pages/mine/mine", + "iconPath": "./assets/images/mine.png", + "selectedIconPath": "./assets/images/mine-active.png" + } + ] + }, + "style": "v2", + "sitemapLocation": "sitemap.json" +} diff --git a/app.wxss b/app.wxss new file mode 100644 index 0000000..050dc03 --- /dev/null +++ b/app.wxss @@ -0,0 +1,8 @@ +/**app.wxss**/ +.container { + background-color: #f5f5f5; + width: 100%; + height: 100%; +} +@import './assets/css/common.wxss'; +@import '/assets/font/iconfont.wxss'; \ No newline at end of file diff --git a/assets/css/common.wxss b/assets/css/common.wxss new file mode 100644 index 0000000..fa062f5 --- /dev/null +++ b/assets/css/common.wxss @@ -0,0 +1,770 @@ +page { + overflow-x: hidden; + width: 100%; + background-color: #fff; + color: #333; + font-size: 30rpx; +} +page::after { + content: ""; + position: fixed; + left: 0; + bottom: 0; + width: 100%; + height: 2rpx; + background-color: #E5E6EA; + z-index: 9999; +} +.container{ + overflow-x: hidden; + width: 100%; +} +image { + width: 100%; + height: 100%; +} +.bg_fff{ + background-color: #fff; +} +.bg_d{ + background-color: #00b3c7; +} +.cd { + color: #65A6FF; +} +.cb{ + color: #4DA8FF; +} +.cg { + color: #AB9985; +} +.cw { + color: #fff; +} +.c6{ + color: #666666; +} +.cc{ + color: #CCCCCC; +} +.c9{ + color:#999999; +} +.a2{ +color: #2A2A2A; +} +.hover-default { + opacity: 0.8; +} +.button { + position: relative; +} +.button button { + position: absolute; + left: 0; + top: 0; + width: 100%; + height: 100%; + z-index: 1; + opacity: 0; +} +.button.primary { + display: flex; + align-items: center; + justify-content: center; + background-color: #00b3c7; + border-radius: 8rpx; + color: #fff; +} +.button.disable { + display: flex; + align-items: center; + justify-content: center; + background-color: #EBEBED; + border-radius: 8rpx; + color: #666666; +} + +.dn { + display: none; +} +.di { + display: inline; +} +.db { + display: block; +} +.w100 { + width: 100%; +} +.h100 { + height: 100%; +} +.dib { + display: inline-block; +} +.box_bb { + box-sizing: border-box; +} +.lh14 { + line-height: 14rpx; +} +.lh16 { + line-height: 16rpx; +} +.lh18 { + line-height: 18rpx; +} +.lh20 { + line-height: 20rpx; +} +.lh22 { + line-height: 22rpx; +} +.lh24 { + line-height: 24rpx; +} +.lh28 { + line-height: 28rpx; +} +.lh40 { + line-height: 40rpx; +} +.m0 { + margin: 0; +} +.m5 { + margin: 5rpx; +} +.m10 { + margin: 10rpx; +} +.m15 { + margin: 15rpx; +} +.m20 { + margin: 20rpx; +} +.m25 { + margin: 25rpx; +} +.m30 { + margin: 30rpx; +} +.mla { + margin-left: auto; +} +.ml1 { + margin-left: 1rpx; +} +.ml2 { + margin-left: 2rpx; +} +.ml5 { + margin-left: 5rpx; +} +.ml10 { + margin-left: 10rpx; +} +.ml15 { + margin-left: 15rpx; +} +.ml20 { + margin-left: 20rpx; +} +.ml25 { + margin-left: 25rpx; +} +.ml30 { + margin-left: 30rpx; +} +.mra { + margin-right: auto; +} +.mr1 { + margin-right: 1rpx; +} +.mr2 { + margin-right: 2rpx; +} +.mr5 { + margin-right: 5rpx; +} +.mr10 { + margin-right: 10rpx; +} +.mr15 { + margin-right: 15rpx; +} +.mr20 { + margin-right: 20rpx; +} +.mr25 { + margin-right: 25rpx; +} +.mr30 { + margin-right: 30rpx; +} +.mr-10 { + margin-right: -10rpx; +} +.mr-15 { + margin-right: -15rpx; +} +.mta { + margin-top: auto; +} +.mt1 { + margin-top: 1rpx; +} +.mt2 { + margin-top: 2rpx; +} +.mt5 { + margin-top: 5rpx; +} +.mt10 { + margin-top: 10rpx; +} +.mt15 { + margin-top: 15rpx; +} +.mt20 { + margin-top: 20rpx; +} +.mt25 { + margin-top: 25rpx; +} +.mt30 { + margin-top: 30rpx; +} +.mt50 { + margin-top: 50rpx; +} +.mt-5 { + margin-top: -5rpx; +} +.mt-10 { + margin-top: -10rpx; +} +.mt-15 { + margin-top: -15rpx; +} +.mb1 { + margin-bottom: 1rpx; +} +.mb2 { + margin-bottom: 2rpx; +} +.mb5 { + margin-bottom: 5rpx; +} +.mb10 { + margin-bottom: 10rpx; +} +.mb15 { + margin-bottom: 15rpx; +} +.mb20 { + margin-bottom: 20rpx; +} +.mb25 { + margin-bottom: 25rpx; +} +.mb30 { + margin-bottom: 30rpx; +} +.mb-5 { + margin-bottom: -5rpx; +} +.mb-10 { + margin-bottom: -10rpx; +} +.mb-15 { + margin-bottom: -15rpx; +} +.p0 { + padding: 0; +} +.p1 { + padding: 1rpx; +} +.pl1 { + padding-left: 1rpx; +} +.pt1 { + padding-top: 1rpx; +} +.pr1 { + padding-right: 1rpx; +} +.pb1 { + padding-bottom: 1rpx; +} +.p2 { + padding: 2rpx; +} +.pl2 { + padding-left: 2rpx; +} +.pt2 { + padding-top: 2rpx; +} +.pr2 { + padding-right: 2rpx; +} +.pb2 { + padding-bottom: 2rpx; +} +.pl5 { + padding-left: 5rpx; +} +.p5 { + padding: 5rpx; +} +.pt5 { + padding-top: 5rpx; +} +.pr5 { + padding-right: 5rpx; +} +.pb5 { + padding-bottom: 5rpx; +} +.p10 { + padding: 10rpx; +} +.pl10 { + padding-left: 10rpx; +} +.pt10 { + padding-top: 10rpx; +} +.pr10 { + padding-right: 10rpx; +} +.pb10 { + padding-bottom: 10rpx; +} +.p15 { + padding: 15rpx; +} +.pl15 { + padding-left: 15rpx; +} +.pt15 { + padding-top: 15rpx; +} +.pr15 { + padding-right: 15rpx; +} +.pb15 { + padding-bottom: 15rpx; +} +.p20 { + padding: 20rpx; +} +.pl20 { + padding-left: 20rpx; +} +.pt20 { + padding-top: 20rpx; +} +.pr20 { + padding-right: 20rpx; +} +.pb20 { + padding-bottom: 20rpx; +} +.p25 { + padding: 25rpx; +} +.pl25 { + padding-left: 25rpx; +} +.pt25 { + padding-top: 25rpx; +} +.pr25 { + padding-right: 25rpx; +} +.pb25 { + padding-bottom: 25rpx; +} +.p30 { + padding: 30rpx; +} +.pl30 { + padding-left: 30rpx; +} +.pt30 { + padding-top: 30rpx; +} +.pr30 { + padding-right: 30rpx; +} +.pb30 { + padding-bottom: 30rpx; +} +.bt1 { + border-top: 1rpx solid #f6f8fc; +} +.bb1 { + border-bottom: 1rpx solid #f6f8fc; +} +.bl1 { + border-left: 1rpx solid #f6f8fc; +} +.br1 { + border-right: 1rpx solid #f6f8fc; +} +.bt10 { + border-top: 10rpx solid #f6f8fc; +} +.bb10 { + border-bottom: 10rpx solid #f6f8fc; +} +.f0 { + font-size: 0; +} +.f20 { + font-size: 20rpx; +} +.f24 { + font-size: 24rpx; +} +.f26 { + font-size: 26rpx; +} +.f28 { + font-size: 28rpx; +} +.f32 { + font-size: 32rpx; +} +.f34 { + font-size: 34rpx; +} +.f36 { + font-size: 36rpx; +} +.f40 { + font-size: 40rpx; +} +.f44 { + font-size: 44rpx; +} +.f48 { + font-size: 48rpx; +} +.f56 { + font-size: 56rpx; +} +.n { + font-weight: normal; + font-style: normal; +} +.b { + font-weight: bold; +} +.i { + font-style: italic; +} +.tc { + text-align: center; +} +.tr { + text-align: right; +} +.tl { + text-align: left; +} +.tj,.th_tj { + text-align: justify; +} +.th_tj:after{ + content: ''; + display: inline-block; + width: 100%; + height: 1rpx; +} +.tdl { + text-decoration: underline; +} +.lt-1 { + letter-spacing: -1rpx; +} +.lt0 { + letter-spacing: 0; +} +.lt1 { + letter-spacing: 1rpx; +} +.nowrap { + white-space: nowrap; +} +.bk { + word-wrap: break-word; +} +.vm { + vertical-align: middle; +} +.vb { + vertical-align: bottom; +} +.vt { + vertical-align: top; +} +.vn { + vertical-align: -5rpx; +} +.l { + float: left; +} +.r { + float: right; +} +.cl { + clear: both; +} +.rel { + position: relative; +} +.abs,.cm { + position: absolute; +} +.fixed { + position: fixed; +} +.zx1 { + z-index: 1; +} +.zx2 { + z-index: 2; +} +.zx8 { + z-index: 8; +} +.zx9 { + z-index: 9; +} +.zx99 { + z-index: 99; +} +.zx999 { + z-index: 999; +} +.cm{ + left: 50%; + top: 50%; + transform: translate(-50%,-50%); +} +.t0{ + top: 0; +} +.t50{ + top: 50%; +} +.b0{ + bottom: 0; +} +.l0{ + left: 0; +} +.l50{ + left: 50%; +} +.r0{ + right: 0; +} +.ovh { + overflow: hidden; +} +.ova { + overflow: auto; +} +.vh { + visibility: hidden; +} +.vv { + visibility: visible; +} +.o0{ + opacity: 0; +} +.clearfix, +.fix { + zoom: 1; +} +.clearfix:after, +.fix:after { + display: table; + content: ""; + clear: both; +} +.ell { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} +.ell_more{ + overflow : hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-box-orient: vertical; +} +.ell_2{ + -webkit-line-clamp: 2; +} +.ell_3{ + -webkit-line-clamp: 3; +} +.middle { + display: inline-block; + width: 0; + height: 100%; + vertical-align: middle; +} +.trans { + transition: all 250ms; +} +.disabled { + opacity: 0.4; + filter: alpha(opacity=40); + cursor: default; + -ms-pointer-events: none; + pointer-events: none; +} + +.flex { + /* 转为弹性盒模型 */ + display: flex; +} +.flex_wrap { + /* 转为弹性盒模型并自动换行 */ + display: flex; + flex-wrap: wrap; +} + +.flex_b { + /* 垂直底部对齐 */ + display: flex; + align-items: flex-end; +} +.flex_tb { + /* 垂直两端对齐 */ + display: flex; + flex-direction: column; + justify-content: space-between; +} + +.flex_tb_c { + /* 多行垂直两端对齐,水平居中 */ + display: flex; + flex-direction: column; + align-items: center; + justify-content: space-between; +} +.flex_line_c { + /* 多行垂直水平居中 */ + display: flex; + flex-direction: column; + align-items: center; +} +.flex_line_c_m { + /* 多行垂直居中,水平居中 */ + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; +} +.flex_line_end { + /* 多行垂直起点在下沿 */ + display: flex; + flex-direction: column-reverse; +} +.flex_lr { + /* 水平两端对齐,剩余空间平均分布 */ + display: flex; + justify-content: space-between; +} + +.flex_lr_m { + /* 水平两端对齐,剩余空间平均分布,垂直居中 */ + display: flex; + align-items: center; + justify-content: space-between; +} + +.flex_c_m { + /* 垂直水平居中 */ + display: flex; + align-items: center; + justify-content: center; +} + +.flex_c { + /* 水平居中 */ + display: flex; + justify-content: center; +} + +.flex_m { + /* 垂直居中 */ + display: flex; + align-items: center; +} + +.flex_nosize { + /* 子元素不自动 */ + flex-shrink: 0; +} + +.flex_autosize { + /* 子元素自动宽度 */ + flex-grow: 1; +} + +.flex_inline { + /* 转为行内弹性盒模型 */ + display: inline-flex; +} + +.flex0{ + flex: 0; + min-width: 0; +} +.flex1{ + flex: 1; + min-width: 0; +} + +.Mask{ + position: fixed; + left: 0; + top: 0; + right: 0; + bottom: 0; + background-color: rgba(0,0,0,0.5); +} +.Mask .maskClick{ + position: absolute; + left: 0; + top: 0; + width: 100%; + height: 100%; +} + +.container{ + min-height: 100%; +} +.errorMessageBox{ + min-height: 100%; +} +.errorMessageBox .bottom{ + position: absolute; + left: 0; + bottom: 0; + width: 100%; + border-top: 10rpx solid #f6f8fc; +} \ No newline at end of file diff --git a/assets/font/demo.css b/assets/font/demo.css new file mode 100644 index 0000000..a67054a --- /dev/null +++ b/assets/font/demo.css @@ -0,0 +1,539 @@ +/* Logo 字体 */ +@font-face { + font-family: "iconfont logo"; + src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834'); + src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834#iefix') format('embedded-opentype'), + url('https://at.alicdn.com/t/font_985780_km7mi63cihi.woff?t=1545807318834') format('woff'), + url('https://at.alicdn.com/t/font_985780_km7mi63cihi.ttf?t=1545807318834') format('truetype'), + url('https://at.alicdn.com/t/font_985780_km7mi63cihi.svg?t=1545807318834#iconfont') format('svg'); +} + +.logo { + font-family: "iconfont logo"; + font-size: 160px; + font-style: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +/* tabs */ +.nav-tabs { + position: relative; +} + +.nav-tabs .nav-more { + position: absolute; + right: 0; + bottom: 0; + height: 42px; + line-height: 42px; + color: #666; +} + +#tabs { + border-bottom: 1px solid #eee; +} + +#tabs li { + cursor: pointer; + width: 100px; + height: 40px; + line-height: 40px; + text-align: center; + font-size: 16px; + border-bottom: 2px solid transparent; + position: relative; + z-index: 1; + margin-bottom: -1px; + color: #666; +} + + +#tabs .active { + border-bottom-color: #f00; + color: #222; +} + +.tab-container .content { + display: none; +} + +/* 页面布局 */ +.main { + padding: 30px 100px; + width: 960px; + margin: 0 auto; +} + +.main .logo { + color: #333; + text-align: left; + margin-bottom: 30px; + line-height: 1; + height: 110px; + margin-top: -50px; + overflow: hidden; + *zoom: 1; +} + +.main .logo a { + font-size: 160px; + color: #333; +} + +.helps { + margin-top: 40px; +} + +.helps pre { + padding: 20px; + margin: 10px 0; + border: solid 1px #e7e1cd; + background-color: #fffdef; + overflow: auto; +} + +.icon_lists { + width: 100% !important; + overflow: hidden; + *zoom: 1; +} + +.icon_lists li { + width: 100px; + margin-bottom: 10px; + margin-right: 20px; + text-align: center; + list-style: none !important; + cursor: default; +} + +.icon_lists li .code-name { + line-height: 1.2; +} + +.icon_lists .icon { + display: block; + height: 100px; + line-height: 100px; + font-size: 42px; + margin: 10px auto; + color: #333; + -webkit-transition: font-size 0.25s linear, width 0.25s linear; + -moz-transition: font-size 0.25s linear, width 0.25s linear; + transition: font-size 0.25s linear, width 0.25s linear; +} + +.icon_lists .icon:hover { + font-size: 100px; +} + +.icon_lists .svg-icon { + /* 通过设置 font-size 来改变图标大小 */ + width: 1em; + /* 图标和文字相邻时,垂直对齐 */ + vertical-align: -0.15em; + /* 通过设置 color 来改变 SVG 的颜色/fill */ + fill: currentColor; + /* path 和 stroke 溢出 viewBox 部分在 IE 下会显示 + normalize.css 中也包含这行 */ + overflow: hidden; +} + +.icon_lists li .name, +.icon_lists li .code-name { + color: #666; +} + +/* markdown 样式 */ +.markdown { + color: #666; + font-size: 14px; + line-height: 1.8; +} + +.highlight { + line-height: 1.5; +} + +.markdown img { + vertical-align: middle; + max-width: 100%; +} + +.markdown h1 { + color: #404040; + font-weight: 500; + line-height: 40px; + margin-bottom: 24px; +} + +.markdown h2, +.markdown h3, +.markdown h4, +.markdown h5, +.markdown h6 { + color: #404040; + margin: 1.6em 0 0.6em 0; + font-weight: 500; + clear: both; +} + +.markdown h1 { + font-size: 28px; +} + +.markdown h2 { + font-size: 22px; +} + +.markdown h3 { + font-size: 16px; +} + +.markdown h4 { + font-size: 14px; +} + +.markdown h5 { + font-size: 12px; +} + +.markdown h6 { + font-size: 12px; +} + +.markdown hr { + height: 1px; + border: 0; + background: #e9e9e9; + margin: 16px 0; + clear: both; +} + +.markdown p { + margin: 1em 0; +} + +.markdown>p, +.markdown>blockquote, +.markdown>.highlight, +.markdown>ol, +.markdown>ul { + width: 80%; +} + +.markdown ul>li { + list-style: circle; +} + +.markdown>ul li, +.markdown blockquote ul>li { + margin-left: 20px; + padding-left: 4px; +} + +.markdown>ul li p, +.markdown>ol li p { + margin: 0.6em 0; +} + +.markdown ol>li { + list-style: decimal; +} + +.markdown>ol li, +.markdown blockquote ol>li { + margin-left: 20px; + padding-left: 4px; +} + +.markdown code { + margin: 0 3px; + padding: 0 5px; + background: #eee; + border-radius: 3px; +} + +.markdown strong, +.markdown b { + font-weight: 600; +} + +.markdown>table { + border-collapse: collapse; + border-spacing: 0px; + empty-cells: show; + border: 1px solid #e9e9e9; + width: 95%; + margin-bottom: 24px; +} + +.markdown>table th { + white-space: nowrap; + color: #333; + font-weight: 600; +} + +.markdown>table th, +.markdown>table td { + border: 1px solid #e9e9e9; + padding: 8px 16px; + text-align: left; +} + +.markdown>table th { + background: #F7F7F7; +} + +.markdown blockquote { + font-size: 90%; + color: #999; + border-left: 4px solid #e9e9e9; + padding-left: 0.8em; + margin: 1em 0; +} + +.markdown blockquote p { + margin: 0; +} + +.markdown .anchor { + opacity: 0; + transition: opacity 0.3s ease; + margin-left: 8px; +} + +.markdown .waiting { + color: #ccc; +} + +.markdown h1:hover .anchor, +.markdown h2:hover .anchor, +.markdown h3:hover .anchor, +.markdown h4:hover .anchor, +.markdown h5:hover .anchor, +.markdown h6:hover .anchor { + opacity: 1; + display: inline-block; +} + +.markdown>br, +.markdown>p>br { + clear: both; +} + + +.hljs { + display: block; + background: white; + padding: 0.5em; + color: #333333; + overflow-x: auto; +} + +.hljs-comment, +.hljs-meta { + color: #969896; +} + +.hljs-string, +.hljs-variable, +.hljs-template-variable, +.hljs-strong, +.hljs-emphasis, +.hljs-quote { + color: #df5000; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-type { + color: #a71d5d; +} + +.hljs-literal, +.hljs-symbol, +.hljs-bullet, +.hljs-attribute { + color: #0086b3; +} + +.hljs-section, +.hljs-name { + color: #63a35c; +} + +.hljs-tag { + color: #333333; +} + +.hljs-title, +.hljs-attr, +.hljs-selector-id, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo { + color: #795da3; +} + +.hljs-addition { + color: #55a532; + background-color: #eaffea; +} + +.hljs-deletion { + color: #bd2c00; + background-color: #ffecec; +} + +.hljs-link { + text-decoration: underline; +} + +/* 代码高亮 */ +/* PrismJS 1.15.0 +https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript */ +/** + * prism.js default theme for JavaScript, CSS and HTML + * Based on dabblet (http://dabblet.com) + * @author Lea Verou + */ +code[class*="language-"], +pre[class*="language-"] { + color: black; + background: none; + text-shadow: 0 1px white; + font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; + text-align: left; + white-space: pre; + word-spacing: normal; + word-break: normal; + word-wrap: normal; + line-height: 1.5; + + -moz-tab-size: 4; + -o-tab-size: 4; + tab-size: 4; + + -webkit-hyphens: none; + -moz-hyphens: none; + -ms-hyphens: none; + hyphens: none; +} + +pre[class*="language-"]::-moz-selection, +pre[class*="language-"] ::-moz-selection, +code[class*="language-"]::-moz-selection, +code[class*="language-"] ::-moz-selection { + text-shadow: none; + background: #b3d4fc; +} + +pre[class*="language-"]::selection, +pre[class*="language-"] ::selection, +code[class*="language-"]::selection, +code[class*="language-"] ::selection { + text-shadow: none; + background: #b3d4fc; +} + +@media print { + + code[class*="language-"], + pre[class*="language-"] { + text-shadow: none; + } +} + +/* Code blocks */ +pre[class*="language-"] { + padding: 1em; + margin: .5em 0; + overflow: auto; +} + +:not(pre)>code[class*="language-"], +pre[class*="language-"] { + background: #f5f2f0; +} + +/* Inline code */ +:not(pre)>code[class*="language-"] { + padding: .1em; + border-radius: .3em; + white-space: normal; +} + +.token.comment, +.token.prolog, +.token.doctype, +.token.cdata { + color: slategray; +} + +.token.punctuation { + color: #999; +} + +.namespace { + opacity: .7; +} + +.token.property, +.token.tag, +.token.boolean, +.token.number, +.token.constant, +.token.symbol, +.token.deleted { + color: #905; +} + +.token.selector, +.token.attr-name, +.token.string, +.token.char, +.token.builtin, +.token.inserted { + color: #690; +} + +.token.operator, +.token.entity, +.token.url, +.language-css .token.string, +.style .token.string { + color: #9a6e3a; + background: hsla(0, 0%, 100%, .5); +} + +.token.atrule, +.token.attr-value, +.token.keyword { + color: #07a; +} + +.token.function, +.token.class-name { + color: #DD4A68; +} + +.token.regex, +.token.important, +.token.variable { + color: #e90; +} + +.token.important, +.token.bold { + font-weight: bold; +} + +.token.italic { + font-style: italic; +} + +.token.entity { + cursor: help; +} diff --git a/assets/font/demo_index.html b/assets/font/demo_index.html new file mode 100644 index 0000000..43e6786 --- /dev/null +++ b/assets/font/demo_index.html @@ -0,0 +1,214 @@ + + + + + IconFont Demo + + + + + + + + + + + +
+

+ +
+
+
    + +
  • + +
    +
    &#xe619;
    +
  • + +
  • + +
    +
    &#xe61a;
    +
  • + +
+
+

Unicode 引用

+
+ +

Unicode 是字体在网页端最原始的应用方式,特点是:

+
    +
  • 兼容性最好,支持 IE6+,及所有现代浏览器。
  • +
  • 支持按字体的方式去动态调整图标大小,颜色等等。
  • +
  • 但是因为是字体,所以不支持多色。只能使用平台里单色的图标,就算项目里有多色图标也会自动去色。
  • +
+
+

注意:新版 iconfont 支持多色图标,这些多色图标在 Unicode 模式下将不能使用,如果有需求建议使用symbol 的引用方式

+
+

Unicode 使用步骤如下:

+

第一步:拷贝项目下面生成的 @font-face

+
@font-face {
+  font-family: 'iconfont';
+  src: url('iconfont.eot');
+  src: url('iconfont.eot?#iefix') format('embedded-opentype'),
+      url('iconfont.woff2') format('woff2'),
+      url('iconfont.woff') format('woff'),
+      url('iconfont.ttf') format('truetype'),
+      url('iconfont.svg#iconfont') format('svg');
+}
+
+

第二步:定义使用 iconfont 的样式

+
.iconfont {
+  font-family: "iconfont" !important;
+  font-size: 16px;
+  font-style: normal;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+

第三步:挑选相应图标并获取字体编码,应用于页面

+
+<span class="iconfont">&#x33;</span>
+
+
+

"iconfont" 是你项目下的 font-family。可以通过编辑项目查看,默认是 "iconfont"。

+
+
+
+
+
    + +
  • + +
    + 减 +
    +
    .icon-jian +
    +
  • + +
  • + +
    + 加 +
    +
    .icon-jia +
    +
  • + +
+
+

font-class 引用

+
+ +

font-class 是 Unicode 使用方式的一种变种,主要是解决 Unicode 书写不直观,语意不明确的问题。

+

与 Unicode 使用方式相比,具有如下特点:

+
    +
  • 兼容性良好,支持 IE8+,及所有现代浏览器。
  • +
  • 相比于 Unicode 语意明确,书写更直观。可以很容易分辨这个 icon 是什么。
  • +
  • 因为使用 class 来定义图标,所以当要替换图标时,只需要修改 class 里面的 Unicode 引用。
  • +
  • 不过因为本质上还是使用的字体,所以多色图标还是不支持的。
  • +
+

使用步骤如下:

+

第一步:引入项目下面生成的 fontclass 代码:

+
<link rel="stylesheet" href="./iconfont.css">
+
+

第二步:挑选相应图标并获取类名,应用于页面:

+
<span class="iconfont icon-xxx"></span>
+
+
+

" + iconfont" 是你项目下的 font-family。可以通过编辑项目查看,默认是 "iconfont"。

+
+
+
+
+
    + +
  • + +
    +
    #icon-jian
    +
  • + +
  • + +
    +
    #icon-jia
    +
  • + +
+
+

Symbol 引用

+
+ +

这是一种全新的使用方式,应该说这才是未来的主流,也是平台目前推荐的用法。相关介绍可以参考这篇文章 + 这种用法其实是做了一个 SVG 的集合,与另外两种相比具有如下特点:

+
    +
  • 支持多色图标了,不再受单色限制。
  • +
  • 通过一些技巧,支持像字体那样,通过 font-size, color 来调整样式。
  • +
  • 兼容性较差,支持 IE9+,及现代浏览器。
  • +
  • 浏览器渲染 SVG 的性能一般,还不如 png。
  • +
+

使用步骤如下:

+

第一步:引入项目下面生成的 symbol 代码:

+
<script src="./iconfont.js"></script>
+
+

第二步:加入通用 CSS 代码(引入一次就行):

+
<style>
+.icon {
+  width: 1em;
+  height: 1em;
+  vertical-align: -0.15em;
+  fill: currentColor;
+  overflow: hidden;
+}
+</style>
+
+

第三步:挑选相应图标并获取类名,应用于页面:

+
<svg class="icon" aria-hidden="true">
+  <use xlink:href="#icon-xxx"></use>
+</svg>
+
+
+
+ +
+
+ + + diff --git a/assets/font/iconfont.eot b/assets/font/iconfont.eot new file mode 100644 index 0000000..81ae563 Binary files /dev/null and b/assets/font/iconfont.eot differ diff --git a/assets/font/iconfont.js b/assets/font/iconfont.js new file mode 100644 index 0000000..51b8739 --- /dev/null +++ b/assets/font/iconfont.js @@ -0,0 +1 @@ +!function(a){var e,n='',t=(e=document.getElementsByTagName("script"))[e.length-1].getAttribute("data-injectcss");if(t&&!a.__iconfont__svg__cssinject__){a.__iconfont__svg__cssinject__=!0;try{document.write("")}catch(e){console&&console.log(e)}}!function(e){if(document.addEventListener)if(~["complete","loaded","interactive"].indexOf(document.readyState))setTimeout(e,0);else{var t=function(){document.removeEventListener("DOMContentLoaded",t,!1),e()};document.addEventListener("DOMContentLoaded",t,!1)}else document.attachEvent&&(o=e,i=a.document,c=!1,(d=function(){try{i.documentElement.doScroll("left")}catch(e){return void setTimeout(d,50)}n()})(),i.onreadystatechange=function(){"complete"==i.readyState&&(i.onreadystatechange=null,n())});function n(){c||(c=!0,o())}var o,i,c,d}(function(){var e,t;(e=document.createElement("div")).innerHTML=n,n=null,(t=e.getElementsByTagName("svg")[0])&&(t.setAttribute("aria-hidden","true"),t.style.position="absolute",t.style.width=0,t.style.height=0,t.style.overflow="hidden",function(e,t){t.firstChild?function(e,t){t.parentNode.insertBefore(e,t)}(e,t.firstChild):t.appendChild(e)}(t,document.body))})}(window); \ No newline at end of file diff --git a/assets/font/iconfont.json b/assets/font/iconfont.json new file mode 100644 index 0000000..269921f --- /dev/null +++ b/assets/font/iconfont.json @@ -0,0 +1,23 @@ +{ + "id": "", + "name": "", + "font_family": "iconfont", + "css_prefix_text": "icon-", + "description": "", + "glyphs": [ + { + "icon_id": "654162", + "name": "减", + "font_class": "jian", + "unicode": "e619", + "unicode_decimal": 58905 + }, + { + "icon_id": "654163", + "name": "加", + "font_class": "jia", + "unicode": "e61a", + "unicode_decimal": 58906 + } + ] +} diff --git a/assets/font/iconfont.svg b/assets/font/iconfont.svg new file mode 100644 index 0000000..72fcddc --- /dev/null +++ b/assets/font/iconfont.svg @@ -0,0 +1,32 @@ + + + + + +Created by iconfont + + + + + + + + + + + + + + + + + diff --git a/assets/font/iconfont.ttf b/assets/font/iconfont.ttf new file mode 100644 index 0000000..5c23064 Binary files /dev/null and b/assets/font/iconfont.ttf differ diff --git a/assets/font/iconfont.woff b/assets/font/iconfont.woff new file mode 100644 index 0000000..f26c0e4 Binary files /dev/null and b/assets/font/iconfont.woff differ diff --git a/assets/font/iconfont.woff2 b/assets/font/iconfont.woff2 new file mode 100644 index 0000000..15c7189 Binary files /dev/null and b/assets/font/iconfont.woff2 differ diff --git a/assets/font/iconfont.wxss b/assets/font/iconfont.wxss new file mode 100644 index 0000000..7b849a8 --- /dev/null +++ b/assets/font/iconfont.wxss @@ -0,0 +1,25 @@ +@font-face {font-family: "iconfont"; + src: url('iconfont.eot?t=1574240438561'); /* IE9 */ + src: url('iconfont.eot?t=1574240438561#iefix') format('embedded-opentype'), /* IE6-IE8 */ + url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAALMAAsAAAAABuAAAAJ/AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCCfgqBVIFEATYCJAMMCwgABCAFhG0HNBsABsg+QDZkA29GJAJpmfH2sw9ROWtmL/4jQrmpIh6+9ns9d/d+2hdgBQpQRgKOj4qCEhoRW9UIX12hazuehWFh6f7X2pxZ6PP6ebxkAum0rc9f8dlBOy2TClQahEYDDIAMS5DZ+gag0eTmBgcvUvTC/i0wlK622QkAONtff77D/rh3+kedd1k0n0XlNMfGT12A8dau870xiqxAQm8Yu8AlPCbQLOsrnW0fL9CUrFWBeOm7JjRzQSlZZij0aw6muNUzLK/KF+B1+P34zTSGFL3K2nj+eOPA/BvEuPmfSx8RIsDjPVTsAElc1CbPVQSjVjTuqhUgZcM32nwDNou90grx1znlY2ADpgrf4HIIvvGQAiroe4X0LnCFyJlTlbGxdCbf+9Ht890/7vXDvAP5JeJnhz/JGVd/kdaiaTpddP89U/1q6ytPmtb03ry/ak1IWaVwTLdvM0My3bnWiYDf+ht/MpN7N7sEX78Ll/wvod5geGJX8BNFPZtS18CqVIWu0HRXizeVKGi6x3+Wd8bfePV87zhhmBMxKAaWoBpaQZO8Az2dXegbOoRm2+54ZxariBxhyweAMOUTignvoJryjSb5F3oW/EPfVFRoLmL2ws5aPGufMplCDlpv6NtpohyLtKPKE7lPkclZSUi/ERd+BCfDcTGzo4R4ji3FszsVUag4jXELnqMoSjHjNCBbhp5INhuNVN2bhnYaQ9spRkyCOJDlDfLZUgnltxft0udPiOtJxMQthBrvDWEFf3Q0MTTuge6USS/CvbxSeOaaEkJBCkvF0BbYSWQnUyirnxcgNjHkjYhnZkaoleqrHK6vjr9vBzTWlholaqR87ptJxTMAAAA=') format('woff2'), + url('iconfont.woff?t=1574240438561') format('woff'), + url('iconfont.ttf?t=1574240438561') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ + url('iconfont.svg?t=1574240438561#iconfont') format('svg'); /* iOS 4.1- */ +} + +.iconfont { + font-family: "iconfont" !important; + font-size: 16px; + font-style: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.icon-jian:before { + content: "\e619"; +} + +.icon-jia:before { + content: "\e61a"; +} + diff --git a/assets/images/meeting-active.png b/assets/images/meeting-active.png new file mode 100644 index 0000000..0335aa8 Binary files /dev/null and b/assets/images/meeting-active.png differ diff --git a/assets/images/meeting.png b/assets/images/meeting.png new file mode 100644 index 0000000..abf0b5d Binary files /dev/null and b/assets/images/meeting.png differ diff --git a/assets/images/mine-active.png b/assets/images/mine-active.png new file mode 100644 index 0000000..ef650c0 Binary files /dev/null and b/assets/images/mine-active.png differ diff --git a/assets/images/mine.png b/assets/images/mine.png new file mode 100644 index 0000000..b091697 Binary files /dev/null and b/assets/images/mine.png differ diff --git a/assets/images/notice-active.png b/assets/images/notice-active.png new file mode 100644 index 0000000..77b8ebd Binary files /dev/null and b/assets/images/notice-active.png differ diff --git a/assets/images/notice.png b/assets/images/notice.png new file mode 100644 index 0000000..d2fadab Binary files /dev/null and b/assets/images/notice.png differ diff --git a/assets/images/project-active.png b/assets/images/project-active.png new file mode 100644 index 0000000..f56d81a Binary files /dev/null and b/assets/images/project-active.png differ diff --git a/assets/images/project.png b/assets/images/project.png new file mode 100644 index 0000000..a0fd3a4 Binary files /dev/null and b/assets/images/project.png differ diff --git a/assets/images/wx.png b/assets/images/wx.png new file mode 100644 index 0000000..20dc292 Binary files /dev/null and b/assets/images/wx.png differ diff --git a/assets/js/dataTimePicker.js b/assets/js/dataTimePicker.js new file mode 100644 index 0000000..0a4d09c --- /dev/null +++ b/assets/js/dataTimePicker.js @@ -0,0 +1,81 @@ +function withData(param){ + return param < 10 ? '0' + param : '' + param; +} +function getLoopArray(start,end){ + var start = start || 0; + var end = end || 1; + var array = []; + for (var i = start; i <= end; i++) { + array.push(withData(i)); + } + return array; +} +function getMonthDay(year,month){ + var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0), array = null; + + switch (month) { + case '01': + case '03': + case '05': + case '07': + case '08': + case '10': + case '12': + array = getLoopArray(1, 31) + break; + case '04': + case '06': + case '09': + case '11': + array = getLoopArray(1, 30) + break; + case '02': + array = flag ? getLoopArray(1, 29) : getLoopArray(1, 28) + break; + default: + array = '月份格式不正确,请重新输入!' + } + return array; +} +function getNewDateArry(){ + // 当前时间的处理 + var newDate = new Date(); + var year = withData(newDate.getFullYear()), + mont = withData(newDate.getMonth() + 1), + date = withData(newDate.getDate()), + hour = withData(newDate.getHours()), + minu = withData(newDate.getMinutes()), + seco = withData(newDate.getSeconds()); + + return [year, mont, date, hour, minu, seco]; +} +function dateTimePicker(startYear,endYear,date) { + // 返回默认显示的数组和联动数组的声明 + var dateTime = [], dateTimeArray = [[],[],[],[],[],[]]; + var start = startYear || 1978; + var end = endYear || 2100; + // 默认开始显示数据 + var defaultDate = date ? [...date.split(' ')[0].split('-'), ...date.split(' ')[1].split(':')] : getNewDateArry(); + // 处理联动列表数据 + /*年月日 时分秒*/ + dateTimeArray[0] = getLoopArray(start,end); + dateTimeArray[1] = getLoopArray(1, 12); + dateTimeArray[2] = getMonthDay(defaultDate[0], defaultDate[1]); + dateTimeArray[3] = getLoopArray(0, 23); + dateTimeArray[4] = getLoopArray(0, 59); + dateTimeArray[5] = getLoopArray(0, 59); + + dateTimeArray.forEach((current,index) => { + dateTime.push(current.indexOf(defaultDate[index])); + }); + + return { + dateTimeArray: dateTimeArray, + dateTime: dateTime + } +} +module.exports = { + dateTimePicker: dateTimePicker, + getMonthDay: getMonthDay +} + \ No newline at end of file diff --git a/assets/js/http/api.js b/assets/js/http/api.js new file mode 100644 index 0000000..1d2d495 --- /dev/null +++ b/assets/js/http/api.js @@ -0,0 +1,43 @@ +import http from './http.js' + +// let baseUrl = 'https://share.hzwlsoft.com' +// let baseUrl = 'http://localhost:8080' +let baseUrl = 'http://10.0.1.63:8080' +// let baseUrl = 'http://192.168.1.110:8080' +/* 配置路径 */ + + +let apiUrl = { + // 登录 + wxLoginByUserName: '/api/sys/login', //微信账号密码登陆--1 +} + +export default { + baseUrl, + //微信账号密码登陆--1 + wxLoginByUserName(option, success, error) { + http.post1(baseUrl + apiUrl.wxLoginByUserName, option).then(res => { + return success && success(res) + }).catch(err => { + return error && error(err) + }) + }, + + //微信小程序授权--2 + wxAuthorization(option, success, error) { + http.post1(baseUrl + apiUrl.wxAuthorization, option).then(res => { + return success && success(res) + }).catch(err => { + return error && error(err) + }) + }, + + //微信小程序登录 + wxLoginByOpenId(option, success, error) { + http.post(baseUrl + apiUrl.wxLoginByOpenId, option).then(res => { + return success && success(res) + }).catch(err => { + return error && error(err) + }) + } +} diff --git a/assets/js/http/http.js b/assets/js/http/http.js new file mode 100644 index 0000000..59c9bfe --- /dev/null +++ b/assets/js/http/http.js @@ -0,0 +1,71 @@ + +let headerDefault = { + 'Accept': 'application/json' +} +let headerDefault1 = { + 'content-type': 'application/x-www-form-urlencoded' +} +let TokenKey = 'X-Access-Token' +let baseUrl = 'http://10.0.1.63:8080' +// let baseUrl = 'http://localhost:8080' +const http = (method, url, data, header= headerDefault) => { + let Authorization = wx.getStorageSync(TokenKey) ? wx.getStorageSync(TokenKey) : ''; + header[TokenKey] = Authorization == '' ? '' : JSON.parse(Authorization) + return new Promise((resolve, reject) => { + wx.showLoading({ + title: '加载中...', + mask: true + }) + wx.request({ + method: method, + url: baseUrl + url, + header: header, + data: data, + success: res => { + console.log(res) + if (res.statusCode === 200) { + // 接口请求错误的时候提示 + if((res.data.code !== 200 && res.data.code !== 0) && (res.data.message)) { + wx.showToast({ + title: res.data.message, + icon: "none", + duration: 800, + mask: true + }); + } + // 200: 服务端业务处理正常结束 + resolve(res.data) + wx.hideLoading(); + } else { + console.error(res.data); + reject(res.data); + wx.hideLoading(); + wx.showToast({ + title: "登录失效,请重新登录", + icon: "none", + duration: 1500, + mask: true + }); + wx.navigateTo({ + url: '/pages/login/login', + }) + console.error("登录失效3"); + } + }, + fail: err => { + console.error(err); + reject(err); + wx.hideLoading(); + }, + + }) + }) +} + +module.exports = { + get: (url, data, header) => http('GET', url, data, header), + post: (url, data, header) => http('POST', url, data, header), + post1: (url, data, header) => http('POST', url, data, headerDefault1), + put: (url, data, header) => http('PUT', url, data, header), + delete: (url, data, header) => http('DELETE', url, data, header) +} diff --git a/assets/js/http/qs.js b/assets/js/http/qs.js new file mode 100644 index 0000000..4474559 --- /dev/null +++ b/assets/js/http/qs.js @@ -0,0 +1,806 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i -1) { + val = val.split(','); + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options) { + var leaf = val; + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; + +},{"./utils":5}],4:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = obj.join(','); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key'); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (isArray(obj)) { + pushToArray(values, stringify( + obj[key], + typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } else { + pushToArray(values, stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly, + charset + )); + } + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.formatter, + options.encodeValuesOnly, + options.charset + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":1,"./utils":5}],5:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + merge: merge +}; + +},{}]},{},[2])(2) +}); diff --git a/assets/js/http/userApi.js b/assets/js/http/userApi.js new file mode 100644 index 0000000..1371539 --- /dev/null +++ b/assets/js/http/userApi.js @@ -0,0 +1,17 @@ +import http from './http.js' +let URL_CONFIG = '/api/' +const UserApi = { + // 登录 + login: (params) => http.post(`${URL_CONFIG}sys/login`, params), + // 获得公钥 + getRSAPublicKey: (params) => http.get(`${URL_CONFIG}sys/getRSAPublicKey`, params), + // 图片的验证码 + getImgCode: (params, urlParam) => http.get(`${URL_CONFIG}sys/randomImage/${urlParam}`, params), + // 退出 + logout: (params) => http.post(`${URL_CONFIG}sys/logout`, params), + //修改密码 + upDatePass:(params) => http.put(`${URL_CONFIG}sys/user/updatePassword`, params), + +} + +export default UserApi \ No newline at end of file diff --git a/assets/js/jsencrypt/jsencrypt.js b/assets/js/jsencrypt/jsencrypt.js new file mode 100644 index 0000000..052a036 --- /dev/null +++ b/assets/js/jsencrypt/jsencrypt.js @@ -0,0 +1,5363 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.JSEncrypt = {}))); +}(this, (function (exports) { 'use strict'; + +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; +function int2char(n) { + return BI_RM.charAt(n); +} +//#region BIT_OPERATIONS +// (public) this & a +function op_and(x, y) { + return x & y; +} +// (public) this | a +function op_or(x, y) { + return x | y; +} +// (public) this ^ a +function op_xor(x, y) { + return x ^ y; +} +// (public) this & ~a +function op_andnot(x, y) { + return x & ~y; +} +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if (x == 0) { + return -1; + } + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) { + ++r; + } + return r; +} +// return number of 1 bits in x +function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; +} +//#endregion BIT_OPERATIONS + +var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var b64pad = "="; +function hex2b64(h) { + var i; + var c; + var ret = ""; + for (i = 0; i + 3 <= h.length; i += 3) { + c = parseInt(h.substring(i, i + 3), 16); + ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); + } + if (i + 1 == h.length) { + c = parseInt(h.substring(i, i + 1), 16); + ret += b64map.charAt(c << 2); + } + else if (i + 2 == h.length) { + c = parseInt(h.substring(i, i + 2), 16); + ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); + } + while ((ret.length & 3) > 0) { + ret += b64pad; + } + return ret; +} +// convert a base64 string to hex +function b64tohex(s) { + var ret = ""; + var i; + var k = 0; // b64 state, 0-3 + var slop = 0; + for (i = 0; i < s.length; ++i) { + if (s.charAt(i) == b64pad) { + break; + } + var v = b64map.indexOf(s.charAt(i)); + if (v < 0) { + continue; + } + if (k == 0) { + ret += int2char(v >> 2); + slop = v & 3; + k = 1; + } + else if (k == 1) { + ret += int2char((slop << 2) | (v >> 4)); + slop = v & 0xf; + k = 2; + } + else if (k == 2) { + ret += int2char(slop); + ret += int2char(v >> 2); + slop = v & 3; + k = 3; + } + else { + ret += int2char((slop << 2) | (v >> 4)); + ret += int2char(v & 0xf); + k = 0; + } + } + if (k == 1) { + ret += int2char(slop << 2); + } + return ret; +} + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +// Hex JavaScript decoder +// Copyright (c) 2008-2013 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var decoder; +var Hex = { + decode: function (a) { + var i; + if (decoder === undefined) { + var hex = "0123456789ABCDEF"; + var ignore = " \f\n\r\t\u00A0\u2028\u2029"; + decoder = {}; + for (i = 0; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + hex = hex.toLowerCase(); + for (i = 10; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 2) { + out[out.length] = bits; + bits = 0; + char_count = 0; + } + else { + bits <<= 4; + } + } + if (char_count) { + throw new Error("Hex encoding incomplete: 4 bits missing"); + } + return out; + } +}; + +// Base64 JavaScript decoder +// Copyright (c) 2008-2013 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var decoder$1; +var Base64 = { + decode: function (a) { + var i; + if (decoder$1 === undefined) { + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; + decoder$1 = Object.create(null); + for (i = 0; i < 64; ++i) { + decoder$1[b64.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder$1[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder$1[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 4) { + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + out[out.length] = bits & 0xFF; + bits = 0; + char_count = 0; + } + else { + bits <<= 6; + } + } + switch (char_count) { + case 1: + throw new Error("Base64 encoding incomplete: at least 2 bits missing"); + case 2: + out[out.length] = (bits >> 10); + break; + case 3: + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + break; + } + return out; + }, + re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, + unarmor: function (a) { + var m = Base64.re.exec(a); + if (m) { + if (m[1]) { + a = m[1]; + } + else if (m[2]) { + a = m[2]; + } + else { + throw new Error("RegExp out of sync"); + } + } + return Base64.decode(a); + } +}; + +// Big integer base-10 printing library +// Copyright (c) 2014 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 +var Int10 = /** @class */ (function () { + function Int10(value) { + this.buf = [+value || 0]; + } + Int10.prototype.mulAdd = function (m, c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] * m + c; + if (t < max) { + c = 0; + } + else { + c = 0 | (t / max); + t -= c * max; + } + b[i] = t; + } + if (c > 0) { + b[i] = c; + } + }; + Int10.prototype.sub = function (c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] - c; + if (t < 0) { + t += max; + c = 1; + } + else { + c = 0; + } + b[i] = t; + } + while (b[b.length - 1] === 0) { + b.pop(); + } + }; + Int10.prototype.toString = function (base) { + if ((base || 10) != 10) { + throw new Error("only base 10 is supported"); + } + var b = this.buf; + var s = b[b.length - 1].toString(); + for (var i = b.length - 2; i >= 0; --i) { + s += (max + b[i]).toString().substring(1); + } + return s; + }; + Int10.prototype.valueOf = function () { + var b = this.buf; + var v = 0; + for (var i = b.length - 1; i >= 0; --i) { + v = v * max + b[i]; + } + return v; + }; + Int10.prototype.simplify = function () { + var b = this.buf; + return (b.length == 1) ? b[0] : this; + }; + return Int10; +}()); + +// ASN.1 JavaScript decoder +var ellipsis = "\u2026"; +var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; +var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; +function stringCut(str, len) { + if (str.length > len) { + str = str.substring(0, len) + ellipsis; + } + return str; +} +var Stream = /** @class */ (function () { + function Stream(enc, pos) { + this.hexDigits = "0123456789ABCDEF"; + if (enc instanceof Stream) { + this.enc = enc.enc; + this.pos = enc.pos; + } + else { + // enc should be an array or a binary string + this.enc = enc; + this.pos = pos; + } + } + Stream.prototype.get = function (pos) { + if (pos === undefined) { + pos = this.pos++; + } + if (pos >= this.enc.length) { + throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length); + } + return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; + }; + Stream.prototype.hexByte = function (b) { + return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); + }; + Stream.prototype.hexDump = function (start, end, raw) { + var s = ""; + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + if (raw !== true) { + switch (i & 0xF) { + case 0x7: + s += " "; + break; + case 0xF: + s += "\n"; + break; + default: + s += " "; + } + } + } + return s; + }; + Stream.prototype.isASCII = function (start, end) { + for (var i = start; i < end; ++i) { + var c = this.get(i); + if (c < 32 || c > 176) { + return false; + } + } + return true; + }; + Stream.prototype.parseStringISO = function (start, end) { + var s = ""; + for (var i = start; i < end; ++i) { + s += String.fromCharCode(this.get(i)); + } + return s; + }; + Stream.prototype.parseStringUTF = function (start, end) { + var s = ""; + for (var i = start; i < end;) { + var c = this.get(i++); + if (c < 128) { + s += String.fromCharCode(c); + } + else if ((c > 191) && (c < 224)) { + s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); + } + else { + s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); + } + } + return s; + }; + Stream.prototype.parseStringBMP = function (start, end) { + var str = ""; + var hi; + var lo; + for (var i = start; i < end;) { + hi = this.get(i++); + lo = this.get(i++); + str += String.fromCharCode((hi << 8) | lo); + } + return str; + }; + Stream.prototype.parseTime = function (start, end, shortYear) { + var s = this.parseStringISO(start, end); + var m = (shortYear ? reTimeS : reTimeL).exec(s); + if (!m) { + return "Unrecognized time: " + s; + } + if (shortYear) { + // to avoid querying the timer, use the fixed range [1970, 2069] + // it will conform with ITU X.400 [-10, +40] sliding window until 2030 + m[1] = +m[1]; + m[1] += (+m[1] < 70) ? 2000 : 1900; + } + s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; + if (m[5]) { + s += ":" + m[5]; + if (m[6]) { + s += ":" + m[6]; + if (m[7]) { + s += "." + m[7]; + } + } + } + if (m[8]) { + s += " UTC"; + if (m[8] != "Z") { + s += m[8]; + if (m[9]) { + s += ":" + m[9]; + } + } + } + return s; + }; + Stream.prototype.parseInteger = function (start, end) { + var v = this.get(start); + var neg = (v > 127); + var pad = neg ? 255 : 0; + var len; + var s = ""; + // skip unuseful bits (not allowed in DER) + while (v == pad && ++start < end) { + v = this.get(start); + } + len = end - start; + if (len === 0) { + return neg ? -1 : 0; + } + // show bit length of huge integers + if (len > 4) { + s = v; + len <<= 3; + while (((+s ^ pad) & 0x80) == 0) { + s = +s << 1; + --len; + } + s = "(" + len + " bit)\n"; + } + // decode the integer + if (neg) { + v = v - 256; + } + var n = new Int10(v); + for (var i = start + 1; i < end; ++i) { + n.mulAdd(256, this.get(i)); + } + return s + n.toString(); + }; + Stream.prototype.parseBitString = function (start, end, maxLength) { + var unusedBit = this.get(start); + var lenBit = ((end - start - 1) << 3) - unusedBit; + var intro = "(" + lenBit + " bit)\n"; + var s = ""; + for (var i = start + 1; i < end; ++i) { + var b = this.get(i); + var skip = (i == end - 1) ? unusedBit : 0; + for (var j = 7; j >= skip; --j) { + s += (b >> j) & 1 ? "1" : "0"; + } + if (s.length > maxLength) { + return intro + stringCut(s, maxLength); + } + } + return intro + s; + }; + Stream.prototype.parseOctetString = function (start, end, maxLength) { + if (this.isASCII(start, end)) { + return stringCut(this.parseStringISO(start, end), maxLength); + } + var len = end - start; + var s = "(" + len + " byte)\n"; + maxLength /= 2; // we work in bytes + if (len > maxLength) { + end = start + maxLength; + } + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + } + if (len > maxLength) { + s += ellipsis; + } + return s; + }; + Stream.prototype.parseOID = function (start, end, maxLength) { + var s = ""; + var n = new Int10(); + var bits = 0; + for (var i = start; i < end; ++i) { + var v = this.get(i); + n.mulAdd(128, v & 0x7F); + bits += 7; + if (!(v & 0x80)) { // finished + if (s === "") { + n = n.simplify(); + if (n instanceof Int10) { + n.sub(80); + s = "2." + n.toString(); + } + else { + var m = n < 80 ? n < 40 ? 0 : 1 : 2; + s = m + "." + (n - m * 40); + } + } + else { + s += "." + n.toString(); + } + if (s.length > maxLength) { + return stringCut(s, maxLength); + } + n = new Int10(); + bits = 0; + } + } + if (bits > 0) { + s += ".incomplete"; + } + return s; + }; + return Stream; +}()); +var ASN1 = /** @class */ (function () { + function ASN1(stream, header, length, tag, sub) { + if (!(tag instanceof ASN1Tag)) { + throw new Error("Invalid tag value."); + } + this.stream = stream; + this.header = header; + this.length = length; + this.tag = tag; + this.sub = sub; + } + ASN1.prototype.typeName = function () { + switch (this.tag.tagClass) { + case 0: // universal + switch (this.tag.tagNumber) { + case 0x00: + return "EOC"; + case 0x01: + return "BOOLEAN"; + case 0x02: + return "INTEGER"; + case 0x03: + return "BIT_STRING"; + case 0x04: + return "OCTET_STRING"; + case 0x05: + return "NULL"; + case 0x06: + return "OBJECT_IDENTIFIER"; + case 0x07: + return "ObjectDescriptor"; + case 0x08: + return "EXTERNAL"; + case 0x09: + return "REAL"; + case 0x0A: + return "ENUMERATED"; + case 0x0B: + return "EMBEDDED_PDV"; + case 0x0C: + return "UTF8String"; + case 0x10: + return "SEQUENCE"; + case 0x11: + return "SET"; + case 0x12: + return "NumericString"; + case 0x13: + return "PrintableString"; // ASCII subset + case 0x14: + return "TeletexString"; // aka T61String + case 0x15: + return "VideotexString"; + case 0x16: + return "IA5String"; // ASCII + case 0x17: + return "UTCTime"; + case 0x18: + return "GeneralizedTime"; + case 0x19: + return "GraphicString"; + case 0x1A: + return "VisibleString"; // ASCII subset + case 0x1B: + return "GeneralString"; + case 0x1C: + return "UniversalString"; + case 0x1E: + return "BMPString"; + } + return "Universal_" + this.tag.tagNumber.toString(); + case 1: + return "Application_" + this.tag.tagNumber.toString(); + case 2: + return "[" + this.tag.tagNumber.toString() + "]"; // Context + case 3: + return "Private_" + this.tag.tagNumber.toString(); + } + }; + ASN1.prototype.content = function (maxLength) { + if (this.tag === undefined) { + return null; + } + if (maxLength === undefined) { + maxLength = Infinity; + } + var content = this.posContent(); + var len = Math.abs(this.length); + if (!this.tag.isUniversal()) { + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } + return this.stream.parseOctetString(content, content + len, maxLength); + } + switch (this.tag.tagNumber) { + case 0x01: // BOOLEAN + return (this.stream.get(content) === 0) ? "false" : "true"; + case 0x02: // INTEGER + return this.stream.parseInteger(content, content + len); + case 0x03: // BIT_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseBitString(content, content + len, maxLength); + case 0x04: // OCTET_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseOctetString(content, content + len, maxLength); + // case 0x05: // NULL + case 0x06: // OBJECT_IDENTIFIER + return this.stream.parseOID(content, content + len, maxLength); + // case 0x07: // ObjectDescriptor + // case 0x08: // EXTERNAL + // case 0x09: // REAL + // case 0x0A: // ENUMERATED + // case 0x0B: // EMBEDDED_PDV + case 0x10: // SEQUENCE + case 0x11: // SET + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } + else { + return "(no elem)"; + } + case 0x0C: // UTF8String + return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); + case 0x12: // NumericString + case 0x13: // PrintableString + case 0x14: // TeletexString + case 0x15: // VideotexString + case 0x16: // IA5String + // case 0x19: // GraphicString + case 0x1A: // VisibleString + // case 0x1B: // GeneralString + // case 0x1C: // UniversalString + return stringCut(this.stream.parseStringISO(content, content + len), maxLength); + case 0x1E: // BMPString + return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); + case 0x17: // UTCTime + case 0x18: // GeneralizedTime + return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); + } + return null; + }; + ASN1.prototype.toString = function () { + return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]"; + }; + ASN1.prototype.toPrettyString = function (indent) { + if (indent === undefined) { + indent = ""; + } + var s = indent + this.typeName() + " @" + this.stream.pos; + if (this.length >= 0) { + s += "+"; + } + s += this.length; + if (this.tag.tagConstructed) { + s += " (constructed)"; + } + else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) { + s += " (encapsulates)"; + } + s += "\n"; + if (this.sub !== null) { + indent += " "; + for (var i = 0, max = this.sub.length; i < max; ++i) { + s += this.sub[i].toPrettyString(indent); + } + } + return s; + }; + ASN1.prototype.posStart = function () { + return this.stream.pos; + }; + ASN1.prototype.posContent = function () { + return this.stream.pos + this.header; + }; + ASN1.prototype.posEnd = function () { + return this.stream.pos + this.header + Math.abs(this.length); + }; + ASN1.prototype.toHexString = function () { + return this.stream.hexDump(this.posStart(), this.posEnd(), true); + }; + ASN1.decodeLength = function (stream) { + var buf = stream.get(); + var len = buf & 0x7F; + if (len == buf) { + return len; + } + // no reason to use Int10, as it would be a huge buffer anyways + if (len > 6) { + throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1)); + } + if (len === 0) { + return null; + } // undefined + buf = 0; + for (var i = 0; i < len; ++i) { + buf = (buf * 256) + stream.get(); + } + return buf; + }; + /** + * Retrieve the hexadecimal value (as a string) of the current ASN.1 element + * @returns {string} + * @public + */ + ASN1.prototype.getHexStringValue = function () { + var hexString = this.toHexString(); + var offset = this.header * 2; + var length = this.length * 2; + return hexString.substr(offset, length); + }; + ASN1.decode = function (str) { + var stream; + if (!(str instanceof Stream)) { + stream = new Stream(str, 0); + } + else { + stream = str; + } + var streamStart = new Stream(stream); + var tag = new ASN1Tag(stream); + var len = ASN1.decodeLength(stream); + var start = stream.pos; + var header = start - streamStart.pos; + var sub = null; + var getSub = function () { + var ret = []; + if (len !== null) { + // definite length + var end = start + len; + while (stream.pos < end) { + ret[ret.length] = ASN1.decode(stream); + } + if (stream.pos != end) { + throw new Error("Content size is not correct for container starting at offset " + start); + } + } + else { + // undefined length + try { + for (;;) { + var s = ASN1.decode(stream); + if (s.tag.isEOC()) { + break; + } + ret[ret.length] = s; + } + len = start - stream.pos; // undefined lengths are represented as negative values + } + catch (e) { + throw new Error("Exception while decoding undefined length content: " + e); + } + } + return ret; + }; + if (tag.tagConstructed) { + // must have valid content + sub = getSub(); + } + else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { + // sometimes BitString and OctetString are used to encapsulate ASN.1 + try { + if (tag.tagNumber == 0x03) { + if (stream.get() != 0) { + throw new Error("BIT STRINGs with unused bits cannot encapsulate."); + } + } + sub = getSub(); + for (var i = 0; i < sub.length; ++i) { + if (sub[i].tag.isEOC()) { + throw new Error("EOC is not supposed to be actual content."); + } + } + } + catch (e) { + // but silently ignore when they don't + sub = null; + } + } + if (sub === null) { + if (len === null) { + throw new Error("We can't skip over an invalid tag with undefined length at offset " + start); + } + stream.pos = start + Math.abs(len); + } + return new ASN1(streamStart, header, len, tag, sub); + }; + return ASN1; +}()); +var ASN1Tag = /** @class */ (function () { + function ASN1Tag(stream) { + var buf = stream.get(); + this.tagClass = buf >> 6; + this.tagConstructed = ((buf & 0x20) !== 0); + this.tagNumber = buf & 0x1F; + if (this.tagNumber == 0x1F) { // long tag + var n = new Int10(); + do { + buf = stream.get(); + n.mulAdd(128, buf & 0x7F); + } while (buf & 0x80); + this.tagNumber = n.simplify(); + } + } + ASN1Tag.prototype.isUniversal = function () { + return this.tagClass === 0x00; + }; + ASN1Tag.prototype.isEOC = function () { + return this.tagClass === 0x00 && this.tagNumber === 0x00; + }; + return ASN1Tag; +}()); + +// Copyright (c) 2005 Tom Wu +// Bits per digit +var dbits; +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary & 0xffffff) == 0xefcafe); +//#region +var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; +//#endregion +// (public) Constructor +var BigInteger = /** @class */ (function () { + function BigInteger(a, b, c) { + if (a != null) { + if ("number" == typeof a) { + this.fromNumber(a, b, c); + } + else if (b == null && "string" != typeof a) { + this.fromString(a, 256); + } + else { + this.fromString(a, b); + } + } + } + //#region PUBLIC + // BigInteger.prototype.toString = bnToString; + // (public) return string representation in given radix + BigInteger.prototype.toString = function (b) { + if (this.s < 0) { + return "-" + this.negate().toString(b); + } + var k; + if (b == 16) { + k = 4; + } + else if (b == 8) { + k = 3; + } + else if (b == 2) { + k = 1; + } + else if (b == 32) { + k = 5; + } + else if (b == 4) { + k = 2; + } + else { + return this.toRadix(b); + } + var km = (1 << k) - 1; + var d; + var m = false; + var r = ""; + var i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } + else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) { + m = true; + } + if (m) { + r += int2char(d); + } + } + } + return m ? r : "0"; + }; + // BigInteger.prototype.negate = bnNegate; + // (public) -this + BigInteger.prototype.negate = function () { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + }; + // BigInteger.prototype.abs = bnAbs; + // (public) |this| + BigInteger.prototype.abs = function () { + return (this.s < 0) ? this.negate() : this; + }; + // BigInteger.prototype.compareTo = bnCompareTo; + // (public) return + if this > a, - if this < a, 0 if equal + BigInteger.prototype.compareTo = function (a) { + var r = this.s - a.s; + if (r != 0) { + return r; + } + var i = this.t; + r = i - a.t; + if (r != 0) { + return (this.s < 0) ? -r : r; + } + while (--i >= 0) { + if ((r = this[i] - a[i]) != 0) { + return r; + } + } + return 0; + }; + // BigInteger.prototype.bitLength = bnBitLength; + // (public) return the number of bits in "this" + BigInteger.prototype.bitLength = function () { + if (this.t <= 0) { + return 0; + } + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); + }; + // BigInteger.prototype.mod = bnMod; + // (public) this mod a + BigInteger.prototype.mod = function (a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + a.subTo(r, r); + } + return r; + }; + // BigInteger.prototype.modPowInt = bnModPowInt; + // (public) this^e % m, 0 <= e < 2^32 + BigInteger.prototype.modPowInt = function (e, m) { + var z; + if (e < 256 || m.isEven()) { + z = new Classic(m); + } + else { + z = new Montgomery(m); + } + return this.exp(e, z); + }; + // BigInteger.prototype.clone = bnClone; + // (public) + BigInteger.prototype.clone = function () { + var r = nbi(); + this.copyTo(r); + return r; + }; + // BigInteger.prototype.intValue = bnIntValue; + // (public) return value as integer + BigInteger.prototype.intValue = function () { + if (this.s < 0) { + if (this.t == 1) { + return this[0] - this.DV; + } + else if (this.t == 0) { + return -1; + } + } + else if (this.t == 1) { + return this[0]; + } + else if (this.t == 0) { + return 0; + } + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + }; + // BigInteger.prototype.byteValue = bnByteValue; + // (public) return value as byte + BigInteger.prototype.byteValue = function () { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; + }; + // BigInteger.prototype.shortValue = bnShortValue; + // (public) return value as short (assumes DB>=16) + BigInteger.prototype.shortValue = function () { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; + }; + // BigInteger.prototype.signum = bnSigNum; + // (public) 0 if this == 0, 1 if this > 0 + BigInteger.prototype.signum = function () { + if (this.s < 0) { + return -1; + } + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { + return 0; + } + else { + return 1; + } + }; + // BigInteger.prototype.toByteArray = bnToByteArray; + // (public) convert to bigendian byte array + BigInteger.prototype.toByteArray = function () { + var i = this.t; + var r = []; + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8; + var d; + var k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { + r[k++] = d | (this.s << (this.DB - p)); + } + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } + else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) { + d |= -256; + } + if (k == 0 && (this.s & 0x80) != (d & 0x80)) { + ++k; + } + if (k > 0 || d != this.s) { + r[k++] = d; + } + } + } + return r; + }; + // BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.equals = function (a) { + return (this.compareTo(a) == 0); + }; + // BigInteger.prototype.min = bnMin; + BigInteger.prototype.min = function (a) { + return (this.compareTo(a) < 0) ? this : a; + }; + // BigInteger.prototype.max = bnMax; + BigInteger.prototype.max = function (a) { + return (this.compareTo(a) > 0) ? this : a; + }; + // BigInteger.prototype.and = bnAnd; + BigInteger.prototype.and = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + }; + // BigInteger.prototype.or = bnOr; + BigInteger.prototype.or = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + }; + // BigInteger.prototype.xor = bnXor; + BigInteger.prototype.xor = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + }; + // BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.andNot = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + }; + // BigInteger.prototype.not = bnNot; + // (public) ~this + BigInteger.prototype.not = function () { + var r = nbi(); + for (var i = 0; i < this.t; ++i) { + r[i] = this.DM & ~this[i]; + } + r.t = this.t; + r.s = ~this.s; + return r; + }; + // BigInteger.prototype.shiftLeft = bnShiftLeft; + // (public) this << n + BigInteger.prototype.shiftLeft = function (n) { + var r = nbi(); + if (n < 0) { + this.rShiftTo(-n, r); + } + else { + this.lShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.shiftRight = bnShiftRight; + // (public) this >> n + BigInteger.prototype.shiftRight = function (n) { + var r = nbi(); + if (n < 0) { + this.lShiftTo(-n, r); + } + else { + this.rShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + // (public) returns index of lowest 1-bit (or -1 if none) + BigInteger.prototype.getLowestSetBit = function () { + for (var i = 0; i < this.t; ++i) { + if (this[i] != 0) { + return i * this.DB + lbit(this[i]); + } + } + if (this.s < 0) { + return this.t * this.DB; + } + return -1; + }; + // BigInteger.prototype.bitCount = bnBitCount; + // (public) return number of set bits + BigInteger.prototype.bitCount = function () { + var r = 0; + var x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) { + r += cbit(this[i] ^ x); + } + return r; + }; + // BigInteger.prototype.testBit = bnTestBit; + // (public) true iff nth bit is set + BigInteger.prototype.testBit = function (n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) { + return (this.s != 0); + } + return ((this[j] & (1 << (n % this.DB))) != 0); + }; + // BigInteger.prototype.setBit = bnSetBit; + // (public) this | (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1; + var w; + var is1 = true; + var r2 = nbi(); + var t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) { + w = (e[j] >> (i - k1)) & km; + } + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) { + w |= e[j - 1] >> (this.DB + i - k1); + } + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) { + z.sqrTo(r, r2); + } + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + }; + // BigInteger.prototype.modInverse = bnModInverse; + // (public) 1/this % m (HAC 14.61) + BigInteger.prototype.modInverse = function (m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) { + return BigInteger.ZERO; + } + var u = m.clone(); + var v = this.clone(); + var a = nbv(1); + var b = nbv(0); + var c = nbv(0); + var d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } + else if (!b.isEven()) { + b.subTo(m, b); + } + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } + else if (!d.isEven()) { + d.subTo(m, d); + } + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) { + a.subTo(c, a); + } + b.subTo(d, b); + } + else { + v.subTo(u, v); + if (ac) { + c.subTo(a, c); + } + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) { + return BigInteger.ZERO; + } + if (d.compareTo(m) >= 0) { + return d.subtract(m); + } + if (d.signum() < 0) { + d.addTo(m, d); + } + else { + return d; + } + if (d.signum() < 0) { + return d.add(m); + } + else { + return d; + } + }; + // BigInteger.prototype.pow = bnPow; + // (public) this^e + BigInteger.prototype.pow = function (e) { + return this.exp(e, new NullExp()); + }; + // BigInteger.prototype.gcd = bnGCD; + // (public) gcd(this,a) (HAC 14.54) + BigInteger.prototype.gcd = function (a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + return x; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) { + y.lShiftTo(g, y); + } + return y; + }; + // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + // (public) test primality with certainty >= 1-.5^t + BigInteger.prototype.isProbablePrime = function (t) { + var i; + var x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) { + if (x[0] == lowprimes[i]) { + return true; + } + } + return false; + } + if (x.isEven()) { + return false; + } + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i]; + var j = i + 1; + while (j < lowprimes.length && m < lplim) { + m *= lowprimes[j++]; + } + m = x.modInt(m); + while (i < j) { + if (m % lowprimes[i++] == 0) { + return false; + } + } + } + return x.millerRabin(t); + }; + //#endregion PUBLIC + //#region PROTECTED + // BigInteger.prototype.copyTo = bnpCopyTo; + // (protected) copy this to r + BigInteger.prototype.copyTo = function (r) { + for (var i = this.t - 1; i >= 0; --i) { + r[i] = this[i]; + } + r.t = this.t; + r.s = this.s; + }; + // BigInteger.prototype.fromInt = bnpFromInt; + // (protected) set from integer value x, -DV <= x < DV + BigInteger.prototype.fromInt = function (x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) { + this[0] = x; + } + else if (x < -1) { + this[0] = x + this.DV; + } + else { + this.t = 0; + } + }; + // BigInteger.prototype.fromString = bnpFromString; + // (protected) set from string and radix + BigInteger.prototype.fromString = function (s, b) { + var k; + if (b == 16) { + k = 4; + } + else if (b == 8) { + k = 3; + } + else if (b == 256) { + k = 8; + /* byte array */ + } + else if (b == 2) { + k = 1; + } + else if (b == 32) { + k = 5; + } + else if (b == 4) { + k = 2; + } + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length; + var mi = false; + var sh = 0; + while (--i >= 0) { + var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") { + mi = true; + } + continue; + } + mi = false; + if (sh == 0) { + this[this.t++] = x; + } + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } + else { + this[this.t - 1] |= x << sh; + } + sh += k; + if (sh >= this.DB) { + sh -= this.DB; + } + } + if (k == 8 && ((+s[0]) & 0x80) != 0) { + this.s = -1; + if (sh > 0) { + this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + } + this.clamp(); + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.clamp = bnpClamp; + // (protected) clamp off excess high words + BigInteger.prototype.clamp = function () { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) { + --this.t; + } + }; + // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + // (protected) r = this << n*DB + BigInteger.prototype.dlShiftTo = function (n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) { + r[i + n] = this[i]; + } + for (i = n - 1; i >= 0; --i) { + r[i] = 0; + } + r.t = this.t + n; + r.s = this.s; + }; + // BigInteger.prototype.drShiftTo = bnpDRShiftTo; + // (protected) r = this >> n*DB + BigInteger.prototype.drShiftTo = function (n, r) { + for (var i = n; i < this.t; ++i) { + r[i - n] = this[i]; + } + r.t = Math.max(this.t - n, 0); + r.s = this.s; + }; + // BigInteger.prototype.lShiftTo = bnpLShiftTo; + // (protected) r = this << n + BigInteger.prototype.lShiftTo = function (n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB); + var c = (this.s << bs) & this.DM; + for (var i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (var i = ds - 1; i >= 0; --i) { + r[i] = 0; + } + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + }; + // BigInteger.prototype.rShiftTo = bnpRShiftTo; + // (protected) r = this >> n + BigInteger.prototype.rShiftTo = function (n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) { + r[this.t - ds - 1] |= (this.s & bm) << cbs; + } + r.t = this.t - ds; + r.clamp(); + }; + // BigInteger.prototype.subTo = bnpSubTo; + // (protected) r = this - a + BigInteger.prototype.subTo = function (a, r) { + var i = 0; + var c = 0; + var m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) { + r[i++] = this.DV + c; + } + else if (c > 0) { + r[i++] = c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.multiplyTo = bnpMultiplyTo; + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyTo = function (a, r) { + var x = this.abs(); + var y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < y.t; ++i) { + r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + } + r.s = 0; + r.clamp(); + if (this.s != a.s) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.squareTo = bnpSquareTo; + // (protected) r = this^2, r != this (HAC 14.16) + BigInteger.prototype.squareTo = function (r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) { + r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + } + r.s = 0; + r.clamp(); + }; + // BigInteger.prototype.divRemTo = bnpDivRemTo; + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + BigInteger.prototype.divRemTo = function (m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) { + return; + } + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) { + q.fromInt(0); + } + if (r != null) { + this.copyTo(r); + } + return; + } + if (r == null) { + r = nbi(); + } + var y = nbi(); + var ts = this.s; + var ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } + else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) { + return; + } + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt; + var d2 = (1 << this.F1) / yt; + var e = 1 << this.F2; + var i = r.t; + var j = i - ys; + var t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) { + y[y.t++] = 0; + } + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) { + r.subTo(t, r); + } + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) { + BigInteger.ZERO.subTo(q, q); + } + } + r.t = ys; + r.clamp(); + if (nsh > 0) { + r.rShiftTo(nsh, r); + } // Denormalize remainder + if (ts < 0) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.invDigit = bnpInvDigit; + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + BigInteger.prototype.invDigit = function () { + if (this.t < 1) { + return 0; + } + var x = this[0]; + if ((x & 1) == 0) { + return 0; + } + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; + }; + // BigInteger.prototype.isEven = bnpIsEven; + // (protected) true iff this is even + BigInteger.prototype.isEven = function () { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; + }; + // BigInteger.prototype.exp = bnpExp; + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + BigInteger.prototype.exp = function (e, z) { + if (e > 0xffffffff || e < 1) { + return BigInteger.ONE; + } + var r = nbi(); + var r2 = nbi(); + var g = z.convert(this); + var i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) { + z.mulTo(r2, g, r); + } + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + }; + // BigInteger.prototype.chunkSize = bnpChunkSize; + // (protected) return x s.t. r^x < DV + BigInteger.prototype.chunkSize = function (r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + }; + // BigInteger.prototype.toRadix = bnpToRadix; + // (protected) convert to radix string + BigInteger.prototype.toRadix = function (b) { + if (b == null) { + b = 10; + } + if (this.signum() == 0 || b < 2 || b > 36) { + return "0"; + } + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a); + var y = nbi(); + var z = nbi(); + var r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + }; + // BigInteger.prototype.fromRadix = bnpFromRadix; + // (protected) convert from radix string + BigInteger.prototype.fromRadix = function (s, b) { + this.fromInt(0); + if (b == null) { + b = 10; + } + var cs = this.chunkSize(b); + var d = Math.pow(b, cs); + var mi = false; + var j = 0; + var w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) { + mi = true; + } + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.fromNumber = bnpFromNumber; + // (protected) alternate constructor + BigInteger.prototype.fromNumber = function (a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) { + this.fromInt(1); + } + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) { + this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } + } + else { + // new BigInteger(int,RNG) + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } + else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + // (protected) r = this op a (bitwise) + BigInteger.prototype.bitwiseTo = function (a, op, r) { + var i; + var f; + var m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) { + r[i] = op(this[i], a[i]); + } + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) { + r[i] = op(this[i], f); + } + r.t = this.t; + } + else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) { + r[i] = op(f, a[i]); + } + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + }; + // BigInteger.prototype.changeBit = bnpChangeBit; + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c > 0) { + r[i++] = c; + } + else if (c < -1) { + r[i++] = this.DV + c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.dMultiply = bnpDMultiply; + // (protected) this *= n, this >= 0, 1 < n < DV + BigInteger.prototype.dMultiply = function (n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + }; + // BigInteger.prototype.dAddOffset = bnpDAddOffset; + // (protected) this += n << w words, this >= 0 + BigInteger.prototype.dAddOffset = function (n, w) { + if (n == 0) { + return; + } + while (this.t <= w) { + this[this.t++] = 0; + } + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) { + this[this.t++] = 0; + } + ++this[w]; + } + }; + // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyLowerTo = function (a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) { + r[--i] = 0; + } + for (var j = r.t - this.t; i < j; ++i) { + r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + } + for (var j = Math.min(a.t, n); i < j; ++i) { + this.am(0, a[i], r, i, 0, n - i); + } + r.clamp(); + }; + // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyUpperTo = function (a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) { + r[i] = 0; + } + for (i = Math.max(n - this.t, 0); i < a.t; ++i) { + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + } + r.clamp(); + r.drShiftTo(1, r); + }; + // BigInteger.prototype.modInt = bnpModInt; + // (protected) this % n, n < 2^26 + BigInteger.prototype.modInt = function (n) { + if (n <= 0) { + return 0; + } + var d = this.DV % n; + var r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) { + if (d == 0) { + r = this[0] % n; + } + else { + for (var i = this.t - 1; i >= 0; --i) { + r = (d * r + this[i]) % n; + } + } + } + return r; + }; + // BigInteger.prototype.millerRabin = bnpMillerRabin; + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + BigInteger.prototype.millerRabin = function (t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) { + return false; + } + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) { + t = lowprimes.length; + } + var a = nbi(); + for (var i = 0; i < t; ++i) { + // Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) { + return false; + } + } + if (y.compareTo(n1) != 0) { + return false; + } + } + } + return true; + }; + // BigInteger.prototype.square = bnSquare; + // (public) this^2 + BigInteger.prototype.square = function () { + var r = nbi(); + this.squareTo(r); + return r; + }; + //#region ASYNC + // Public API method + BigInteger.prototype.gcda = function (a, callback) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + callback(x); + return; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. + var gcda1 = function () { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + if (!(x.signum() > 0)) { + if (g > 0) { + y.lShiftTo(g, y); + } + setTimeout(function () { callback(y); }, 0); // escape + } + else { + setTimeout(gcda1, 0); + } + }; + setTimeout(gcda1, 10); + }; + // (protected) alternate constructor + BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) { + if ("number" == typeof b) { + if (a < 2) { + this.fromInt(1); + } + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } + var bnp_1 = this; + var bnpfn1_1 = function () { + bnp_1.dAddOffset(2, 0); + if (bnp_1.bitLength() > a) { + bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); + } + if (bnp_1.isProbablePrime(b)) { + setTimeout(function () { callback(); }, 0); // escape + } + else { + setTimeout(bnpfn1_1, 0); + } + }; + setTimeout(bnpfn1_1, 0); + } + } + else { + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } + else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + return BigInteger; +}()); +//#region REDUCERS +//#region NullExp +var NullExp = /** @class */ (function () { + function NullExp() { + } + // NullExp.prototype.convert = nNop; + NullExp.prototype.convert = function (x) { + return x; + }; + // NullExp.prototype.revert = nNop; + NullExp.prototype.revert = function (x) { + return x; + }; + // NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + }; + // NullExp.prototype.sqrTo = nSqrTo; + NullExp.prototype.sqrTo = function (x, r) { + x.squareTo(r); + }; + return NullExp; +}()); +// Modular reduction using "classic" algorithm +var Classic = /** @class */ (function () { + function Classic(m) { + this.m = m; + } + // Classic.prototype.convert = cConvert; + Classic.prototype.convert = function (x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) { + return x.mod(this.m); + } + else { + return x; + } + }; + // Classic.prototype.revert = cRevert; + Classic.prototype.revert = function (x) { + return x; + }; + // Classic.prototype.reduce = cReduce; + Classic.prototype.reduce = function (x) { + x.divRemTo(this.m, null, x); + }; + // Classic.prototype.mulTo = cMulTo; + Classic.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Classic.prototype.sqrTo = cSqrTo; + Classic.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Classic; +}()); +//#endregion +//#region Montgomery +// Montgomery reduction +var Montgomery = /** @class */ (function () { + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + // Montgomery.prototype.convert = montConvert; + // xR mod m + Montgomery.prototype.convert = function (x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + this.m.subTo(r, r); + } + return r; + }; + // Montgomery.prototype.revert = montRevert; + // x/R mod m + Montgomery.prototype.revert = function (x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + }; + // Montgomery.prototype.reduce = montReduce; + // x = x/R mod m (HAC 14.32) + Montgomery.prototype.reduce = function (x) { + while (x.t <= this.mt2) { + // pad x so am has enough room later + x[x.t++] = 0; + } + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Montgomery.prototype.mulTo = montMulTo; + // r = "xy/R mod m"; x,y != r + Montgomery.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Montgomery.prototype.sqrTo = montSqrTo; + // r = "x^2/R mod m"; x != r + Montgomery.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Montgomery; +}()); +//#endregion Montgomery +//#region Barrett +// Barrett modular reduction +var Barrett = /** @class */ (function () { + function Barrett(m) { + this.m = m; + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + } + // Barrett.prototype.convert = barrettConvert; + Barrett.prototype.convert = function (x) { + if (x.s < 0 || x.t > 2 * this.m.t) { + return x.mod(this.m); + } + else if (x.compareTo(this.m) < 0) { + return x; + } + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + }; + // Barrett.prototype.revert = barrettRevert; + Barrett.prototype.revert = function (x) { + return x; + }; + // Barrett.prototype.reduce = barrettReduce; + // x = x mod m (HAC 14.42) + Barrett.prototype.reduce = function (x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) { + x.dAddOffset(1, this.m.t + 1); + } + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Barrett.prototype.mulTo = barrettMulTo; + // r = x*y mod m; x,y != r + Barrett.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Barrett.prototype.sqrTo = barrettSqrTo; + // r = x^2 mod m; x != r + Barrett.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Barrett; +}()); +//#endregion +//#endregion REDUCERS +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } +function parseBigInt(str, r) { + return new BigInteger(str, r); +} +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff; + var xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff; + var xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; + } + return c; +} + + +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1 << dbits) - 1); +BigInteger.prototype.DV = (1 << dbits); +var BI_FP = 52; +BigInteger.prototype.FV = Math.pow(2, BI_FP); +BigInteger.prototype.F1 = BI_FP - dbits; +BigInteger.prototype.F2 = 2 * dbits - BI_FP; +// Digit conversions +var BI_RC = []; +var rr; +var vv; +rr = "0".charCodeAt(0); +for (vv = 0; vv <= 9; ++vv) { + BI_RC[rr++] = vv; +} +rr = "a".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; +} +rr = "A".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; +} +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; +} +// return bigint initialized to value +function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; +} +// returns bit length of the integer x +function nbits(x) { + var r = 1; + var t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; +} +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + +// prng4.js - uses Arcfour as a PRNG +var Arcfour = /** @class */ (function () { + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = []; + } + // Arcfour.prototype.init = ARC4init; + // Initialize arcfour context from key, an array of ints, each from [0..255] + Arcfour.prototype.init = function (key) { + var i; + var j; + var t; + for (i = 0; i < 256; ++i) { + this.S[i] = i; + } + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; + }; + // Arcfour.prototype.next = ARC4next; + Arcfour.prototype.next = function () { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + }; + return Arcfour; +}()); +// Plug in your RNG constructor here +function prng_newstate() { + return new Arcfour(); +} +// Pool size must be a multiple of 4 and greater than 32. +// An array of bytes the size of the pool will be passed to init() +var rng_psize = 256; + +// Random number generator - requires a PRNG backend, e.g. prng4.js +var rng_state; +var rng_pool = null; +var rng_pptr; +// Initialize the pool with junk if needed. +if (rng_pool == null) { + rng_pool = []; + rng_pptr = 0; + var t = void 0; + var getRandomValues = function (array) { + for (var i = 0, l = array.length; i < l; i++) { + array[i] = Math.floor(Math.random() * 256); + } + return array; + } + + var z = new Uint32Array(256); + + getRandomValues(z); + // for (t = 0; t < z.length; ++t) { + // rng_pool[rng_pptr++] = z[t] & 255; + // } + // if (window.crypto && window.crypto.getRandomValues) { + // Extract entropy (2048 bits) from RNG if available + + // var z = new Uint32Array(256); + // window.crypto.getRandomValues(z); + // for (t = 0; t < z.length; ++t) { + // rng_pool[rng_pptr++] = z[t] & 255; + // } + // } + // Use mouse events for entropy, if we do not have enough entropy by the time + // we need it, entropy will be generated by Math.random. + var onMouseMoveListener_1 = function (ev) { + this.count = this.count || 0; + if (this.count >= 256 || rng_pptr >= rng_psize) { + + 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. + } + }; +} +function rng_get_byte() { + if (rng_state == null) { + rng_state = prng_newstate(); + // At this point, we may not have collected enough entropy. If not, fall back to Math.random + while (rng_pptr < rng_psize) { + var random = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = random & 255; + } + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { + rng_pool[rng_pptr] = 0; + } + rng_pptr = 0; + } + // TODO: allow reseeding after first request + return rng_state.next(); +} +var SecureRandom = /** @class */ (function () { + function SecureRandom() { + } + SecureRandom.prototype.nextBytes = function (ba) { + for (var i = 0; i < ba.length; ++i) { + ba[i] = rng_get_byte(); + } + }; + return SecureRandom; +}()); + +// Depends on jsbn.js and rng.js +// function linebrk(s,n) { +// var ret = ""; +// var i = 0; +// while(i + n < s.length) { +// ret += s.substring(i,i+n) + "\n"; +// i += n; +// } +// return ret + s.substring(i,s.length); +// } +// function byte2Hex(b) { +// if(b < 0x10) +// return "0" + b.toString(16); +// else +// return b.toString(16); +// } +function pkcs1pad1(s, n) { + if (n < s.length + 22) { + console.error("Message too long for RSA"); + return null; + } + var len = n - s.length - 6; + var filler = ""; + for (var f = 0; f < len; f += 2) { + filler += "ff"; + } + var m = "0001" + filler + "00" + s; + return parseBigInt(m, 16); +} +// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint +function pkcs1pad2(s, n) { + if (n < s.length + 11) { // TODO: fix for utf-8 + console.error("Message too long for RSA"); + return null; + } + var ba = []; + var i = s.length - 1; + while (i >= 0 && n > 0) { + var c = s.charCodeAt(i--); + if (c < 128) { // encode using utf-8 + ba[--n] = c; + } + else if ((c > 127) && (c < 2048)) { + ba[--n] = (c & 63) | 128; + ba[--n] = (c >> 6) | 192; + } + else { + ba[--n] = (c & 63) | 128; + ba[--n] = ((c >> 6) & 63) | 128; + ba[--n] = (c >> 12) | 224; + } + } + ba[--n] = 0; + var rng = new SecureRandom(); + var x = []; + while (n > 2) { // random non-zero pad + x[0] = 0; + while (x[0] == 0) { + rng.nextBytes(x); + } + ba[--n] = x[0]; + } + ba[--n] = 2; + ba[--n] = 0; + return new BigInteger(ba); +} +// "empty" RSA key constructor +var RSAKey = /** @class */ (function () { + function RSAKey() { + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; + } + //#region PROTECTED + // protected + // RSAKey.prototype.doPublic = RSADoPublic; + // Perform raw public operation on "x": return x^e (mod n) + RSAKey.prototype.doPublic = function (x) { + return x.modPowInt(this.e, this.n); + }; + // RSAKey.prototype.doPrivate = RSADoPrivate; + // Perform raw private operation on "x": return x^d (mod n) + RSAKey.prototype.doPrivate = function (x) { + if (this.p == null || this.q == null) { + return x.modPow(this.d, this.n); + } + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(this.p); + } + return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); + }; + //#endregion PROTECTED + //#region PUBLIC + // RSAKey.prototype.setPublic = RSASetPublic; + // Set the public key fields N and e from hex strings + RSAKey.prototype.setPublic = function (N, E) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + } + else { + console.error("Invalid RSA public key"); + } + }; + // RSAKey.prototype.encrypt = RSAEncrypt; + // Return the PKCS#1 RSA encryption of "text" as an even-length hex string + RSAKey.prototype.encrypt = function (text) { + var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); + if (m == null) { + return null; + } + var c = this.doPublic(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } + else { + return "0" + h; + } + }; + // RSAKey.prototype.setPrivate = RSASetPrivate; + // Set the private key fields N, e, and d from hex strings + RSAKey.prototype.setPrivate = function (N, E, D) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + } + else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; + // Set the private key fields N, e, d and CRT params from hex strings + RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + this.p = parseBigInt(P, 16); + this.q = parseBigInt(Q, 16); + this.dmp1 = parseBigInt(DP, 16); + this.dmq1 = parseBigInt(DQ, 16); + this.coeff = parseBigInt(C, 16); + } + else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.generate = RSAGenerate; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generate = function (B, E) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + for (;;) { + for (;;) { + this.p = new BigInteger(B - qs, 1, rng); + if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) { + break; + } + } + for (;;) { + this.q = new BigInteger(qs, 1, rng); + if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) { + break; + } + } + if (this.p.compareTo(this.q) <= 0) { + var t = this.p; + this.p = this.q; + this.q = t; + } + var p1 = this.p.subtract(BigInteger.ONE); + var q1 = this.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + this.n = this.p.multiply(this.q); + this.d = ee.modInverse(phi); + this.dmp1 = this.d.mod(p1); + this.dmq1 = this.d.mod(q1); + this.coeff = this.q.modInverse(this.p); + break; + } + } + }; + // RSAKey.prototype.decrypt = RSADecrypt; + // Return the PKCS#1 RSA decryption of "ctext". + // "ctext" is an even-length hex string and the output is a plain string. + RSAKey.prototype.decrypt = function (ctext) { + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if (m == null) { + return null; + } + return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); + }; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generateAsync = function (B, E, callback) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + var rsa = this; + // These functions have non-descript names because they were originally for(;;) loops. + // I don't know about cryptography to give them better names than loop1-4. + var loop1 = function () { + var loop4 = function () { + if (rsa.p.compareTo(rsa.q) <= 0) { + var t = rsa.p; + rsa.p = rsa.q; + rsa.q = t; + } + var p1 = rsa.p.subtract(BigInteger.ONE); + var q1 = rsa.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + rsa.n = rsa.p.multiply(rsa.q); + rsa.d = ee.modInverse(phi); + rsa.dmp1 = rsa.d.mod(p1); + rsa.dmq1 = rsa.d.mod(q1); + rsa.coeff = rsa.q.modInverse(rsa.p); + setTimeout(function () { callback(); }, 0); // escape + } + else { + setTimeout(loop1, 0); + } + }; + var loop3 = function () { + rsa.q = nbi(); + rsa.q.fromNumberAsync(qs, 1, rng, function () { + rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) { + setTimeout(loop4, 0); + } + else { + setTimeout(loop3, 0); + } + }); + }); + }; + var loop2 = function () { + rsa.p = nbi(); + rsa.p.fromNumberAsync(B - qs, 1, rng, function () { + rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) { + setTimeout(loop3, 0); + } + else { + setTimeout(loop2, 0); + } + }); + }); + }; + setTimeout(loop2, 0); + }; + setTimeout(loop1, 0); + }; + RSAKey.prototype.sign = function (text, digestMethod, digestName) { + var header = getDigestHeader(digestName); + var digest = header + digestMethod(text).toString(); + var m = pkcs1pad1(digest, this.n.bitLength() / 4); + if (m == null) { + return null; + } + var c = this.doPrivate(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } + else { + return "0" + h; + } + }; + RSAKey.prototype.verify = function (text, signature, digestMethod) { + var c = parseBigInt(signature, 16); + var m = this.doPublic(c); + if (m == null) { + return null; + } + var unpadded = m.toString(16).replace(/^1f+00/, ""); + var digest = removeDigestHeader(unpadded); + return digest == digestMethod(text).toString(); + }; + return RSAKey; +}()); +// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext +function pkcs1unpad2(d, n) { + var b = d.toByteArray(); + var i = 0; + while (i < b.length && b[i] == 0) { + ++i; + } + if (b.length - i != n - 1 || b[i] != 2) { + return null; + } + ++i; + while (b[i] != 0) { + if (++i >= b.length) { + return null; + } + } + var ret = ""; + while (++i < b.length) { + var c = b[i] & 255; + if (c < 128) { // utf-8 decode + ret += String.fromCharCode(c); + } + else if ((c > 191) && (c < 224)) { + ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63)); + ++i; + } + else { + ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)); + i += 2; + } + } + return ret; +} +// https://tools.ietf.org/html/rfc3447#page-43 +var DIGEST_HEADERS = { + md2: "3020300c06082a864886f70d020205000410", + md5: "3020300c06082a864886f70d020505000410", + sha1: "3021300906052b0e03021a05000414", + sha224: "302d300d06096086480165030402040500041c", + sha256: "3031300d060960864801650304020105000420", + sha384: "3041300d060960864801650304020205000430", + sha512: "3051300d060960864801650304020305000440", + ripemd160: "3021300906052b2403020105000414", +}; +function getDigestHeader(name) { + return DIGEST_HEADERS[name] || ""; +} +function removeDigestHeader(str) { + for (var name_1 in DIGEST_HEADERS) { + if (DIGEST_HEADERS.hasOwnProperty(name_1)) { + var header = DIGEST_HEADERS[name_1]; + var len = header.length; + if (str.substr(0, len) == header) { + return str.substr(len); + } + } + } + return str; +} +// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string +// function RSAEncryptB64(text) { +// var h = this.encrypt(text); +// if(h) return hex2b64(h); else return null; +// } +// public +// RSAKey.prototype.encrypt_b64 = RSAEncryptB64; + +/*! +Copyright (c) 2011, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.html +version: 2.9.0 +*/ +var YAHOO = {}; +YAHOO.lang = { + /** + * Utility to set up the prototype, constructor and superclass properties to + * support an inheritance strategy that can chain constructors and methods. + * Static members will not be inherited. + * + * @method extend + * @static + * @param {Function} subc the object to modify + * @param {Function} superc the object to inherit + * @param {Object} overrides additional properties/methods to add to the + * subclass prototype. These will override the + * matching items obtained from the superclass + * if present. + */ + extend: function(subc, superc, overrides) { + if (! superc || ! subc) { + throw new Error("YAHOO.lang.extend failed, please check that " + + "all dependencies are included."); + } + + var F = function() {}; + F.prototype = superc.prototype; + subc.prototype = new F(); + subc.prototype.constructor = subc; + subc.superclass = superc.prototype; + + if (superc.prototype.constructor == Object.prototype.constructor) { + superc.prototype.constructor = superc; + } + + if (overrides) { + var i; + for (i in overrides) { + subc.prototype[i] = overrides[i]; + } + + /* + * IE will not enumerate native functions in a derived object even if the + * function was overridden. This is a workaround for specific functions + * we care about on the Object prototype. + * @property _IEEnumFix + * @param {Function} r the object to receive the augmentation + * @param {Function} s the object that supplies the properties to augment + * @static + * @private + */ + var _IEEnumFix = function() {}, + ADD = ["toString", "valueOf"]; + try { + if (/MSIE/.test(navigator.userAgent)) { + _IEEnumFix = function(r, s) { + for (i = 0; i < ADD.length; i = i + 1) { + var fname = ADD[i], f = s[fname]; + if (typeof f === 'function' && f != Object.prototype[fname]) { + r[fname] = f; + } + } + }; + } + } catch (ex) {} _IEEnumFix(subc.prototype, overrides); + } + } +}; + +/* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license + */ + +/** + * @fileOverview + * @name asn1-1.0.js + * @author Kenji Urushima kenji.urushima@gmail.com + * @version asn1 1.0.13 (2017-Jun-02) + * @since jsrsasign 2.1 + * @license MIT License + */ + +/** + * kjur's class library name space + *

+ * This name space provides following name spaces: + *

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

+ * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. + * @name KJUR + * @namespace kjur's class library name space + */ +var KJUR = {}; + +/** + * kjur's ASN.1 class library name space + *

+ * 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. + *

PROVIDING ASN.1 PRIMITIVES

+ * Here are ASN.1 DER primitive classes. + *
    + *
  • 0x01 {@link KJUR.asn1.DERBoolean}
  • + *
  • 0x02 {@link KJUR.asn1.DERInteger}
  • + *
  • 0x03 {@link KJUR.asn1.DERBitString}
  • + *
  • 0x04 {@link KJUR.asn1.DEROctetString}
  • + *
  • 0x05 {@link KJUR.asn1.DERNull}
  • + *
  • 0x06 {@link KJUR.asn1.DERObjectIdentifier}
  • + *
  • 0x0a {@link KJUR.asn1.DEREnumerated}
  • + *
  • 0x0c {@link KJUR.asn1.DERUTF8String}
  • + *
  • 0x12 {@link KJUR.asn1.DERNumericString}
  • + *
  • 0x13 {@link KJUR.asn1.DERPrintableString}
  • + *
  • 0x14 {@link KJUR.asn1.DERTeletexString}
  • + *
  • 0x16 {@link KJUR.asn1.DERIA5String}
  • + *
  • 0x17 {@link KJUR.asn1.DERUTCTime}
  • + *
  • 0x18 {@link KJUR.asn1.DERGeneralizedTime}
  • + *
  • 0x30 {@link KJUR.asn1.DERSequence}
  • + *
  • 0x31 {@link KJUR.asn1.DERSet}
  • + *
+ *

OTHER ASN.1 CLASSES

+ *
    + *
  • {@link KJUR.asn1.ASN1Object}
  • + *
  • {@link KJUR.asn1.DERAbstractString}
  • + *
  • {@link KJUR.asn1.DERAbstractTime}
  • + *
  • {@link KJUR.asn1.DERAbstractStructured}
  • + *
  • {@link KJUR.asn1.DERTaggedObject}
  • + *
+ *

SUB NAME SPACES

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

+ * NOTE: Please ignore method summary and document of this namespace. + * This caused by a bug of jsdoc2. + * @name KJUR.asn1 + * @namespace + */ +if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; + +/** + * ASN1 utilities class + * @name KJUR.asn1.ASN1Util + * @class ASN1 utilities class + * @since asn1 1.0.2 + */ +KJUR.asn1.ASN1Util = new function() { + this.integerToByteHex = function(i) { + var h = i.toString(16); + if ((h.length % 2) == 1) h = '0' + h; + return h; + }; + this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { + var h = bigIntegerValue.toString(16); + if (h.substr(0, 1) != '-') { + if (h.length % 2 == 1) { + h = '0' + h; + } else { + if (! h.match(/^[0-7]/)) { + h = '00' + h; + } + } + } else { + var hPos = h.substr(1); + var xorLen = hPos.length; + if (xorLen % 2 == 1) { + xorLen += 1; + } else { + if (! h.match(/^[0-7]/)) { + xorLen += 2; + } + } + var hMask = ''; + for (var i = 0; i < xorLen; i++) { + hMask += 'f'; + } + var biMask = new BigInteger(hMask, 16); + var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); + h = biNeg.toString(16).replace(/^-/, ''); + } + return h; + }; + /** + * get PEM string from hexadecimal data and header string + * @name getPEMStringFromHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} dataHex hexadecimal string of PEM body + * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') + * @return {String} PEM formatted string of input data + * @description + * This method converts a hexadecimal string to a PEM string with + * a specified header. Its line break will be CRLF("\r\n"). + * @example + * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); + * // value of pem will be: + * -----BEGIN PRIVATE KEY----- + * YWFh + * -----END PRIVATE KEY----- + */ + this.getPEMStringFromHex = function(dataHex, pemHeader) { + return hextopem(dataHex, pemHeader); + }; + + /** + * generate ASN1Object specifed by JSON parameters + * @name newObject + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return {KJUR.asn1.ASN1Object} generated object + * @since asn1 1.0.3 + * @description + * generate any ASN1Object specified by JSON param + * including ASN.1 primitive or structured. + * Generally 'param' can be described as follows: + *
+ * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} + *
+ * 'TYPE-OF-ASN1OBJ' can be one of following symbols: + *
    + *
  • 'bool' - DERBoolean
  • + *
  • 'int' - DERInteger
  • + *
  • 'bitstr' - DERBitString
  • + *
  • 'octstr' - DEROctetString
  • + *
  • 'null' - DERNull
  • + *
  • 'oid' - DERObjectIdentifier
  • + *
  • 'enum' - DEREnumerated
  • + *
  • 'utf8str' - DERUTF8String
  • + *
  • 'numstr' - DERNumericString
  • + *
  • 'prnstr' - DERPrintableString
  • + *
  • 'telstr' - DERTeletexString
  • + *
  • 'ia5str' - DERIA5String
  • + *
  • 'utctime' - DERUTCTime
  • + *
  • 'gentime' - DERGeneralizedTime
  • + *
  • 'seq' - DERSequence
  • + *
  • 'set' - DERSet
  • + *
  • 'tag' - DERTaggedObject
  • + *
+ * @example + * newObject({'prnstr': 'aaa'}); + * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) + * // ASN.1 Tagged Object + * newObject({'tag': {'tag': 'a1', + * 'explicit': true, + * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); + * // more simple representation of ASN.1 Tagged Object + * newObject({'tag': ['a1', + * true, + * {'seq': [ + * {'int': 3}, + * {'prnstr': 'aaa'}]} + * ]}); + */ + this.newObject = function(param) { + var _KJUR = KJUR, + _KJUR_asn1 = _KJUR.asn1, + _DERBoolean = _KJUR_asn1.DERBoolean, + _DERInteger = _KJUR_asn1.DERInteger, + _DERBitString = _KJUR_asn1.DERBitString, + _DEROctetString = _KJUR_asn1.DEROctetString, + _DERNull = _KJUR_asn1.DERNull, + _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, + _DEREnumerated = _KJUR_asn1.DEREnumerated, + _DERUTF8String = _KJUR_asn1.DERUTF8String, + _DERNumericString = _KJUR_asn1.DERNumericString, + _DERPrintableString = _KJUR_asn1.DERPrintableString, + _DERTeletexString = _KJUR_asn1.DERTeletexString, + _DERIA5String = _KJUR_asn1.DERIA5String, + _DERUTCTime = _KJUR_asn1.DERUTCTime, + _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, + _DERSequence = _KJUR_asn1.DERSequence, + _DERSet = _KJUR_asn1.DERSet, + _DERTaggedObject = _KJUR_asn1.DERTaggedObject, + _newObject = _KJUR_asn1.ASN1Util.newObject; + + var keys = Object.keys(param); + if (keys.length != 1) + throw "key of param shall be only one."; + var key = keys[0]; + + if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1) + throw "undefined key: " + key; + + if (key == "bool") return new _DERBoolean(param[key]); + if (key == "int") return new _DERInteger(param[key]); + if (key == "bitstr") return new _DERBitString(param[key]); + if (key == "octstr") return new _DEROctetString(param[key]); + if (key == "null") return new _DERNull(param[key]); + if (key == "oid") return new _DERObjectIdentifier(param[key]); + if (key == "enum") return new _DEREnumerated(param[key]); + if (key == "utf8str") return new _DERUTF8String(param[key]); + if (key == "numstr") return new _DERNumericString(param[key]); + if (key == "prnstr") return new _DERPrintableString(param[key]); + if (key == "telstr") return new _DERTeletexString(param[key]); + if (key == "ia5str") return new _DERIA5String(param[key]); + if (key == "utctime") return new _DERUTCTime(param[key]); + if (key == "gentime") return new _DERGeneralizedTime(param[key]); + + if (key == "seq") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSequence({'array': a}); + } + + if (key == "set") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSet({'array': a}); + } + + if (key == "tag") { + var tagParam = param[key]; + if (Object.prototype.toString.call(tagParam) === '[object Array]' && + tagParam.length == 3) { + var obj = _newObject(tagParam[2]); + return new _DERTaggedObject({tag: tagParam[0], + explicit: tagParam[1], + obj: obj}); + } else { + var newParam = {}; + if (tagParam.explicit !== undefined) + newParam.explicit = tagParam.explicit; + if (tagParam.tag !== undefined) + newParam.tag = tagParam.tag; + if (tagParam.obj === undefined) + throw "obj shall be specified for 'tag'."; + newParam.obj = _newObject(tagParam.obj); + return new _DERTaggedObject(newParam); + } + } + }; + + /** + * get encoded hexadecimal string of ASN1Object specifed by JSON parameters + * @name jsonToASN1HEX + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return hexadecimal string of ASN1Object + * @since asn1 1.0.4 + * @description + * As for ASN.1 object representation of JSON object, + * please see {@link newObject}. + * @example + * jsonToASN1HEX({'prnstr': 'aaa'}); + */ + this.jsonToASN1HEX = function(param) { + var asn1Obj = this.newObject(param); + return asn1Obj.getEncodedHex(); + }; +}; + +/** + * get dot noted oid number string from hexadecimal value of OID + * @name oidHexToInt + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} hex hexadecimal value of object identifier + * @return {String} dot noted string of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from hexadecimal string representation of + * ASN.1 value of object identifier to oid number string. + * @example + * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6" + */ +KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { + var s = ""; + var i01 = parseInt(hex.substr(0, 2), 16); + var i0 = Math.floor(i01 / 40); + var i1 = i01 % 40; + var s = i0 + "." + i1; + + var binbuf = ""; + for (var i = 2; i < hex.length; i += 2) { + var value = parseInt(hex.substr(i, 2), 16); + var bin = ("00000000" + value.toString(2)).slice(- 8); + binbuf = binbuf + bin.substr(1, 7); + if (bin.substr(0, 1) == "0") { + var bi = new BigInteger(binbuf, 2); + s = s + "." + bi.toString(10); + binbuf = ""; + } + } + return s; +}; + +/** + * get hexadecimal value of object identifier from dot noted oid value + * @name oidIntToHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} oidString dot noted string of object identifier + * @return {String} hexadecimal value of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from object identifier value string. + * to hexadecimal string representation of it. + * @example + * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406" + */ +KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { + var itox = function(i) { + var h = i.toString(16); + if (h.length == 1) h = '0' + h; + return h; + }; + + var roidtox = function(roid) { + var h = ''; + var bi = new BigInteger(roid, 10); + var b = bi.toString(2); + var padLen = 7 - b.length % 7; + if (padLen == 7) padLen = 0; + var bPad = ''; + for (var i = 0; i < padLen; i++) bPad += '0'; + b = bPad + b; + for (var i = 0; i < b.length - 1; i += 7) { + var b8 = b.substr(i, 7); + if (i != b.length - 7) b8 = '1' + b8; + h += itox(parseInt(b8, 2)); + } + return h; + }; + + if (! oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + return h; +}; + + +// ******************************************************************** +// Abstract ASN.1 Classes +// ******************************************************************** + +// ******************************************************************** + +/** + * base class for ASN.1 DER encoder object + * @name KJUR.asn1.ASN1Object + * @class base class for ASN.1 DER encoder object + * @property {Boolean} isModified flag whether internal data was changed + * @property {String} hTLV hexadecimal string of ASN.1 TLV + * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) + * @property {String} hL hexadecimal string of ASN.1 TLV length(L) + * @property {String} hV hexadecimal string of ASN.1 TLV value(V) + * @description + */ +KJUR.asn1.ASN1Object = function() { + var hV = ''; + + /** + * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) + * @name getLengthHexFromValue + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV length(L) + */ + this.getLengthHexFromValue = function() { + if (typeof this.hV == "undefined" || this.hV == null) { + throw "this.hV is null or undefined."; + } + if (this.hV.length % 2 == 1) { + throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; + } + var n = this.hV.length / 2; + var hN = n.toString(16); + if (hN.length % 2 == 1) { + hN = "0" + hN; + } + if (n < 128) { + return hN; + } else { + var hNlen = hN.length / 2; + if (hNlen > 15) { + throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); + } + var head = 128 + hNlen; + return head.toString(16) + hN; + } + }; + + /** + * get hexadecimal string of ASN.1 TLV bytes + * @name getEncodedHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV + */ + this.getEncodedHex = function() { + if (this.hTLV == null || this.isModified) { + this.hV = this.getFreshValueHex(); + this.hL = this.getLengthHexFromValue(); + this.hTLV = this.hT + this.hL + this.hV; + this.isModified = false; + //alert("first time: " + this.hTLV); + } + return this.hTLV; + }; + + /** + * get hexadecimal string of ASN.1 TLV value(V) bytes + * @name getValueHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes + */ + this.getValueHex = function() { + this.getEncodedHex(); + return this.hV; + }; + + this.getFreshValueHex = function() { + return ''; + }; +}; + +// == BEGIN DERAbstractString ================================================ +/** + * base class for ASN.1 DER string classes + * @name KJUR.asn1.DERAbstractString + * @class base class for ASN.1 DER string classes + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @property {String} s internal string of value + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + */ +KJUR.asn1.DERAbstractString = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @return {String} string value of this string object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newS value by a string to set + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(this.s); + }; + + /** + * set value by a hexadecimal string + * @name setStringHex + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newHexString value by a hexadecimal string to set + */ + this.setStringHex = function(newHexString) { + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string") { + this.setString(params); + } else if (typeof params['str'] != "undefined") { + this.setString(params['str']); + } else if (typeof params['hex'] != "undefined") { + this.setStringHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); +// == END DERAbstractString ================================================ + +// == BEGIN DERAbstractTime ================================================== +/** + * base class for ASN.1 DER Generalized/UTCTime class + * @name KJUR.asn1.DERAbstractTime + * @class base class for ASN.1 DER Generalized/UTCTime class + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERAbstractTime = function(params) { + KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); + + // --- PRIVATE METHODS -------------------- + this.localDateToUTC = function(d) { + utc = d.getTime() + (d.getTimezoneOffset() * 60000); + var utcDate = new Date(utc); + return utcDate; + }; + + /* + * format date string by Data object + * @name formatDate + * @memberOf KJUR.asn1.AbstractTime; + * @param {Date} dateObject + * @param {string} type 'utc' or 'gen' + * @param {boolean} withMillis flag for with millisections or not + * @description + * 'withMillis' flag is supported from asn1 1.0.6. + */ + this.formatDate = function(dateObject, type, withMillis) { + var pad = this.zeroPadding; + var d = this.localDateToUTC(dateObject); + var year = String(d.getFullYear()); + if (type == 'utc') year = year.substr(2, 2); + var month = pad(String(d.getMonth() + 1), 2); + var day = pad(String(d.getDate()), 2); + var hour = pad(String(d.getHours()), 2); + var min = pad(String(d.getMinutes()), 2); + var sec = pad(String(d.getSeconds()), 2); + var s = year + month + day + hour + min + sec; + if (withMillis === true) { + var millis = d.getMilliseconds(); + if (millis != 0) { + var sMillis = pad(String(millis), 3); + sMillis = sMillis.replace(/[0]+$/, ""); + s = s + "." + sMillis; + } + } + return s + "Z"; + }; + + this.zeroPadding = function(s, len) { + if (s.length >= len) return s; + return new Array(len - s.length + 1).join('0') + s; + }; + + // --- PUBLIC METHODS -------------------- + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @return {String} string value of this time object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {String} newS value by a string to set such like "130430235959Z" + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(newS); + }; + + /** + * set value by a Date object + * @name setByDateValue + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {Integer} year year of date (ex. 2013) + * @param {Integer} month month of date between 1 and 12 (ex. 12) + * @param {Integer} day day of month + * @param {Integer} hour hours of date + * @param {Integer} min minutes of date + * @param {Integer} sec seconds of date + */ + this.setByDateValue = function(year, month, day, hour, min, sec) { + var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); + this.setByDate(dateObject); + }; + + this.getFreshValueHex = function() { + return this.hV; + }; +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); +// == END DERAbstractTime ================================================== + +// == BEGIN DERAbstractStructured ============================================ +/** + * base class for ASN.1 DER structured class + * @name KJUR.asn1.DERAbstractStructured + * @class base class for ASN.1 DER structured class + * @property {Array} asn1Array internal array of ASN1Object + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERAbstractStructured = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * set value by array of ASN1Object + * @name setByASN1ObjectArray + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {array} asn1ObjectArray array of ASN1Object to set + */ + this.setByASN1ObjectArray = function(asn1ObjectArray) { + this.hTLV = null; + this.isModified = true; + this.asn1Array = asn1ObjectArray; + }; + + /** + * append an ASN1Object to internal array + * @name appendASN1Object + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {ASN1Object} asn1Object to add + */ + this.appendASN1Object = function(asn1Object) { + this.hTLV = null; + this.isModified = true; + this.asn1Array.push(asn1Object); + }; + + this.asn1Array = new Array(); + if (typeof params != "undefined") { + if (typeof params['array'] != "undefined") { + this.asn1Array = params['array']; + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); + + +// ******************************************************************** +// ASN.1 Object Classes +// ******************************************************************** + +// ******************************************************************** +/** + * class for ASN.1 DER Boolean + * @name KJUR.asn1.DERBoolean + * @class class for ASN.1 DER Boolean + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERBoolean = function() { + KJUR.asn1.DERBoolean.superclass.constructor.call(this); + this.hT = "01"; + this.hTLV = "0101ff"; +}; +YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER Integer + * @name KJUR.asn1.DERInteger + * @class class for ASN.1 DER Integer + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • bigint - specify initial ASN.1 value(V) by BigInteger object
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * 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 + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + * @example + * new KJUR.asn1.DERInteger(123); + * new KJUR.asn1.DERInteger({'int': 123}); + * new KJUR.asn1.DERInteger({'hex': '1fad'}); + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['bigint'] != "undefined") { + this.setByBigInteger(params['bigint']); + } else if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER encoded BitString primitive + * @name KJUR.asn1.DERBitString + * @class class for ASN.1 DER encoded BitString primitive + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • bin - specify binary string (ex. '10111')
  • + *
  • array - specify array of boolean (ex. [true,false,true,true])
  • + *
  • hex - specify hexadecimal string of ASN.1 value(V) including unused bits
  • + *
  • obj - specify {@link KJUR.asn1.ASN1Util.newObject} + * argument for "BitString encapsulates" structure.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: 'obj' parameter have been supported since + * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
+ * @example + * // default constructor + * o = new KJUR.asn1.DERBitString(); + * // initialize with binary string + * o = new KJUR.asn1.DERBitString({bin: "1011"}); + * // initialize with boolean array + * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); + * // initialize with hexadecimal string (04 is unused bits) + * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); + * // initialize with ASN1Util.newObject argument for encapsulated + * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // BIT STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ +KJUR.asn1.DERBitString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = "00" + o.getEncodedHex(); + } + KJUR.asn1.DERBitString.superclass.constructor.call(this); + this.hT = "03"; + + /** + * set ASN.1 value(V) by a hexadecimal string including unused bits + * @name setHexValueIncludingUnusedBits + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {String} newHexStringIncludingUnusedBits + */ + this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { + this.hTLV = null; + this.isModified = true; + this.hV = newHexStringIncludingUnusedBits; + }; + + /** + * set ASN.1 value(V) by unused bit and hexadecimal string of value + * @name setUnusedBitsAndHexValue + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {Integer} unusedBits + * @param {String} hValue + */ + this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { + if (unusedBits < 0 || 7 < unusedBits) { + throw "unused bits shall be from 0 to 7: u = " + unusedBits; + } + var hUnusedBits = "0" + unusedBits; + this.hTLV = null; + this.isModified = true; + this.hV = hUnusedBits + hValue; + }; + + /** + * set ASN.1 DER BitString by binary string
+ * @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'.
+ * NOTE: Trailing zeros '0' will be ignored. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray("01011"); + */ + this.setByBinaryString = function(binaryString) { + binaryString = binaryString.replace(/0+$/, ''); + var unusedBits = 8 - binaryString.length % 8; + if (unusedBits == 8) unusedBits = 0; + for (var i = 0; i <= unusedBits; i++) { + binaryString += '0'; + } + var h = ''; + for (var i = 0; i < binaryString.length - 1; i += 8) { + var b = binaryString.substr(i, 8); + var x = parseInt(b, 2).toString(16); + if (x.length == 1) x = '0' + x; + h += x; + } + this.hTLV = null; + this.isModified = true; + this.hV = '0' + unusedBits + h; + }; + + /** + * set ASN.1 TLV value(V) by an array of boolean
+ * @name setByBooleanArray + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {array} booleanArray array of boolean (ex. [true, false, true]) + * @description + * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray([false, true, false, true, true]); + */ + this.setByBooleanArray = function(booleanArray) { + var s = ''; + for (var i = 0; i < booleanArray.length; i++) { + if (booleanArray[i] == true) { + s += '1'; + } else { + s += '0'; + } + } + this.setByBinaryString(s); + }; + + /** + * generate an array of falses with specified length
+ * @name newFalseArray + * @memberOf KJUR.asn1.DERBitString + * @function + * @param {Integer} nLength length of array to generate + * @return {array} array of boolean falses + * @description + * This static method may be useful to initialize boolean array. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.newFalseArray(3) → [false, false, false] + */ + this.newFalseArray = function(nLength) { + var a = new Array(nLength); + for (var i = 0; i < nLength; i++) { + a[i] = false; + } + return a; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { + this.setHexValueIncludingUnusedBits(params); + } else if (typeof params['hex'] != "undefined") { + this.setHexValueIncludingUnusedBits(params['hex']); + } else if (typeof params['bin'] != "undefined") { + this.setByBinaryString(params['bin']); + } else if (typeof params['array'] != "undefined") { + this.setByBooleanArray(params['array']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER OctetString
+ * @name KJUR.asn1.DEROctetString + * @class class for ASN.1 DER OctetString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * This class provides ASN.1 OctetString simple type.
+ * Supported "params" attributes are: + *
    + *
  • str - to set a string as a value
  • + *
  • hex - to set a hexadecimal string as a value
  • + *
  • obj - to set a encapsulated ASN.1 value by JSON object + * which is defined in {@link KJUR.asn1.ASN1Util.newObject}
  • + *
+ * NOTE: A parameter 'obj' have been supported + * for "OCTET STRING, encapsulates" structure. + * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). + * @see KJUR.asn1.DERAbstractString - superclass + * @example + * // default constructor + * o = new KJUR.asn1.DEROctetString(); + * // initialize with string + * o = new KJUR.asn1.DEROctetString({str: "aaa"}); + * // initialize with hexadecimal string + * o = new KJUR.asn1.DEROctetString({hex: "616161"}); + * // initialize with ASN1Util.newObject argument + * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // OCTET STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ +KJUR.asn1.DEROctetString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = o.getEncodedHex(); + } + KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); + this.hT = "04"; +}; +YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER Null + * @name KJUR.asn1.DERNull + * @class class for ASN.1 DER Null + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERNull = function() { + KJUR.asn1.DERNull.superclass.constructor.call(this); + this.hT = "05"; + this.hTLV = "0500"; +}; +YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER ObjectIdentifier + * @name KJUR.asn1.DERObjectIdentifier + * @class class for ASN.1 DER ObjectIdentifier + * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * 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) + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueOidString("2.5.4.13"); + */ + this.setValueOidString = function(oidString) { + if (! oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = h; + }; + + /** + * set value by a OID name + * @name setValueName + * @memberOf KJUR.asn1.DERObjectIdentifier# + * @function + * @param {String} oidName OID name (ex. 'serverAuth') + * @since 1.0.1 + * @description + * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. + * Otherwise raise error. + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueName("serverAuth"); + */ + this.setValueName = function(oidName) { + var oid = KJUR.asn1.x509.OID.name2oid(oidName); + if (oid !== '') { + this.setValueOidString(oid); + } else { + throw "DERObjectIdentifier oidName undefined: " + oidName; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (params !== undefined) { + if (typeof params === "string") { + if (params.match(/^[0-2].[0-9.]+$/)) { + this.setValueOidString(params); + } else { + this.setValueName(params); + } + } else if (params.oid !== undefined) { + this.setValueOidString(params.oid); + } else if (params.hex !== undefined) { + this.setValueHex(params.hex); + } else if (params.name !== undefined) { + this.setValueName(params.name); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER Enumerated + * @name KJUR.asn1.DEREnumerated + * @class class for ASN.1 DER Enumerated + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + * @example + * new KJUR.asn1.DEREnumerated(123); + * new KJUR.asn1.DEREnumerated({int: 123}); + * new KJUR.asn1.DEREnumerated({hex: '1fad'}); + */ +KJUR.asn1.DEREnumerated = function(params) { + KJUR.asn1.DEREnumerated.superclass.constructor.call(this); + this.hT = "0a"; + + /** + * set value by Tom Wu's BigInteger object + * @name setByBigInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {BigInteger} bigIntegerValue to set + */ + this.setByBigInteger = function(bigIntegerValue) { + this.hTLV = null; + this.isModified = true; + this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); + }; + + /** + * set value by integer value + * @name setByInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {Integer} integer value to set + */ + this.setByInteger = function(intValue) { + var bi = new BigInteger(String(intValue), 10); + this.setByBigInteger(bi); + }; + + /** + * set value by integer value + * @name setValueHex + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {String} hexadecimal string of integer value + * @description + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER UTF8String + * @name KJUR.asn1.DERUTF8String + * @class class for ASN.1 DER UTF8String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERUTF8String = function(params) { + KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); + this.hT = "0c"; +}; +YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER NumericString + * @name KJUR.asn1.DERNumericString + * @class class for ASN.1 DER NumericString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERNumericString = function(params) { + KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); + this.hT = "12"; +}; +YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER PrintableString + * @name KJUR.asn1.DERPrintableString + * @class class for ASN.1 DER PrintableString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERPrintableString = function(params) { + KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); + this.hT = "13"; +}; +YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER TeletexString + * @name KJUR.asn1.DERTeletexString + * @class class for ASN.1 DER TeletexString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERTeletexString = function(params) { + KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); + this.hT = "14"; +}; +YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER IA5String + * @name KJUR.asn1.DERIA5String + * @class class for ASN.1 DER IA5String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERIA5String = function(params) { + KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); + this.hT = "16"; +}; +YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER UTCTime + * @name KJUR.asn1.DERUTCTime + * @class class for ASN.1 DER UTCTime + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
+ * NOTE: 'params' can be omitted. + *

EXAMPLES

+ * @example + * d1 = new KJUR.asn1.DERUTCTime(); + * d1.setString('130430125959Z'); + * + * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); + * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); + * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); + */ +KJUR.asn1.DERUTCTime = function(params) { + KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); + this.hT = "17"; + + /** + * set value by a Date object
+ * @name setByDate + * @memberOf KJUR.asn1.DERUTCTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * o = new KJUR.asn1.DERUTCTime(); + * o.setByDate(new Date("2016/12/31")); + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (typeof this.date == "undefined" && typeof this.s == "undefined") { + this.date = new Date(); + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); + +// ******************************************************************** +/** + * class for ASN.1 DER GeneralizedTime + * @name KJUR.asn1.DERGeneralizedTime + * @class class for ASN.1 DER GeneralizedTime + * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) + * @property {Boolean} withMillis flag to show milliseconds or not + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
  • millis - specify flag to show milliseconds (from 1.0.6)
  • + *
+ * NOTE1: 'params' can be omitted. + * NOTE2: 'withMillis' property is supported from asn1 1.0.6. + */ +KJUR.asn1.DERGeneralizedTime = function(params) { + KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); + this.hT = "18"; + this.withMillis = false; + + /** + * set value by a Date object + * @name setByDate + * @memberOf KJUR.asn1.DERGeneralizedTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * When you specify UTC time, use 'Date.UTC' method like this:
+ * o1 = new DERUTCTime(); + * o1.setByDate(date); + * + * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (this.date === undefined && this.s === undefined) { + this.date = new Date(); + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + if (params.millis === true) { + this.withMillis = true; + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); + +// ******************************************************************** +/** + * class for ASN.1 DER Sequence + * @name KJUR.asn1.DERSequence + * @class class for ASN.1 DER Sequence + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
+ * NOTE: 'params' can be omitted. + */ +KJUR.asn1.DERSequence = function(params) { + KJUR.asn1.DERSequence.superclass.constructor.call(this, params); + this.hT = "30"; + this.getFreshValueHex = function() { + var h = ''; + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + h += asn1Obj.getEncodedHex(); + } + this.hV = h; + return this.hV; + }; +}; +YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); + +// ******************************************************************** +/** + * class for ASN.1 DER Set + * @name KJUR.asn1.DERSet + * @class class for ASN.1 DER Set + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
  • sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: sortflag is supported since 1.0.5. + */ +KJUR.asn1.DERSet = function(params) { + KJUR.asn1.DERSet.superclass.constructor.call(this, params); + this.hT = "31"; + this.sortFlag = true; // item shall be sorted only in ASN.1 DER + this.getFreshValueHex = function() { + var a = new Array(); + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + a.push(asn1Obj.getEncodedHex()); + } + if (this.sortFlag == true) a.sort(); + this.hV = a.join(''); + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params.sortflag != "undefined" && + params.sortflag == false) + this.sortFlag = false; + } +}; +YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); + +// ******************************************************************** +/** + * class for ASN.1 DER TaggedObject + * @name KJUR.asn1.DERTaggedObject + * @class class for ASN.1 DER TaggedObject + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * 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'. + *
+ * As for optional argument 'params' for constructor, you can specify *ANY* of + * following properties: + *
    + *
  • explicit - specify true if this is explicit tag otherwise false + * (default is 'true').
  • + *
  • tag - specify tag (default is 'a0' which means [0])
  • + *
  • obj - specify ASN1Object which is tagged
  • + *
+ * @example + * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); + * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); + * hex = d2.getEncodedHex(); + */ +KJUR.asn1.DERTaggedObject = function(params) { + KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); + this.hT = "a0"; + this.hV = ''; + this.isExplicit = true; + this.asn1Object = null; + + /** + * set value by an ASN1Object + * @name setString + * @memberOf KJUR.asn1.DERTaggedObject# + * @function + * @param {Boolean} isExplicitFlag flag for explicit/implicit tag + * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag + * @param {ASN1Object} asn1Object ASN.1 to encapsulate + */ + this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { + this.hT = tagNoHex; + this.isExplicit = isExplicitFlag; + this.asn1Object = asn1Object; + if (this.isExplicit) { + this.hV = this.asn1Object.getEncodedHex(); + this.hTLV = null; + this.isModified = true; + } else { + this.hV = null; + this.hTLV = asn1Object.getEncodedHex(); + this.hTLV = this.hTLV.replace(/^../, tagNoHex); + this.isModified = false; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['tag'] != "undefined") { + this.hT = params['tag']; + } + if (typeof params['explicit'] != "undefined") { + this.isExplicit = params['explicit']; + } + if (typeof params['obj'] != "undefined") { + this.asn1Object = params['obj']; + this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); + +/** + * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. + * This object is just a decorator for parsing the key parameter + * @param {string|Object} key - The key in string format, or an object containing + * the parameters needed to build a RSAKey object. + * @constructor + */ +var JSEncryptRSAKey = /** @class */ (function (_super) { + __extends(JSEncryptRSAKey, _super); + function JSEncryptRSAKey(key) { + var _this = _super.call(this) || this; + // Call the super constructor. + // RSAKey.call(this); + // If a key key was provided. + if (key) { + // If this is a string... + if (typeof key === "string") { + _this.parseKey(key); + } + else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || + JSEncryptRSAKey.hasPublicKeyProperty(key)) { + // Set the values for the key. + _this.parsePropertiesFrom(key); + } + } + return _this; + } + /** + * Method to parse a pem encoded string containing both a public or private key. + * The method will translate the pem encoded string in a der encoded string and + * will parse private key and public key parameters. This method accepts public key + * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). + * + * @todo Check how many rsa formats use the same format of pkcs #1. + * + * The format is defined as: + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * it's possible to examine the structure of the keys obtained from openssl using + * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ + * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer + * @private + */ + JSEncryptRSAKey.prototype.parseKey = function (pem) { + try { + var modulus = 0; + var public_exponent = 0; + var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; + var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); + var asn1 = ASN1.decode(der); + // Fixes a bug with OpenSSL 1.0+ private keys + if (asn1.sub.length === 3) { + asn1 = asn1.sub[2].sub[0]; + } + if (asn1.sub.length === 9) { + // Parse the private key. + modulus = asn1.sub[1].getHexStringValue(); // bigint + this.n = parseBigInt(modulus, 16); + public_exponent = asn1.sub[2].getHexStringValue(); // int + this.e = parseInt(public_exponent, 16); + var private_exponent = asn1.sub[3].getHexStringValue(); // bigint + this.d = parseBigInt(private_exponent, 16); + var prime1 = asn1.sub[4].getHexStringValue(); // bigint + this.p = parseBigInt(prime1, 16); + var prime2 = asn1.sub[5].getHexStringValue(); // bigint + this.q = parseBigInt(prime2, 16); + var exponent1 = asn1.sub[6].getHexStringValue(); // bigint + this.dmp1 = parseBigInt(exponent1, 16); + var exponent2 = asn1.sub[7].getHexStringValue(); // bigint + this.dmq1 = parseBigInt(exponent2, 16); + var coefficient = asn1.sub[8].getHexStringValue(); // bigint + this.coeff = parseBigInt(coefficient, 16); + } + else if (asn1.sub.length === 2) { + // Parse the public key. + var bit_string = asn1.sub[1]; + var sequence = bit_string.sub[0]; + modulus = sequence.sub[0].getHexStringValue(); + this.n = parseBigInt(modulus, 16); + public_exponent = sequence.sub[1].getHexStringValue(); + this.e = parseInt(public_exponent, 16); + } + else { + return false; + } + return true; + } + catch (ex) { + return false; + } + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa key. + * + * The translation follow the ASN.1 notation : + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER, -- (inverse of q) mod p + * } + * @returns {string} DER Encoded String representing the rsa private key + * @private + */ + JSEncryptRSAKey.prototype.getPrivateBaseKey = function () { + var options = { + array: [ + new KJUR.asn1.DERInteger({ int: 0 }), + new KJUR.asn1.DERInteger({ bigint: this.n }), + new KJUR.asn1.DERInteger({ int: this.e }), + new KJUR.asn1.DERInteger({ bigint: this.d }), + new KJUR.asn1.DERInteger({ bigint: this.p }), + new KJUR.asn1.DERInteger({ bigint: this.q }), + new KJUR.asn1.DERInteger({ bigint: this.dmp1 }), + new KJUR.asn1.DERInteger({ bigint: this.dmq1 }), + new KJUR.asn1.DERInteger({ bigint: this.coeff }) + ] + }; + var seq = new KJUR.asn1.DERSequence(options); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () { + return hex2b64(this.getPrivateBaseKey()); + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa public key. + * The representation follow the ASN.1 notation : + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * @returns {string} DER Encoded String representing the rsa public key + * @private + */ + JSEncryptRSAKey.prototype.getPublicBaseKey = function () { + var first_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }), + new KJUR.asn1.DERNull() + ] + }); + var second_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERInteger({ bigint: this.n }), + new KJUR.asn1.DERInteger({ int: this.e }) + ] + }); + var bit_string = new KJUR.asn1.DERBitString({ + hex: "00" + second_sequence.getEncodedHex() + }); + var seq = new KJUR.asn1.DERSequence({ + array: [ + first_sequence, + bit_string + ] + }); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () { + return hex2b64(this.getPublicBaseKey()); + }; + /** + * wrap the string in block of width chars. The default value for rsa keys is 64 + * characters. + * @param {string} str the pem encoded string without header and footer + * @param {Number} [width=64] - the length the string has to be wrapped at + * @returns {string} + * @private + */ + JSEncryptRSAKey.wordwrap = function (str, width) { + width = width || 64; + if (!str) { + return str; + } + var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; + return str.match(RegExp(regex, "g")).join("\n"); + }; + /** + * Retrieve the pem encoded private key + * @returns {string} the pem encoded private key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateKey = function () { + var key = "-----BEGIN RSA PRIVATE KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; + key += "-----END RSA PRIVATE KEY-----"; + return key; + }; + /** + * Retrieve the pem encoded public key + * @returns {string} the pem encoded public key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicKey = function () { + var key = "-----BEGIN PUBLIC KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; + key += "-----END PUBLIC KEY-----"; + return key; + }; + /** + * Check if the object contains the necessary parameters to populate the rsa modulus + * and public exponent parameters. + * @param {Object} [obj={}] - An object that may contain the two public key + * parameters + * @returns {boolean} true if the object contains both the modulus and the public exponent + * properties (n and e) + * @todo check for types of n and e. N should be a parseable bigInt object, E should + * be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPublicKeyProperty = function (obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e")); + }; + /** + * Check if the object contains ALL the parameters of an RSA key. + * @param {Object} [obj={}] - An object that may contain nine rsa key + * parameters + * @returns {boolean} true if the object contains all the parameters needed + * @todo check for types of the parameters all the parameters but the public exponent + * should be parseable bigint objects, the public exponent should be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e") && + obj.hasOwnProperty("d") && + obj.hasOwnProperty("p") && + obj.hasOwnProperty("q") && + obj.hasOwnProperty("dmp1") && + obj.hasOwnProperty("dmq1") && + obj.hasOwnProperty("coeff")); + }; + /** + * Parse the properties of obj in the current rsa object. Obj should AT LEAST + * include the modulus and public exponent (n, e) parameters. + * @param {Object} obj - the object containing rsa parameters + * @private + */ + JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) { + this.n = obj.n; + this.e = obj.e; + if (obj.hasOwnProperty("d")) { + this.d = obj.d; + this.p = obj.p; + this.q = obj.q; + this.dmp1 = obj.dmp1; + this.dmq1 = obj.dmq1; + this.coeff = obj.coeff; + } + }; + return JSEncryptRSAKey; +}(RSAKey)); + +/** + * + * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour + * possible parameters are: + * - default_key_size {number} default: 1024 the key size in bit + * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent + * - log {boolean} default: false whether log warn/error or not + * @constructor + */ +var JSEncrypt = /** @class */ (function () { + function JSEncrypt(options) { + options = options || {}; + this.default_key_size = parseInt(options.default_key_size, 10) || 1024; + this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type + this.log = options.log || false; + // The private and public key. + this.key = null; + } + /** + * Method to set the rsa key parameter (one method is enough to set both the public + * and the private key, since the private key contains the public key paramenters) + * Log a warning if logs are enabled + * @param {Object|string} key the pem encoded string or an object (with or without header/footer) + * @public + */ + JSEncrypt.prototype.setKey = function (key) { + if (this.log && this.key) { + console.warn("A key was already set, overriding existing."); + } + this.key = new JSEncryptRSAKey(key); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPrivateKey = function (privkey) { + // Create the key. + this.setKey(privkey); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPublicKey = function (pubkey) { + // Sets the public key. + this.setKey(pubkey); + }; + /** + * Proxy method for RSAKey object's decrypt, decrypt the string using the private + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str base64 encoded crypted string to decrypt + * @return {string} the decrypted string + * @public + */ + JSEncrypt.prototype.decrypt = function (str) { + // Return the decrypted string. + try { + return this.getKey().decrypt(b64tohex(str)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's encrypt, encrypt the string using the public + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str the string to encrypt + * @return {string} the encrypted string encoded in base64 + * @public + */ + JSEncrypt.prototype.encrypt = function (str) { + // Return the encrypted string. + try { + return hex2b64(this.getKey().encrypt(str)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's sign. + * @param {string} str the string to sign + * @param {function} digestMethod hash method + * @param {string} digestName the name of the hash algorithm + * @return {string} the signature encoded in base64 + * @public + */ + JSEncrypt.prototype.sign = function (str, digestMethod, digestName) { + // return the RSA signature of 'str' in 'hex' format. + try { + return hex2b64(this.getKey().sign(str, digestMethod, digestName)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's verify. + * @param {string} str the string to verify + * @param {string} signature the signature encoded in base64 to compare the string to + * @param {function} digestMethod hash method + * @return {boolean} whether the data and signature match + * @public + */ + JSEncrypt.prototype.verify = function (str, signature, digestMethod) { + // Return the decrypted 'digest' of the signature. + try { + return this.getKey().verify(str, b64tohex(signature), digestMethod); + } + catch (ex) { + return false; + } + }; + /** + * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object + * will be created and returned + * @param {callback} [cb] the callback to be called if we want the key to be generated + * in an async fashion + * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object + * @public + */ + JSEncrypt.prototype.getKey = function (cb) { + // Only create new if it does not exist. + if (!this.key) { + // Get a new private key. + this.key = new JSEncryptRSAKey(); + if (cb && {}.toString.call(cb) === "[object Function]") { + this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb); + return; + } + // Generate the key. + this.key.generate(this.default_key_size, this.default_public_exponent); + } + return this.key; + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKey = function () { + // Return the private representation of this key. + return this.getKey().getPrivateKey(); + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKeyB64 = function () { + // Return the private representation of this key. + return this.getKey().getPrivateBaseKeyB64(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPublicKey = function () { + // Return the private representation of this key. + return this.getKey().getPublicKey(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPublicKeyB64 = function () { + // Return the private representation of this key. + return this.getKey().getPublicBaseKeyB64(); + }; + JSEncrypt.version = "3.0.0-rc.1"; + return JSEncrypt; +}()); + +// window.JSEncrypt = JSEncrypt; + +exports.JSEncrypt = JSEncrypt; +exports.default = JSEncrypt; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/assets/js/jsencrypt/jsencryptInit.js b/assets/js/jsencrypt/jsencryptInit.js new file mode 100644 index 0000000..833d92b --- /dev/null +++ b/assets/js/jsencrypt/jsencryptInit.js @@ -0,0 +1,5388 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.JSEncrypt = {}))); +}(this, (function (exports) { 'use strict'; + +var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; +function int2char(n) { + return BI_RM.charAt(n); +} +//#region BIT_OPERATIONS +// (public) this & a +function op_and(x, y) { + return x & y; +} +// (public) this | a +function op_or(x, y) { + return x | y; +} +// (public) this ^ a +function op_xor(x, y) { + return x ^ y; +} +// (public) this & ~a +function op_andnot(x, y) { + return x & ~y; +} +// return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { + if (x == 0) { + return -1; + } + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) { + ++r; + } + return r; +} +// return number of 1 bits in x +function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; +} +//#endregion BIT_OPERATIONS + +var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var b64pad = "="; +function hex2b64(h) { + var i; + var c; + var ret = ""; + for (i = 0; i + 3 <= h.length; i += 3) { + c = parseInt(h.substring(i, i + 3), 16); + ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); + } + if (i + 1 == h.length) { + c = parseInt(h.substring(i, i + 1), 16); + ret += b64map.charAt(c << 2); + } + else if (i + 2 == h.length) { + c = parseInt(h.substring(i, i + 2), 16); + ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); + } + while ((ret.length & 3) > 0) { + ret += b64pad; + } + return ret; +} +// convert a base64 string to hex +function b64tohex(s) { + var ret = ""; + var i; + var k = 0; // b64 state, 0-3 + var slop = 0; + for (i = 0; i < s.length; ++i) { + if (s.charAt(i) == b64pad) { + break; + } + var v = b64map.indexOf(s.charAt(i)); + if (v < 0) { + continue; + } + if (k == 0) { + ret += int2char(v >> 2); + slop = v & 3; + k = 1; + } + else if (k == 1) { + ret += int2char((slop << 2) | (v >> 4)); + slop = v & 0xf; + k = 2; + } + else if (k == 2) { + ret += int2char(slop); + ret += int2char(v >> 2); + slop = v & 3; + k = 3; + } + else { + ret += int2char((slop << 2) | (v >> 4)); + ret += int2char(v & 0xf); + k = 0; + } + } + if (k == 1) { + ret += int2char(slop << 2); + } + return ret; +} + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +// Hex JavaScript decoder +// Copyright (c) 2008-2013 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var decoder; +var Hex = { + decode: function (a) { + var i; + if (decoder === undefined) { + var hex = "0123456789ABCDEF"; + var ignore = " \f\n\r\t\u00A0\u2028\u2029"; + decoder = {}; + for (i = 0; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + hex = hex.toLowerCase(); + for (i = 10; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 2) { + out[out.length] = bits; + bits = 0; + char_count = 0; + } + else { + bits <<= 4; + } + } + if (char_count) { + throw new Error("Hex encoding incomplete: 4 bits missing"); + } + return out; + } +}; + +// Base64 JavaScript decoder +// Copyright (c) 2008-2013 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var decoder$1; +var Base64 = { + decode: function (a) { + var i; + if (decoder$1 === undefined) { + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; + decoder$1 = Object.create(null); + for (i = 0; i < 64; ++i) { + decoder$1[b64.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder$1[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder$1[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 4) { + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + out[out.length] = bits & 0xFF; + bits = 0; + char_count = 0; + } + else { + bits <<= 6; + } + } + switch (char_count) { + case 1: + throw new Error("Base64 encoding incomplete: at least 2 bits missing"); + case 2: + out[out.length] = (bits >> 10); + break; + case 3: + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + break; + } + return out; + }, + re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, + unarmor: function (a) { + var m = Base64.re.exec(a); + if (m) { + if (m[1]) { + a = m[1]; + } + else if (m[2]) { + a = m[2]; + } + else { + throw new Error("RegExp out of sync"); + } + } + return Base64.decode(a); + } +}; + +// Big integer base-10 printing library +// Copyright (c) 2014 Lapo Luchini +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ +var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 +var Int10 = /** @class */ (function () { + function Int10(value) { + this.buf = [+value || 0]; + } + Int10.prototype.mulAdd = function (m, c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] * m + c; + if (t < max) { + c = 0; + } + else { + c = 0 | (t / max); + t -= c * max; + } + b[i] = t; + } + if (c > 0) { + b[i] = c; + } + }; + Int10.prototype.sub = function (c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] - c; + if (t < 0) { + t += max; + c = 1; + } + else { + c = 0; + } + b[i] = t; + } + while (b[b.length - 1] === 0) { + b.pop(); + } + }; + Int10.prototype.toString = function (base) { + if ((base || 10) != 10) { + throw new Error("only base 10 is supported"); + } + var b = this.buf; + var s = b[b.length - 1].toString(); + for (var i = b.length - 2; i >= 0; --i) { + s += (max + b[i]).toString().substring(1); + } + return s; + }; + Int10.prototype.valueOf = function () { + var b = this.buf; + var v = 0; + for (var i = b.length - 1; i >= 0; --i) { + v = v * max + b[i]; + } + return v; + }; + Int10.prototype.simplify = function () { + var b = this.buf; + return (b.length == 1) ? b[0] : this; + }; + return Int10; +}()); + +// ASN.1 JavaScript decoder +var ellipsis = "\u2026"; +var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; +var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; +function stringCut(str, len) { + if (str.length > len) { + str = str.substring(0, len) + ellipsis; + } + return str; +} +var Stream = /** @class */ (function () { + function Stream(enc, pos) { + this.hexDigits = "0123456789ABCDEF"; + if (enc instanceof Stream) { + this.enc = enc.enc; + this.pos = enc.pos; + } + else { + // enc should be an array or a binary string + this.enc = enc; + this.pos = pos; + } + } + Stream.prototype.get = function (pos) { + if (pos === undefined) { + pos = this.pos++; + } + if (pos >= this.enc.length) { + throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length); + } + return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; + }; + Stream.prototype.hexByte = function (b) { + return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); + }; + Stream.prototype.hexDump = function (start, end, raw) { + var s = ""; + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + if (raw !== true) { + switch (i & 0xF) { + case 0x7: + s += " "; + break; + case 0xF: + s += "\n"; + break; + default: + s += " "; + } + } + } + return s; + }; + Stream.prototype.isASCII = function (start, end) { + for (var i = start; i < end; ++i) { + var c = this.get(i); + if (c < 32 || c > 176) { + return false; + } + } + return true; + }; + Stream.prototype.parseStringISO = function (start, end) { + var s = ""; + for (var i = start; i < end; ++i) { + s += String.fromCharCode(this.get(i)); + } + return s; + }; + Stream.prototype.parseStringUTF = function (start, end) { + var s = ""; + for (var i = start; i < end;) { + var c = this.get(i++); + if (c < 128) { + s += String.fromCharCode(c); + } + else if ((c > 191) && (c < 224)) { + s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); + } + else { + s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); + } + } + return s; + }; + Stream.prototype.parseStringBMP = function (start, end) { + var str = ""; + var hi; + var lo; + for (var i = start; i < end;) { + hi = this.get(i++); + lo = this.get(i++); + str += String.fromCharCode((hi << 8) | lo); + } + return str; + }; + Stream.prototype.parseTime = function (start, end, shortYear) { + var s = this.parseStringISO(start, end); + var m = (shortYear ? reTimeS : reTimeL).exec(s); + if (!m) { + return "Unrecognized time: " + s; + } + if (shortYear) { + // to avoid querying the timer, use the fixed range [1970, 2069] + // it will conform with ITU X.400 [-10, +40] sliding window until 2030 + m[1] = +m[1]; + m[1] += (+m[1] < 70) ? 2000 : 1900; + } + s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; + if (m[5]) { + s += ":" + m[5]; + if (m[6]) { + s += ":" + m[6]; + if (m[7]) { + s += "." + m[7]; + } + } + } + if (m[8]) { + s += " UTC"; + if (m[8] != "Z") { + s += m[8]; + if (m[9]) { + s += ":" + m[9]; + } + } + } + return s; + }; + Stream.prototype.parseInteger = function (start, end) { + var v = this.get(start); + var neg = (v > 127); + var pad = neg ? 255 : 0; + var len; + var s = ""; + // skip unuseful bits (not allowed in DER) + while (v == pad && ++start < end) { + v = this.get(start); + } + len = end - start; + if (len === 0) { + return neg ? -1 : 0; + } + // show bit length of huge integers + if (len > 4) { + s = v; + len <<= 3; + while (((+s ^ pad) & 0x80) == 0) { + s = +s << 1; + --len; + } + s = "(" + len + " bit)\n"; + } + // decode the integer + if (neg) { + v = v - 256; + } + var n = new Int10(v); + for (var i = start + 1; i < end; ++i) { + n.mulAdd(256, this.get(i)); + } + return s + n.toString(); + }; + Stream.prototype.parseBitString = function (start, end, maxLength) { + var unusedBit = this.get(start); + var lenBit = ((end - start - 1) << 3) - unusedBit; + var intro = "(" + lenBit + " bit)\n"; + var s = ""; + for (var i = start + 1; i < end; ++i) { + var b = this.get(i); + var skip = (i == end - 1) ? unusedBit : 0; + for (var j = 7; j >= skip; --j) { + s += (b >> j) & 1 ? "1" : "0"; + } + if (s.length > maxLength) { + return intro + stringCut(s, maxLength); + } + } + return intro + s; + }; + Stream.prototype.parseOctetString = function (start, end, maxLength) { + if (this.isASCII(start, end)) { + return stringCut(this.parseStringISO(start, end), maxLength); + } + var len = end - start; + var s = "(" + len + " byte)\n"; + maxLength /= 2; // we work in bytes + if (len > maxLength) { + end = start + maxLength; + } + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + } + if (len > maxLength) { + s += ellipsis; + } + return s; + }; + Stream.prototype.parseOID = function (start, end, maxLength) { + var s = ""; + var n = new Int10(); + var bits = 0; + for (var i = start; i < end; ++i) { + var v = this.get(i); + n.mulAdd(128, v & 0x7F); + bits += 7; + if (!(v & 0x80)) { // finished + if (s === "") { + n = n.simplify(); + if (n instanceof Int10) { + n.sub(80); + s = "2." + n.toString(); + } + else { + var m = n < 80 ? n < 40 ? 0 : 1 : 2; + s = m + "." + (n - m * 40); + } + } + else { + s += "." + n.toString(); + } + if (s.length > maxLength) { + return stringCut(s, maxLength); + } + n = new Int10(); + bits = 0; + } + } + if (bits > 0) { + s += ".incomplete"; + } + return s; + }; + return Stream; +}()); +var ASN1 = /** @class */ (function () { + function ASN1(stream, header, length, tag, sub) { + if (!(tag instanceof ASN1Tag)) { + throw new Error("Invalid tag value."); + } + this.stream = stream; + this.header = header; + this.length = length; + this.tag = tag; + this.sub = sub; + } + ASN1.prototype.typeName = function () { + switch (this.tag.tagClass) { + case 0: // universal + switch (this.tag.tagNumber) { + case 0x00: + return "EOC"; + case 0x01: + return "BOOLEAN"; + case 0x02: + return "INTEGER"; + case 0x03: + return "BIT_STRING"; + case 0x04: + return "OCTET_STRING"; + case 0x05: + return "NULL"; + case 0x06: + return "OBJECT_IDENTIFIER"; + case 0x07: + return "ObjectDescriptor"; + case 0x08: + return "EXTERNAL"; + case 0x09: + return "REAL"; + case 0x0A: + return "ENUMERATED"; + case 0x0B: + return "EMBEDDED_PDV"; + case 0x0C: + return "UTF8String"; + case 0x10: + return "SEQUENCE"; + case 0x11: + return "SET"; + case 0x12: + return "NumericString"; + case 0x13: + return "PrintableString"; // ASCII subset + case 0x14: + return "TeletexString"; // aka T61String + case 0x15: + return "VideotexString"; + case 0x16: + return "IA5String"; // ASCII + case 0x17: + return "UTCTime"; + case 0x18: + return "GeneralizedTime"; + case 0x19: + return "GraphicString"; + case 0x1A: + return "VisibleString"; // ASCII subset + case 0x1B: + return "GeneralString"; + case 0x1C: + return "UniversalString"; + case 0x1E: + return "BMPString"; + } + return "Universal_" + this.tag.tagNumber.toString(); + case 1: + return "Application_" + this.tag.tagNumber.toString(); + case 2: + return "[" + this.tag.tagNumber.toString() + "]"; // Context + case 3: + return "Private_" + this.tag.tagNumber.toString(); + } + }; + ASN1.prototype.content = function (maxLength) { + if (this.tag === undefined) { + return null; + } + if (maxLength === undefined) { + maxLength = Infinity; + } + var content = this.posContent(); + var len = Math.abs(this.length); + if (!this.tag.isUniversal()) { + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } + return this.stream.parseOctetString(content, content + len, maxLength); + } + switch (this.tag.tagNumber) { + case 0x01: // BOOLEAN + return (this.stream.get(content) === 0) ? "false" : "true"; + case 0x02: // INTEGER + return this.stream.parseInteger(content, content + len); + case 0x03: // BIT_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseBitString(content, content + len, maxLength); + case 0x04: // OCTET_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseOctetString(content, content + len, maxLength); + // case 0x05: // NULL + case 0x06: // OBJECT_IDENTIFIER + return this.stream.parseOID(content, content + len, maxLength); + // case 0x07: // ObjectDescriptor + // case 0x08: // EXTERNAL + // case 0x09: // REAL + // case 0x0A: // ENUMERATED + // case 0x0B: // EMBEDDED_PDV + case 0x10: // SEQUENCE + case 0x11: // SET + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } + else { + return "(no elem)"; + } + case 0x0C: // UTF8String + return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); + case 0x12: // NumericString + case 0x13: // PrintableString + case 0x14: // TeletexString + case 0x15: // VideotexString + case 0x16: // IA5String + // case 0x19: // GraphicString + case 0x1A: // VisibleString + // case 0x1B: // GeneralString + // case 0x1C: // UniversalString + return stringCut(this.stream.parseStringISO(content, content + len), maxLength); + case 0x1E: // BMPString + return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); + case 0x17: // UTCTime + case 0x18: // GeneralizedTime + return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); + } + return null; + }; + ASN1.prototype.toString = function () { + return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]"; + }; + ASN1.prototype.toPrettyString = function (indent) { + if (indent === undefined) { + indent = ""; + } + var s = indent + this.typeName() + " @" + this.stream.pos; + if (this.length >= 0) { + s += "+"; + } + s += this.length; + if (this.tag.tagConstructed) { + s += " (constructed)"; + } + else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) { + s += " (encapsulates)"; + } + s += "\n"; + if (this.sub !== null) { + indent += " "; + for (var i = 0, max = this.sub.length; i < max; ++i) { + s += this.sub[i].toPrettyString(indent); + } + } + return s; + }; + ASN1.prototype.posStart = function () { + return this.stream.pos; + }; + ASN1.prototype.posContent = function () { + return this.stream.pos + this.header; + }; + ASN1.prototype.posEnd = function () { + return this.stream.pos + this.header + Math.abs(this.length); + }; + ASN1.prototype.toHexString = function () { + return this.stream.hexDump(this.posStart(), this.posEnd(), true); + }; + ASN1.decodeLength = function (stream) { + var buf = stream.get(); + var len = buf & 0x7F; + if (len == buf) { + return len; + } + // no reason to use Int10, as it would be a huge buffer anyways + if (len > 6) { + throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1)); + } + if (len === 0) { + return null; + } // undefined + buf = 0; + for (var i = 0; i < len; ++i) { + buf = (buf * 256) + stream.get(); + } + return buf; + }; + /** + * Retrieve the hexadecimal value (as a string) of the current ASN.1 element + * @returns {string} + * @public + */ + ASN1.prototype.getHexStringValue = function () { + var hexString = this.toHexString(); + var offset = this.header * 2; + var length = this.length * 2; + return hexString.substr(offset, length); + }; + ASN1.decode = function (str) { + var stream; + if (!(str instanceof Stream)) { + stream = new Stream(str, 0); + } + else { + stream = str; + } + var streamStart = new Stream(stream); + var tag = new ASN1Tag(stream); + var len = ASN1.decodeLength(stream); + var start = stream.pos; + var header = start - streamStart.pos; + var sub = null; + var getSub = function () { + var ret = []; + if (len !== null) { + // definite length + var end = start + len; + while (stream.pos < end) { + ret[ret.length] = ASN1.decode(stream); + } + if (stream.pos != end) { + throw new Error("Content size is not correct for container starting at offset " + start); + } + } + else { + // undefined length + try { + for (;;) { + var s = ASN1.decode(stream); + if (s.tag.isEOC()) { + break; + } + ret[ret.length] = s; + } + len = start - stream.pos; // undefined lengths are represented as negative values + } + catch (e) { + throw new Error("Exception while decoding undefined length content: " + e); + } + } + return ret; + }; + if (tag.tagConstructed) { + // must have valid content + sub = getSub(); + } + else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { + // sometimes BitString and OctetString are used to encapsulate ASN.1 + try { + if (tag.tagNumber == 0x03) { + if (stream.get() != 0) { + throw new Error("BIT STRINGs with unused bits cannot encapsulate."); + } + } + sub = getSub(); + for (var i = 0; i < sub.length; ++i) { + if (sub[i].tag.isEOC()) { + throw new Error("EOC is not supposed to be actual content."); + } + } + } + catch (e) { + // but silently ignore when they don't + sub = null; + } + } + if (sub === null) { + if (len === null) { + throw new Error("We can't skip over an invalid tag with undefined length at offset " + start); + } + stream.pos = start + Math.abs(len); + } + return new ASN1(streamStart, header, len, tag, sub); + }; + return ASN1; +}()); +var ASN1Tag = /** @class */ (function () { + function ASN1Tag(stream) { + var buf = stream.get(); + this.tagClass = buf >> 6; + this.tagConstructed = ((buf & 0x20) !== 0); + this.tagNumber = buf & 0x1F; + if (this.tagNumber == 0x1F) { // long tag + var n = new Int10(); + do { + buf = stream.get(); + n.mulAdd(128, buf & 0x7F); + } while (buf & 0x80); + this.tagNumber = n.simplify(); + } + } + ASN1Tag.prototype.isUniversal = function () { + return this.tagClass === 0x00; + }; + ASN1Tag.prototype.isEOC = function () { + return this.tagClass === 0x00 && this.tagNumber === 0x00; + }; + return ASN1Tag; +}()); + +// Copyright (c) 2005 Tom Wu +// Bits per digit +var dbits; +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary & 0xffffff) == 0xefcafe); +//#region +var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]; +var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; +//#endregion +// (public) Constructor +var BigInteger = /** @class */ (function () { + function BigInteger(a, b, c) { + if (a != null) { + if ("number" == typeof a) { + this.fromNumber(a, b, c); + } + else if (b == null && "string" != typeof a) { + this.fromString(a, 256); + } + else { + this.fromString(a, b); + } + } + } + //#region PUBLIC + // BigInteger.prototype.toString = bnToString; + // (public) return string representation in given radix + BigInteger.prototype.toString = function (b) { + if (this.s < 0) { + return "-" + this.negate().toString(b); + } + var k; + if (b == 16) { + k = 4; + } + else if (b == 8) { + k = 3; + } + else if (b == 2) { + k = 1; + } + else if (b == 32) { + k = 5; + } + else if (b == 4) { + k = 2; + } + else { + return this.toRadix(b); + } + var km = (1 << k) - 1; + var d; + var m = false; + var r = ""; + var i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } + else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) { + m = true; + } + if (m) { + r += int2char(d); + } + } + } + return m ? r : "0"; + }; + // BigInteger.prototype.negate = bnNegate; + // (public) -this + BigInteger.prototype.negate = function () { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + }; + // BigInteger.prototype.abs = bnAbs; + // (public) |this| + BigInteger.prototype.abs = function () { + return (this.s < 0) ? this.negate() : this; + }; + // BigInteger.prototype.compareTo = bnCompareTo; + // (public) return + if this > a, - if this < a, 0 if equal + BigInteger.prototype.compareTo = function (a) { + var r = this.s - a.s; + if (r != 0) { + return r; + } + var i = this.t; + r = i - a.t; + if (r != 0) { + return (this.s < 0) ? -r : r; + } + while (--i >= 0) { + if ((r = this[i] - a[i]) != 0) { + return r; + } + } + return 0; + }; + // BigInteger.prototype.bitLength = bnBitLength; + // (public) return the number of bits in "this" + BigInteger.prototype.bitLength = function () { + if (this.t <= 0) { + return 0; + } + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); + }; + // BigInteger.prototype.mod = bnMod; + // (public) this mod a + BigInteger.prototype.mod = function (a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + a.subTo(r, r); + } + return r; + }; + // BigInteger.prototype.modPowInt = bnModPowInt; + // (public) this^e % m, 0 <= e < 2^32 + BigInteger.prototype.modPowInt = function (e, m) { + var z; + if (e < 256 || m.isEven()) { + z = new Classic(m); + } + else { + z = new Montgomery(m); + } + return this.exp(e, z); + }; + // BigInteger.prototype.clone = bnClone; + // (public) + BigInteger.prototype.clone = function () { + var r = nbi(); + this.copyTo(r); + return r; + }; + // BigInteger.prototype.intValue = bnIntValue; + // (public) return value as integer + BigInteger.prototype.intValue = function () { + if (this.s < 0) { + if (this.t == 1) { + return this[0] - this.DV; + } + else if (this.t == 0) { + return -1; + } + } + else if (this.t == 1) { + return this[0]; + } + else if (this.t == 0) { + return 0; + } + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + }; + // BigInteger.prototype.byteValue = bnByteValue; + // (public) return value as byte + BigInteger.prototype.byteValue = function () { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; + }; + // BigInteger.prototype.shortValue = bnShortValue; + // (public) return value as short (assumes DB>=16) + BigInteger.prototype.shortValue = function () { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; + }; + // BigInteger.prototype.signum = bnSigNum; + // (public) 0 if this == 0, 1 if this > 0 + BigInteger.prototype.signum = function () { + if (this.s < 0) { + return -1; + } + else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { + return 0; + } + else { + return 1; + } + }; + // BigInteger.prototype.toByteArray = bnToByteArray; + // (public) convert to bigendian byte array + BigInteger.prototype.toByteArray = function () { + var i = this.t; + var r = []; + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8; + var d; + var k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { + r[k++] = d | (this.s << (this.DB - p)); + } + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } + else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) { + d |= -256; + } + if (k == 0 && (this.s & 0x80) != (d & 0x80)) { + ++k; + } + if (k > 0 || d != this.s) { + r[k++] = d; + } + } + } + return r; + }; + // BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.equals = function (a) { + return (this.compareTo(a) == 0); + }; + // BigInteger.prototype.min = bnMin; + BigInteger.prototype.min = function (a) { + return (this.compareTo(a) < 0) ? this : a; + }; + // BigInteger.prototype.max = bnMax; + BigInteger.prototype.max = function (a) { + return (this.compareTo(a) > 0) ? this : a; + }; + // BigInteger.prototype.and = bnAnd; + BigInteger.prototype.and = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + }; + // BigInteger.prototype.or = bnOr; + BigInteger.prototype.or = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + }; + // BigInteger.prototype.xor = bnXor; + BigInteger.prototype.xor = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + }; + // BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.andNot = function (a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + }; + // BigInteger.prototype.not = bnNot; + // (public) ~this + BigInteger.prototype.not = function () { + var r = nbi(); + for (var i = 0; i < this.t; ++i) { + r[i] = this.DM & ~this[i]; + } + r.t = this.t; + r.s = ~this.s; + return r; + }; + // BigInteger.prototype.shiftLeft = bnShiftLeft; + // (public) this << n + BigInteger.prototype.shiftLeft = function (n) { + var r = nbi(); + if (n < 0) { + this.rShiftTo(-n, r); + } + else { + this.lShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.shiftRight = bnShiftRight; + // (public) this >> n + BigInteger.prototype.shiftRight = function (n) { + var r = nbi(); + if (n < 0) { + this.lShiftTo(-n, r); + } + else { + this.rShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + // (public) returns index of lowest 1-bit (or -1 if none) + BigInteger.prototype.getLowestSetBit = function () { + for (var i = 0; i < this.t; ++i) { + if (this[i] != 0) { + return i * this.DB + lbit(this[i]); + } + } + if (this.s < 0) { + return this.t * this.DB; + } + return -1; + }; + // BigInteger.prototype.bitCount = bnBitCount; + // (public) return number of set bits + BigInteger.prototype.bitCount = function () { + var r = 0; + var x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) { + r += cbit(this[i] ^ x); + } + return r; + }; + // BigInteger.prototype.testBit = bnTestBit; + // (public) true iff nth bit is set + BigInteger.prototype.testBit = function (n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) { + return (this.s != 0); + } + return ((this[j] & (1 << (n % this.DB))) != 0); + }; + // BigInteger.prototype.setBit = bnSetBit; + // (public) this | (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1; + var w; + var is1 = true; + var r2 = nbi(); + var t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) { + w = (e[j] >> (i - k1)) & km; + } + else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) { + w |= e[j - 1] >> (this.DB + i - k1); + } + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) { + z.sqrTo(r, r2); + } + else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + }; + // BigInteger.prototype.modInverse = bnModInverse; + // (public) 1/this % m (HAC 14.61) + BigInteger.prototype.modInverse = function (m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) { + return BigInteger.ZERO; + } + var u = m.clone(); + var v = this.clone(); + var a = nbv(1); + var b = nbv(0); + var c = nbv(0); + var d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } + else if (!b.isEven()) { + b.subTo(m, b); + } + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } + else if (!d.isEven()) { + d.subTo(m, d); + } + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) { + a.subTo(c, a); + } + b.subTo(d, b); + } + else { + v.subTo(u, v); + if (ac) { + c.subTo(a, c); + } + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) { + return BigInteger.ZERO; + } + if (d.compareTo(m) >= 0) { + return d.subtract(m); + } + if (d.signum() < 0) { + d.addTo(m, d); + } + else { + return d; + } + if (d.signum() < 0) { + return d.add(m); + } + else { + return d; + } + }; + // BigInteger.prototype.pow = bnPow; + // (public) this^e + BigInteger.prototype.pow = function (e) { + return this.exp(e, new NullExp()); + }; + // BigInteger.prototype.gcd = bnGCD; + // (public) gcd(this,a) (HAC 14.54) + BigInteger.prototype.gcd = function (a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + return x; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) { + y.lShiftTo(g, y); + } + return y; + }; + // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + // (public) test primality with certainty >= 1-.5^t + BigInteger.prototype.isProbablePrime = function (t) { + var i; + var x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) { + if (x[0] == lowprimes[i]) { + return true; + } + } + return false; + } + if (x.isEven()) { + return false; + } + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i]; + var j = i + 1; + while (j < lowprimes.length && m < lplim) { + m *= lowprimes[j++]; + } + m = x.modInt(m); + while (i < j) { + if (m % lowprimes[i++] == 0) { + return false; + } + } + } + return x.millerRabin(t); + }; + //#endregion PUBLIC + //#region PROTECTED + // BigInteger.prototype.copyTo = bnpCopyTo; + // (protected) copy this to r + BigInteger.prototype.copyTo = function (r) { + for (var i = this.t - 1; i >= 0; --i) { + r[i] = this[i]; + } + r.t = this.t; + r.s = this.s; + }; + // BigInteger.prototype.fromInt = bnpFromInt; + // (protected) set from integer value x, -DV <= x < DV + BigInteger.prototype.fromInt = function (x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) { + this[0] = x; + } + else if (x < -1) { + this[0] = x + this.DV; + } + else { + this.t = 0; + } + }; + // BigInteger.prototype.fromString = bnpFromString; + // (protected) set from string and radix + BigInteger.prototype.fromString = function (s, b) { + var k; + if (b == 16) { + k = 4; + } + else if (b == 8) { + k = 3; + } + else if (b == 256) { + k = 8; + /* byte array */ + } + else if (b == 2) { + k = 1; + } + else if (b == 32) { + k = 5; + } + else if (b == 4) { + k = 2; + } + else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length; + var mi = false; + var sh = 0; + while (--i >= 0) { + var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") { + mi = true; + } + continue; + } + mi = false; + if (sh == 0) { + this[this.t++] = x; + } + else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } + else { + this[this.t - 1] |= x << sh; + } + sh += k; + if (sh >= this.DB) { + sh -= this.DB; + } + } + if (k == 8 && ((+s[0]) & 0x80) != 0) { + this.s = -1; + if (sh > 0) { + this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + } + this.clamp(); + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.clamp = bnpClamp; + // (protected) clamp off excess high words + BigInteger.prototype.clamp = function () { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) { + --this.t; + } + }; + // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + // (protected) r = this << n*DB + BigInteger.prototype.dlShiftTo = function (n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) { + r[i + n] = this[i]; + } + for (i = n - 1; i >= 0; --i) { + r[i] = 0; + } + r.t = this.t + n; + r.s = this.s; + }; + // BigInteger.prototype.drShiftTo = bnpDRShiftTo; + // (protected) r = this >> n*DB + BigInteger.prototype.drShiftTo = function (n, r) { + for (var i = n; i < this.t; ++i) { + r[i - n] = this[i]; + } + r.t = Math.max(this.t - n, 0); + r.s = this.s; + }; + // BigInteger.prototype.lShiftTo = bnpLShiftTo; + // (protected) r = this << n + BigInteger.prototype.lShiftTo = function (n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB); + var c = (this.s << bs) & this.DM; + for (var i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (var i = ds - 1; i >= 0; --i) { + r[i] = 0; + } + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + }; + // BigInteger.prototype.rShiftTo = bnpRShiftTo; + // (protected) r = this >> n + BigInteger.prototype.rShiftTo = function (n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) { + r[this.t - ds - 1] |= (this.s & bm) << cbs; + } + r.t = this.t - ds; + r.clamp(); + }; + // BigInteger.prototype.subTo = bnpSubTo; + // (protected) r = this - a + BigInteger.prototype.subTo = function (a, r) { + var i = 0; + var c = 0; + var m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) { + r[i++] = this.DV + c; + } + else if (c > 0) { + r[i++] = c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.multiplyTo = bnpMultiplyTo; + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyTo = function (a, r) { + var x = this.abs(); + var y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < y.t; ++i) { + r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + } + r.s = 0; + r.clamp(); + if (this.s != a.s) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.squareTo = bnpSquareTo; + // (protected) r = this^2, r != this (HAC 14.16) + BigInteger.prototype.squareTo = function (r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) { + r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + } + r.s = 0; + r.clamp(); + }; + // BigInteger.prototype.divRemTo = bnpDivRemTo; + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + BigInteger.prototype.divRemTo = function (m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) { + return; + } + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) { + q.fromInt(0); + } + if (r != null) { + this.copyTo(r); + } + return; + } + if (r == null) { + r = nbi(); + } + var y = nbi(); + var ts = this.s; + var ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } + else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) { + return; + } + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt; + var d2 = (1 << this.F1) / yt; + var e = 1 << this.F2; + var i = r.t; + var j = i - ys; + var t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) { + y[y.t++] = 0; + } + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) { + r.subTo(t, r); + } + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) { + BigInteger.ZERO.subTo(q, q); + } + } + r.t = ys; + r.clamp(); + if (nsh > 0) { + r.rShiftTo(nsh, r); + } // Denormalize remainder + if (ts < 0) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.invDigit = bnpInvDigit; + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + BigInteger.prototype.invDigit = function () { + if (this.t < 1) { + return 0; + } + var x = this[0]; + if ((x & 1) == 0) { + return 0; + } + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; + }; + // BigInteger.prototype.isEven = bnpIsEven; + // (protected) true iff this is even + BigInteger.prototype.isEven = function () { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; + }; + // BigInteger.prototype.exp = bnpExp; + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + BigInteger.prototype.exp = function (e, z) { + if (e > 0xffffffff || e < 1) { + return BigInteger.ONE; + } + var r = nbi(); + var r2 = nbi(); + var g = z.convert(this); + var i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) { + z.mulTo(r2, g, r); + } + else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + }; + // BigInteger.prototype.chunkSize = bnpChunkSize; + // (protected) return x s.t. r^x < DV + BigInteger.prototype.chunkSize = function (r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + }; + // BigInteger.prototype.toRadix = bnpToRadix; + // (protected) convert to radix string + BigInteger.prototype.toRadix = function (b) { + if (b == null) { + b = 10; + } + if (this.signum() == 0 || b < 2 || b > 36) { + return "0"; + } + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a); + var y = nbi(); + var z = nbi(); + var r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + }; + // BigInteger.prototype.fromRadix = bnpFromRadix; + // (protected) convert from radix string + BigInteger.prototype.fromRadix = function (s, b) { + this.fromInt(0); + if (b == null) { + b = 10; + } + var cs = this.chunkSize(b); + var d = Math.pow(b, cs); + var mi = false; + var j = 0; + var w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) { + mi = true; + } + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.fromNumber = bnpFromNumber; + // (protected) alternate constructor + BigInteger.prototype.fromNumber = function (a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) { + this.fromInt(1); + } + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) { + this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } + } + else { + // new BigInteger(int,RNG) + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } + else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + // (protected) r = this op a (bitwise) + BigInteger.prototype.bitwiseTo = function (a, op, r) { + var i; + var f; + var m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) { + r[i] = op(this[i], a[i]); + } + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) { + r[i] = op(this[i], f); + } + r.t = this.t; + } + else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) { + r[i] = op(f, a[i]); + } + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + }; + // BigInteger.prototype.changeBit = bnpChangeBit; + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c > 0) { + r[i++] = c; + } + else if (c < -1) { + r[i++] = this.DV + c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.dMultiply = bnpDMultiply; + // (protected) this *= n, this >= 0, 1 < n < DV + BigInteger.prototype.dMultiply = function (n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + }; + // BigInteger.prototype.dAddOffset = bnpDAddOffset; + // (protected) this += n << w words, this >= 0 + BigInteger.prototype.dAddOffset = function (n, w) { + if (n == 0) { + return; + } + while (this.t <= w) { + this[this.t++] = 0; + } + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) { + this[this.t++] = 0; + } + ++this[w]; + } + }; + // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyLowerTo = function (a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) { + r[--i] = 0; + } + for (var j = r.t - this.t; i < j; ++i) { + r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + } + for (var j = Math.min(a.t, n); i < j; ++i) { + this.am(0, a[i], r, i, 0, n - i); + } + r.clamp(); + }; + // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyUpperTo = function (a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) { + r[i] = 0; + } + for (i = Math.max(n - this.t, 0); i < a.t; ++i) { + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + } + r.clamp(); + r.drShiftTo(1, r); + }; + // BigInteger.prototype.modInt = bnpModInt; + // (protected) this % n, n < 2^26 + BigInteger.prototype.modInt = function (n) { + if (n <= 0) { + return 0; + } + var d = this.DV % n; + var r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) { + if (d == 0) { + r = this[0] % n; + } + else { + for (var i = this.t - 1; i >= 0; --i) { + r = (d * r + this[i]) % n; + } + } + } + return r; + }; + // BigInteger.prototype.millerRabin = bnpMillerRabin; + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + BigInteger.prototype.millerRabin = function (t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) { + return false; + } + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) { + t = lowprimes.length; + } + var a = nbi(); + for (var i = 0; i < t; ++i) { + // Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) { + return false; + } + } + if (y.compareTo(n1) != 0) { + return false; + } + } + } + return true; + }; + // BigInteger.prototype.square = bnSquare; + // (public) this^2 + BigInteger.prototype.square = function () { + var r = nbi(); + this.squareTo(r); + return r; + }; + //#region ASYNC + // Public API method + BigInteger.prototype.gcda = function (a, callback) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + callback(x); + return; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. + var gcda1 = function () { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } + else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + if (!(x.signum() > 0)) { + if (g > 0) { + y.lShiftTo(g, y); + } + setTimeout(function () { callback(y); }, 0); // escape + } + else { + setTimeout(gcda1, 0); + } + }; + setTimeout(gcda1, 10); + }; + // (protected) alternate constructor + BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) { + if ("number" == typeof b) { + if (a < 2) { + this.fromInt(1); + } + else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } + var bnp_1 = this; + var bnpfn1_1 = function () { + bnp_1.dAddOffset(2, 0); + if (bnp_1.bitLength() > a) { + bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); + } + if (bnp_1.isProbablePrime(b)) { + setTimeout(function () { callback(); }, 0); // escape + } + else { + setTimeout(bnpfn1_1, 0); + } + }; + setTimeout(bnpfn1_1, 0); + } + } + else { + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } + else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + return BigInteger; +}()); +//#region REDUCERS +//#region NullExp +var NullExp = /** @class */ (function () { + function NullExp() { + } + // NullExp.prototype.convert = nNop; + NullExp.prototype.convert = function (x) { + return x; + }; + // NullExp.prototype.revert = nNop; + NullExp.prototype.revert = function (x) { + return x; + }; + // NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + }; + // NullExp.prototype.sqrTo = nSqrTo; + NullExp.prototype.sqrTo = function (x, r) { + x.squareTo(r); + }; + return NullExp; +}()); +// Modular reduction using "classic" algorithm +var Classic = /** @class */ (function () { + function Classic(m) { + this.m = m; + } + // Classic.prototype.convert = cConvert; + Classic.prototype.convert = function (x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) { + return x.mod(this.m); + } + else { + return x; + } + }; + // Classic.prototype.revert = cRevert; + Classic.prototype.revert = function (x) { + return x; + }; + // Classic.prototype.reduce = cReduce; + Classic.prototype.reduce = function (x) { + x.divRemTo(this.m, null, x); + }; + // Classic.prototype.mulTo = cMulTo; + Classic.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Classic.prototype.sqrTo = cSqrTo; + Classic.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Classic; +}()); +//#endregion +//#region Montgomery +// Montgomery reduction +var Montgomery = /** @class */ (function () { + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + // Montgomery.prototype.convert = montConvert; + // xR mod m + Montgomery.prototype.convert = function (x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + this.m.subTo(r, r); + } + return r; + }; + // Montgomery.prototype.revert = montRevert; + // x/R mod m + Montgomery.prototype.revert = function (x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + }; + // Montgomery.prototype.reduce = montReduce; + // x = x/R mod m (HAC 14.32) + Montgomery.prototype.reduce = function (x) { + while (x.t <= this.mt2) { + // pad x so am has enough room later + x[x.t++] = 0; + } + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Montgomery.prototype.mulTo = montMulTo; + // r = "xy/R mod m"; x,y != r + Montgomery.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Montgomery.prototype.sqrTo = montSqrTo; + // r = "x^2/R mod m"; x != r + Montgomery.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Montgomery; +}()); +//#endregion Montgomery +//#region Barrett +// Barrett modular reduction +var Barrett = /** @class */ (function () { + function Barrett(m) { + this.m = m; + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + } + // Barrett.prototype.convert = barrettConvert; + Barrett.prototype.convert = function (x) { + if (x.s < 0 || x.t > 2 * this.m.t) { + return x.mod(this.m); + } + else if (x.compareTo(this.m) < 0) { + return x; + } + else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + }; + // Barrett.prototype.revert = barrettRevert; + Barrett.prototype.revert = function (x) { + return x; + }; + // Barrett.prototype.reduce = barrettReduce; + // x = x mod m (HAC 14.42) + Barrett.prototype.reduce = function (x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) { + x.dAddOffset(1, this.m.t + 1); + } + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Barrett.prototype.mulTo = barrettMulTo; + // r = x*y mod m; x,y != r + Barrett.prototype.mulTo = function (x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Barrett.prototype.sqrTo = barrettSqrTo; + // r = x^2 mod m; x != r + Barrett.prototype.sqrTo = function (x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Barrett; +}()); +//#endregion +//#endregion REDUCERS +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } +function parseBigInt(str, r) { + return new BigInteger(str, r); +} +// am: Compute w_j += (x*this_i), propagate carries, +// c is initial carry, returns final carry. +// c < 3*dvalue, x < 2*dvalue, this_i < dvalue +// We need to select the fastest one that works in this environment. +// am1: use a single mult and divide to get the high bits, +// max digit bits should be 26 because +// max internal value = 2*dvalue^2-2*dvalue (< 2^53) +function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; + } + return c; +} +// am2 avoids a big mult-and-extract completely. +// Max digit bits should be <= 30 because we do bitwise ops +// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) +function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff; + var xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; + } + return c; +} +// Alternately, set max digit bits to 28 since some +// browsers slow down when dealing with 32-bit numbers. +function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff; + var xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; + } + return c; +} +// if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) { +// BigInteger.prototype.am = am2; +// dbits = 30; +// } +// else if (j_lm && (navigator.appName != "Netscape")) { +// BigInteger.prototype.am = am1; +// dbits = 26; +// } +// else { // Mozilla/Netscape seems to prefer am3 +// BigInteger.prototype.am = am3; +// dbits = 28; +// } +BigInteger.prototype.am = am3; + dbits = 28; +BigInteger.prototype.DB = dbits; +BigInteger.prototype.DM = ((1 << dbits) - 1); +BigInteger.prototype.DV = (1 << dbits); +var BI_FP = 52; +BigInteger.prototype.FV = Math.pow(2, BI_FP); +BigInteger.prototype.F1 = BI_FP - dbits; +BigInteger.prototype.F2 = 2 * dbits - BI_FP; +// Digit conversions +var BI_RC = []; +var rr; +var vv; +rr = "0".charCodeAt(0); +for (vv = 0; vv <= 9; ++vv) { + BI_RC[rr++] = vv; +} +rr = "a".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; +} +rr = "A".charCodeAt(0); +for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; +} +function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; +} +// return bigint initialized to value +function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; +} +// returns bit length of the integer x +function nbits(x) { + var r = 1; + var t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; +} +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + +// prng4.js - uses Arcfour as a PRNG +var Arcfour = /** @class */ (function () { + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = []; + } + // Arcfour.prototype.init = ARC4init; + // Initialize arcfour context from key, an array of ints, each from [0..255] + Arcfour.prototype.init = function (key) { + var i; + var j; + var t; + for (i = 0; i < 256; ++i) { + this.S[i] = i; + } + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; + }; + // Arcfour.prototype.next = ARC4next; + Arcfour.prototype.next = function () { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + }; + return Arcfour; +}()); +// Plug in your RNG constructor here +function prng_newstate() { + return new Arcfour(); +} +// Pool size must be a multiple of 4 and greater than 32. +// An array of bytes the size of the pool will be passed to init() +var rng_psize = 256; + +// Random number generator - requires a PRNG backend, e.g. prng4.js +var rng_state; +var rng_pool = null; +var rng_pptr; +// Initialize the pool with junk if needed. +if (rng_pool == null) { + rng_pool = []; + rng_pptr = 0; + var t = void 0; + // 2222222222222222222222222222 + // 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; + // } + // } + var getRandomValues = function (array) { + + for (var i = 0, l = array.length; i < l; i++) { + + array[i] = Math.floor(Math.random() * Math.pow(2,32)); + } return array; + } + + var z = new Uint32Array(256); + + getRandomValues(z); + for (t = 0; t < z.length; ++t) { + rng_pool[rng_pptr++] = z[t] & 255; + } + // Use mouse events for entropy, if we do not have enough entropy by the time + // we need it, entropy will be generated by Math.random. + var onMouseMoveListener_1 = function (ev) { + this.count = this.count || 0; + if (this.count >= 256 || rng_pptr >= rng_psize) { + if (window.removeEventListener) { + window.removeEventListener("mousemove", onMouseMoveListener_1, false); + } + else if (window.detachEvent) { + window.detachEvent("onmousemove", onMouseMoveListener_1); + } + return; + } + try { + var mouseCoordinates = ev.x + ev.y; + rng_pool[rng_pptr++] = mouseCoordinates & 255; + this.count += 1; + } + catch (e) { + // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. + } + }; + // if (window.addEventListener) { + // window.addEventListener("mousemove", onMouseMoveListener_1, false); + // } + // else if (window.attachEvent) { + // window.attachEvent("onmousemove", onMouseMoveListener_1); + // } +} +function rng_get_byte() { + if (rng_state == null) { + rng_state = prng_newstate(); + // At this point, we may not have collected enough entropy. If not, fall back to Math.random + while (rng_pptr < rng_psize) { + var random = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = random & 255; + } + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { + rng_pool[rng_pptr] = 0; + } + rng_pptr = 0; + } + // TODO: allow reseeding after first request + return rng_state.next(); +} +var SecureRandom = /** @class */ (function () { + function SecureRandom() { + } + SecureRandom.prototype.nextBytes = function (ba) { + for (var i = 0; i < ba.length; ++i) { + ba[i] = rng_get_byte(); + } + }; + return SecureRandom; +}()); + +// Depends on jsbn.js and rng.js +// function linebrk(s,n) { +// var ret = ""; +// var i = 0; +// while(i + n < s.length) { +// ret += s.substring(i,i+n) + "\n"; +// i += n; +// } +// return ret + s.substring(i,s.length); +// } +// function byte2Hex(b) { +// if(b < 0x10) +// return "0" + b.toString(16); +// else +// return b.toString(16); +// } +function pkcs1pad1(s, n) { + if (n < s.length + 22) { + console.error("Message too long for RSA"); + return null; + } + var len = n - s.length - 6; + var filler = ""; + for (var f = 0; f < len; f += 2) { + filler += "ff"; + } + var m = "0001" + filler + "00" + s; + return parseBigInt(m, 16); +} +// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint +function pkcs1pad2(s, n) { + if (n < s.length + 11) { // TODO: fix for utf-8 + console.error("Message too long for RSA"); + return null; + } + var ba = []; + var i = s.length - 1; + while (i >= 0 && n > 0) { + var c = s.charCodeAt(i--); + if (c < 128) { // encode using utf-8 + ba[--n] = c; + } + else if ((c > 127) && (c < 2048)) { + ba[--n] = (c & 63) | 128; + ba[--n] = (c >> 6) | 192; + } + else { + ba[--n] = (c & 63) | 128; + ba[--n] = ((c >> 6) & 63) | 128; + ba[--n] = (c >> 12) | 224; + } + } + ba[--n] = 0; + var rng = new SecureRandom(); + var x = []; + while (n > 2) { // random non-zero pad + x[0] = 0; + while (x[0] == 0) { + rng.nextBytes(x); + } + ba[--n] = x[0]; + } + ba[--n] = 2; + ba[--n] = 0; + return new BigInteger(ba); +} +// "empty" RSA key constructor +var RSAKey = /** @class */ (function () { + function RSAKey() { + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; + } + //#region PROTECTED + // protected + // RSAKey.prototype.doPublic = RSADoPublic; + // Perform raw public operation on "x": return x^e (mod n) + RSAKey.prototype.doPublic = function (x) { + return x.modPowInt(this.e, this.n); + }; + // RSAKey.prototype.doPrivate = RSADoPrivate; + // Perform raw private operation on "x": return x^d (mod n) + RSAKey.prototype.doPrivate = function (x) { + if (this.p == null || this.q == null) { + return x.modPow(this.d, this.n); + } + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(this.p); + } + return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); + }; + //#endregion PROTECTED + //#region PUBLIC + // RSAKey.prototype.setPublic = RSASetPublic; + // Set the public key fields N and e from hex strings + RSAKey.prototype.setPublic = function (N, E) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + } + else { + console.error("Invalid RSA public key"); + } + }; + // RSAKey.prototype.encrypt = RSAEncrypt; + // Return the PKCS#1 RSA encryption of "text" as an even-length hex string + RSAKey.prototype.encrypt = function (text) { + var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); + if (m == null) { + return null; + } + var c = this.doPublic(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } + else { + return "0" + h; + } + }; + // RSAKey.prototype.setPrivate = RSASetPrivate; + // Set the private key fields N, e, and d from hex strings + RSAKey.prototype.setPrivate = function (N, E, D) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + } + else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; + // Set the private key fields N, e, d and CRT params from hex strings + RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + this.p = parseBigInt(P, 16); + this.q = parseBigInt(Q, 16); + this.dmp1 = parseBigInt(DP, 16); + this.dmq1 = parseBigInt(DQ, 16); + this.coeff = parseBigInt(C, 16); + } + else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.generate = RSAGenerate; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generate = function (B, E) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + for (;;) { + for (;;) { + this.p = new BigInteger(B - qs, 1, rng); + if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) { + break; + } + } + for (;;) { + this.q = new BigInteger(qs, 1, rng); + if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) { + break; + } + } + if (this.p.compareTo(this.q) <= 0) { + var t = this.p; + this.p = this.q; + this.q = t; + } + var p1 = this.p.subtract(BigInteger.ONE); + var q1 = this.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + this.n = this.p.multiply(this.q); + this.d = ee.modInverse(phi); + this.dmp1 = this.d.mod(p1); + this.dmq1 = this.d.mod(q1); + this.coeff = this.q.modInverse(this.p); + break; + } + } + }; + // RSAKey.prototype.decrypt = RSADecrypt; + // Return the PKCS#1 RSA decryption of "ctext". + // "ctext" is an even-length hex string and the output is a plain string. + RSAKey.prototype.decrypt = function (ctext) { + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if (m == null) { + return null; + } + return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); + }; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generateAsync = function (B, E, callback) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + var rsa = this; + // These functions have non-descript names because they were originally for(;;) loops. + // I don't know about cryptography to give them better names than loop1-4. + var loop1 = function () { + var loop4 = function () { + if (rsa.p.compareTo(rsa.q) <= 0) { + var t = rsa.p; + rsa.p = rsa.q; + rsa.q = t; + } + var p1 = rsa.p.subtract(BigInteger.ONE); + var q1 = rsa.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + rsa.n = rsa.p.multiply(rsa.q); + rsa.d = ee.modInverse(phi); + rsa.dmp1 = rsa.d.mod(p1); + rsa.dmq1 = rsa.d.mod(q1); + rsa.coeff = rsa.q.modInverse(rsa.p); + setTimeout(function () { callback(); }, 0); // escape + } + else { + setTimeout(loop1, 0); + } + }; + var loop3 = function () { + rsa.q = nbi(); + rsa.q.fromNumberAsync(qs, 1, rng, function () { + rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) { + setTimeout(loop4, 0); + } + else { + setTimeout(loop3, 0); + } + }); + }); + }; + var loop2 = function () { + rsa.p = nbi(); + rsa.p.fromNumberAsync(B - qs, 1, rng, function () { + rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) { + setTimeout(loop3, 0); + } + else { + setTimeout(loop2, 0); + } + }); + }); + }; + setTimeout(loop2, 0); + }; + setTimeout(loop1, 0); + }; + RSAKey.prototype.sign = function (text, digestMethod, digestName) { + var header = getDigestHeader(digestName); + var digest = header + digestMethod(text).toString(); + var m = pkcs1pad1(digest, this.n.bitLength() / 4); + if (m == null) { + return null; + } + var c = this.doPrivate(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } + else { + return "0" + h; + } + }; + RSAKey.prototype.verify = function (text, signature, digestMethod) { + var c = parseBigInt(signature, 16); + var m = this.doPublic(c); + if (m == null) { + return null; + } + var unpadded = m.toString(16).replace(/^1f+00/, ""); + var digest = removeDigestHeader(unpadded); + return digest == digestMethod(text).toString(); + }; + return RSAKey; +}()); +// Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext +function pkcs1unpad2(d, n) { + var b = d.toByteArray(); + var i = 0; + while (i < b.length && b[i] == 0) { + ++i; + } + if (b.length - i != n - 1 || b[i] != 2) { + return null; + } + ++i; + while (b[i] != 0) { + if (++i >= b.length) { + return null; + } + } + var ret = ""; + while (++i < b.length) { + var c = b[i] & 255; + if (c < 128) { // utf-8 decode + ret += String.fromCharCode(c); + } + else if ((c > 191) && (c < 224)) { + ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63)); + ++i; + } + else { + ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)); + i += 2; + } + } + return ret; +} +// https://tools.ietf.org/html/rfc3447#page-43 +var DIGEST_HEADERS = { + md2: "3020300c06082a864886f70d020205000410", + md5: "3020300c06082a864886f70d020505000410", + sha1: "3021300906052b0e03021a05000414", + sha224: "302d300d06096086480165030402040500041c", + sha256: "3031300d060960864801650304020105000420", + sha384: "3041300d060960864801650304020205000430", + sha512: "3051300d060960864801650304020305000440", + ripemd160: "3021300906052b2403020105000414", +}; +function getDigestHeader(name) { + return DIGEST_HEADERS[name] || ""; +} +function removeDigestHeader(str) { + for (var name_1 in DIGEST_HEADERS) { + if (DIGEST_HEADERS.hasOwnProperty(name_1)) { + var header = DIGEST_HEADERS[name_1]; + var len = header.length; + if (str.substr(0, len) == header) { + return str.substr(len); + } + } + } + return str; +} +// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string +// function RSAEncryptB64(text) { +// var h = this.encrypt(text); +// if(h) return hex2b64(h); else return null; +// } +// public +// RSAKey.prototype.encrypt_b64 = RSAEncryptB64; + +/*! +Copyright (c) 2011, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.html +version: 2.9.0 +*/ +var YAHOO = {}; +YAHOO.lang = { + /** + * Utility to set up the prototype, constructor and superclass properties to + * support an inheritance strategy that can chain constructors and methods. + * Static members will not be inherited. + * + * @method extend + * @static + * @param {Function} subc the object to modify + * @param {Function} superc the object to inherit + * @param {Object} overrides additional properties/methods to add to the + * subclass prototype. These will override the + * matching items obtained from the superclass + * if present. + */ + extend: function(subc, superc, overrides) { + if (! superc || ! subc) { + throw new Error("YAHOO.lang.extend failed, please check that " + + "all dependencies are included."); + } + + var F = function() {}; + F.prototype = superc.prototype; + subc.prototype = new F(); + subc.prototype.constructor = subc; + subc.superclass = superc.prototype; + + if (superc.prototype.constructor == Object.prototype.constructor) { + superc.prototype.constructor = superc; + } + + if (overrides) { + var i; + for (i in overrides) { + subc.prototype[i] = overrides[i]; + } + + /* + * IE will not enumerate native functions in a derived object even if the + * function was overridden. This is a workaround for specific functions + * we care about on the Object prototype. + * @property _IEEnumFix + * @param {Function} r the object to receive the augmentation + * @param {Function} s the object that supplies the properties to augment + * @static + * @private + */ + var _IEEnumFix = function() {}, + ADD = ["toString", "valueOf"]; + try { + if (/MSIE/.test(navigator.userAgent)) { + _IEEnumFix = function(r, s) { + for (i = 0; i < ADD.length; i = i + 1) { + var fname = ADD[i], f = s[fname]; + if (typeof f === 'function' && f != Object.prototype[fname]) { + r[fname] = f; + } + } + }; + } + } catch (ex) {} _IEEnumFix(subc.prototype, overrides); + } + } +}; + +/* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license + */ + +/** + * @fileOverview + * @name asn1-1.0.js + * @author Kenji Urushima kenji.urushima@gmail.com + * @version asn1 1.0.13 (2017-Jun-02) + * @since jsrsasign 2.1 + * @license MIT License + */ + +/** + * kjur's class library name space + *

+ * This name space provides following name spaces: + *

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

+ * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. + * @name KJUR + * @namespace kjur's class library name space + */ +var KJUR = {}; + +/** + * kjur's ASN.1 class library name space + *

+ * 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. + *

PROVIDING ASN.1 PRIMITIVES

+ * Here are ASN.1 DER primitive classes. + *
    + *
  • 0x01 {@link KJUR.asn1.DERBoolean}
  • + *
  • 0x02 {@link KJUR.asn1.DERInteger}
  • + *
  • 0x03 {@link KJUR.asn1.DERBitString}
  • + *
  • 0x04 {@link KJUR.asn1.DEROctetString}
  • + *
  • 0x05 {@link KJUR.asn1.DERNull}
  • + *
  • 0x06 {@link KJUR.asn1.DERObjectIdentifier}
  • + *
  • 0x0a {@link KJUR.asn1.DEREnumerated}
  • + *
  • 0x0c {@link KJUR.asn1.DERUTF8String}
  • + *
  • 0x12 {@link KJUR.asn1.DERNumericString}
  • + *
  • 0x13 {@link KJUR.asn1.DERPrintableString}
  • + *
  • 0x14 {@link KJUR.asn1.DERTeletexString}
  • + *
  • 0x16 {@link KJUR.asn1.DERIA5String}
  • + *
  • 0x17 {@link KJUR.asn1.DERUTCTime}
  • + *
  • 0x18 {@link KJUR.asn1.DERGeneralizedTime}
  • + *
  • 0x30 {@link KJUR.asn1.DERSequence}
  • + *
  • 0x31 {@link KJUR.asn1.DERSet}
  • + *
+ *

OTHER ASN.1 CLASSES

+ *
    + *
  • {@link KJUR.asn1.ASN1Object}
  • + *
  • {@link KJUR.asn1.DERAbstractString}
  • + *
  • {@link KJUR.asn1.DERAbstractTime}
  • + *
  • {@link KJUR.asn1.DERAbstractStructured}
  • + *
  • {@link KJUR.asn1.DERTaggedObject}
  • + *
+ *

SUB NAME SPACES

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

+ * NOTE: Please ignore method summary and document of this namespace. + * This caused by a bug of jsdoc2. + * @name KJUR.asn1 + * @namespace + */ +if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; + +/** + * ASN1 utilities class + * @name KJUR.asn1.ASN1Util + * @class ASN1 utilities class + * @since asn1 1.0.2 + */ +KJUR.asn1.ASN1Util = new function() { + this.integerToByteHex = function(i) { + var h = i.toString(16); + if ((h.length % 2) == 1) h = '0' + h; + return h; + }; + this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { + var h = bigIntegerValue.toString(16); + if (h.substr(0, 1) != '-') { + if (h.length % 2 == 1) { + h = '0' + h; + } else { + if (! h.match(/^[0-7]/)) { + h = '00' + h; + } + } + } else { + var hPos = h.substr(1); + var xorLen = hPos.length; + if (xorLen % 2 == 1) { + xorLen += 1; + } else { + if (! h.match(/^[0-7]/)) { + xorLen += 2; + } + } + var hMask = ''; + for (var i = 0; i < xorLen; i++) { + hMask += 'f'; + } + var biMask = new BigInteger(hMask, 16); + var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); + h = biNeg.toString(16).replace(/^-/, ''); + } + return h; + }; + /** + * get PEM string from hexadecimal data and header string + * @name getPEMStringFromHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} dataHex hexadecimal string of PEM body + * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') + * @return {String} PEM formatted string of input data + * @description + * This method converts a hexadecimal string to a PEM string with + * a specified header. Its line break will be CRLF("\r\n"). + * @example + * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); + * // value of pem will be: + * -----BEGIN PRIVATE KEY----- + * YWFh + * -----END PRIVATE KEY----- + */ + this.getPEMStringFromHex = function(dataHex, pemHeader) { + return hextopem(dataHex, pemHeader); + }; + + /** + * generate ASN1Object specifed by JSON parameters + * @name newObject + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return {KJUR.asn1.ASN1Object} generated object + * @since asn1 1.0.3 + * @description + * generate any ASN1Object specified by JSON param + * including ASN.1 primitive or structured. + * Generally 'param' can be described as follows: + *
+ * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} + *
+ * 'TYPE-OF-ASN1OBJ' can be one of following symbols: + *
    + *
  • 'bool' - DERBoolean
  • + *
  • 'int' - DERInteger
  • + *
  • 'bitstr' - DERBitString
  • + *
  • 'octstr' - DEROctetString
  • + *
  • 'null' - DERNull
  • + *
  • 'oid' - DERObjectIdentifier
  • + *
  • 'enum' - DEREnumerated
  • + *
  • 'utf8str' - DERUTF8String
  • + *
  • 'numstr' - DERNumericString
  • + *
  • 'prnstr' - DERPrintableString
  • + *
  • 'telstr' - DERTeletexString
  • + *
  • 'ia5str' - DERIA5String
  • + *
  • 'utctime' - DERUTCTime
  • + *
  • 'gentime' - DERGeneralizedTime
  • + *
  • 'seq' - DERSequence
  • + *
  • 'set' - DERSet
  • + *
  • 'tag' - DERTaggedObject
  • + *
+ * @example + * newObject({'prnstr': 'aaa'}); + * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) + * // ASN.1 Tagged Object + * newObject({'tag': {'tag': 'a1', + * 'explicit': true, + * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); + * // more simple representation of ASN.1 Tagged Object + * newObject({'tag': ['a1', + * true, + * {'seq': [ + * {'int': 3}, + * {'prnstr': 'aaa'}]} + * ]}); + */ + this.newObject = function(param) { + var _KJUR = KJUR, + _KJUR_asn1 = _KJUR.asn1, + _DERBoolean = _KJUR_asn1.DERBoolean, + _DERInteger = _KJUR_asn1.DERInteger, + _DERBitString = _KJUR_asn1.DERBitString, + _DEROctetString = _KJUR_asn1.DEROctetString, + _DERNull = _KJUR_asn1.DERNull, + _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, + _DEREnumerated = _KJUR_asn1.DEREnumerated, + _DERUTF8String = _KJUR_asn1.DERUTF8String, + _DERNumericString = _KJUR_asn1.DERNumericString, + _DERPrintableString = _KJUR_asn1.DERPrintableString, + _DERTeletexString = _KJUR_asn1.DERTeletexString, + _DERIA5String = _KJUR_asn1.DERIA5String, + _DERUTCTime = _KJUR_asn1.DERUTCTime, + _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, + _DERSequence = _KJUR_asn1.DERSequence, + _DERSet = _KJUR_asn1.DERSet, + _DERTaggedObject = _KJUR_asn1.DERTaggedObject, + _newObject = _KJUR_asn1.ASN1Util.newObject; + + var keys = Object.keys(param); + if (keys.length != 1) + throw "key of param shall be only one."; + var key = keys[0]; + + if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1) + throw "undefined key: " + key; + + if (key == "bool") return new _DERBoolean(param[key]); + if (key == "int") return new _DERInteger(param[key]); + if (key == "bitstr") return new _DERBitString(param[key]); + if (key == "octstr") return new _DEROctetString(param[key]); + if (key == "null") return new _DERNull(param[key]); + if (key == "oid") return new _DERObjectIdentifier(param[key]); + if (key == "enum") return new _DEREnumerated(param[key]); + if (key == "utf8str") return new _DERUTF8String(param[key]); + if (key == "numstr") return new _DERNumericString(param[key]); + if (key == "prnstr") return new _DERPrintableString(param[key]); + if (key == "telstr") return new _DERTeletexString(param[key]); + if (key == "ia5str") return new _DERIA5String(param[key]); + if (key == "utctime") return new _DERUTCTime(param[key]); + if (key == "gentime") return new _DERGeneralizedTime(param[key]); + + if (key == "seq") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSequence({'array': a}); + } + + if (key == "set") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSet({'array': a}); + } + + if (key == "tag") { + var tagParam = param[key]; + if (Object.prototype.toString.call(tagParam) === '[object Array]' && + tagParam.length == 3) { + var obj = _newObject(tagParam[2]); + return new _DERTaggedObject({tag: tagParam[0], + explicit: tagParam[1], + obj: obj}); + } else { + var newParam = {}; + if (tagParam.explicit !== undefined) + newParam.explicit = tagParam.explicit; + if (tagParam.tag !== undefined) + newParam.tag = tagParam.tag; + if (tagParam.obj === undefined) + throw "obj shall be specified for 'tag'."; + newParam.obj = _newObject(tagParam.obj); + return new _DERTaggedObject(newParam); + } + } + }; + + /** + * get encoded hexadecimal string of ASN1Object specifed by JSON parameters + * @name jsonToASN1HEX + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return hexadecimal string of ASN1Object + * @since asn1 1.0.4 + * @description + * As for ASN.1 object representation of JSON object, + * please see {@link newObject}. + * @example + * jsonToASN1HEX({'prnstr': 'aaa'}); + */ + this.jsonToASN1HEX = function(param) { + var asn1Obj = this.newObject(param); + return asn1Obj.getEncodedHex(); + }; +}; + +/** + * get dot noted oid number string from hexadecimal value of OID + * @name oidHexToInt + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} hex hexadecimal value of object identifier + * @return {String} dot noted string of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from hexadecimal string representation of + * ASN.1 value of object identifier to oid number string. + * @example + * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6" + */ +KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { + var s = ""; + var i01 = parseInt(hex.substr(0, 2), 16); + var i0 = Math.floor(i01 / 40); + var i1 = i01 % 40; + var s = i0 + "." + i1; + + var binbuf = ""; + for (var i = 2; i < hex.length; i += 2) { + var value = parseInt(hex.substr(i, 2), 16); + var bin = ("00000000" + value.toString(2)).slice(- 8); + binbuf = binbuf + bin.substr(1, 7); + if (bin.substr(0, 1) == "0") { + var bi = new BigInteger(binbuf, 2); + s = s + "." + bi.toString(10); + binbuf = ""; + } + } + return s; +}; + +/** + * get hexadecimal value of object identifier from dot noted oid value + * @name oidIntToHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} oidString dot noted string of object identifier + * @return {String} hexadecimal value of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from object identifier value string. + * to hexadecimal string representation of it. + * @example + * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406" + */ +KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { + var itox = function(i) { + var h = i.toString(16); + if (h.length == 1) h = '0' + h; + return h; + }; + + var roidtox = function(roid) { + var h = ''; + var bi = new BigInteger(roid, 10); + var b = bi.toString(2); + var padLen = 7 - b.length % 7; + if (padLen == 7) padLen = 0; + var bPad = ''; + for (var i = 0; i < padLen; i++) bPad += '0'; + b = bPad + b; + for (var i = 0; i < b.length - 1; i += 7) { + var b8 = b.substr(i, 7); + if (i != b.length - 7) b8 = '1' + b8; + h += itox(parseInt(b8, 2)); + } + return h; + }; + + if (! oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + return h; +}; + + +// ******************************************************************** +// Abstract ASN.1 Classes +// ******************************************************************** + +// ******************************************************************** + +/** + * base class for ASN.1 DER encoder object + * @name KJUR.asn1.ASN1Object + * @class base class for ASN.1 DER encoder object + * @property {Boolean} isModified flag whether internal data was changed + * @property {String} hTLV hexadecimal string of ASN.1 TLV + * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) + * @property {String} hL hexadecimal string of ASN.1 TLV length(L) + * @property {String} hV hexadecimal string of ASN.1 TLV value(V) + * @description + */ +KJUR.asn1.ASN1Object = function() { + var hV = ''; + + /** + * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) + * @name getLengthHexFromValue + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV length(L) + */ + this.getLengthHexFromValue = function() { + if (typeof this.hV == "undefined" || this.hV == null) { + throw "this.hV is null or undefined."; + } + if (this.hV.length % 2 == 1) { + throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; + } + var n = this.hV.length / 2; + var hN = n.toString(16); + if (hN.length % 2 == 1) { + hN = "0" + hN; + } + if (n < 128) { + return hN; + } else { + var hNlen = hN.length / 2; + if (hNlen > 15) { + throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); + } + var head = 128 + hNlen; + return head.toString(16) + hN; + } + }; + + /** + * get hexadecimal string of ASN.1 TLV bytes + * @name getEncodedHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV + */ + this.getEncodedHex = function() { + if (this.hTLV == null || this.isModified) { + this.hV = this.getFreshValueHex(); + this.hL = this.getLengthHexFromValue(); + this.hTLV = this.hT + this.hL + this.hV; + this.isModified = false; + //alert("first time: " + this.hTLV); + } + return this.hTLV; + }; + + /** + * get hexadecimal string of ASN.1 TLV value(V) bytes + * @name getValueHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes + */ + this.getValueHex = function() { + this.getEncodedHex(); + return this.hV; + }; + + this.getFreshValueHex = function() { + return ''; + }; +}; + +// == BEGIN DERAbstractString ================================================ +/** + * base class for ASN.1 DER string classes + * @name KJUR.asn1.DERAbstractString + * @class base class for ASN.1 DER string classes + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @property {String} s internal string of value + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + */ +KJUR.asn1.DERAbstractString = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @return {String} string value of this string object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newS value by a string to set + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(this.s); + }; + + /** + * set value by a hexadecimal string + * @name setStringHex + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newHexString value by a hexadecimal string to set + */ + this.setStringHex = function(newHexString) { + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string") { + this.setString(params); + } else if (typeof params['str'] != "undefined") { + this.setString(params['str']); + } else if (typeof params['hex'] != "undefined") { + this.setStringHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); +// == END DERAbstractString ================================================ + +// == BEGIN DERAbstractTime ================================================== +/** + * base class for ASN.1 DER Generalized/UTCTime class + * @name KJUR.asn1.DERAbstractTime + * @class base class for ASN.1 DER Generalized/UTCTime class + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERAbstractTime = function(params) { + KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); + + // --- PRIVATE METHODS -------------------- + this.localDateToUTC = function(d) { + utc = d.getTime() + (d.getTimezoneOffset() * 60000); + var utcDate = new Date(utc); + return utcDate; + }; + + /* + * format date string by Data object + * @name formatDate + * @memberOf KJUR.asn1.AbstractTime; + * @param {Date} dateObject + * @param {string} type 'utc' or 'gen' + * @param {boolean} withMillis flag for with millisections or not + * @description + * 'withMillis' flag is supported from asn1 1.0.6. + */ + this.formatDate = function(dateObject, type, withMillis) { + var pad = this.zeroPadding; + var d = this.localDateToUTC(dateObject); + var year = String(d.getFullYear()); + if (type == 'utc') year = year.substr(2, 2); + var month = pad(String(d.getMonth() + 1), 2); + var day = pad(String(d.getDate()), 2); + var hour = pad(String(d.getHours()), 2); + var min = pad(String(d.getMinutes()), 2); + var sec = pad(String(d.getSeconds()), 2); + var s = year + month + day + hour + min + sec; + if (withMillis === true) { + var millis = d.getMilliseconds(); + if (millis != 0) { + var sMillis = pad(String(millis), 3); + sMillis = sMillis.replace(/[0]+$/, ""); + s = s + "." + sMillis; + } + } + return s + "Z"; + }; + + this.zeroPadding = function(s, len) { + if (s.length >= len) return s; + return new Array(len - s.length + 1).join('0') + s; + }; + + // --- PUBLIC METHODS -------------------- + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @return {String} string value of this time object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {String} newS value by a string to set such like "130430235959Z" + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(newS); + }; + + /** + * set value by a Date object + * @name setByDateValue + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {Integer} year year of date (ex. 2013) + * @param {Integer} month month of date between 1 and 12 (ex. 12) + * @param {Integer} day day of month + * @param {Integer} hour hours of date + * @param {Integer} min minutes of date + * @param {Integer} sec seconds of date + */ + this.setByDateValue = function(year, month, day, hour, min, sec) { + var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); + this.setByDate(dateObject); + }; + + this.getFreshValueHex = function() { + return this.hV; + }; +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); +// == END DERAbstractTime ================================================== + +// == BEGIN DERAbstractStructured ============================================ +/** + * base class for ASN.1 DER structured class + * @name KJUR.asn1.DERAbstractStructured + * @class base class for ASN.1 DER structured class + * @property {Array} asn1Array internal array of ASN1Object + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERAbstractStructured = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * set value by array of ASN1Object + * @name setByASN1ObjectArray + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {array} asn1ObjectArray array of ASN1Object to set + */ + this.setByASN1ObjectArray = function(asn1ObjectArray) { + this.hTLV = null; + this.isModified = true; + this.asn1Array = asn1ObjectArray; + }; + + /** + * append an ASN1Object to internal array + * @name appendASN1Object + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {ASN1Object} asn1Object to add + */ + this.appendASN1Object = function(asn1Object) { + this.hTLV = null; + this.isModified = true; + this.asn1Array.push(asn1Object); + }; + + this.asn1Array = new Array(); + if (typeof params != "undefined") { + if (typeof params['array'] != "undefined") { + this.asn1Array = params['array']; + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); + + +// ******************************************************************** +// ASN.1 Object Classes +// ******************************************************************** + +// ******************************************************************** +/** + * class for ASN.1 DER Boolean + * @name KJUR.asn1.DERBoolean + * @class class for ASN.1 DER Boolean + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERBoolean = function() { + KJUR.asn1.DERBoolean.superclass.constructor.call(this); + this.hT = "01"; + this.hTLV = "0101ff"; +}; +YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER Integer + * @name KJUR.asn1.DERInteger + * @class class for ASN.1 DER Integer + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • bigint - specify initial ASN.1 value(V) by BigInteger object
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * 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 + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + * @example + * new KJUR.asn1.DERInteger(123); + * new KJUR.asn1.DERInteger({'int': 123}); + * new KJUR.asn1.DERInteger({'hex': '1fad'}); + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['bigint'] != "undefined") { + this.setByBigInteger(params['bigint']); + } else if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER encoded BitString primitive + * @name KJUR.asn1.DERBitString + * @class class for ASN.1 DER encoded BitString primitive + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • bin - specify binary string (ex. '10111')
  • + *
  • array - specify array of boolean (ex. [true,false,true,true])
  • + *
  • hex - specify hexadecimal string of ASN.1 value(V) including unused bits
  • + *
  • obj - specify {@link KJUR.asn1.ASN1Util.newObject} + * argument for "BitString encapsulates" structure.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: 'obj' parameter have been supported since + * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
+ * @example + * // default constructor + * o = new KJUR.asn1.DERBitString(); + * // initialize with binary string + * o = new KJUR.asn1.DERBitString({bin: "1011"}); + * // initialize with boolean array + * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); + * // initialize with hexadecimal string (04 is unused bits) + * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); + * // initialize with ASN1Util.newObject argument for encapsulated + * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // BIT STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ +KJUR.asn1.DERBitString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = "00" + o.getEncodedHex(); + } + KJUR.asn1.DERBitString.superclass.constructor.call(this); + this.hT = "03"; + + /** + * set ASN.1 value(V) by a hexadecimal string including unused bits + * @name setHexValueIncludingUnusedBits + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {String} newHexStringIncludingUnusedBits + */ + this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { + this.hTLV = null; + this.isModified = true; + this.hV = newHexStringIncludingUnusedBits; + }; + + /** + * set ASN.1 value(V) by unused bit and hexadecimal string of value + * @name setUnusedBitsAndHexValue + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {Integer} unusedBits + * @param {String} hValue + */ + this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { + if (unusedBits < 0 || 7 < unusedBits) { + throw "unused bits shall be from 0 to 7: u = " + unusedBits; + } + var hUnusedBits = "0" + unusedBits; + this.hTLV = null; + this.isModified = true; + this.hV = hUnusedBits + hValue; + }; + + /** + * set ASN.1 DER BitString by binary string
+ * @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'.
+ * NOTE: Trailing zeros '0' will be ignored. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray("01011"); + */ + this.setByBinaryString = function(binaryString) { + binaryString = binaryString.replace(/0+$/, ''); + var unusedBits = 8 - binaryString.length % 8; + if (unusedBits == 8) unusedBits = 0; + for (var i = 0; i <= unusedBits; i++) { + binaryString += '0'; + } + var h = ''; + for (var i = 0; i < binaryString.length - 1; i += 8) { + var b = binaryString.substr(i, 8); + var x = parseInt(b, 2).toString(16); + if (x.length == 1) x = '0' + x; + h += x; + } + this.hTLV = null; + this.isModified = true; + this.hV = '0' + unusedBits + h; + }; + + /** + * set ASN.1 TLV value(V) by an array of boolean
+ * @name setByBooleanArray + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {array} booleanArray array of boolean (ex. [true, false, true]) + * @description + * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray([false, true, false, true, true]); + */ + this.setByBooleanArray = function(booleanArray) { + var s = ''; + for (var i = 0; i < booleanArray.length; i++) { + if (booleanArray[i] == true) { + s += '1'; + } else { + s += '0'; + } + } + this.setByBinaryString(s); + }; + + /** + * generate an array of falses with specified length
+ * @name newFalseArray + * @memberOf KJUR.asn1.DERBitString + * @function + * @param {Integer} nLength length of array to generate + * @return {array} array of boolean falses + * @description + * This static method may be useful to initialize boolean array. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.newFalseArray(3) → [false, false, false] + */ + this.newFalseArray = function(nLength) { + var a = new Array(nLength); + for (var i = 0; i < nLength; i++) { + a[i] = false; + } + return a; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { + this.setHexValueIncludingUnusedBits(params); + } else if (typeof params['hex'] != "undefined") { + this.setHexValueIncludingUnusedBits(params['hex']); + } else if (typeof params['bin'] != "undefined") { + this.setByBinaryString(params['bin']); + } else if (typeof params['array'] != "undefined") { + this.setByBooleanArray(params['array']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER OctetString
+ * @name KJUR.asn1.DEROctetString + * @class class for ASN.1 DER OctetString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * This class provides ASN.1 OctetString simple type.
+ * Supported "params" attributes are: + *
    + *
  • str - to set a string as a value
  • + *
  • hex - to set a hexadecimal string as a value
  • + *
  • obj - to set a encapsulated ASN.1 value by JSON object + * which is defined in {@link KJUR.asn1.ASN1Util.newObject}
  • + *
+ * NOTE: A parameter 'obj' have been supported + * for "OCTET STRING, encapsulates" structure. + * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). + * @see KJUR.asn1.DERAbstractString - superclass + * @example + * // default constructor + * o = new KJUR.asn1.DEROctetString(); + * // initialize with string + * o = new KJUR.asn1.DEROctetString({str: "aaa"}); + * // initialize with hexadecimal string + * o = new KJUR.asn1.DEROctetString({hex: "616161"}); + * // initialize with ASN1Util.newObject argument + * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // OCTET STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ +KJUR.asn1.DEROctetString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = o.getEncodedHex(); + } + KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); + this.hT = "04"; +}; +YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER Null + * @name KJUR.asn1.DERNull + * @class class for ASN.1 DER Null + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ +KJUR.asn1.DERNull = function() { + KJUR.asn1.DERNull.superclass.constructor.call(this); + this.hT = "05"; + this.hTLV = "0500"; +}; +YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER ObjectIdentifier + * @name KJUR.asn1.DERObjectIdentifier + * @class class for ASN.1 DER ObjectIdentifier + * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * 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) + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueOidString("2.5.4.13"); + */ + this.setValueOidString = function(oidString) { + if (! oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = h; + }; + + /** + * set value by a OID name + * @name setValueName + * @memberOf KJUR.asn1.DERObjectIdentifier# + * @function + * @param {String} oidName OID name (ex. 'serverAuth') + * @since 1.0.1 + * @description + * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. + * Otherwise raise error. + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueName("serverAuth"); + */ + this.setValueName = function(oidName) { + var oid = KJUR.asn1.x509.OID.name2oid(oidName); + if (oid !== '') { + this.setValueOidString(oid); + } else { + throw "DERObjectIdentifier oidName undefined: " + oidName; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (params !== undefined) { + if (typeof params === "string") { + if (params.match(/^[0-2].[0-9.]+$/)) { + this.setValueOidString(params); + } else { + this.setValueName(params); + } + } else if (params.oid !== undefined) { + this.setValueOidString(params.oid); + } else if (params.hex !== undefined) { + this.setValueHex(params.hex); + } else if (params.name !== undefined) { + this.setValueName(params.name); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER Enumerated + * @name KJUR.asn1.DEREnumerated + * @class class for ASN.1 DER Enumerated + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + * @example + * new KJUR.asn1.DEREnumerated(123); + * new KJUR.asn1.DEREnumerated({int: 123}); + * new KJUR.asn1.DEREnumerated({hex: '1fad'}); + */ +KJUR.asn1.DEREnumerated = function(params) { + KJUR.asn1.DEREnumerated.superclass.constructor.call(this); + this.hT = "0a"; + + /** + * set value by Tom Wu's BigInteger object + * @name setByBigInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {BigInteger} bigIntegerValue to set + */ + this.setByBigInteger = function(bigIntegerValue) { + this.hTLV = null; + this.isModified = true; + this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); + }; + + /** + * set value by integer value + * @name setByInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {Integer} integer value to set + */ + this.setByInteger = function(intValue) { + var bi = new BigInteger(String(intValue), 10); + this.setByBigInteger(bi); + }; + + /** + * set value by integer value + * @name setValueHex + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {String} hexadecimal string of integer value + * @description + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); + +// ******************************************************************** +/** + * class for ASN.1 DER UTF8String + * @name KJUR.asn1.DERUTF8String + * @class class for ASN.1 DER UTF8String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERUTF8String = function(params) { + KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); + this.hT = "0c"; +}; +YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER NumericString + * @name KJUR.asn1.DERNumericString + * @class class for ASN.1 DER NumericString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERNumericString = function(params) { + KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); + this.hT = "12"; +}; +YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER PrintableString + * @name KJUR.asn1.DERPrintableString + * @class class for ASN.1 DER PrintableString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERPrintableString = function(params) { + KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); + this.hT = "13"; +}; +YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER TeletexString + * @name KJUR.asn1.DERTeletexString + * @class class for ASN.1 DER TeletexString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERTeletexString = function(params) { + KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); + this.hT = "14"; +}; +YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER IA5String + * @name KJUR.asn1.DERIA5String + * @class class for ASN.1 DER IA5String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ +KJUR.asn1.DERIA5String = function(params) { + KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); + this.hT = "16"; +}; +YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); + +// ******************************************************************** +/** + * class for ASN.1 DER UTCTime + * @name KJUR.asn1.DERUTCTime + * @class class for ASN.1 DER UTCTime + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
+ * NOTE: 'params' can be omitted. + *

EXAMPLES

+ * @example + * d1 = new KJUR.asn1.DERUTCTime(); + * d1.setString('130430125959Z'); + * + * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); + * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); + * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); + */ +KJUR.asn1.DERUTCTime = function(params) { + KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); + this.hT = "17"; + + /** + * set value by a Date object
+ * @name setByDate + * @memberOf KJUR.asn1.DERUTCTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * o = new KJUR.asn1.DERUTCTime(); + * o.setByDate(new Date("2016/12/31")); + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (typeof this.date == "undefined" && typeof this.s == "undefined") { + this.date = new Date(); + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); + +// ******************************************************************** +/** + * class for ASN.1 DER GeneralizedTime + * @name KJUR.asn1.DERGeneralizedTime + * @class class for ASN.1 DER GeneralizedTime + * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) + * @property {Boolean} withMillis flag to show milliseconds or not + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
  • millis - specify flag to show milliseconds (from 1.0.6)
  • + *
+ * NOTE1: 'params' can be omitted. + * NOTE2: 'withMillis' property is supported from asn1 1.0.6. + */ +KJUR.asn1.DERGeneralizedTime = function(params) { + KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); + this.hT = "18"; + this.withMillis = false; + + /** + * set value by a Date object + * @name setByDate + * @memberOf KJUR.asn1.DERGeneralizedTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * When you specify UTC time, use 'Date.UTC' method like this:
+ * o1 = new DERUTCTime(); + * o1.setByDate(date); + * + * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (this.date === undefined && this.s === undefined) { + this.date = new Date(); + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + if (params.millis === true) { + this.withMillis = true; + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); + +// ******************************************************************** +/** + * class for ASN.1 DER Sequence + * @name KJUR.asn1.DERSequence + * @class class for ASN.1 DER Sequence + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
+ * NOTE: 'params' can be omitted. + */ +KJUR.asn1.DERSequence = function(params) { + KJUR.asn1.DERSequence.superclass.constructor.call(this, params); + this.hT = "30"; + this.getFreshValueHex = function() { + var h = ''; + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + h += asn1Obj.getEncodedHex(); + } + this.hV = h; + return this.hV; + }; +}; +YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); + +// ******************************************************************** +/** + * class for ASN.1 DER Set + * @name KJUR.asn1.DERSet + * @class class for ASN.1 DER Set + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
  • sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: sortflag is supported since 1.0.5. + */ +KJUR.asn1.DERSet = function(params) { + KJUR.asn1.DERSet.superclass.constructor.call(this, params); + this.hT = "31"; + this.sortFlag = true; // item shall be sorted only in ASN.1 DER + this.getFreshValueHex = function() { + var a = new Array(); + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + a.push(asn1Obj.getEncodedHex()); + } + if (this.sortFlag == true) a.sort(); + this.hV = a.join(''); + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params.sortflag != "undefined" && + params.sortflag == false) + this.sortFlag = false; + } +}; +YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); + +// ******************************************************************** +/** + * class for ASN.1 DER TaggedObject + * @name KJUR.asn1.DERTaggedObject + * @class class for ASN.1 DER TaggedObject + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * 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'. + *
+ * As for optional argument 'params' for constructor, you can specify *ANY* of + * following properties: + *
    + *
  • explicit - specify true if this is explicit tag otherwise false + * (default is 'true').
  • + *
  • tag - specify tag (default is 'a0' which means [0])
  • + *
  • obj - specify ASN1Object which is tagged
  • + *
+ * @example + * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); + * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); + * hex = d2.getEncodedHex(); + */ +KJUR.asn1.DERTaggedObject = function(params) { + KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); + this.hT = "a0"; + this.hV = ''; + this.isExplicit = true; + this.asn1Object = null; + + /** + * set value by an ASN1Object + * @name setString + * @memberOf KJUR.asn1.DERTaggedObject# + * @function + * @param {Boolean} isExplicitFlag flag for explicit/implicit tag + * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag + * @param {ASN1Object} asn1Object ASN.1 to encapsulate + */ + this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { + this.hT = tagNoHex; + this.isExplicit = isExplicitFlag; + this.asn1Object = asn1Object; + if (this.isExplicit) { + this.hV = this.asn1Object.getEncodedHex(); + this.hTLV = null; + this.isModified = true; + } else { + this.hV = null; + this.hTLV = asn1Object.getEncodedHex(); + this.hTLV = this.hTLV.replace(/^../, tagNoHex); + this.isModified = false; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['tag'] != "undefined") { + this.hT = params['tag']; + } + if (typeof params['explicit'] != "undefined") { + this.isExplicit = params['explicit']; + } + if (typeof params['obj'] != "undefined") { + this.asn1Object = params['obj']; + this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); + } + } +}; +YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); + +/** + * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. + * This object is just a decorator for parsing the key parameter + * @param {string|Object} key - The key in string format, or an object containing + * the parameters needed to build a RSAKey object. + * @constructor + */ +var JSEncryptRSAKey = /** @class */ (function (_super) { + __extends(JSEncryptRSAKey, _super); + function JSEncryptRSAKey(key) { + var _this = _super.call(this) || this; + // Call the super constructor. + // RSAKey.call(this); + // If a key key was provided. + if (key) { + // If this is a string... + if (typeof key === "string") { + _this.parseKey(key); + } + else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || + JSEncryptRSAKey.hasPublicKeyProperty(key)) { + // Set the values for the key. + _this.parsePropertiesFrom(key); + } + } + return _this; + } + /** + * Method to parse a pem encoded string containing both a public or private key. + * The method will translate the pem encoded string in a der encoded string and + * will parse private key and public key parameters. This method accepts public key + * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). + * + * @todo Check how many rsa formats use the same format of pkcs #1. + * + * The format is defined as: + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * it's possible to examine the structure of the keys obtained from openssl using + * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ + * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer + * @private + */ + JSEncryptRSAKey.prototype.parseKey = function (pem) { + try { + var modulus = 0; + var public_exponent = 0; + var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; + var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); + var asn1 = ASN1.decode(der); + // Fixes a bug with OpenSSL 1.0+ private keys + if (asn1.sub.length === 3) { + asn1 = asn1.sub[2].sub[0]; + } + if (asn1.sub.length === 9) { + // Parse the private key. + modulus = asn1.sub[1].getHexStringValue(); // bigint + this.n = parseBigInt(modulus, 16); + public_exponent = asn1.sub[2].getHexStringValue(); // int + this.e = parseInt(public_exponent, 16); + var private_exponent = asn1.sub[3].getHexStringValue(); // bigint + this.d = parseBigInt(private_exponent, 16); + var prime1 = asn1.sub[4].getHexStringValue(); // bigint + this.p = parseBigInt(prime1, 16); + var prime2 = asn1.sub[5].getHexStringValue(); // bigint + this.q = parseBigInt(prime2, 16); + var exponent1 = asn1.sub[6].getHexStringValue(); // bigint + this.dmp1 = parseBigInt(exponent1, 16); + var exponent2 = asn1.sub[7].getHexStringValue(); // bigint + this.dmq1 = parseBigInt(exponent2, 16); + var coefficient = asn1.sub[8].getHexStringValue(); // bigint + this.coeff = parseBigInt(coefficient, 16); + } + else if (asn1.sub.length === 2) { + // Parse the public key. + var bit_string = asn1.sub[1]; + var sequence = bit_string.sub[0]; + modulus = sequence.sub[0].getHexStringValue(); + this.n = parseBigInt(modulus, 16); + public_exponent = sequence.sub[1].getHexStringValue(); + this.e = parseInt(public_exponent, 16); + } + else { + return false; + } + return true; + } + catch (ex) { + return false; + } + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa key. + * + * The translation follow the ASN.1 notation : + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER, -- (inverse of q) mod p + * } + * @returns {string} DER Encoded String representing the rsa private key + * @private + */ + JSEncryptRSAKey.prototype.getPrivateBaseKey = function () { + var options = { + array: [ + new KJUR.asn1.DERInteger({ int: 0 }), + new KJUR.asn1.DERInteger({ bigint: this.n }), + new KJUR.asn1.DERInteger({ int: this.e }), + new KJUR.asn1.DERInteger({ bigint: this.d }), + new KJUR.asn1.DERInteger({ bigint: this.p }), + new KJUR.asn1.DERInteger({ bigint: this.q }), + new KJUR.asn1.DERInteger({ bigint: this.dmp1 }), + new KJUR.asn1.DERInteger({ bigint: this.dmq1 }), + new KJUR.asn1.DERInteger({ bigint: this.coeff }) + ] + }; + var seq = new KJUR.asn1.DERSequence(options); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () { + return hex2b64(this.getPrivateBaseKey()); + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa public key. + * The representation follow the ASN.1 notation : + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * @returns {string} DER Encoded String representing the rsa public key + * @private + */ + JSEncryptRSAKey.prototype.getPublicBaseKey = function () { + var first_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }), + new KJUR.asn1.DERNull() + ] + }); + var second_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERInteger({ bigint: this.n }), + new KJUR.asn1.DERInteger({ int: this.e }) + ] + }); + var bit_string = new KJUR.asn1.DERBitString({ + hex: "00" + second_sequence.getEncodedHex() + }); + var seq = new KJUR.asn1.DERSequence({ + array: [ + first_sequence, + bit_string + ] + }); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () { + return hex2b64(this.getPublicBaseKey()); + }; + /** + * wrap the string in block of width chars. The default value for rsa keys is 64 + * characters. + * @param {string} str the pem encoded string without header and footer + * @param {Number} [width=64] - the length the string has to be wrapped at + * @returns {string} + * @private + */ + JSEncryptRSAKey.wordwrap = function (str, width) { + width = width || 64; + if (!str) { + return str; + } + var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; + return str.match(RegExp(regex, "g")).join("\n"); + }; + /** + * Retrieve the pem encoded private key + * @returns {string} the pem encoded private key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateKey = function () { + var key = "-----BEGIN RSA PRIVATE KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; + key += "-----END RSA PRIVATE KEY-----"; + return key; + }; + /** + * Retrieve the pem encoded public key + * @returns {string} the pem encoded public key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicKey = function () { + var key = "-----BEGIN PUBLIC KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; + key += "-----END PUBLIC KEY-----"; + return key; + }; + /** + * Check if the object contains the necessary parameters to populate the rsa modulus + * and public exponent parameters. + * @param {Object} [obj={}] - An object that may contain the two public key + * parameters + * @returns {boolean} true if the object contains both the modulus and the public exponent + * properties (n and e) + * @todo check for types of n and e. N should be a parseable bigInt object, E should + * be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPublicKeyProperty = function (obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e")); + }; + /** + * Check if the object contains ALL the parameters of an RSA key. + * @param {Object} [obj={}] - An object that may contain nine rsa key + * parameters + * @returns {boolean} true if the object contains all the parameters needed + * @todo check for types of the parameters all the parameters but the public exponent + * should be parseable bigint objects, the public exponent should be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e") && + obj.hasOwnProperty("d") && + obj.hasOwnProperty("p") && + obj.hasOwnProperty("q") && + obj.hasOwnProperty("dmp1") && + obj.hasOwnProperty("dmq1") && + obj.hasOwnProperty("coeff")); + }; + /** + * Parse the properties of obj in the current rsa object. Obj should AT LEAST + * include the modulus and public exponent (n, e) parameters. + * @param {Object} obj - the object containing rsa parameters + * @private + */ + JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) { + this.n = obj.n; + this.e = obj.e; + if (obj.hasOwnProperty("d")) { + this.d = obj.d; + this.p = obj.p; + this.q = obj.q; + this.dmp1 = obj.dmp1; + this.dmq1 = obj.dmq1; + this.coeff = obj.coeff; + } + }; + return JSEncryptRSAKey; +}(RSAKey)); + +/** + * + * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour + * possible parameters are: + * - default_key_size {number} default: 1024 the key size in bit + * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent + * - log {boolean} default: false whether log warn/error or not + * @constructor + */ +var JSEncrypt = /** @class */ (function () { + function JSEncrypt(options) { + options = options || {}; + this.default_key_size = parseInt(options.default_key_size, 10) || 1024; + this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type + this.log = options.log || false; + // The private and public key. + this.key = null; + } + /** + * Method to set the rsa key parameter (one method is enough to set both the public + * and the private key, since the private key contains the public key paramenters) + * Log a warning if logs are enabled + * @param {Object|string} key the pem encoded string or an object (with or without header/footer) + * @public + */ + JSEncrypt.prototype.setKey = function (key) { + if (this.log && this.key) { + console.warn("A key was already set, overriding existing."); + } + console.log("JSEncryptRSAKey", new JSEncryptRSAKey) + this.key = new JSEncryptRSAKey(key); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPrivateKey = function (privkey) { + // Create the key. + this.setKey(privkey); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPublicKey = function (pubkey) { + // Sets the public key. + this.setKey(pubkey); + }; + /** + * Proxy method for RSAKey object's decrypt, decrypt the string using the private + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str base64 encoded crypted string to decrypt + * @return {string} the decrypted string + * @public + */ + JSEncrypt.prototype.decrypt = function (str) { + // Return the decrypted string. + try { + return this.getKey().decrypt(b64tohex(str)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's encrypt, encrypt the string using the public + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str the string to encrypt + * @return {string} the encrypted string encoded in base64 + * @public + */ + JSEncrypt.prototype.encrypt = function (str) { + // Return the encrypted string. + try { + return hex2b64(this.getKey().encrypt(str)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's sign. + * @param {string} str the string to sign + * @param {function} digestMethod hash method + * @param {string} digestName the name of the hash algorithm + * @return {string} the signature encoded in base64 + * @public + */ + JSEncrypt.prototype.sign = function (str, digestMethod, digestName) { + // return the RSA signature of 'str' in 'hex' format. + try { + return hex2b64(this.getKey().sign(str, digestMethod, digestName)); + } + catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's verify. + * @param {string} str the string to verify + * @param {string} signature the signature encoded in base64 to compare the string to + * @param {function} digestMethod hash method + * @return {boolean} whether the data and signature match + * @public + */ + JSEncrypt.prototype.verify = function (str, signature, digestMethod) { + // Return the decrypted 'digest' of the signature. + try { + return this.getKey().verify(str, b64tohex(signature), digestMethod); + } + catch (ex) { + return false; + } + }; + /** + * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object + * will be created and returned + * @param {callback} [cb] the callback to be called if we want the key to be generated + * in an async fashion + * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object + * @public + */ + JSEncrypt.prototype.getKey = function (cb) { + // Only create new if it does not exist. + if (!this.key) { + // Get a new private key. + this.key = new JSEncryptRSAKey(); + if (cb && {}.toString.call(cb) === "[object Function]") { + this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb); + return; + } + // Generate the key. + this.key.generate(this.default_key_size, this.default_public_exponent); + } + return this.key; + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKey = function () { + // Return the private representation of this key. + return this.getKey().getPrivateKey(); + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKeyB64 = function () { + // Return the private representation of this key. + return this.getKey().getPrivateBaseKeyB64(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPublicKey = function () { + // Return the private representation of this key. + return this.getKey().getPublicKey(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPublicKeyB64 = function () { + // Return the private representation of this key. + return this.getKey().getPublicBaseKeyB64(); + }; + JSEncrypt.version = "3.0.0-rc.1"; + return JSEncrypt; +}()); + +// window.JSEncrypt = JSEncrypt; + +exports.JSEncrypt = JSEncrypt; +exports.default = JSEncrypt; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/assets/js/jsencrypt/rsa.js b/assets/js/jsencrypt/rsa.js new file mode 100644 index 0000000..c00da71 --- /dev/null +++ b/assets/js/jsencrypt/rsa.js @@ -0,0 +1,9 @@ + +// import JSEncrypt from '../jsencrypt/jsencrypt' +// import JSEncrypt from '../jsencrypt/jsencryptInit' +import JSEncrypt from '../jsencrypt/jsencryptInit' +export function encrypt(publicKey, message) { + const encrypt = new JSEncrypt() + encrypt.setPublicKey(publicKey) // publicKey为公钥 + return encrypt.encrypt(message) +} \ No newline at end of file diff --git a/components/Dialog/dialog.js b/components/Dialog/dialog.js new file mode 100644 index 0000000..e6c4654 --- /dev/null +++ b/components/Dialog/dialog.js @@ -0,0 +1,73 @@ +// components/Dialog/dialog.js +Component({ + options: { + multipleSlots: true // 在组件定义时的选项中启用多slot支持 + }, + /** + * 组件的属性列表 + */ + properties: { + // 弹窗标题 + title: { // 属性名 + type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) + value: '标题' // 属性初始值(可选),如果未指定则会根据类型选择一个 + }, + // 弹窗内容 + content: { + type: String, + value: '弹窗内容' + }, + // 弹窗取消按钮文字 + cancelText: { + type: String, + value: '取消' + }, + // 弹窗确认按钮文字 + confirmText: { + type: String, + value: '确定' + } + }, + + /** + * 组件的初始数据 + */ + data: { + // 弹窗显示控制 + isShow: false + }, + + /** + * 组件的方法列表 + */ + methods: { + /* + * 公有方法 + */ + + //隐藏弹框 + hideDialog() { + this.setData({ + isShow: !this.data.isShow + }) + }, + //展示弹框 + showDialog() { + this.setData({ + isShow: !this.data.isShow + }) + }, + /* + * 内部私有方法建议以下划线开头 + * triggerEvent 用于触发事件 + */ + _cancelEvent() { + //触发取消回调 + this.triggerEvent("cancelEvent") + }, + _confirmEvent() { + //触发成功回调 + this.triggerEvent("confirmEvent"); + } + } +}) \ No newline at end of file diff --git a/components/Dialog/dialog.json b/components/Dialog/dialog.json new file mode 100644 index 0000000..e8cfaaf --- /dev/null +++ b/components/Dialog/dialog.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/components/Dialog/dialog.wxml b/components/Dialog/dialog.wxml new file mode 100644 index 0000000..78dfb35 --- /dev/null +++ b/components/Dialog/dialog.wxml @@ -0,0 +1,13 @@ + + + diff --git a/components/Dialog/dialog.wxss b/components/Dialog/dialog.wxss new file mode 100644 index 0000000..ad31753 --- /dev/null +++ b/components/Dialog/dialog.wxss @@ -0,0 +1,95 @@ +/* components/Dialog/dialog.wxss */ +/* components/Dialog/dialog.wxss */ +.wx-mask { + position: fixed; + z-index: 1000; + top: 0; + right: 0; + left: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.3); +} + +.wx-dialog { + position: fixed; + z-index: 5000; + width: 80%; + max-width: 600rpx; + top: 50%; + left: 50%; + -webkit-transform: translate(-50%, -50%); + transform: translate(-50%, -50%); + background-color: #FFFFFF; + text-align: center; + border-radius: 3px; + overflow: hidden; +} + +.wx-dialog-title { + font-size: 18px; + padding: 15px 15px 5px; +} + +.wx-dialog-content { + padding: 15px 15px 5px; + min-height: 40px; + font-size: 16px; + line-height: 1.3; + word-wrap: break-word; + word-break: break-all; + color: #999999; +} + +.wx-dialog-footer { + display: flex; + align-items: center; + position: relative; + line-height: 45px; + font-size: 17px; +} + +.wx-dialog-footer::before { + content: ''; + position: absolute; + left: 0; + top: 0; + right: 0; + height: 1px; + border-top: 1px solid #D5D5D6; + color: #D5D5D6; + -webkit-transform-origin: 0 0; + transform-origin: 0 0; + -webkit-transform: scaleY(0.5); + transform: scaleY(0.5); +} + +.wx-dialog-btn { + display: block; + -webkit-flex: 1; + flex: 1; + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); + position: relative; +} + +.wx-dialog-footer .wx-dialog-btn:nth-of-type(1) { + color: #353535; +} + +.wx-dialog-footer .wx-dialog-btn:nth-of-type(2) { + color: #3CC51F; +} + +.wx-dialog-footer .wx-dialog-btn:nth-of-type(2):after { + content: " "; + position: absolute; + left: 0; + top: 0; + width: 1px; + bottom: 0; + border-left: 1px solid #D5D5D6; + color: #D5D5D6; + -webkit-transform-origin: 0 0; + transform-origin: 0 0; + -webkit-transform: scaleX(0.5); + transform: scaleX(0.5); +} \ No newline at end of file diff --git a/components/getPhoneNumer/getPhoneNumber.js b/components/getPhoneNumer/getPhoneNumber.js new file mode 100644 index 0000000..f11bab4 --- /dev/null +++ b/components/getPhoneNumer/getPhoneNumber.js @@ -0,0 +1,89 @@ +// components/getPhoneNumer/getPhoneNumber.js +const app = getApp() + +Component({ + /** + * 组件的属性列表 + */ + properties: { + appid:{ + type: String, + value:'' + }, + secret: { + type: String, + value:'' + } + }, + // 可以定义外部样式类 影响组件的样式 + externalClasses: ['class'], + options: { + // 配置样式是否可以被父组件影响 详细见文档 + styleIsolation: 'apply-shared' + }, + /** + * 组件的初始数据 + */ + data: { + // session_key + session_key:'', + // 用户openid + openid:'' + }, + + /** + * 组件的方法列表 + */ + methods: { + getPhoneNumber(e) { + console.log(e); + const that = this + wx.checkSession({ + success: (res) => { + console.log(res); + if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){ + console.log("用户拒绝了授权"); + return + }else{ + console.log("用户同意了授权"); + let key = that.data.session_key + let phone = e.detail.encryptedData; + let iv = e.detail.iv; + const RdWXBizDataCrypt = require('./utils/RdWXBizDataCrypt'); + const pc = new RdWXBizDataCrypt(that.data.appid, key); + const data = pc.decryptData(phone, iv); + console.log(data.phoneNumber); //当前手机号码 + that.triggerEvent("myevent",data) + } + }, + fail:(err) => { + console.log("登录状态失效,请重新登录",err); + } + }) + + }, + }, + /** + * 组件生命周期 + */ + lifetimes: { + attached(){ + const that = this + wx.login({ + timeout: 2000, + success(res){ + wx.request({ + url: `https://api.weixin.qq.com/sns/jscode2session?appid=${that.data.appid}&secret=${that.data.secret}&js_code=${res.code}&grant_type=authorization_code`, + success(result){ + that.setData({ + session_key:result.data.session_key, + openid:result.data.openid + }) + } + }) + } + }) + } + } + +}) \ No newline at end of file diff --git a/components/getPhoneNumer/getPhoneNumber.json b/components/getPhoneNumer/getPhoneNumber.json new file mode 100644 index 0000000..e8cfaaf --- /dev/null +++ b/components/getPhoneNumer/getPhoneNumber.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/components/getPhoneNumer/getPhoneNumber.wxml b/components/getPhoneNumer/getPhoneNumber.wxml new file mode 100644 index 0000000..1da65ee --- /dev/null +++ b/components/getPhoneNumer/getPhoneNumber.wxml @@ -0,0 +1,6 @@ + + + + diff --git a/components/getPhoneNumer/getPhoneNumber.wxss b/components/getPhoneNumer/getPhoneNumber.wxss new file mode 100644 index 0000000..e74b8a6 --- /dev/null +++ b/components/getPhoneNumer/getPhoneNumber.wxss @@ -0,0 +1 @@ +/* components/getPhoneNumer/getPhoneNumber.wxss */ diff --git a/components/getPhoneNumer/utils/RdWXBizDataCrypt.js b/components/getPhoneNumer/utils/RdWXBizDataCrypt.js new file mode 100644 index 0000000..931d8d4 --- /dev/null +++ b/components/getPhoneNumer/utils/RdWXBizDataCrypt.js @@ -0,0 +1,34 @@ +var Crypto = require('./cryptojs/cryptojs.js').Crypto; +var app = getApp(); + +function RdWXBizDataCrypt(appId, sessionKey) { + this.appId = appId + this.sessionKey = sessionKey +} +RdWXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) { + // base64 decode :使用 CryptoJS 中 Crypto.util.base64ToBytes()进行 base64解码 + var encryptedData = Crypto.util.base64ToBytes(encryptedData) + // console.log(sessionKey) + var key = Crypto.util.base64ToBytes(this.sessionKey); + var iv = Crypto.util.base64ToBytes(iv); + // console.log(encryptedData,key,iv) + // 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充 + var mode = new Crypto.mode.CBC(Crypto.pad.pkcs7); + try { + // 解密 + var bytes = Crypto.AES.decrypt(encryptedData, key, { + asBpytes: true, + iv: iv, + mode: mode + }); + var decryptResult = JSON.parse(bytes); + + } catch (err) { + console.log(err) + } + if (decryptResult.watermark.appid !== this.appId) { + console.log(err) + } + return decryptResult +} +module.exports = RdWXBizDataCrypt \ No newline at end of file diff --git a/components/getPhoneNumer/utils/cryptojs/README.md b/components/getPhoneNumer/utils/cryptojs/README.md new file mode 100644 index 0000000..0726ae7 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/README.md @@ -0,0 +1,32 @@ +cryptojs +-------- + +* with little modification, converted from googlecode project [crypto-js](http://code.google.com/p/crypto-js/), and keep the source code structure of the origin project on googlecode +* source code worked in both browser engines and node scripts. see also: [https://github.com/gwjjeff/crypto-js-npm-conv](https://github.com/gwjjeff/crypto-js-npm-conv) +* inspiration comes from [ezcrypto](https://github.com/ElmerZhang/ezcrypto), but my tests cannot pass with his version ( ECB/pkcs7 mode ), so I made it myself + +### install + +``` +npm install cryptojs +``` + +### usage (example with [coffee-script](http://coffeescript.org/)) + +```coffee +Crypto = (require 'cryptojs').Crypto +key = '12345678' +us = 'Hello, 世界!' + +mode = new Crypto.mode.ECB Crypto.pad.pkcs7 + +ub = Crypto.charenc.UTF8.stringToBytes us +eb = Crypto.DES.encrypt ub, key, {asBytes: true, mode: mode} +ehs= Crypto.util.bytesToHex eb + +eb2= Crypto.util.hexToBytes ehs +ub2= Crypto.DES.decrypt eb2, key, {asBytes: true, mode: mode} +us2= Crypto.charenc.UTF8.bytesToString ub2 +# should be same as the var 'us' +console .log us2 +``` diff --git a/components/getPhoneNumer/utils/cryptojs/cryptojs.js b/components/getPhoneNumer/utils/cryptojs/cryptojs.js new file mode 100644 index 0000000..da2a717 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/cryptojs.js @@ -0,0 +1,17 @@ +var Crypto = exports.Crypto = require('./lib/Crypto').Crypto; + +[ 'CryptoMath' +, 'BlockModes' +, 'DES' +, 'AES' +, 'HMAC' +, 'MARC4' +, 'MD5' +, 'PBKDF2' +, 'PBKDF2Async' +, 'Rabbit' +, 'SHA1' +, 'SHA256' +].forEach( function (path) { + require('./lib/' + path); +}); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/AES.js b/components/getPhoneNumer/utils/cryptojs/lib/AES.js new file mode 100644 index 0000000..2772c11 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/AES.js @@ -0,0 +1,402 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8; + +// Precomputed SBOX +var SBOX = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, + 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, + 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, + 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, + 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, + 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, + 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, + 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, + 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, + 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, + 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, + 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, + 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, + 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, + 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, + 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, + 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ]; + +// Compute inverse SBOX lookup table +for (var INVSBOX = [], i = 0; i < 256; i++) INVSBOX[SBOX[i]] = i; + +// Compute mulitplication in GF(2^8) lookup tables +var MULT2 = [], + MULT3 = [], + MULT9 = [], + MULTB = [], + MULTD = [], + MULTE = []; + +function xtime(a, b) { + for (var result = 0, i = 0; i < 8; i++) { + if (b & 1) result ^= a; + var hiBitSet = a & 0x80; + a = (a << 1) & 0xFF; + if (hiBitSet) a ^= 0x1b; + b >>>= 1; + } + return result; +} + +for (var i = 0; i < 256; i++) { + MULT2[i] = xtime(i,2); + MULT3[i] = xtime(i,3); + MULT9[i] = xtime(i,9); + MULTB[i] = xtime(i,0xB); + MULTD[i] = xtime(i,0xD); + MULTE[i] = xtime(i,0xE); +} + +// Precomputed RCon lookup +var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + +// Inner state +var state = [[], [], [], []], + keylength, + nrounds, + keyschedule; + +var AES = C.AES = { + + /** + * Public API + */ + + encrypt: function (message, password, options) { + + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) mode.fixOptions(options); + + var + + // Convert to bytes if message is a string + m = ( + message.constructor == String ? + UTF8.stringToBytes(message) : + message + ), + + // Generate random IV + iv = options.iv || util.randomBytes(AES._blocksize * 4), + + // Generate key + k = ( + password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password + ); + + // Encrypt + AES._init(k); + mode.encrypt(AES, m, iv); + + // Return ciphertext + m = options.iv ? m : iv.concat(m); + return (options && options.asBytes) ? m : util.bytesToBase64(m); + + }, + + decrypt: function (ciphertext, password, options) { + + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) mode.fixOptions(options); + + var + + // Convert to bytes if ciphertext is a string + c = ( + ciphertext.constructor == String ? + util.base64ToBytes(ciphertext): + ciphertext + ), + + // Separate IV and message + iv = options.iv || c.splice(0, AES._blocksize * 4), + + // Generate key + k = ( + password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password + ); + + // Decrypt + AES._init(k); + mode.decrypt(AES, c, iv); + + // Return plaintext + return (options && options.asBytes) ? c : UTF8.bytesToString(c); + + }, + + + /** + * Package private methods and properties + */ + + _blocksize: 4, + + _encryptblock: function (m, offset) { + + // Set input + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = m[offset + col * 4 + row]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[col][row]; + } + + for (var round = 1; round < nrounds; round++) { + + // Sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = SBOX[state[row][col]]; + } + + // Shift rows + state[1].push(state[1].shift()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].unshift(state[3].pop()); + + // Mix columns + for (var col = 0; col < 4; col++) { + + var s0 = state[0][col], + s1 = state[1][col], + s2 = state[2][col], + s3 = state[3][col]; + + state[0][col] = MULT2[s0] ^ MULT3[s1] ^ s2 ^ s3; + state[1][col] = s0 ^ MULT2[s1] ^ MULT3[s2] ^ s3; + state[2][col] = s0 ^ s1 ^ MULT2[s2] ^ MULT3[s3]; + state[3][col] = MULT3[s0] ^ s1 ^ s2 ^ MULT2[s3]; + + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[round * 4 + col][row]; + } + + } + + // Sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = SBOX[state[row][col]]; + } + + // Shift rows + state[1].push(state[1].shift()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].unshift(state[3].pop()); + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[nrounds * 4 + col][row]; + } + + // Set output + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + m[offset + col * 4 + row] = state[row][col]; + } + + }, + + _decryptblock: function (c, offset) { + + // Set input + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = c[offset + col * 4 + row]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[nrounds * 4 + col][row]; + } + + for (var round = 1; round < nrounds; round++) { + + // Inv shift rows + state[1].unshift(state[1].pop()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].push(state[3].shift()); + + // Inv sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = INVSBOX[state[row][col]]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[(nrounds - round) * 4 + col][row]; + } + + // Inv mix columns + for (var col = 0; col < 4; col++) { + + var s0 = state[0][col], + s1 = state[1][col], + s2 = state[2][col], + s3 = state[3][col]; + + state[0][col] = MULTE[s0] ^ MULTB[s1] ^ MULTD[s2] ^ MULT9[s3]; + state[1][col] = MULT9[s0] ^ MULTE[s1] ^ MULTB[s2] ^ MULTD[s3]; + state[2][col] = MULTD[s0] ^ MULT9[s1] ^ MULTE[s2] ^ MULTB[s3]; + state[3][col] = MULTB[s0] ^ MULTD[s1] ^ MULT9[s2] ^ MULTE[s3]; + + } + + } + + // Inv shift rows + state[1].unshift(state[1].pop()); + state[2].push(state[2].shift()); + state[2].push(state[2].shift()); + state[3].push(state[3].shift()); + + // Inv sub bytes + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] = INVSBOX[state[row][col]]; + } + + // Add round key + for (var row = 0; row < 4; row++) { + for (var col = 0; col < 4; col++) + state[row][col] ^= keyschedule[col][row]; + } + + // Set output + for (var row = 0; row < AES._blocksize; row++) { + for (var col = 0; col < 4; col++) + c[offset + col * 4 + row] = state[row][col]; + } + + }, + + + /** + * Private methods + */ + + _init: function (k) { + keylength = k.length / 4; + nrounds = keylength + 6; + AES._keyexpansion(k); + }, + + // Generate a key schedule + _keyexpansion: function (k) { + + keyschedule = []; + + for (var row = 0; row < keylength; row++) { + keyschedule[row] = [ + k[row * 4], + k[row * 4 + 1], + k[row * 4 + 2], + k[row * 4 + 3] + ]; + } + + for (var row = keylength; row < AES._blocksize * (nrounds + 1); row++) { + + var temp = [ + keyschedule[row - 1][0], + keyschedule[row - 1][1], + keyschedule[row - 1][2], + keyschedule[row - 1][3] + ]; + + if (row % keylength == 0) { + + // Rot word + temp.push(temp.shift()); + + // Sub word + temp[0] = SBOX[temp[0]]; + temp[1] = SBOX[temp[1]]; + temp[2] = SBOX[temp[2]]; + temp[3] = SBOX[temp[3]]; + + temp[0] ^= RCON[row / keylength]; + + } else if (keylength > 6 && row % keylength == 4) { + + // Sub word + temp[0] = SBOX[temp[0]]; + temp[1] = SBOX[temp[1]]; + temp[2] = SBOX[temp[2]]; + temp[3] = SBOX[temp[3]]; + + } + + keyschedule[row] = [ + keyschedule[row - keylength][0] ^ temp[0], + keyschedule[row - keylength][1] ^ temp[1], + keyschedule[row - keylength][2] ^ temp[2], + keyschedule[row - keylength][3] ^ temp[3] + ]; + + } + + } + +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/BlockModes.js b/components/getPhoneNumer/utils/cryptojs/lib/BlockModes.js new file mode 100644 index 0000000..75ce720 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/BlockModes.js @@ -0,0 +1,378 @@ +/*! + * Crypto-JS contribution from Simon Greatrix + */ + +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Create pad namespace +var C_pad = C.pad = {}; + +// Calculate the number of padding bytes required. +function _requiredPadding(cipher, message) { + var blockSizeInBytes = cipher._blocksize * 4; + var reqd = blockSizeInBytes - message.length % blockSizeInBytes; + return reqd; +}; + +// Remove padding when the final byte gives the number of padding bytes. +var _unpadLength = function (message) { + var pad = message.pop(); + for (var i = 1; i < pad; i++) { + message.pop(); + } + }; + +// No-operation padding, used for stream ciphers +C_pad.NoPadding = { + pad : function (cipher,message) {}, + unpad : function (message) {} + }; + +// Zero Padding. +// +// If the message is not an exact number of blocks, the final block is +// completed with 0x00 bytes. There is no unpadding. +C_pad.ZeroPadding = { + pad : function (cipher, message) { + var blockSizeInBytes = cipher._blocksize * 4; + var reqd = message.length % blockSizeInBytes; + if( reqd!=0 ) { + for(reqd = blockSizeInBytes - reqd; reqd>0; reqd--) { + message.push(0x00); + } + } + }, + + unpad : function (message) {} +}; + +// ISO/IEC 7816-4 padding. +// +// Pads the plain text with an 0x80 byte followed by as many 0x00 +// bytes are required to complete the block. +C_pad.iso7816 = { + pad : function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + message.push(0x80); + for (; reqd > 1; reqd--) { + message.push(0x00); + } + }, + + unpad : function (message) { + while (message.pop() != 0x80) {} + } +}; + +// ANSI X.923 padding +// +// The final block is padded with zeros except for the last byte of the +// last block which contains the number of padding bytes. +C_pad.ansix923 = { + pad : function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 1; i < reqd; i++) { + message.push(0x00); + } + message.push(reqd); + }, + + unpad : _unpadLength +}; + +// ISO 10126 +// +// The final block is padded with random bytes except for the last +// byte of the last block which contains the number of padding bytes. +C_pad.iso10126 = { + pad : function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 1; i < reqd; i++) { + message.push(Math.floor(Math.random() * 256)); + } + message.push(reqd); + }, + + unpad : _unpadLength +}; + +// PKCS7 padding +// +// PKCS7 is described in RFC 5652. Padding is in whole bytes. The +// value of each added byte is the number of bytes that are added, +// i.e. N bytes, each of value N are added. +C_pad.pkcs7 = { + pad : function (cipher, message) { + var reqd = _requiredPadding(cipher, message); + for (var i = 0; i < reqd; i++) { + message.push(reqd); + } + }, + + unpad : _unpadLength +}; + +// Create mode namespace +var C_mode = C.mode = {}; + +/** + * Mode base "class". + */ +var Mode = C_mode.Mode = function (padding) { + if (padding) { + this._padding = padding; + } +}; + +Mode.prototype = { + encrypt: function (cipher, m, iv) { + this._padding.pad(cipher, m); + this._doEncrypt(cipher, m, iv); + }, + + decrypt: function (cipher, m, iv) { + this._doDecrypt(cipher, m, iv); + this._padding.unpad(m); + }, + + // Default padding + _padding: C_pad.iso7816 +}; + + +/** + * Electronic Code Book mode. + * + * ECB applies the cipher directly against each block of the input. + * + * ECB does not require an initialization vector. + */ +var ECB = C_mode.ECB = function () { + // Call parent constructor + Mode.apply(this, arguments); +}; + +// Inherit from Mode +var ECB_prototype = ECB.prototype = new Mode; + +// Concrete steps for Mode template +ECB_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + // Encrypt each block + for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { + cipher._encryptblock(m, offset); + } +}; +ECB_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + // Decrypt each block + for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { + cipher._decryptblock(c, offset); + } +}; + +// ECB never uses an IV +ECB_prototype.fixOptions = function (options) { + options.iv = []; +}; + + +/** + * Cipher block chaining + * + * The first block is XORed with the IV. Subsequent blocks are XOR with the + * previous cipher output. + */ +var CBC = C_mode.CBC = function () { + // Call parent constructor + Mode.apply(this, arguments); +}; + +// Inherit from Mode +var CBC_prototype = CBC.prototype = new Mode; + +// Concrete steps for Mode template +CBC_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + + // Encrypt each block + for (var offset = 0; offset < m.length; offset += blockSizeInBytes) { + if (offset == 0) { + // XOR first block using IV + for (var i = 0; i < blockSizeInBytes; i++) + m[i] ^= iv[i]; + } else { + // XOR this block using previous crypted block + for (var i = 0; i < blockSizeInBytes; i++) + m[offset + i] ^= m[offset + i - blockSizeInBytes]; + } + // Encrypt block + cipher._encryptblock(m, offset); + } +}; +CBC_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + + // At the start, the previously crypted block is the IV + var prevCryptedBlock = iv; + + // Decrypt each block + for (var offset = 0; offset < c.length; offset += blockSizeInBytes) { + // Save this crypted block + var thisCryptedBlock = c.slice(offset, offset + blockSizeInBytes); + // Decrypt block + cipher._decryptblock(c, offset); + // XOR decrypted block using previous crypted block + for (var i = 0; i < blockSizeInBytes; i++) { + c[offset + i] ^= prevCryptedBlock[i]; + } + prevCryptedBlock = thisCryptedBlock; + } +}; + + +/** + * Cipher feed back + * + * The cipher output is XORed with the plain text to produce the cipher output, + * which is then fed back into the cipher to produce a bit pattern to XOR the + * next block with. + * + * This is a stream cipher mode and does not require padding. + */ +var CFB = C_mode.CFB = function () { + // Call parent constructor + Mode.apply(this, arguments); +}; + +// Inherit from Mode +var CFB_prototype = CFB.prototype = new Mode; + +// Override padding +CFB_prototype._padding = C_pad.NoPadding; + +// Concrete steps for Mode template +CFB_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < m.length; i++) { + + var j = i % blockSizeInBytes; + if (j == 0) cipher._encryptblock(keystream, 0); + + m[i] ^= keystream[j]; + keystream[j] = m[i]; + } +}; +CFB_prototype._doDecrypt = function (cipher, c, iv) { + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < c.length; i++) { + + var j = i % blockSizeInBytes; + if (j == 0) cipher._encryptblock(keystream, 0); + + var b = c[i]; + c[i] ^= keystream[j]; + keystream[j] = b; + } +}; + + +/** + * Output feed back + * + * The cipher repeatedly encrypts its own output. The output is XORed with the + * plain text to produce the cipher text. + * + * This is a stream cipher mode and does not require padding. + */ +var OFB = C_mode.OFB = function () { + // Call parent constructor + Mode.apply(this, arguments); +}; + +// Inherit from Mode +var OFB_prototype = OFB.prototype = new Mode; + +// Override padding +OFB_prototype._padding = C_pad.NoPadding; + +// Concrete steps for Mode template +OFB_prototype._doEncrypt = function (cipher, m, iv) { + + var blockSizeInBytes = cipher._blocksize * 4, + keystream = iv.slice(0); + + // Encrypt each byte + for (var i = 0; i < m.length; i++) { + + // Generate keystream + if (i % blockSizeInBytes == 0) + cipher._encryptblock(keystream, 0); + + // Encrypt byte + m[i] ^= keystream[i % blockSizeInBytes]; + + } +}; +OFB_prototype._doDecrypt = OFB_prototype._doEncrypt; + +/** + * Counter + * @author Gergely Risko + * + * After every block the last 4 bytes of the IV is increased by one + * with carry and that IV is used for the next block. + * + * This is a stream cipher mode and does not require padding. + */ +var CTR = C_mode.CTR = function () { + // Call parent constructor + Mode.apply(this, arguments); +}; + +// Inherit from Mode +var CTR_prototype = CTR.prototype = new Mode; + +// Override padding +CTR_prototype._padding = C_pad.NoPadding; + +CTR_prototype._doEncrypt = function (cipher, m, iv) { + var blockSizeInBytes = cipher._blocksize * 4; + var counter = iv.slice(0); + + for (var i = 0; i < m.length;) { + // do not lose iv + var keystream = counter.slice(0); + + // Generate keystream for next block + cipher._encryptblock(keystream, 0); + + // XOR keystream with block + for (var j = 0; i < m.length && j < blockSizeInBytes; j++, i++) { + m[i] ^= keystream[j]; + } + + // Increase counter + if(++(counter[blockSizeInBytes-1]) == 256) { + counter[blockSizeInBytes-1] = 0; + if(++(counter[blockSizeInBytes-2]) == 256) { + counter[blockSizeInBytes-2] = 0; + if(++(counter[blockSizeInBytes-3]) == 256) { + counter[blockSizeInBytes-3] = 0; + ++(counter[blockSizeInBytes-4]); + } + } + } + } +}; +CTR_prototype._doDecrypt = CTR_prototype._doEncrypt; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/Crypto.js b/components/getPhoneNumer/utils/cryptojs/lib/Crypto.js new file mode 100644 index 0000000..e375736 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/Crypto.js @@ -0,0 +1,155 @@ +if (typeof Crypto == "undefined" || ! Crypto.util) +{ +(function(){ + +var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// Global Crypto object +// with browser window or with node module +var Crypto = (typeof window === 'undefined') ? exports.Crypto = {} : window.Crypto = {}; + +// Crypto utilities +var util = Crypto.util = { + + // Bit-wise rotate left + rotl: function (n, b) { + return (n << b) | (n >>> (32 - b)); + }, + + // Bit-wise rotate right + rotr: function (n, b) { + return (n << (32 - b)) | (n >>> b); + }, + + // Swap big-endian to little-endian and vice versa + endian: function (n) { + + // If number given, swap endian + if (n.constructor == Number) { + return util.rotl(n, 8) & 0x00FF00FF | + util.rotl(n, 24) & 0xFF00FF00; + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = util.endian(n[i]); + return n; + + }, + + // Generate an array of any length of random bytes + randomBytes: function (n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function (bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); + return words; + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function (words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, + + // Convert a byte array to a hex string + bytesToHex: function (bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(""); + }, + + // Convert a hex string to a byte array + hexToBytes: function (hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function (bytes) { + + // Use browser-native function if it exists + if (typeof btoa == "function") return btoa(Binary.bytesToString(bytes)); + + for(var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) { + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else base64.push("="); + } + } + + return base64.join(""); + + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function (base64) { + + // Use browser-native function if it exists + if (typeof atob == "function") return Binary.stringToBytes(atob(base64)); + + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | + (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + + return bytes; + + } + +}; + +// Crypto character encodings +var charenc = Crypto.charenc = {}; + +// UTF-8 encoding +var UTF8 = charenc.UTF8 = { + + // Convert a string to a byte array + stringToBytes: function (str) { + return Binary.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + return decodeURIComponent(escape(Binary.bytesToString(bytes))); + } + +}; + +// Binary encoding +var Binary = charenc.Binary = { + + // Convert a string to a byte array + stringToBytes: function (str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function (bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(""); + } + +}; + +})(); +} diff --git a/components/getPhoneNumer/utils/cryptojs/lib/CryptoMath.js b/components/getPhoneNumer/utils/cryptojs/lib/CryptoMath.js new file mode 100644 index 0000000..4f8bdbf --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/CryptoMath.js @@ -0,0 +1,37 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcut +var util = C.util; + +// Convert n to unsigned 32-bit integer +util.u32 = function (n) { + return n >>> 0; +}; + +// Unsigned 32-bit addition +util.add = function () { + var result = this.u32(arguments[0]); + for (var i = 1; i < arguments.length; i++) + result = this.u32(result + this.u32(arguments[i])); + return result; +}; + +// Unsigned 32-bit multiplication +util.mult = function (m, n) { + return this.add((n & 0xFFFF0000) * m, + (n & 0x0000FFFF) * m); +}; + +// Unsigned 32-bit greater than (>) comparison +util.gt = function (m, n) { + return this.u32(m) > this.u32(n); +}; + +// Unsigned 32-bit less than (<) comparison +util.lt = function (m, n) { + return this.u32(m) < this.u32(n); +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/DES.js b/components/getPhoneNumer/utils/cryptojs/lib/DES.js new file mode 100644 index 0000000..760138b --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/DES.js @@ -0,0 +1,1003 @@ +/** + * Definition of Data Encryption Standard (DES) taken from: + * http://www.itl.nist.gov/fipspubs/fip46-2.htm + */ + +(function() { + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + + // Shortcuts + var util = C.util, charenc = C.charenc, UTF8 = charenc.UTF8; + + /*************************************************************************** + * + * DES Key Schedule. + * + * The Key consists of 16 sub-keys of 48 bits each. As each sub-key is + * applied to an expanded 32-bit value where each 4 bits of input is + * expanded into 6 bits of output the sub-key can be broken down into 8 + * 32-bit values which allows the key to be used without expansion. + * + * To create the 16 sub-keys, 56 bits are selected from the input 64 bit key + * according to PC1. Each sub-key is generated by left rotating the + * bits a different amount and then selecting 48 bits according to PC2. + * + **************************************************************************/ + + var KeySchedule; + + /** + * Representation of a DES key schedule. + * + * @param {Array + * of 8 bytes} key The cipher key + * + * @constructor + */ + KeySchedule = function(key) { + /** + * The schedule of 16 keys + */ + this.keys = new Array(16); + this._initialiseKeys(key); + }; + + /** + * Permuted Choice 1 (PC1) byte offsets into the key. Each of the 56 entries + * selects one bit of DES's 56 bit key. + *

+ * + *

+     * The PC1 is defined as:
+     * 
+     * 57,   49,    41,   33,    25,    17,    9,
+     *  1,   58,    50,   42,    34,    26,   18,
+     * 10,    2,    59,   51,    43,    35,   27,
+     * 19,   11,     3,   60,    52,    44,   36,
+     * 63,   55,    47,   39,    31,    23,   15,
+     *  7,   62,    54,   46,    38,    30,   22,
+     * 14,    6,    61,   53,    45,    37,   29,
+     * 21,   13,     5,   28,    20,    12,    4
+     * 
+ * + * We represent this as an offset into an 8-byte array and a bit mask upon + * that byte. For example 57=(7*8)+1 so is the first (MSB) of the 7th byte. + * + * @constant + */ + KeySchedule.PC1_offsets = [ 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, + 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 7, 6, 5, 4, 3, 2, 1, 0, 7, 6, + 5, 4, 3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 0, 3, 2, 1, 0 ]; + + /** + * Permuted Choice 1 (PC1) bit masks. Each of the 56 entries selects one bit + * of DES's 56 bit key. + * + * @constant + */ + KeySchedule.PC1_masks = [ 128, 128, 128, 128, 128, 128, 128, 128, 64, 64, + 64, 64, 64, 64, 64, 64, 32, 32, 32, 32, 32, 32, 32, 32, 16, 16, 16, + 16, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, + 8, 8, 8, 16, 16, 16, 16 ]; + + /** + * Permuted Choice 2 (PC2) selects the active 48 bits from the 56 bits of + * the key. + *

+ * + *

+     * The PC2 is defined as:
+     * 
+     * 14,   17,   11,   24,    1,    5,
+     *  3,   28,   15,    6,   21,   10,
+     * 23,   19,   12,    4,   26,    8,
+     * 16,    7,   27,   20,   13,    2,
+     * 41,   52,   31,   37,   47,   55,
+     * 30,   40,   51,   45,   33,   48,
+     * 44,   49,   39,   56,   34,   53,
+     * 46,   42,   50,   36,   29,   32
+     * 
+ * + * We invert the choice to specify what each bit adds to each 6-bit value of + * the key. For example, bit 1 is the 5th bit selected so this add 2 to the + * first 6-bit value. + * + * @constant + */ + KeySchedule.PC2_offsets1 = [ 0, 3, 1, 2, 0, 1, 3, 2, 0, 1, 0, 2, 3, 0, 1, + 3, 0, 0, 2, 3, 1, 0, 2, 0, 0, 2, 3, 1 ]; + + /** + * PC2 offsets for 2nd block. + * + * @constant + */ + KeySchedule.PC2_offsets2 = [ 7, 5, 4, 7, 5, 6, 0, 7, 4, 0, 6, 5, 4, 7, 0, + 6, 5, 7, 4, 5, 6, 7, 5, 4, 6, 0, 4, 6 ]; + + /** + * Permuted Choice 2 (PC2) masks for 1st block. + * + * @constant + */ + KeySchedule.PC2_masks1 = [ 2, 1, 32, 4, 1, 4, 16, 1, 0, 1, 8, 8, 2, 32, 8, + 32, 16, 0, 16, 4, 2, 0, 32, 4, 0, 2, 8, 16 ]; + + /** + * PC2 masks for 2nd block. + * + * @constant + */ + KeySchedule.PC2_masks2 = [ 2, 32, 8, 1, 2, 2, 0, 4, 4, 0, 8, 16, 32, 16, 0, + 32, 4, 32, 2, 1, 16, 8, 8, 16, 1, 0, 1, 4 ]; + + /** + * Cumulative key shifts. + * + * @constant + */ + KeySchedule.keyShifts = [ 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, + 25, 27, 28 ]; + + KeySchedule.prototype._initialiseKeys = function(key) { + var i; + + // extract 56 key bits in order determined by PC1 + var bits = new Array(56); + for (i = 0; i < 56; i++) { + bits[i] = (key[KeySchedule.PC1_offsets[i]] & KeySchedule.PC1_masks[i]) != 0; + } + + // split 56 bits into two 28-bit chunks + var bits1 = bits.slice(0, 28); + var bits2 = bits.slice(28, 56); + + // duplicate each half to allow for easy bit shifts + bits1 = bits1.concat(bits1); + bits2 = bits2.concat(bits2); + + // assemble the 16 keys + for (i = 0; i < 16; i++) { + var k = [ 0, 0, 0, 0, 0, 0, 0, 0 ]; + + // select the bits of the key according to PC2 + var s = KeySchedule.keyShifts[i]; + for ( var j = 0; j < 28; j++) { + if (bits1[j + s]) { + k[KeySchedule.PC2_offsets1[j]] += KeySchedule.PC2_masks1[j]; + } + if (bits2[j + s]) { + k[KeySchedule.PC2_offsets2[j]] += KeySchedule.PC2_masks2[j]; + } + } + + // Scale each of the 8 blocks to a 32-bit mask. + k[0] = ((k[0] & 0x1f) << 27) + ((k[0] & 0x20) >> 5); + for ( var j = 1; j <= 6; j++) { + k[j] = k[j] << (27 - 4 * j); + } + k[7] = ((k[7] & 0x3e) >> 1) + ((k[7] & 0x1) << 31); + this.keys[i] = k; + } + }; + + /** + * Retrieve the key for a specified round + * + * @param i + * the round + * @returns the key + */ + KeySchedule.prototype.getKey = function(i) { + return this.keys[i]; + }; + + /*************************************************************************** + * + * DES Engine State + * + **************************************************************************/ + + var State; + + /** + * The algorithm's state. DES operates on two sets of 32-bits, with each + * block of 32-bits treated as a single number. + * + * @class + */ + State = function() { + /** The LHS of the Feistel scheme */ + this.lhs = 0; + /** The RHS of the Feistel scheme */ + this.rhs = 0; + }; + + /** + * The masks that select the SBOX input. Each SBOX accepts 6 bits from the + * input. + * + * @constant + */ + State.SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, + 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; + + /** + * The SBOXes. The 8 SBOXes each map 6 bit masked bit of the input to 4 bits + * of output. These SBOXes include the post SBOX permutation and benefit + * from JavaScript's sparse arrays to make specifying the input match + * simple. + * + * @constant + */ + State.SBOX = new Array(8); + + var SBOX = State.SBOX; + + SBOX[0] = new Array(); + SBOX[0][0] = 0x808200; // 0 (0, 0) = 14 + SBOX[0][268435456] = 0x8000; // 10000000 (0, 1) = 4 + SBOX[0][536870912] = 0x808002; // 20000000 (0, 2) = 13 + SBOX[0][805306368] = 0x2; // 30000000 (0, 3) = 1 + SBOX[0][1073741824] = 0x200; // 40000000 (0, 4) = 2 + SBOX[0][1342177280] = 0x808202; // 50000000 (0, 5) = 15 + SBOX[0][1610612736] = 0x800202; // 60000000 (0, 6) = 11 + SBOX[0][1879048192] = 0x800000; // 70000000 (0, 7) = 8 + SBOX[0][-2147483648] = 0x202; // 80000000 (0, 8) = 3 + SBOX[0][-1879048192] = 0x800200; // 90000000 (0, 9) = 10 + SBOX[0][-1610612736] = 0x8200; // a0000000 (0, 10) = 6 + SBOX[0][-1342177280] = 0x808000; // b0000000 (0, 11) = 12 + SBOX[0][-1073741824] = 0x8002; // c0000000 (0, 12) = 5 + SBOX[0][-805306368] = 0x800002; // d0000000 (0, 13) = 9 + SBOX[0][-536870912] = 0x0; // e0000000 (0, 14) = 0 + SBOX[0][-268435456] = 0x8202; // f0000000 (0, 15) = 7 + SBOX[0][134217728] = 0x0; // 8000000 (1, 0) = 0 + SBOX[0][402653184] = 0x808202; // 18000000 (1, 1) = 15 + SBOX[0][671088640] = 0x8202; // 28000000 (1, 2) = 7 + SBOX[0][939524096] = 0x8000; // 38000000 (1, 3) = 4 + SBOX[0][1207959552] = 0x808200; // 48000000 (1, 4) = 14 + SBOX[0][1476395008] = 0x200; // 58000000 (1, 5) = 2 + SBOX[0][1744830464] = 0x808002; // 68000000 (1, 6) = 13 + SBOX[0][2013265920] = 0x2; // 78000000 (1, 7) = 1 + SBOX[0][-2013265920] = 0x800200; // 88000000 (1, 8) = 10 + SBOX[0][-1744830464] = 0x8200; // 98000000 (1, 9) = 6 + SBOX[0][-1476395008] = 0x808000; // a8000000 (1, 10) = 12 + SBOX[0][-1207959552] = 0x800202; // b8000000 (1, 11) = 11 + SBOX[0][-939524096] = 0x800002; // c8000000 (1, 12) = 9 + SBOX[0][-671088640] = 0x8002; // d8000000 (1, 13) = 5 + SBOX[0][-402653184] = 0x202; // e8000000 (1, 14) = 3 + SBOX[0][-134217728] = 0x800000; // f8000000 (1, 15) = 8 + SBOX[0][1] = 0x8000; // 1 (2, 0) = 4 + SBOX[0][268435457] = 0x2; // 10000001 (2, 1) = 1 + SBOX[0][536870913] = 0x808200; // 20000001 (2, 2) = 14 + SBOX[0][805306369] = 0x800000; // 30000001 (2, 3) = 8 + SBOX[0][1073741825] = 0x808002; // 40000001 (2, 4) = 13 + SBOX[0][1342177281] = 0x8200; // 50000001 (2, 5) = 6 + SBOX[0][1610612737] = 0x200; // 60000001 (2, 6) = 2 + SBOX[0][1879048193] = 0x800202; // 70000001 (2, 7) = 11 + SBOX[0][-2147483647] = 0x808202; // 80000001 (2, 8) = 15 + SBOX[0][-1879048191] = 0x808000; // 90000001 (2, 9) = 12 + SBOX[0][-1610612735] = 0x800002; // a0000001 (2, 10) = 9 + SBOX[0][-1342177279] = 0x8202; // b0000001 (2, 11) = 7 + SBOX[0][-1073741823] = 0x202; // c0000001 (2, 12) = 3 + SBOX[0][-805306367] = 0x800200; // d0000001 (2, 13) = 10 + SBOX[0][-536870911] = 0x8002; // e0000001 (2, 14) = 5 + SBOX[0][-268435455] = 0x0; // f0000001 (2, 15) = 0 + SBOX[0][134217729] = 0x808202; // 8000001 (3, 0) = 15 + SBOX[0][402653185] = 0x808000; // 18000001 (3, 1) = 12 + SBOX[0][671088641] = 0x800000; // 28000001 (3, 2) = 8 + SBOX[0][939524097] = 0x200; // 38000001 (3, 3) = 2 + SBOX[0][1207959553] = 0x8000; // 48000001 (3, 4) = 4 + SBOX[0][1476395009] = 0x800002; // 58000001 (3, 5) = 9 + SBOX[0][1744830465] = 0x2; // 68000001 (3, 6) = 1 + SBOX[0][2013265921] = 0x8202; // 78000001 (3, 7) = 7 + SBOX[0][-2013265919] = 0x8002; // 88000001 (3, 8) = 5 + SBOX[0][-1744830463] = 0x800202; // 98000001 (3, 9) = 11 + SBOX[0][-1476395007] = 0x202; // a8000001 (3, 10) = 3 + SBOX[0][-1207959551] = 0x808200; // b8000001 (3, 11) = 14 + SBOX[0][-939524095] = 0x800200; // c8000001 (3, 12) = 10 + SBOX[0][-671088639] = 0x0; // d8000001 (3, 13) = 0 + SBOX[0][-402653183] = 0x8200; // e8000001 (3, 14) = 6 + SBOX[0][-134217727] = 0x808002; // f8000001 (3, 15) = 13 + + SBOX[1] = new Array(); + SBOX[1][0] = 0x40084010; // 0 (0, 0) = 15 + SBOX[1][16777216] = 0x4000; // 1000000 (0, 1) = 1 + SBOX[1][33554432] = 0x80000; // 2000000 (0, 2) = 8 + SBOX[1][50331648] = 0x40080010; // 3000000 (0, 3) = 14 + SBOX[1][67108864] = 0x40000010; // 4000000 (0, 4) = 6 + SBOX[1][83886080] = 0x40084000; // 5000000 (0, 5) = 11 + SBOX[1][100663296] = 0x40004000; // 6000000 (0, 6) = 3 + SBOX[1][117440512] = 0x10; // 7000000 (0, 7) = 4 + SBOX[1][134217728] = 0x84000; // 8000000 (0, 8) = 9 + SBOX[1][150994944] = 0x40004010; // 9000000 (0, 9) = 7 + SBOX[1][167772160] = 0x40000000; // a000000 (0, 10) = 2 + SBOX[1][184549376] = 0x84010; // b000000 (0, 11) = 13 + SBOX[1][201326592] = 0x80010; // c000000 (0, 12) = 12 + SBOX[1][218103808] = 0x0; // d000000 (0, 13) = 0 + SBOX[1][234881024] = 0x4010; // e000000 (0, 14) = 5 + SBOX[1][251658240] = 0x40080000; // f000000 (0, 15) = 10 + SBOX[1][8388608] = 0x40004000; // 800000 (1, 0) = 3 + SBOX[1][25165824] = 0x84010; // 1800000 (1, 1) = 13 + SBOX[1][41943040] = 0x10; // 2800000 (1, 2) = 4 + SBOX[1][58720256] = 0x40004010; // 3800000 (1, 3) = 7 + SBOX[1][75497472] = 0x40084010; // 4800000 (1, 4) = 15 + SBOX[1][92274688] = 0x40000000; // 5800000 (1, 5) = 2 + SBOX[1][109051904] = 0x80000; // 6800000 (1, 6) = 8 + SBOX[1][125829120] = 0x40080010; // 7800000 (1, 7) = 14 + SBOX[1][142606336] = 0x80010; // 8800000 (1, 8) = 12 + SBOX[1][159383552] = 0x0; // 9800000 (1, 9) = 0 + SBOX[1][176160768] = 0x4000; // a800000 (1, 10) = 1 + SBOX[1][192937984] = 0x40080000; // b800000 (1, 11) = 10 + SBOX[1][209715200] = 0x40000010; // c800000 (1, 12) = 6 + SBOX[1][226492416] = 0x84000; // d800000 (1, 13) = 9 + SBOX[1][243269632] = 0x40084000; // e800000 (1, 14) = 11 + SBOX[1][260046848] = 0x4010; // f800000 (1, 15) = 5 + SBOX[1][268435456] = 0x0; // 10000000 (2, 0) = 0 + SBOX[1][285212672] = 0x40080010; // 11000000 (2, 1) = 14 + SBOX[1][301989888] = 0x40004010; // 12000000 (2, 2) = 7 + SBOX[1][318767104] = 0x40084000; // 13000000 (2, 3) = 11 + SBOX[1][335544320] = 0x40080000; // 14000000 (2, 4) = 10 + SBOX[1][352321536] = 0x10; // 15000000 (2, 5) = 4 + SBOX[1][369098752] = 0x84010; // 16000000 (2, 6) = 13 + SBOX[1][385875968] = 0x4000; // 17000000 (2, 7) = 1 + SBOX[1][402653184] = 0x4010; // 18000000 (2, 8) = 5 + SBOX[1][419430400] = 0x80000; // 19000000 (2, 9) = 8 + SBOX[1][436207616] = 0x80010; // 1a000000 (2, 10) = 12 + SBOX[1][452984832] = 0x40000010; // 1b000000 (2, 11) = 6 + SBOX[1][469762048] = 0x84000; // 1c000000 (2, 12) = 9 + SBOX[1][486539264] = 0x40004000; // 1d000000 (2, 13) = 3 + SBOX[1][503316480] = 0x40000000; // 1e000000 (2, 14) = 2 + SBOX[1][520093696] = 0x40084010; // 1f000000 (2, 15) = 15 + SBOX[1][276824064] = 0x84010; // 10800000 (3, 0) = 13 + SBOX[1][293601280] = 0x80000; // 11800000 (3, 1) = 8 + SBOX[1][310378496] = 0x40080000; // 12800000 (3, 2) = 10 + SBOX[1][327155712] = 0x4000; // 13800000 (3, 3) = 1 + SBOX[1][343932928] = 0x40004000; // 14800000 (3, 4) = 3 + SBOX[1][360710144] = 0x40084010; // 15800000 (3, 5) = 15 + SBOX[1][377487360] = 0x10; // 16800000 (3, 6) = 4 + SBOX[1][394264576] = 0x40000000; // 17800000 (3, 7) = 2 + SBOX[1][411041792] = 0x40084000; // 18800000 (3, 8) = 11 + SBOX[1][427819008] = 0x40000010; // 19800000 (3, 9) = 6 + SBOX[1][444596224] = 0x40004010; // 1a800000 (3, 10) = 7 + SBOX[1][461373440] = 0x80010; // 1b800000 (3, 11) = 12 + SBOX[1][478150656] = 0x0; // 1c800000 (3, 12) = 0 + SBOX[1][494927872] = 0x4010; // 1d800000 (3, 13) = 5 + SBOX[1][511705088] = 0x40080010; // 1e800000 (3, 14) = 14 + SBOX[1][528482304] = 0x84000; // 1f800000 (3, 15) = 9 + + SBOX[2] = new Array(); + SBOX[2][0] = 0x104; // 0 (0, 0) = 10 + SBOX[2][1048576] = 0x0; // 100000 (0, 1) = 0 + SBOX[2][2097152] = 0x4000100; // 200000 (0, 2) = 9 + SBOX[2][3145728] = 0x10104; // 300000 (0, 3) = 14 + SBOX[2][4194304] = 0x10004; // 400000 (0, 4) = 6 + SBOX[2][5242880] = 0x4000004; // 500000 (0, 5) = 3 + SBOX[2][6291456] = 0x4010104; // 600000 (0, 6) = 15 + SBOX[2][7340032] = 0x4010000; // 700000 (0, 7) = 5 + SBOX[2][8388608] = 0x4000000; // 800000 (0, 8) = 1 + SBOX[2][9437184] = 0x4010100; // 900000 (0, 9) = 13 + SBOX[2][10485760] = 0x10100; // a00000 (0, 10) = 12 + SBOX[2][11534336] = 0x4010004; // b00000 (0, 11) = 7 + SBOX[2][12582912] = 0x4000104; // c00000 (0, 12) = 11 + SBOX[2][13631488] = 0x10000; // d00000 (0, 13) = 4 + SBOX[2][14680064] = 0x4; // e00000 (0, 14) = 2 + SBOX[2][15728640] = 0x100; // f00000 (0, 15) = 8 + SBOX[2][524288] = 0x4010100; // 80000 (1, 0) = 13 + SBOX[2][1572864] = 0x4010004; // 180000 (1, 1) = 7 + SBOX[2][2621440] = 0x0; // 280000 (1, 2) = 0 + SBOX[2][3670016] = 0x4000100; // 380000 (1, 3) = 9 + SBOX[2][4718592] = 0x4000004; // 480000 (1, 4) = 3 + SBOX[2][5767168] = 0x10000; // 580000 (1, 5) = 4 + SBOX[2][6815744] = 0x10004; // 680000 (1, 6) = 6 + SBOX[2][7864320] = 0x104; // 780000 (1, 7) = 10 + SBOX[2][8912896] = 0x4; // 880000 (1, 8) = 2 + SBOX[2][9961472] = 0x100; // 980000 (1, 9) = 8 + SBOX[2][11010048] = 0x4010000; // a80000 (1, 10) = 5 + SBOX[2][12058624] = 0x10104; // b80000 (1, 11) = 14 + SBOX[2][13107200] = 0x10100; // c80000 (1, 12) = 12 + SBOX[2][14155776] = 0x4000104; // d80000 (1, 13) = 11 + SBOX[2][15204352] = 0x4010104; // e80000 (1, 14) = 15 + SBOX[2][16252928] = 0x4000000; // f80000 (1, 15) = 1 + SBOX[2][16777216] = 0x4010100; // 1000000 (2, 0) = 13 + SBOX[2][17825792] = 0x10004; // 1100000 (2, 1) = 6 + SBOX[2][18874368] = 0x10000; // 1200000 (2, 2) = 4 + SBOX[2][19922944] = 0x4000100; // 1300000 (2, 3) = 9 + SBOX[2][20971520] = 0x100; // 1400000 (2, 4) = 8 + SBOX[2][22020096] = 0x4010104; // 1500000 (2, 5) = 15 + SBOX[2][23068672] = 0x4000004; // 1600000 (2, 6) = 3 + SBOX[2][24117248] = 0x0; // 1700000 (2, 7) = 0 + SBOX[2][25165824] = 0x4000104; // 1800000 (2, 8) = 11 + SBOX[2][26214400] = 0x4000000; // 1900000 (2, 9) = 1 + SBOX[2][27262976] = 0x4; // 1a00000 (2, 10) = 2 + SBOX[2][28311552] = 0x10100; // 1b00000 (2, 11) = 12 + SBOX[2][29360128] = 0x4010000; // 1c00000 (2, 12) = 5 + SBOX[2][30408704] = 0x104; // 1d00000 (2, 13) = 10 + SBOX[2][31457280] = 0x10104; // 1e00000 (2, 14) = 14 + SBOX[2][32505856] = 0x4010004; // 1f00000 (2, 15) = 7 + SBOX[2][17301504] = 0x4000000; // 1080000 (3, 0) = 1 + SBOX[2][18350080] = 0x104; // 1180000 (3, 1) = 10 + SBOX[2][19398656] = 0x4010100; // 1280000 (3, 2) = 13 + SBOX[2][20447232] = 0x0; // 1380000 (3, 3) = 0 + SBOX[2][21495808] = 0x10004; // 1480000 (3, 4) = 6 + SBOX[2][22544384] = 0x4000100; // 1580000 (3, 5) = 9 + SBOX[2][23592960] = 0x100; // 1680000 (3, 6) = 8 + SBOX[2][24641536] = 0x4010004; // 1780000 (3, 7) = 7 + SBOX[2][25690112] = 0x10000; // 1880000 (3, 8) = 4 + SBOX[2][26738688] = 0x4010104; // 1980000 (3, 9) = 15 + SBOX[2][27787264] = 0x10104; // 1a80000 (3, 10) = 14 + SBOX[2][28835840] = 0x4000004; // 1b80000 (3, 11) = 3 + SBOX[2][29884416] = 0x4000104; // 1c80000 (3, 12) = 11 + SBOX[2][30932992] = 0x4010000; // 1d80000 (3, 13) = 5 + SBOX[2][31981568] = 0x4; // 1e80000 (3, 14) = 2 + SBOX[2][33030144] = 0x10100; // 1f80000 (3, 15) = 12 + + SBOX[3] = new Array(); + SBOX[3][0] = 0x80401000; // 0 (0, 0) = 7 + SBOX[3][65536] = 0x80001040; // 10000 (0, 1) = 13 + SBOX[3][131072] = 0x401040; // 20000 (0, 2) = 14 + SBOX[3][196608] = 0x80400000; // 30000 (0, 3) = 3 + SBOX[3][262144] = 0x0; // 40000 (0, 4) = 0 + SBOX[3][327680] = 0x401000; // 50000 (0, 5) = 6 + SBOX[3][393216] = 0x80000040; // 60000 (0, 6) = 9 + SBOX[3][458752] = 0x400040; // 70000 (0, 7) = 10 + SBOX[3][524288] = 0x80000000; // 80000 (0, 8) = 1 + SBOX[3][589824] = 0x400000; // 90000 (0, 9) = 2 + SBOX[3][655360] = 0x40; // a0000 (0, 10) = 8 + SBOX[3][720896] = 0x80001000; // b0000 (0, 11) = 5 + SBOX[3][786432] = 0x80400040; // c0000 (0, 12) = 11 + SBOX[3][851968] = 0x1040; // d0000 (0, 13) = 12 + SBOX[3][917504] = 0x1000; // e0000 (0, 14) = 4 + SBOX[3][983040] = 0x80401040; // f0000 (0, 15) = 15 + SBOX[3][32768] = 0x80001040; // 8000 (1, 0) = 13 + SBOX[3][98304] = 0x40; // 18000 (1, 1) = 8 + SBOX[3][163840] = 0x80400040; // 28000 (1, 2) = 11 + SBOX[3][229376] = 0x80001000; // 38000 (1, 3) = 5 + SBOX[3][294912] = 0x401000; // 48000 (1, 4) = 6 + SBOX[3][360448] = 0x80401040; // 58000 (1, 5) = 15 + SBOX[3][425984] = 0x0; // 68000 (1, 6) = 0 + SBOX[3][491520] = 0x80400000; // 78000 (1, 7) = 3 + SBOX[3][557056] = 0x1000; // 88000 (1, 8) = 4 + SBOX[3][622592] = 0x80401000; // 98000 (1, 9) = 7 + SBOX[3][688128] = 0x400000; // a8000 (1, 10) = 2 + SBOX[3][753664] = 0x1040; // b8000 (1, 11) = 12 + SBOX[3][819200] = 0x80000000; // c8000 (1, 12) = 1 + SBOX[3][884736] = 0x400040; // d8000 (1, 13) = 10 + SBOX[3][950272] = 0x401040; // e8000 (1, 14) = 14 + SBOX[3][1015808] = 0x80000040; // f8000 (1, 15) = 9 + SBOX[3][1048576] = 0x400040; // 100000 (2, 0) = 10 + SBOX[3][1114112] = 0x401000; // 110000 (2, 1) = 6 + SBOX[3][1179648] = 0x80000040; // 120000 (2, 2) = 9 + SBOX[3][1245184] = 0x0; // 130000 (2, 3) = 0 + SBOX[3][1310720] = 0x1040; // 140000 (2, 4) = 12 + SBOX[3][1376256] = 0x80400040; // 150000 (2, 5) = 11 + SBOX[3][1441792] = 0x80401000; // 160000 (2, 6) = 7 + SBOX[3][1507328] = 0x80001040; // 170000 (2, 7) = 13 + SBOX[3][1572864] = 0x80401040; // 180000 (2, 8) = 15 + SBOX[3][1638400] = 0x80000000; // 190000 (2, 9) = 1 + SBOX[3][1703936] = 0x80400000; // 1a0000 (2, 10) = 3 + SBOX[3][1769472] = 0x401040; // 1b0000 (2, 11) = 14 + SBOX[3][1835008] = 0x80001000; // 1c0000 (2, 12) = 5 + SBOX[3][1900544] = 0x400000; // 1d0000 (2, 13) = 2 + SBOX[3][1966080] = 0x40; // 1e0000 (2, 14) = 8 + SBOX[3][2031616] = 0x1000; // 1f0000 (2, 15) = 4 + SBOX[3][1081344] = 0x80400000; // 108000 (3, 0) = 3 + SBOX[3][1146880] = 0x80401040; // 118000 (3, 1) = 15 + SBOX[3][1212416] = 0x0; // 128000 (3, 2) = 0 + SBOX[3][1277952] = 0x401000; // 138000 (3, 3) = 6 + SBOX[3][1343488] = 0x400040; // 148000 (3, 4) = 10 + SBOX[3][1409024] = 0x80000000; // 158000 (3, 5) = 1 + SBOX[3][1474560] = 0x80001040; // 168000 (3, 6) = 13 + SBOX[3][1540096] = 0x40; // 178000 (3, 7) = 8 + SBOX[3][1605632] = 0x80000040; // 188000 (3, 8) = 9 + SBOX[3][1671168] = 0x1000; // 198000 (3, 9) = 4 + SBOX[3][1736704] = 0x80001000; // 1a8000 (3, 10) = 5 + SBOX[3][1802240] = 0x80400040; // 1b8000 (3, 11) = 11 + SBOX[3][1867776] = 0x1040; // 1c8000 (3, 12) = 12 + SBOX[3][1933312] = 0x80401000; // 1d8000 (3, 13) = 7 + SBOX[3][1998848] = 0x400000; // 1e8000 (3, 14) = 2 + SBOX[3][2064384] = 0x401040; // 1f8000 (3, 15) = 14 + + SBOX[4] = new Array(); + SBOX[4][0] = 0x80; // 0 (0, 0) = 2 + SBOX[4][4096] = 0x1040000; // 1000 (0, 1) = 12 + SBOX[4][8192] = 0x40000; // 2000 (0, 2) = 4 + SBOX[4][12288] = 0x20000000; // 3000 (0, 3) = 1 + SBOX[4][16384] = 0x20040080; // 4000 (0, 4) = 7 + SBOX[4][20480] = 0x1000080; // 5000 (0, 5) = 10 + SBOX[4][24576] = 0x21000080; // 6000 (0, 6) = 11 + SBOX[4][28672] = 0x40080; // 7000 (0, 7) = 6 + SBOX[4][32768] = 0x1000000; // 8000 (0, 8) = 8 + SBOX[4][36864] = 0x20040000; // 9000 (0, 9) = 5 + SBOX[4][40960] = 0x20000080; // a000 (0, 10) = 3 + SBOX[4][45056] = 0x21040080; // b000 (0, 11) = 15 + SBOX[4][49152] = 0x21040000; // c000 (0, 12) = 13 + SBOX[4][53248] = 0x0; // d000 (0, 13) = 0 + SBOX[4][57344] = 0x1040080; // e000 (0, 14) = 14 + SBOX[4][61440] = 0x21000000; // f000 (0, 15) = 9 + SBOX[4][2048] = 0x1040080; // 800 (1, 0) = 14 + SBOX[4][6144] = 0x21000080; // 1800 (1, 1) = 11 + SBOX[4][10240] = 0x80; // 2800 (1, 2) = 2 + SBOX[4][14336] = 0x1040000; // 3800 (1, 3) = 12 + SBOX[4][18432] = 0x40000; // 4800 (1, 4) = 4 + SBOX[4][22528] = 0x20040080; // 5800 (1, 5) = 7 + SBOX[4][26624] = 0x21040000; // 6800 (1, 6) = 13 + SBOX[4][30720] = 0x20000000; // 7800 (1, 7) = 1 + SBOX[4][34816] = 0x20040000; // 8800 (1, 8) = 5 + SBOX[4][38912] = 0x0; // 9800 (1, 9) = 0 + SBOX[4][43008] = 0x21040080; // a800 (1, 10) = 15 + SBOX[4][47104] = 0x1000080; // b800 (1, 11) = 10 + SBOX[4][51200] = 0x20000080; // c800 (1, 12) = 3 + SBOX[4][55296] = 0x21000000; // d800 (1, 13) = 9 + SBOX[4][59392] = 0x1000000; // e800 (1, 14) = 8 + SBOX[4][63488] = 0x40080; // f800 (1, 15) = 6 + SBOX[4][65536] = 0x40000; // 10000 (2, 0) = 4 + SBOX[4][69632] = 0x80; // 11000 (2, 1) = 2 + SBOX[4][73728] = 0x20000000; // 12000 (2, 2) = 1 + SBOX[4][77824] = 0x21000080; // 13000 (2, 3) = 11 + SBOX[4][81920] = 0x1000080; // 14000 (2, 4) = 10 + SBOX[4][86016] = 0x21040000; // 15000 (2, 5) = 13 + SBOX[4][90112] = 0x20040080; // 16000 (2, 6) = 7 + SBOX[4][94208] = 0x1000000; // 17000 (2, 7) = 8 + SBOX[4][98304] = 0x21040080; // 18000 (2, 8) = 15 + SBOX[4][102400] = 0x21000000; // 19000 (2, 9) = 9 + SBOX[4][106496] = 0x1040000; // 1a000 (2, 10) = 12 + SBOX[4][110592] = 0x20040000; // 1b000 (2, 11) = 5 + SBOX[4][114688] = 0x40080; // 1c000 (2, 12) = 6 + SBOX[4][118784] = 0x20000080; // 1d000 (2, 13) = 3 + SBOX[4][122880] = 0x0; // 1e000 (2, 14) = 0 + SBOX[4][126976] = 0x1040080; // 1f000 (2, 15) = 14 + SBOX[4][67584] = 0x21000080; // 10800 (3, 0) = 11 + SBOX[4][71680] = 0x1000000; // 11800 (3, 1) = 8 + SBOX[4][75776] = 0x1040000; // 12800 (3, 2) = 12 + SBOX[4][79872] = 0x20040080; // 13800 (3, 3) = 7 + SBOX[4][83968] = 0x20000000; // 14800 (3, 4) = 1 + SBOX[4][88064] = 0x1040080; // 15800 (3, 5) = 14 + SBOX[4][92160] = 0x80; // 16800 (3, 6) = 2 + SBOX[4][96256] = 0x21040000; // 17800 (3, 7) = 13 + SBOX[4][100352] = 0x40080; // 18800 (3, 8) = 6 + SBOX[4][104448] = 0x21040080; // 19800 (3, 9) = 15 + SBOX[4][108544] = 0x0; // 1a800 (3, 10) = 0 + SBOX[4][112640] = 0x21000000; // 1b800 (3, 11) = 9 + SBOX[4][116736] = 0x1000080; // 1c800 (3, 12) = 10 + SBOX[4][120832] = 0x40000; // 1d800 (3, 13) = 4 + SBOX[4][124928] = 0x20040000; // 1e800 (3, 14) = 5 + SBOX[4][129024] = 0x20000080; // 1f800 (3, 15) = 3 + + SBOX[5] = new Array(); + SBOX[5][0] = 0x10000008; // 0 (0, 0) = 12 + SBOX[5][256] = 0x2000; // 100 (0, 1) = 1 + SBOX[5][512] = 0x10200000; // 200 (0, 2) = 10 + SBOX[5][768] = 0x10202008; // 300 (0, 3) = 15 + SBOX[5][1024] = 0x10002000; // 400 (0, 4) = 9 + SBOX[5][1280] = 0x200000; // 500 (0, 5) = 2 + SBOX[5][1536] = 0x200008; // 600 (0, 6) = 6 + SBOX[5][1792] = 0x10000000; // 700 (0, 7) = 8 + SBOX[5][2048] = 0x0; // 800 (0, 8) = 0 + SBOX[5][2304] = 0x10002008; // 900 (0, 9) = 13 + SBOX[5][2560] = 0x202000; // a00 (0, 10) = 3 + SBOX[5][2816] = 0x8; // b00 (0, 11) = 4 + SBOX[5][3072] = 0x10200008; // c00 (0, 12) = 14 + SBOX[5][3328] = 0x202008; // d00 (0, 13) = 7 + SBOX[5][3584] = 0x2008; // e00 (0, 14) = 5 + SBOX[5][3840] = 0x10202000; // f00 (0, 15) = 11 + SBOX[5][128] = 0x10200000; // 80 (1, 0) = 10 + SBOX[5][384] = 0x10202008; // 180 (1, 1) = 15 + SBOX[5][640] = 0x8; // 280 (1, 2) = 4 + SBOX[5][896] = 0x200000; // 380 (1, 3) = 2 + SBOX[5][1152] = 0x202008; // 480 (1, 4) = 7 + SBOX[5][1408] = 0x10000008; // 580 (1, 5) = 12 + SBOX[5][1664] = 0x10002000; // 680 (1, 6) = 9 + SBOX[5][1920] = 0x2008; // 780 (1, 7) = 5 + SBOX[5][2176] = 0x200008; // 880 (1, 8) = 6 + SBOX[5][2432] = 0x2000; // 980 (1, 9) = 1 + SBOX[5][2688] = 0x10002008; // a80 (1, 10) = 13 + SBOX[5][2944] = 0x10200008; // b80 (1, 11) = 14 + SBOX[5][3200] = 0x0; // c80 (1, 12) = 0 + SBOX[5][3456] = 0x10202000; // d80 (1, 13) = 11 + SBOX[5][3712] = 0x202000; // e80 (1, 14) = 3 + SBOX[5][3968] = 0x10000000; // f80 (1, 15) = 8 + SBOX[5][4096] = 0x10002000; // 1000 (2, 0) = 9 + SBOX[5][4352] = 0x10200008; // 1100 (2, 1) = 14 + SBOX[5][4608] = 0x10202008; // 1200 (2, 2) = 15 + SBOX[5][4864] = 0x2008; // 1300 (2, 3) = 5 + SBOX[5][5120] = 0x200000; // 1400 (2, 4) = 2 + SBOX[5][5376] = 0x10000000; // 1500 (2, 5) = 8 + SBOX[5][5632] = 0x10000008; // 1600 (2, 6) = 12 + SBOX[5][5888] = 0x202000; // 1700 (2, 7) = 3 + SBOX[5][6144] = 0x202008; // 1800 (2, 8) = 7 + SBOX[5][6400] = 0x0; // 1900 (2, 9) = 0 + SBOX[5][6656] = 0x8; // 1a00 (2, 10) = 4 + SBOX[5][6912] = 0x10200000; // 1b00 (2, 11) = 10 + SBOX[5][7168] = 0x2000; // 1c00 (2, 12) = 1 + SBOX[5][7424] = 0x10002008; // 1d00 (2, 13) = 13 + SBOX[5][7680] = 0x10202000; // 1e00 (2, 14) = 11 + SBOX[5][7936] = 0x200008; // 1f00 (2, 15) = 6 + SBOX[5][4224] = 0x8; // 1080 (3, 0) = 4 + SBOX[5][4480] = 0x202000; // 1180 (3, 1) = 3 + SBOX[5][4736] = 0x200000; // 1280 (3, 2) = 2 + SBOX[5][4992] = 0x10000008; // 1380 (3, 3) = 12 + SBOX[5][5248] = 0x10002000; // 1480 (3, 4) = 9 + SBOX[5][5504] = 0x2008; // 1580 (3, 5) = 5 + SBOX[5][5760] = 0x10202008; // 1680 (3, 6) = 15 + SBOX[5][6016] = 0x10200000; // 1780 (3, 7) = 10 + SBOX[5][6272] = 0x10202000; // 1880 (3, 8) = 11 + SBOX[5][6528] = 0x10200008; // 1980 (3, 9) = 14 + SBOX[5][6784] = 0x2000; // 1a80 (3, 10) = 1 + SBOX[5][7040] = 0x202008; // 1b80 (3, 11) = 7 + SBOX[5][7296] = 0x200008; // 1c80 (3, 12) = 6 + SBOX[5][7552] = 0x0; // 1d80 (3, 13) = 0 + SBOX[5][7808] = 0x10000000; // 1e80 (3, 14) = 8 + SBOX[5][8064] = 0x10002008; // 1f80 (3, 15) = 13 + + SBOX[6] = new Array(); + SBOX[6][0] = 0x100000; // 0 (0, 0) = 4 + SBOX[6][16] = 0x2000401; // 10 (0, 1) = 11 + SBOX[6][32] = 0x400; // 20 (0, 2) = 2 + SBOX[6][48] = 0x100401; // 30 (0, 3) = 14 + SBOX[6][64] = 0x2100401; // 40 (0, 4) = 15 + SBOX[6][80] = 0x0; // 50 (0, 5) = 0 + SBOX[6][96] = 0x1; // 60 (0, 6) = 8 + SBOX[6][112] = 0x2100001; // 70 (0, 7) = 13 + SBOX[6][128] = 0x2000400; // 80 (0, 8) = 3 + SBOX[6][144] = 0x100001; // 90 (0, 9) = 12 + SBOX[6][160] = 0x2000001; // a0 (0, 10) = 9 + SBOX[6][176] = 0x2100400; // b0 (0, 11) = 7 + SBOX[6][192] = 0x2100000; // c0 (0, 12) = 5 + SBOX[6][208] = 0x401; // d0 (0, 13) = 10 + SBOX[6][224] = 0x100400; // e0 (0, 14) = 6 + SBOX[6][240] = 0x2000000; // f0 (0, 15) = 1 + SBOX[6][8] = 0x2100001; // 8 (1, 0) = 13 + SBOX[6][24] = 0x0; // 18 (1, 1) = 0 + SBOX[6][40] = 0x2000401; // 28 (1, 2) = 11 + SBOX[6][56] = 0x2100400; // 38 (1, 3) = 7 + SBOX[6][72] = 0x100000; // 48 (1, 4) = 4 + SBOX[6][88] = 0x2000001; // 58 (1, 5) = 9 + SBOX[6][104] = 0x2000000; // 68 (1, 6) = 1 + SBOX[6][120] = 0x401; // 78 (1, 7) = 10 + SBOX[6][136] = 0x100401; // 88 (1, 8) = 14 + SBOX[6][152] = 0x2000400; // 98 (1, 9) = 3 + SBOX[6][168] = 0x2100000; // a8 (1, 10) = 5 + SBOX[6][184] = 0x100001; // b8 (1, 11) = 12 + SBOX[6][200] = 0x400; // c8 (1, 12) = 2 + SBOX[6][216] = 0x2100401; // d8 (1, 13) = 15 + SBOX[6][232] = 0x1; // e8 (1, 14) = 8 + SBOX[6][248] = 0x100400; // f8 (1, 15) = 6 + SBOX[6][256] = 0x2000000; // 100 (2, 0) = 1 + SBOX[6][272] = 0x100000; // 110 (2, 1) = 4 + SBOX[6][288] = 0x2000401; // 120 (2, 2) = 11 + SBOX[6][304] = 0x2100001; // 130 (2, 3) = 13 + SBOX[6][320] = 0x100001; // 140 (2, 4) = 12 + SBOX[6][336] = 0x2000400; // 150 (2, 5) = 3 + SBOX[6][352] = 0x2100400; // 160 (2, 6) = 7 + SBOX[6][368] = 0x100401; // 170 (2, 7) = 14 + SBOX[6][384] = 0x401; // 180 (2, 8) = 10 + SBOX[6][400] = 0x2100401; // 190 (2, 9) = 15 + SBOX[6][416] = 0x100400; // 1a0 (2, 10) = 6 + SBOX[6][432] = 0x1; // 1b0 (2, 11) = 8 + SBOX[6][448] = 0x0; // 1c0 (2, 12) = 0 + SBOX[6][464] = 0x2100000; // 1d0 (2, 13) = 5 + SBOX[6][480] = 0x2000001; // 1e0 (2, 14) = 9 + SBOX[6][496] = 0x400; // 1f0 (2, 15) = 2 + SBOX[6][264] = 0x100400; // 108 (3, 0) = 6 + SBOX[6][280] = 0x2000401; // 118 (3, 1) = 11 + SBOX[6][296] = 0x2100001; // 128 (3, 2) = 13 + SBOX[6][312] = 0x1; // 138 (3, 3) = 8 + SBOX[6][328] = 0x2000000; // 148 (3, 4) = 1 + SBOX[6][344] = 0x100000; // 158 (3, 5) = 4 + SBOX[6][360] = 0x401; // 168 (3, 6) = 10 + SBOX[6][376] = 0x2100400; // 178 (3, 7) = 7 + SBOX[6][392] = 0x2000001; // 188 (3, 8) = 9 + SBOX[6][408] = 0x2100000; // 198 (3, 9) = 5 + SBOX[6][424] = 0x0; // 1a8 (3, 10) = 0 + SBOX[6][440] = 0x2100401; // 1b8 (3, 11) = 15 + SBOX[6][456] = 0x100401; // 1c8 (3, 12) = 14 + SBOX[6][472] = 0x400; // 1d8 (3, 13) = 2 + SBOX[6][488] = 0x2000400; // 1e8 (3, 14) = 3 + SBOX[6][504] = 0x100001; // 1f8 (3, 15) = 12 + + SBOX[7] = new Array(); + SBOX[7][0] = 0x8000820; // 0 (0, 0) = 13 + SBOX[7][1] = 0x20000; // 1 (0, 1) = 2 + SBOX[7][2] = 0x8000000; // 2 (0, 2) = 8 + SBOX[7][3] = 0x20; // 3 (0, 3) = 4 + SBOX[7][4] = 0x20020; // 4 (0, 4) = 6 + SBOX[7][5] = 0x8020820; // 5 (0, 5) = 15 + SBOX[7][6] = 0x8020800; // 6 (0, 6) = 11 + SBOX[7][7] = 0x800; // 7 (0, 7) = 1 + SBOX[7][8] = 0x8020000; // 8 (0, 8) = 10 + SBOX[7][9] = 0x8000800; // 9 (0, 9) = 9 + SBOX[7][10] = 0x20800; // a (0, 10) = 3 + SBOX[7][11] = 0x8020020; // b (0, 11) = 14 + SBOX[7][12] = 0x820; // c (0, 12) = 5 + SBOX[7][13] = 0x0; // d (0, 13) = 0 + SBOX[7][14] = 0x8000020; // e (0, 14) = 12 + SBOX[7][15] = 0x20820; // f (0, 15) = 7 + SBOX[7][-2147483648] = 0x800; // 80000000 (1, 0) = 1 + SBOX[7][-2147483647] = 0x8020820; // 80000001 (1, 1) = 15 + SBOX[7][-2147483646] = 0x8000820; // 80000002 (1, 2) = 13 + SBOX[7][-2147483645] = 0x8000000; // 80000003 (1, 3) = 8 + SBOX[7][-2147483644] = 0x8020000; // 80000004 (1, 4) = 10 + SBOX[7][-2147483643] = 0x20800; // 80000005 (1, 5) = 3 + SBOX[7][-2147483642] = 0x20820; // 80000006 (1, 6) = 7 + SBOX[7][-2147483641] = 0x20; // 80000007 (1, 7) = 4 + SBOX[7][-2147483640] = 0x8000020; // 80000008 (1, 8) = 12 + SBOX[7][-2147483639] = 0x820; // 80000009 (1, 9) = 5 + SBOX[7][-2147483638] = 0x20020; // 8000000a (1, 10) = 6 + SBOX[7][-2147483637] = 0x8020800; // 8000000b (1, 11) = 11 + SBOX[7][-2147483636] = 0x0; // 8000000c (1, 12) = 0 + SBOX[7][-2147483635] = 0x8020020; // 8000000d (1, 13) = 14 + SBOX[7][-2147483634] = 0x8000800; // 8000000e (1, 14) = 9 + SBOX[7][-2147483633] = 0x20000; // 8000000f (1, 15) = 2 + SBOX[7][16] = 0x20820; // 10 (2, 0) = 7 + SBOX[7][17] = 0x8020800; // 11 (2, 1) = 11 + SBOX[7][18] = 0x20; // 12 (2, 2) = 4 + SBOX[7][19] = 0x800; // 13 (2, 3) = 1 + SBOX[7][20] = 0x8000800; // 14 (2, 4) = 9 + SBOX[7][21] = 0x8000020; // 15 (2, 5) = 12 + SBOX[7][22] = 0x8020020; // 16 (2, 6) = 14 + SBOX[7][23] = 0x20000; // 17 (2, 7) = 2 + SBOX[7][24] = 0x0; // 18 (2, 8) = 0 + SBOX[7][25] = 0x20020; // 19 (2, 9) = 6 + SBOX[7][26] = 0x8020000; // 1a (2, 10) = 10 + SBOX[7][27] = 0x8000820; // 1b (2, 11) = 13 + SBOX[7][28] = 0x8020820; // 1c (2, 12) = 15 + SBOX[7][29] = 0x20800; // 1d (2, 13) = 3 + SBOX[7][30] = 0x820; // 1e (2, 14) = 5 + SBOX[7][31] = 0x8000000; // 1f (2, 15) = 8 + SBOX[7][-2147483632] = 0x20000; // 80000010 (3, 0) = 2 + SBOX[7][-2147483631] = 0x800; // 80000011 (3, 1) = 1 + SBOX[7][-2147483630] = 0x8020020; // 80000012 (3, 2) = 14 + SBOX[7][-2147483629] = 0x20820; // 80000013 (3, 3) = 7 + SBOX[7][-2147483628] = 0x20; // 80000014 (3, 4) = 4 + SBOX[7][-2147483627] = 0x8020000; // 80000015 (3, 5) = 10 + SBOX[7][-2147483626] = 0x8000000; // 80000016 (3, 6) = 8 + SBOX[7][-2147483625] = 0x8000820; // 80000017 (3, 7) = 13 + SBOX[7][-2147483624] = 0x8020820; // 80000018 (3, 8) = 15 + SBOX[7][-2147483623] = 0x8000020; // 80000019 (3, 9) = 12 + SBOX[7][-2147483622] = 0x8000800; // 8000001a (3, 10) = 9 + SBOX[7][-2147483621] = 0x0; // 8000001b (3, 11) = 0 + SBOX[7][-2147483620] = 0x20800; // 8000001c (3, 12) = 3 + SBOX[7][-2147483619] = 0x820; // 8000001d (3, 13) = 5 + SBOX[7][-2147483618] = 0x20020; // 8000001e (3, 14) = 6 + SBOX[7][-2147483617] = 0x8020800; // 8000001f (3, 15) = 11 + + State.prototype._exchangeLR = function(v, m) { + var t = ((this.lhs >> v) ^ this.rhs) & m; + this.rhs ^= t; + this.lhs ^= (t << v); + }; + + State.prototype._exchangeRL = function(v, m) { + var t = ((this.rhs >> v) ^ this.lhs) & m; + this.lhs ^= t; + this.rhs ^= (t << v); + }; + + /** + * Perform the initial permutation of the input to create the starting state + * of the algorithm. The initial permutation maps each consecutive bit of + * the input into a different byte of the state. + * + *
+     * The initial permutation is defined to be:
+     * 
+     *      58    50   42    34    26   18    10    2  
+     *      60    52   44    36    28   20    12    4
+     *      62    54   46    38    30   22    14    6
+     *      64    56   48    40    32   24    16    8
+     *      57    49   41    33    25   17     9    1
+     *      59    51   43    35    27   19    11    3
+     *      61    53   45    37    29   21    13    5
+     *      63    55   47    39    31   23    15    7
+     * 
+ * + * + * @param message + * The message as an array of unsigned bytes. + * @param offset + * The offset into the message that the current 64-bit block + * begins. + * @returns the initial engine state + */ + State.prototype.initialPerm = function(message, offset) { + var input = message.slice(offset, offset + 8); + + this.lhs = (input[0] << 24) + (input[1] << 16) + (input[2] << 8) + + input[3]; + this.rhs = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + + input[7]; + + this._exchangeLR(4, 0x0f0f0f0f); + this._exchangeLR(16, 0x0000ffff); + this._exchangeRL(2, 0x33333333); + this._exchangeRL(8, 0x00ff00ff); + this._exchangeLR(1, 0x55555555); + }; + + /** + * Perform one round of the DES algorithm using the given key. A round is + * defined as: + * + *
+     * L&rsquo = R
+     * R&rsquo = L ˆ f(R, k)
+     * 
+ * + * where f consists of expanding, XORing with the key and contracting back + * with the SBOXes. + * + * Note that the final round is defined slightly differently as: + * + *
+     * L&rsquo = L ˆ f(R, k)
+     * R&rsquo = R
+     * 
+ * + * Therefore in the final round this function produces LHS and RHS the wrong + * way around. + * + * @param k + * the key + */ + State.prototype.round = function(k) { + var r = this.rhs, l = this.lhs; + var f = 0; + for ( var i = 0; i < 8; i++) { + var v = (r ^ k[i]) & State.SBOX_MASK[i]; + f += State.SBOX[i][v]; + } + + this.lhs = r; + this.rhs = l ^ f; + }; + + /** + * Apply the inverse of the initial permutation. + * + *
+     * The inverse is defined to be:
+     * 
+     *      40     8   48    16    56   24    64   32
+     *      39     7   47    15    55   23    63   31
+     *      38     6   46    14    54   22    62   30
+     *      37     5   45    13    53   21    61   29
+     *      36     4   44    12    52   20    60   28
+     *      35     3   43    11    51   19    59   27
+     *      34     2   42    10    50   18    58   26
+     *      33     1   41     9    49   17    57   25
+     * 
+ * + * @param cipherText + * @param offset + */ + State.prototype.finalPerm = function(cipherText, offset) { + var t = this.lhs; + this.lhs = this.rhs; + this.rhs = t; + + this._exchangeLR(1, 0x55555555); + this._exchangeRL(8, 0x00ff00ff); + this._exchangeRL(2, 0x33333333); + this._exchangeLR(16, 0x0000ffff); + this._exchangeLR(4, 0x0f0f0f0f); + + cipherText[offset] = (this.lhs >> 24) & 0xff; + cipherText[offset + 1] = (this.lhs >> 16) & 0xff; + cipherText[offset + 2] = (this.lhs >> 8) & 0xff; + cipherText[offset + 3] = (this.lhs) & 0xff; + cipherText[offset + 4] = (this.rhs >> 24) & 0xff; + cipherText[offset + 5] = (this.rhs >> 16) & 0xff; + cipherText[offset + 6] = (this.rhs >> 8) & 0xff; + cipherText[offset + 7] = (this.rhs) & 0xff; + }; + + /** + * DES cipher + */ + var DES = C.DES = { + _blocksize : 2, + + _keyschedule : null, + + _state : new State(), + + _init : function(k) { + this._keyschedule = new KeySchedule(k); + }, + + encrypt : function(message, password, options) { + + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) + mode.fixOptions(options); + + var + // Convert to bytes if message is a string + m = (message.constructor == String ? UTF8.stringToBytes(message) + : message), + + // Generate random IV + iv = options.iv || util.randomBytes(8), + + // Generate key + k = (password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 8, { + asBytes : true + }) : + // else, assume byte array representing cryptographic key + password); + + // Create key schedule + this._keyschedule = new KeySchedule(k); + + // Encrypt + mode.encrypt(DES, m, iv); + + // Return ciphertext + m = options.iv ? m : iv.concat(m); + return (options && options.asBytes) ? m : util.bytesToBase64(m); + }, + + _encryptblock : function(message, offset) { + this._state.initialPerm(message, offset); + for ( var i = 0; i <= 15; i++) { + this._state.round(this._keyschedule.getKey(i)); + } + this._state.finalPerm(message, offset); + }, + + decrypt : function(ciphertext, password, options) { + options = options || {}; + + // Determine mode + var mode = options.mode || new C.mode.OFB; + + // Allow mode to override options + if (mode.fixOptions) + mode.fixOptions(options); + + var + + // Convert to bytes if ciphertext is a string + c = (ciphertext.constructor == String ? util + .base64ToBytes(ciphertext) : ciphertext), + + // Separate IV and message + iv = options.iv || c.splice(0, 8), + + // Generate key + k = (password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { + asBytes : true + }) : + // else, assume byte array representing cryptographic key + password); + + // Create key schedule + this._keyschedule = new KeySchedule(k); + + mode.decrypt(DES, c, iv); + + // Return plaintext + return (options && options.asBytes) ? c : UTF8.bytesToString(c); + }, + + _decryptblock : function(message, offset) { + this._state.initialPerm(message, offset); + for ( var i = 15; i >= 0; i--) { + this._state.round(this._keyschedule.getKey(i)); + } + this._state.finalPerm(message, offset); + } + + }; +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/HMAC.js b/components/getPhoneNumer/utils/cryptojs/lib/HMAC.js new file mode 100644 index 0000000..cc87cd9 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/HMAC.js @@ -0,0 +1,38 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +C.HMAC = function (hasher, message, key, options) { + + // Convert to byte arrays + if (message.constructor == String) message = UTF8.stringToBytes(message); + if (key.constructor == String) key = UTF8.stringToBytes(key); + /* else, assume byte arrays already */ + + // Allow arbitrary length keys + if (key.length > hasher._blocksize * 4) + key = hasher(key, { asBytes: true }); + + // XOR keys with pad constants + var okey = key.slice(0), + ikey = key.slice(0); + for (var i = 0; i < hasher._blocksize * 4; i++) { + okey[i] ^= 0x5C; + ikey[i] ^= 0x36; + } + + var hmacbytes = hasher(okey.concat(hasher(ikey.concat(message), { asBytes: true })), { asBytes: true }); + + return options && options.asBytes ? hmacbytes : + options && options.asString ? Binary.bytesToString(hmacbytes) : + util.bytesToHex(hmacbytes); + +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/MARC4.js b/components/getPhoneNumer/utils/cryptojs/lib/MARC4.js new file mode 100644 index 0000000..3c0d478 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/MARC4.js @@ -0,0 +1,117 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +var MARC4 = C.MARC4 = { + + /** + * Public API + */ + + encrypt: function (message, password) { + + var + + // Convert to bytes + m = UTF8.stringToBytes(message), + + // Generate random IV + iv = util.randomBytes(16), + + // Generate key + k = password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password; + + // Encrypt + MARC4._marc4(m, k, 1536); + + // Return ciphertext + return util.bytesToBase64(iv.concat(m)); + + }, + + decrypt: function (ciphertext, password) { + + var + + // Convert to bytes + c = util.base64ToBytes(ciphertext), + + // Separate IV and message + iv = c.splice(0, 16), + + // Generate key + k = password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password; + + // Decrypt + MARC4._marc4(c, k, 1536); + + // Return plaintext + return UTF8.bytesToString(c); + + }, + + + /** + * Internal methods + */ + + // The core + _marc4: function (m, k, drop) { + + // State variables + var i, j, s, temp; + + // Key setup + for (i = 0, s = []; i < 256; i++) s[i] = i; + for (i = 0, j = 0; i < 256; i++) { + + j = (j + s[i] + k[i % k.length]) % 256; + + // Swap + temp = s[i]; + s[i] = s[j]; + s[j] = temp; + + } + + // Clear counters + i = j = 0; + + // Encryption + for (var k = -drop; k < m.length; k++) { + + i = (i + 1) % 256; + j = (j + s[i]) % 256; + + // Swap + temp = s[i]; + s[i] = s[j]; + s[j] = temp; + + // Stop here if we're still dropping keystream + if (k < 0) continue; + + // Encrypt + m[k] ^= s[(s[i] + s[j]) % 256]; + + } + + } + +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/MD5.js b/components/getPhoneNumer/utils/cryptojs/lib/MD5.js new file mode 100644 index 0000000..90330b5 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/MD5.js @@ -0,0 +1,158 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +// Public API +var MD5 = C.MD5 = function (message, options) { + var digestbytes = util.wordsToBytes(MD5._md5(message)); + return options && options.asBytes ? digestbytes : + options && options.asString ? Binary.bytesToString(digestbytes) : + util.bytesToHex(digestbytes); +}; + +// The core +MD5._md5 = function (message) { + + // Convert to byte array + if (message.constructor == String) message = UTF8.stringToBytes(message); + /* else, assume byte array already */ + + var m = util.bytesToWords(message), + l = message.length * 8, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + // Swap endian + for (var i = 0; i < m.length; i++) { + m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF | + ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00; + } + + // Padding + m[l >>> 5] |= 0x80 << (l % 32); + m[(((l + 64) >>> 9) << 4) + 14] = l; + + // Method shortcuts + var FF = MD5._ff, + GG = MD5._gg, + HH = MD5._hh, + II = MD5._ii; + + for (var i = 0; i < m.length; i += 16) { + + var aa = a, + bb = b, + cc = c, + dd = d; + + a = FF(a, b, c, d, m[i+ 0], 7, -680876936); + d = FF(d, a, b, c, m[i+ 1], 12, -389564586); + c = FF(c, d, a, b, m[i+ 2], 17, 606105819); + b = FF(b, c, d, a, m[i+ 3], 22, -1044525330); + a = FF(a, b, c, d, m[i+ 4], 7, -176418897); + d = FF(d, a, b, c, m[i+ 5], 12, 1200080426); + c = FF(c, d, a, b, m[i+ 6], 17, -1473231341); + b = FF(b, c, d, a, m[i+ 7], 22, -45705983); + a = FF(a, b, c, d, m[i+ 8], 7, 1770035416); + d = FF(d, a, b, c, m[i+ 9], 12, -1958414417); + c = FF(c, d, a, b, m[i+10], 17, -42063); + b = FF(b, c, d, a, m[i+11], 22, -1990404162); + a = FF(a, b, c, d, m[i+12], 7, 1804603682); + d = FF(d, a, b, c, m[i+13], 12, -40341101); + c = FF(c, d, a, b, m[i+14], 17, -1502002290); + b = FF(b, c, d, a, m[i+15], 22, 1236535329); + + a = GG(a, b, c, d, m[i+ 1], 5, -165796510); + d = GG(d, a, b, c, m[i+ 6], 9, -1069501632); + c = GG(c, d, a, b, m[i+11], 14, 643717713); + b = GG(b, c, d, a, m[i+ 0], 20, -373897302); + a = GG(a, b, c, d, m[i+ 5], 5, -701558691); + d = GG(d, a, b, c, m[i+10], 9, 38016083); + c = GG(c, d, a, b, m[i+15], 14, -660478335); + b = GG(b, c, d, a, m[i+ 4], 20, -405537848); + a = GG(a, b, c, d, m[i+ 9], 5, 568446438); + d = GG(d, a, b, c, m[i+14], 9, -1019803690); + c = GG(c, d, a, b, m[i+ 3], 14, -187363961); + b = GG(b, c, d, a, m[i+ 8], 20, 1163531501); + a = GG(a, b, c, d, m[i+13], 5, -1444681467); + d = GG(d, a, b, c, m[i+ 2], 9, -51403784); + c = GG(c, d, a, b, m[i+ 7], 14, 1735328473); + b = GG(b, c, d, a, m[i+12], 20, -1926607734); + + a = HH(a, b, c, d, m[i+ 5], 4, -378558); + d = HH(d, a, b, c, m[i+ 8], 11, -2022574463); + c = HH(c, d, a, b, m[i+11], 16, 1839030562); + b = HH(b, c, d, a, m[i+14], 23, -35309556); + a = HH(a, b, c, d, m[i+ 1], 4, -1530992060); + d = HH(d, a, b, c, m[i+ 4], 11, 1272893353); + c = HH(c, d, a, b, m[i+ 7], 16, -155497632); + b = HH(b, c, d, a, m[i+10], 23, -1094730640); + a = HH(a, b, c, d, m[i+13], 4, 681279174); + d = HH(d, a, b, c, m[i+ 0], 11, -358537222); + c = HH(c, d, a, b, m[i+ 3], 16, -722521979); + b = HH(b, c, d, a, m[i+ 6], 23, 76029189); + a = HH(a, b, c, d, m[i+ 9], 4, -640364487); + d = HH(d, a, b, c, m[i+12], 11, -421815835); + c = HH(c, d, a, b, m[i+15], 16, 530742520); + b = HH(b, c, d, a, m[i+ 2], 23, -995338651); + + a = II(a, b, c, d, m[i+ 0], 6, -198630844); + d = II(d, a, b, c, m[i+ 7], 10, 1126891415); + c = II(c, d, a, b, m[i+14], 15, -1416354905); + b = II(b, c, d, a, m[i+ 5], 21, -57434055); + a = II(a, b, c, d, m[i+12], 6, 1700485571); + d = II(d, a, b, c, m[i+ 3], 10, -1894986606); + c = II(c, d, a, b, m[i+10], 15, -1051523); + b = II(b, c, d, a, m[i+ 1], 21, -2054922799); + a = II(a, b, c, d, m[i+ 8], 6, 1873313359); + d = II(d, a, b, c, m[i+15], 10, -30611744); + c = II(c, d, a, b, m[i+ 6], 15, -1560198380); + b = II(b, c, d, a, m[i+13], 21, 1309151649); + a = II(a, b, c, d, m[i+ 4], 6, -145523070); + d = II(d, a, b, c, m[i+11], 10, -1120210379); + c = II(c, d, a, b, m[i+ 2], 15, 718787259); + b = II(b, c, d, a, m[i+ 9], 21, -343485551); + + a = (a + aa) >>> 0; + b = (b + bb) >>> 0; + c = (c + cc) >>> 0; + d = (d + dd) >>> 0; + + } + + return util.endian([a, b, c, d]); + +}; + +// Auxiliary functions +MD5._ff = function (a, b, c, d, x, s, t) { + var n = a + (b & c | ~b & d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; +}; +MD5._gg = function (a, b, c, d, x, s, t) { + var n = a + (b & d | c & ~d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; +}; +MD5._hh = function (a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; +}; +MD5._ii = function (a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; +}; + +// Package private blocksize +MD5._blocksize = 16; + +MD5._digestsize = 16; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2.js b/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2.js new file mode 100644 index 0000000..2c833cc --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2.js @@ -0,0 +1,49 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +C.PBKDF2 = function (password, salt, keylen, options) { + + // Convert to byte arrays + if (password.constructor == String) password = UTF8.stringToBytes(password); + if (salt.constructor == String) salt = UTF8.stringToBytes(salt); + /* else, assume byte arrays already */ + + // Defaults + var hasher = options && options.hasher || C.SHA1, + iterations = options && options.iterations || 1; + + // Pseudo-random function + function PRF(password, salt) { + return C.HMAC(hasher, salt, password, { asBytes: true }); + } + + // Generate key + var derivedKeyBytes = [], + blockindex = 1; + while (derivedKeyBytes.length < keylen) { + var block = PRF(password, salt.concat(util.wordsToBytes([blockindex]))); + for (var u = block, i = 1; i < iterations; i++) { + u = PRF(password, u); + for (var j = 0; j < block.length; j++) block[j] ^= u[j]; + } + derivedKeyBytes = derivedKeyBytes.concat(block); + blockindex++; + } + + // Truncate excess bytes + derivedKeyBytes.length = keylen; + + return options && options.asBytes ? derivedKeyBytes : + options && options.asString ? Binary.bytesToString(derivedKeyBytes) : + util.bytesToHex(derivedKeyBytes); + +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2Async.js b/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2Async.js new file mode 100644 index 0000000..be966cf --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/PBKDF2Async.js @@ -0,0 +1,88 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +if (!C.nextTick) { + // node.js has setTime out but prefer process.nextTick + if (typeof process != 'undefined' && typeof process.nextTick !== 'undefined') { + C.nextTick = process.nextTick; + } else if (typeof setTimeout !== 'undefined') { + C.nextTick = function (callback) { + setTimeout(callback, 0); + }; + } +} + +C.PBKDF2Async = function (password, salt, keylen, callback, options) { + + // Convert to byte arrays + if (password.constructor == String) password = UTF8.stringToBytes(password); + if (salt.constructor == String) salt = UTF8.stringToBytes(salt); + /* else, assume byte arrays already */ + + // Defaults + var hasher = options && options.hasher || C.SHA1, + iterations = options && options.iterations || 1; + + // Progress callback option + var progressChangeHandler = options && options.onProgressChange; + var totalIterations = Math.ceil(keylen / hasher._digestsize) * iterations; + function fireProgressChange(currentIteration) { + if (progressChangeHandler) { + var iterationsSoFar = derivedKeyBytes.length / hasher._digestsize * iterations + currentIteration; + setTimeout(function () { + progressChangeHandler(Math.round(iterationsSoFar / totalIterations * 100)); + }, 0); + } + } + + // Pseudo-random function + function PRF(password, salt) { + return C.HMAC(hasher, salt, password, { asBytes: true }); + } + + var nextTick = C.nextTick; + + // Generate key + var derivedKeyBytes = [], + blockindex = 1; + + var outer, inner; + nextTick(outer = function () { + if (derivedKeyBytes.length < keylen) { + var block = PRF(password, salt.concat(util.wordsToBytes([blockindex]))); + fireProgressChange(1); + + var u = block, i = 1; + nextTick(inner = function () { + if (i < iterations) { + u = PRF(password, u); + for (var j = 0; j < block.length; j++) block[j] ^= u[j]; + i++; + fireProgressChange(i); + + nextTick(inner); + } else { + derivedKeyBytes = derivedKeyBytes.concat(block); + blockindex++; + nextTick(outer); + } + }); + } else { + // Truncate excess bytes + derivedKeyBytes.length = keylen; + callback( + options && options.asBytes ? derivedKeyBytes : + options && options.asString ? Binary.bytesToString(derivedKeyBytes) : + util.bytesToHex(derivedKeyBytes)); + } + }); +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/Rabbit.js b/components/getPhoneNumer/utils/cryptojs/lib/Rabbit.js new file mode 100644 index 0000000..950abe6 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/Rabbit.js @@ -0,0 +1,221 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +// Inner state +var x = [], + c = [], + b; + +var Rabbit = C.Rabbit = { + + /** + * Public API + */ + + encrypt: function (message, password) { + + var + + // Convert to bytes + m = UTF8.stringToBytes(message), + + // Generate random IV + iv = util.randomBytes(8), + + // Generate key + k = password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password; + + // Encrypt + Rabbit._rabbit(m, k, util.bytesToWords(iv)); + + // Return ciphertext + return util.bytesToBase64(iv.concat(m)); + + }, + + decrypt: function (ciphertext, password) { + + var + + // Convert to bytes + c = util.base64ToBytes(ciphertext), + + // Separate IV and message + iv = c.splice(0, 8), + + // Generate key + k = password.constructor == String ? + // Derive key from passphrase + C.PBKDF2(password, iv, 32, { asBytes: true }) : + // else, assume byte array representing cryptographic key + password; + + // Decrypt + Rabbit._rabbit(c, k, util.bytesToWords(iv)); + + // Return plaintext + return UTF8.bytesToString(c); + + }, + + + /** + * Internal methods + */ + + // Encryption/decryption scheme + _rabbit: function (m, k, iv) { + + Rabbit._keysetup(k); + if (iv) Rabbit._ivsetup(iv); + + for (var s = [], i = 0; i < m.length; i++) { + + if (i % 16 == 0) { + + // Iterate the system + Rabbit._nextstate(); + + // Generate 16 bytes of pseudo-random data + s[0] = x[0] ^ (x[5] >>> 16) ^ (x[3] << 16); + s[1] = x[2] ^ (x[7] >>> 16) ^ (x[5] << 16); + s[2] = x[4] ^ (x[1] >>> 16) ^ (x[7] << 16); + s[3] = x[6] ^ (x[3] >>> 16) ^ (x[1] << 16); + + // Swap endian + for (var j = 0; j < 4; j++) { + s[j] = ((s[j] << 8) | (s[j] >>> 24)) & 0x00FF00FF | + ((s[j] << 24) | (s[j] >>> 8)) & 0xFF00FF00; + } + + // Convert words to bytes + for (var b = 120; b >= 0; b -= 8) + s[b / 8] = (s[b >>> 5] >>> (24 - b % 32)) & 0xFF; + + } + + m[i] ^= s[i % 16]; + + } + + }, + + // Key setup scheme + _keysetup: function (k) { + + // Generate initial state values + x[0] = k[0]; + x[2] = k[1]; + x[4] = k[2]; + x[6] = k[3]; + x[1] = (k[3] << 16) | (k[2] >>> 16); + x[3] = (k[0] << 16) | (k[3] >>> 16); + x[5] = (k[1] << 16) | (k[0] >>> 16); + x[7] = (k[2] << 16) | (k[1] >>> 16); + + // Generate initial counter values + c[0] = util.rotl(k[2], 16); + c[2] = util.rotl(k[3], 16); + c[4] = util.rotl(k[0], 16); + c[6] = util.rotl(k[1], 16); + c[1] = (k[0] & 0xFFFF0000) | (k[1] & 0xFFFF); + c[3] = (k[1] & 0xFFFF0000) | (k[2] & 0xFFFF); + c[5] = (k[2] & 0xFFFF0000) | (k[3] & 0xFFFF); + c[7] = (k[3] & 0xFFFF0000) | (k[0] & 0xFFFF); + + // Clear carry bit + b = 0; + + // Iterate the system four times + for (var i = 0; i < 4; i++) Rabbit._nextstate(); + + // Modify the counters + for (var i = 0; i < 8; i++) c[i] ^= x[(i + 4) & 7]; + + }, + + // IV setup scheme + _ivsetup: function (iv) { + + // Generate four subvectors + var i0 = util.endian(iv[0]), + i2 = util.endian(iv[1]), + i1 = (i0 >>> 16) | (i2 & 0xFFFF0000), + i3 = (i2 << 16) | (i0 & 0x0000FFFF); + + // Modify counter values + c[0] ^= i0; + c[1] ^= i1; + c[2] ^= i2; + c[3] ^= i3; + c[4] ^= i0; + c[5] ^= i1; + c[6] ^= i2; + c[7] ^= i3; + + // Iterate the system four times + for (var i = 0; i < 4; i++) Rabbit._nextstate(); + + }, + + // Next-state function + _nextstate: function () { + + // Save old counter values + for (var c_old = [], i = 0; i < 8; i++) c_old[i] = c[i]; + + // Calculate new counter values + c[0] = (c[0] + 0x4D34D34D + b) >>> 0; + c[1] = (c[1] + 0xD34D34D3 + ((c[0] >>> 0) < (c_old[0] >>> 0) ? 1 : 0)) >>> 0; + c[2] = (c[2] + 0x34D34D34 + ((c[1] >>> 0) < (c_old[1] >>> 0) ? 1 : 0)) >>> 0; + c[3] = (c[3] + 0x4D34D34D + ((c[2] >>> 0) < (c_old[2] >>> 0) ? 1 : 0)) >>> 0; + c[4] = (c[4] + 0xD34D34D3 + ((c[3] >>> 0) < (c_old[3] >>> 0) ? 1 : 0)) >>> 0; + c[5] = (c[5] + 0x34D34D34 + ((c[4] >>> 0) < (c_old[4] >>> 0) ? 1 : 0)) >>> 0; + c[6] = (c[6] + 0x4D34D34D + ((c[5] >>> 0) < (c_old[5] >>> 0) ? 1 : 0)) >>> 0; + c[7] = (c[7] + 0xD34D34D3 + ((c[6] >>> 0) < (c_old[6] >>> 0) ? 1 : 0)) >>> 0; + b = (c[7] >>> 0) < (c_old[7] >>> 0) ? 1 : 0; + + // Calculate the g-values + for (var g = [], i = 0; i < 8; i++) { + + var gx = (x[i] + c[i]) >>> 0; + + // Construct high and low argument for squaring + var ga = gx & 0xFFFF, + gb = gx >>> 16; + + // Calculate high and low result of squaring + var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb, + gl = (((gx & 0xFFFF0000) * gx) >>> 0) + (((gx & 0x0000FFFF) * gx) >>> 0) >>> 0; + + // High XOR low + g[i] = gh ^ gl; + + } + + // Calculate new state values + x[0] = g[0] + ((g[7] << 16) | (g[7] >>> 16)) + ((g[6] << 16) | (g[6] >>> 16)); + x[1] = g[1] + ((g[0] << 8) | (g[0] >>> 24)) + g[7]; + x[2] = g[2] + ((g[1] << 16) | (g[1] >>> 16)) + ((g[0] << 16) | (g[0] >>> 16)); + x[3] = g[3] + ((g[2] << 8) | (g[2] >>> 24)) + g[1]; + x[4] = g[4] + ((g[3] << 16) | (g[3] >>> 16)) + ((g[2] << 16) | (g[2] >>> 16)); + x[5] = g[5] + ((g[4] << 8) | (g[4] >>> 24)) + g[3]; + x[6] = g[6] + ((g[5] << 16) | (g[5] >>> 16)) + ((g[4] << 16) | (g[4] >>> 16)); + x[7] = g[7] + ((g[6] << 8) | (g[6] >>> 24)) + g[5]; + + } + +}; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/SHA1.js b/components/getPhoneNumer/utils/cryptojs/lib/SHA1.js new file mode 100644 index 0000000..d2109b7 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/SHA1.js @@ -0,0 +1,86 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +// Public API +var SHA1 = C.SHA1 = function (message, options) { + var digestbytes = util.wordsToBytes(SHA1._sha1(message)); + return options && options.asBytes ? digestbytes : + options && options.asString ? Binary.bytesToString(digestbytes) : + util.bytesToHex(digestbytes); +}; + +// The core +SHA1._sha1 = function (message) { + + // Convert to byte array + if (message.constructor == String) message = UTF8.stringToBytes(message); + /* else, assume byte array already */ + + var m = util.bytesToWords(message), + l = message.length * 8, + w = [], + H0 = 1732584193, + H1 = -271733879, + H2 = -1732584194, + H3 = 271733878, + H4 = -1009589776; + + // Padding + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >>> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + + var a = H0, + b = H1, + c = H2, + d = H3, + e = H4; + + for (var j = 0; j < 80; j++) { + + if (j < 16) w[j] = m[i + j]; + else { + var n = w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16]; + w[j] = (n << 1) | (n >>> 31); + } + + var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + ( + j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 : + j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 : + j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 : + (H1 ^ H2 ^ H3) - 899497514); + + H4 = H3; + H3 = H2; + H2 = (H1 << 30) | (H1 >>> 2); + H1 = H0; + H0 = t; + + } + + H0 += a; + H1 += b; + H2 += c; + H3 += d; + H4 += e; + + } + + return [H0, H1, H2, H3, H4]; + +}; + +// Package private blocksize +SHA1._blocksize = 16; + +SHA1._digestsize = 20; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/lib/SHA256.js b/components/getPhoneNumer/utils/cryptojs/lib/SHA256.js new file mode 100644 index 0000000..8871b75 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/lib/SHA256.js @@ -0,0 +1,130 @@ +(function(){ + +var C = (typeof window === 'undefined') ? require('./Crypto').Crypto : window.Crypto; + +// Shortcuts +var util = C.util, + charenc = C.charenc, + UTF8 = charenc.UTF8, + Binary = charenc.Binary; + +// Constants +var K = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 ]; + +// Public API +var SHA256 = C.SHA256 = function (message, options) { + var digestbytes = util.wordsToBytes(SHA256._sha256(message)); + return options && options.asBytes ? digestbytes : + options && options.asString ? Binary.bytesToString(digestbytes) : + util.bytesToHex(digestbytes); +}; + +// The core +SHA256._sha256 = function (message) { + + // Convert to byte array + if (message.constructor == String) message = UTF8.stringToBytes(message); + /* else, assume byte array already */ + + var m = util.bytesToWords(message), + l = message.length * 8, + H = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 ], + w = [], + a, b, c, d, e, f, g, h, i, j, + t1, t2; + + // Padding + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + + a = H[0]; + b = H[1]; + c = H[2]; + d = H[3]; + e = H[4]; + f = H[5]; + g = H[6]; + h = H[7]; + + for (var j = 0; j < 64; j++) { + + if (j < 16) w[j] = m[j + i]; + else { + + var gamma0x = w[j - 15], + gamma1x = w[j - 2], + gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3), + gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + w[j] = gamma0 + (w[j - 7] >>> 0) + + gamma1 + (w[j - 16] >>> 0); + + } + + var ch = e & f ^ ~e & g, + maj = a & b ^ a & c ^ b & c, + sigma0 = ((a << 30) | (a >>> 2)) ^ + ((a << 19) | (a >>> 13)) ^ + ((a << 10) | (a >>> 22)), + sigma1 = ((e << 26) | (e >>> 6)) ^ + ((e << 21) | (e >>> 11)) ^ + ((e << 7) | (e >>> 25)); + + + t1 = (h >>> 0) + sigma1 + ch + (K[j]) + (w[j] >>> 0); + t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + a = (t1 + t2) >>> 0; + + } + + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; + + } + + return H; + +}; + +// Package private blocksize +SHA256._blocksize = 16; + +SHA256._digestsize = 32; + +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/package.json b/components/getPhoneNumer/utils/cryptojs/package.json new file mode 100644 index 0000000..ecb3de0 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/package.json @@ -0,0 +1,18 @@ +{ + "author": "Jeff Guo ", + "name": "cryptojs", + "tags": ["Hash", "MD5", "SHA1", "SHA-1", "SHA256", "SHA-256", "RC4", "Rabbit", "AES", "DES", "PBKDF2", "HMAC", "OFB", "CFB", "CTR", "CBC", "Base64"], + "description": "Following googlecode project crypto-js, provide standard and secure cryptographic algorithms for NodeJS. Support MD5, SHA-1, SHA-256, RC4, Rabbit, AES, DES, PBKDF2, HMAC, OFB, CFB, CTR, CBC, Base64", + "version": "2.5.3", + "homepage": "https://github.com/gwjjeff/cryptojs", + "repository": { + "type": "git", + "url": "git://github.com/gwjjeff/cryptojs.git" + }, + "main": "cryptojs.js", + "engines": { + "node": "*" + }, + "dependencies": {}, + "devDependencies": {} +} diff --git a/components/getPhoneNumer/utils/cryptojs/test/PBKDF2-test.js b/components/getPhoneNumer/utils/cryptojs/test/PBKDF2-test.js new file mode 100644 index 0000000..b92e7cd --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/test/PBKDF2-test.js @@ -0,0 +1,25 @@ +var assert = require('assert'); +var Crypto = require('../cryptojs').Crypto; + +(function test_PBKDF2() { + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 128 / 8), "cdedb5281bb2f801565a1122b2563515"); + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 256 / 8), "cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837"); + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 128 / 8, { iterations : 2 }), "01dbee7f4a9e243e988b62c73cda935d"); + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 256 / 8, { iterations : 2 }), "01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86"); + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 128 / 8, { iterations : 1200}), "5c08eb61fdf71e4e4ec3cf6ba1f5512b"); + assert.strictEqual(Crypto.PBKDF2("password", "ATHENA.MIT.EDUraeburn", 256 / 8, { iterations : 1200}), "5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13"); + assert.strictEqual(Crypto.PBKDF2("password", "\x12\x34\x56\x78\x78\x56\x34\x12", 128 / 8, { iterations : 5 }), "d1daa78615f287e6a1c8b120d7062a49"); + assert.strictEqual(Crypto.PBKDF2("password", "\x12\x34\x56\x78\x78\x56\x34\x12", 256 / 8, { iterations : 5 }), "d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee"); + assert.strictEqual(Crypto.PBKDF2("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase equals block size", 128 / 8, { iterations : 1200 }), "139c30c0966bc32ba55fdbf212530ac9"); + assert.strictEqual(Crypto.PBKDF2("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase equals block size", 256 / 8, { iterations : 1200 }), "139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1"); + assert.strictEqual(Crypto.PBKDF2("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", 128 / 8, { iterations : 1200 }), "9ccad6d468770cd51b10e6a68721be61"); + assert.strictEqual(Crypto.PBKDF2("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", 256 / 8, { iterations : 1200 }), "9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a"); + assert.strictEqual(Crypto.PBKDF2([0xf0, 0x9d, 0x84, 0x9e], "EXAMPLE.COMpianist", 128 / 8, { iterations : 50 }), "6b9cf26d45455a43a5b8bb276a403b39"); + assert.strictEqual(Crypto.PBKDF2([0xf0, 0x9d, 0x84, 0x9e], "EXAMPLE.COMpianist", 256 / 8, { iterations : 50 }), "6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52"); +})(); + +(function test_PBKSD2Async() { + Crypto.PBKDF2Async("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", 256 / 8, function(result) { + assert.strictEqual(result, "9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a"); + }, { iterations : 1200 }); +})(); diff --git a/components/getPhoneNumer/utils/cryptojs/test/test.coffee b/components/getPhoneNumer/utils/cryptojs/test/test.coffee new file mode 100644 index 0000000..149f1c1 --- /dev/null +++ b/components/getPhoneNumer/utils/cryptojs/test/test.coffee @@ -0,0 +1,13 @@ +Crypto = (require '../cryptojs').Crypto +key = '12345678' +us = 'Hello, 世界!' + +mode = new Crypto.mode.ECB Crypto.pad.pkcs7 + +console.log "ub = #{ub = Crypto.charenc.UTF8.stringToBytes us}" +console.log "eb = #{eb = Crypto.DES.encrypt ub, key, {asBytes: true, mode: mode}}" +console.log "ehs= #{ehs= Crypto.util.bytesToHex eb}" + +console.log "eb2= #{eb2= Crypto.util.hexToBytes ehs}" +console.log "ub2= #{ub2= Crypto.DES.decrypt eb2, key, {asBytes: true, mode: mode}}" +console.log "us2= #{us2= Crypto.charenc.UTF8.bytesToString ub2}" diff --git a/components/getPhoneNumer/utils/util.js b/components/getPhoneNumer/utils/util.js new file mode 100644 index 0000000..764bc2c --- /dev/null +++ b/components/getPhoneNumer/utils/util.js @@ -0,0 +1,19 @@ +const formatTime = date => { + const year = date.getFullYear() + const month = date.getMonth() + 1 + const day = date.getDate() + const hour = date.getHours() + const minute = date.getMinutes() + const second = date.getSeconds() + + return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}` +} + +const formatNumber = n => { + n = n.toString() + return n[1] ? n : `0${n}` +} + +module.exports = { + formatTime +} diff --git a/components/imageUpload/imageUpload.js b/components/imageUpload/imageUpload.js new file mode 100644 index 0000000..6d5d5f1 --- /dev/null +++ b/components/imageUpload/imageUpload.js @@ -0,0 +1,164 @@ +// components/imageUpload/imageUpload.js +Component({ + /** + * 组件的属性列表 + */ + properties: { + // 最大上传个数 + maxLength: { + type: Number, + value: 9 + }, + // 单个图片限制 单位MB + maxSize: { + type: Number, + value: 1 + } + }, + + /** + * 组件的初始数据 + */ + data: { + // 图片路径数组 + tempFilePaths: [] + }, + + /** + * 组件的方法列表 + */ + methods: { + // 选择图片 + upload() { + let that = this; + let maxSize = this.data.maxSize * 1024 * 1024 + let flag = true + let maxLength = this.data.maxLength + console.log("maxLength",maxLength); + wx.chooseImage({ + count: maxLength, // 默认9 + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success: res => { + wx.showToast({ + title: '正在上传...', + icon: 'loading', + mask: true, + duration: 1000 + }) + // 判断数量 + if (res.tempFiles.length > maxLength) { + wx.hideToast() + flag = false + wx.showToast({ + title: `最多上传${maxLength}张`, + mask: true, + duration: 1000 + }) + return false + } + res.tempFiles.forEach(item => { + if (item.size > maxSize) { + wx.hideToast() + flag = false + wx.showModal({ + title: '错误提示', + content: `图片大于${that.data.maxSize}M`, + showCancel: false, + success(res) { + if (res.confirm) { + console.log('用户点击确定') + } + } + }) + return false + } + }) + // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 + let tempFilePaths = res.tempFilePaths; + if (flag) { + that.setData({ + tempFilePaths: tempFilePaths + }) + } + /** + * 上传完成后把文件上传到服务器 + */ + // if (flag) { + // let count = 0; + // for (let i = 0; i < tempFilePaths.length; i++) { + // //上传文件 + // wx.uploadFile({ + // url: 'imgUploadUrl', + // filePath: tempFilePaths[i], + // name: 'uploadfile_ant', + // header: { + // "Content-Type": "multipart/form-data" + // }, + // success: function (res) { + // console.log("上传图片", res); + // count++; + // //如果是最后一张,则隐藏等待中 + // if (count == tempFilePaths.length) { + // wx.hideToast(); + // } + // }, + // fail: function (res) { + // wx.hideToast(); + // wx.showModal({ + // title: '错误提示', + // content: '上传图片失败', + // showCancel: false, + // success: function (res) {} + // }) + // } + // }); + // } + // } + }, + + fail(err) { + console.log("失败", err); + } + }) + }, + // 预览图片 + previewImage(e) { + console.log("e", e); + let index = e.target.dataset.index; + let that = this; + wx.previewImage({ + current: that.data.tempFilePaths[index], + urls: that.data.tempFilePaths, + success: function (res) { + console.log("res", res); + }, + fail: function (fail) { + //console.log('fail') + } + }) + }, + // 删除图片 + deleteImage(e) { + let that = this; + let tempFilePaths = that.data.tempFilePaths; + let index = e.currentTarget.dataset.index; //获取当前长按图片下标 + wx.showModal({ + title: '提示', + content: '确定要删除此图片吗?', + success: function (res) { + if (res.confirm) { + console.log('确定'); + tempFilePaths.splice(index, 1); + } else if (res.cancel) { + console.log('取消'); + return false; + } + that.setData({ + tempFilePaths + }); + } + }) + } + } +}) \ No newline at end of file diff --git a/components/imageUpload/imageUpload.json b/components/imageUpload/imageUpload.json new file mode 100644 index 0000000..e8cfaaf --- /dev/null +++ b/components/imageUpload/imageUpload.json @@ -0,0 +1,4 @@ +{ + "component": true, + "usingComponents": {} +} \ No newline at end of file diff --git a/components/imageUpload/imageUpload.wxml b/components/imageUpload/imageUpload.wxml new file mode 100644 index 0000000..e89488c --- /dev/null +++ b/components/imageUpload/imageUpload.wxml @@ -0,0 +1,11 @@ + + + + + + + + + + + + diff --git a/components/imageUpload/imageUpload.wxss b/components/imageUpload/imageUpload.wxss new file mode 100644 index 0000000..c5aae3a --- /dev/null +++ b/components/imageUpload/imageUpload.wxss @@ -0,0 +1,49 @@ +/* components/imageUpload/imageUpload.wxss */ +/* 图片 */ +.img_box{ + width:690rpx; + position:relative; + display: flex; + flex-wrap: wrap; + margin:0 auto; +} +.imgs{ + width:33.33333333%; + display: flex; + justify-content: center; + margin-bottom:20rpx; +} +.imgs image{ + width:90%; + max-height:212rpx; + border:1px solid rgba(214, 212, 212, 0.1); + /* box-shadow: 5rpx 5rpx 1rpx 3rpx #e2e0e0; */ +} +.imgs .images{ + position:relative; +} +.images button{ + width:100%; + height:100%; + position:absolute; + top:0; + left:0; +} +.img_box .images{ + width:90%; + height: 212rpx; + border:1px solid #E8E8E8; + border-radius:4rpx; + display: flex; + align-items: center; + justify-content: center; +} +.img_box .images>image{ + width:60rpx; + height:60rpx; +} +/* 上传加号 */ +.add-images { + color: #ccc; + font-size: 100rpx; +} \ No newline at end of file diff --git a/pages/index/index.js b/pages/index/index.js new file mode 100644 index 0000000..0bc1771 --- /dev/null +++ b/pages/index/index.js @@ -0,0 +1,48 @@ +// index.js +// 获取应用实例 +const app = getApp() + +Page({ + data: { + motto: 'Hello World', + userInfo: {}, + hasUserInfo: false, + canIUse: wx.canIUse('button.open-type.getUserInfo'), + canIUseGetUserProfile: false, + canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false + }, + // 事件处理函数 + bindViewTap() { + wx.navigateTo({ + url: '../logs/logs' + }) + }, + onLoad() { + if (wx.getUserProfile) { + this.setData({ + canIUseGetUserProfile: true + }) + } + }, + getUserProfile(e) { + // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗 + wx.getUserProfile({ + desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 + success: (res) => { + console.log(res) + this.setData({ + userInfo: res.userInfo, + hasUserInfo: true + }) + } + }) + }, + getUserInfo(e) { + // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息 + console.log(e) + this.setData({ + userInfo: e.detail.userInfo, + hasUserInfo: true + }) + } +}) diff --git a/pages/index/index.json b/pages/index/index.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/index/index.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/index/index.wxml b/pages/index/index.wxml new file mode 100644 index 0000000..f00d294 --- /dev/null +++ b/pages/index/index.wxml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + 请使用1.4.4及以上版本基础库 + + + + {{userInfo.nickName}} + + + + {{motto}} + + diff --git a/pages/index/index.wxss b/pages/index/index.wxss new file mode 100644 index 0000000..eb64203 --- /dev/null +++ b/pages/index/index.wxss @@ -0,0 +1,19 @@ +/**index.wxss**/ +.userinfo { + display: flex; + flex-direction: column; + align-items: center; + color: #aaa; +} + +.userinfo-avatar { + overflow: hidden; + width: 128rpx; + height: 128rpx; + margin: 20rpx; + border-radius: 50%; +} + +.usermotto { + margin-top: 200px; +} \ No newline at end of file diff --git a/pages/logs/logs.js b/pages/logs/logs.js new file mode 100644 index 0000000..85f6aac --- /dev/null +++ b/pages/logs/logs.js @@ -0,0 +1,18 @@ +// logs.js +const util = require('../../utils/util.js') + +Page({ + data: { + logs: [] + }, + onLoad() { + this.setData({ + logs: (wx.getStorageSync('logs') || []).map(log => { + return { + date: util.formatTime(new Date(log)), + timeStamp: log + } + }) + }) + } +}) diff --git a/pages/logs/logs.json b/pages/logs/logs.json new file mode 100644 index 0000000..3ee76c1 --- /dev/null +++ b/pages/logs/logs.json @@ -0,0 +1,4 @@ +{ + "navigationBarTitleText": "查看启动日志", + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/logs/logs.wxml b/pages/logs/logs.wxml new file mode 100644 index 0000000..0b6b645 --- /dev/null +++ b/pages/logs/logs.wxml @@ -0,0 +1,6 @@ + + + + {{index + 1}}. {{log.date}} + + diff --git a/pages/logs/logs.wxss b/pages/logs/logs.wxss new file mode 100644 index 0000000..94d4b88 --- /dev/null +++ b/pages/logs/logs.wxss @@ -0,0 +1,8 @@ +.log-list { + display: flex; + flex-direction: column; + padding: 40rpx; +} +.log-item { + margin: 10rpx; +} diff --git a/pages/meeting/meeting.js b/pages/meeting/meeting.js new file mode 100644 index 0000000..cec7b0d --- /dev/null +++ b/pages/meeting/meeting.js @@ -0,0 +1,66 @@ +// pages/meeting/meeting.js +Page({ + + /** + * 页面的初始数据 + */ + data: { + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad: function (options) { + + }, + + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () { + + }, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () { + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () { + + }, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () { + + }, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage: function () { + + } +}) \ No newline at end of file diff --git a/pages/meeting/meeting.json b/pages/meeting/meeting.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/meeting/meeting.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/meeting/meeting.wxml b/pages/meeting/meeting.wxml new file mode 100644 index 0000000..e974447 --- /dev/null +++ b/pages/meeting/meeting.wxml @@ -0,0 +1,2 @@ + +pages/meeting/meeting.wxml diff --git a/pages/meeting/meeting.wxss b/pages/meeting/meeting.wxss new file mode 100644 index 0000000..572c3b8 --- /dev/null +++ b/pages/meeting/meeting.wxss @@ -0,0 +1 @@ +/* pages/meeting/meeting.wxss */ \ No newline at end of file diff --git a/pages/mine/mine.js b/pages/mine/mine.js new file mode 100644 index 0000000..607f4f2 --- /dev/null +++ b/pages/mine/mine.js @@ -0,0 +1,66 @@ +// pages/mine/mine.js +Page({ + + /** + * 页面的初始数据 + */ + data: { + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad: function (options) { + + }, + + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () { + + }, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () { + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () { + + }, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () { + + }, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage: function () { + + } +}) \ No newline at end of file diff --git a/pages/mine/mine.json b/pages/mine/mine.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/mine/mine.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/mine/mine.wxml b/pages/mine/mine.wxml new file mode 100644 index 0000000..d236877 --- /dev/null +++ b/pages/mine/mine.wxml @@ -0,0 +1,2 @@ + +pages/mine/mine.wxml diff --git a/pages/mine/mine.wxss b/pages/mine/mine.wxss new file mode 100644 index 0000000..91eea05 --- /dev/null +++ b/pages/mine/mine.wxss @@ -0,0 +1 @@ +/* pages/mine/mine.wxss */ \ No newline at end of file diff --git a/pages/notice/notice.js b/pages/notice/notice.js new file mode 100644 index 0000000..0ba401f --- /dev/null +++ b/pages/notice/notice.js @@ -0,0 +1,66 @@ +// pages/notice/notice.js +Page({ + + /** + * 页面的初始数据 + */ + data: { + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad: function (options) { + + }, + + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () { + + }, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () { + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () { + + }, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () { + + }, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage: function () { + + } +}) \ No newline at end of file diff --git a/pages/notice/notice.json b/pages/notice/notice.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/notice/notice.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/notice/notice.wxml b/pages/notice/notice.wxml new file mode 100644 index 0000000..a87c7ae --- /dev/null +++ b/pages/notice/notice.wxml @@ -0,0 +1,2 @@ + + diff --git a/pages/notice/notice.wxss b/pages/notice/notice.wxss new file mode 100644 index 0000000..947b40e --- /dev/null +++ b/pages/notice/notice.wxss @@ -0,0 +1 @@ +/* pages/notice/notice.wxss */ \ No newline at end of file diff --git a/pages/project/project.js b/pages/project/project.js new file mode 100644 index 0000000..7abe794 --- /dev/null +++ b/pages/project/project.js @@ -0,0 +1,66 @@ +// pages/project/project.js +Page({ + + /** + * 页面的初始数据 + */ + data: { + + }, + + /** + * 生命周期函数--监听页面加载 + */ + onLoad: function (options) { + + }, + + /** + * 生命周期函数--监听页面初次渲染完成 + */ + onReady: function () { + + }, + + /** + * 生命周期函数--监听页面显示 + */ + onShow: function () { + + }, + + /** + * 生命周期函数--监听页面隐藏 + */ + onHide: function () { + + }, + + /** + * 生命周期函数--监听页面卸载 + */ + onUnload: function () { + + }, + + /** + * 页面相关事件处理函数--监听用户下拉动作 + */ + onPullDownRefresh: function () { + + }, + + /** + * 页面上拉触底事件的处理函数 + */ + onReachBottom: function () { + + }, + + /** + * 用户点击右上角分享 + */ + onShareAppMessage: function () { + + } +}) \ No newline at end of file diff --git a/pages/project/project.json b/pages/project/project.json new file mode 100644 index 0000000..8835af0 --- /dev/null +++ b/pages/project/project.json @@ -0,0 +1,3 @@ +{ + "usingComponents": {} +} \ No newline at end of file diff --git a/pages/project/project.wxml b/pages/project/project.wxml new file mode 100644 index 0000000..8a1cb4c --- /dev/null +++ b/pages/project/project.wxml @@ -0,0 +1,2 @@ + +pages/project/project.wxml diff --git a/pages/project/project.wxss b/pages/project/project.wxss new file mode 100644 index 0000000..abac20b --- /dev/null +++ b/pages/project/project.wxss @@ -0,0 +1 @@ +/* pages/project/project.wxss */ \ No newline at end of file diff --git a/project.config.json b/project.config.json new file mode 100644 index 0000000..f4917f0 --- /dev/null +++ b/project.config.json @@ -0,0 +1,75 @@ +{ + "description": "项目配置文件", + "packOptions": { + "ignore": [] + }, + "setting": { + "urlCheck": true, + "es6": true, + "enhance": true, + "postcss": true, + "preloadBackgroundData": false, + "minified": true, + "newFeature": false, + "coverView": true, + "nodeModules": false, + "autoAudits": false, + "showShadowRootInWxmlPanel": true, + "scopeDataCheck": false, + "uglifyFileName": false, + "checkInvalidKey": true, + "checkSiteMap": true, + "uploadWithSourceMap": true, + "compileHotReLoad": false, + "lazyloadPlaceholderEnable": false, + "useMultiFrameRuntime": true, + "useApiHook": true, + "useApiHostProcess": false, + "babelSetting": { + "ignore": [], + "disablePlugins": [], + "outputPath": "" + }, + "enableEngineNative": false, + "useIsolateContext": true, + "userConfirmedBundleSwitch": false, + "packNpmManually": false, + "packNpmRelationList": [], + "minifyWXSS": true, + "showES6CompileOption": false, + "bundle": false + }, + "compileType": "miniprogram", + "libVersion": "2.19.0", + "appid": "wx62b116308b97d953", + "projectname": "income_payments_applet", + "debugOptions": { + "hidedInDevtools": [] + }, + "scripts": {}, + "staticServerOptions": { + "baseURL": "", + "servePath": "" + }, + "isGameTourist": false, + "condition": { + "search": { + "list": [] + }, + "conversation": { + "list": [] + }, + "game": { + "list": [] + }, + "plugin": { + "list": [] + }, + "gamePlugin": { + "list": [] + }, + "miniprogram": { + "list": [] + } + } +} \ No newline at end of file diff --git a/sitemap.json b/sitemap.json new file mode 100644 index 0000000..ca02add --- /dev/null +++ b/sitemap.json @@ -0,0 +1,7 @@ +{ + "desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html", + "rules": [{ + "action": "allow", + "page": "*" + }] +} \ No newline at end of file diff --git a/utils/util.js b/utils/util.js new file mode 100644 index 0000000..764bc2c --- /dev/null +++ b/utils/util.js @@ -0,0 +1,19 @@ +const formatTime = date => { + const year = date.getFullYear() + const month = date.getMonth() + 1 + const day = date.getDate() + const hour = date.getHours() + const minute = date.getMinutes() + const second = date.getSeconds() + + return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}` +} + +const formatNumber = n => { + n = n.toString() + return n[1] ? n : `0${n}` +} + +module.exports = { + formatTime +}