Переглянути джерело

Merge branch 'v9' of github.com:gchq/CyberChef into node-lib

d98762625 6 роки тому
батько
коміт
368f508b17
100 змінених файлів з 18566 додано та 2650 видалено
  1. 1 14
      .github/ISSUE_TEMPLATE.md
  2. 35 0
      .github/ISSUE_TEMPLATE/bug_report.md
  3. 20 0
      .github/ISSUE_TEMPLATE/feature_request.md
  4. 16 0
      .github/ISSUE_TEMPLATE/operation-request.md
  5. 38 0
      CHANGELOG.md
  6. 2 2
      README.md
  7. 0 6
      babel.config.js
  8. 106 602
      package-lock.json
  9. 41 35
      package.json
  10. 1 7
      postcss.config.js
  11. 18 34
      src/core/Chef.mjs
  12. 68 13
      src/core/ChefWorker.js
  13. 49 0
      src/core/Dish.mjs
  14. 6 1
      src/core/Recipe.mjs
  15. 11 2
      src/core/Utils.mjs
  16. 9 2
      src/core/config/Categories.json
  17. 360 2
      src/core/lib/FileSignatures.mjs
  18. 4 2
      src/core/lib/Hex.mjs
  19. 251 0
      src/core/lib/ImageManipulation.mjs
  20. 11 1
      src/core/lib/Magic.mjs
  21. 93 0
      src/core/lib/QRCode.mjs
  22. 2 2
      src/core/operations/AESEncrypt.mjs
  23. 266 0
      src/core/operations/AddTextToImage.mjs
  24. 22 13
      src/core/operations/BlurImage.mjs
  25. 72 0
      src/core/operations/Bzip2Compress.mjs
  26. 29 13
      src/core/operations/Bzip2Decompress.mjs
  27. 157 0
      src/core/operations/CRC8Checksum.mjs
  28. 30 12
      src/core/operations/ContainImage.mjs
  29. 143 0
      src/core/operations/ConvertImageFormat.mjs
  30. 17 11
      src/core/operations/CoverImage.mjs
  31. 17 11
      src/core/operations/CropImage.mjs
  32. 14 8
      src/core/operations/DetectFileType.mjs
  33. 18 11
      src/core/operations/DitherImage.mjs
  34. 374 41
      src/core/operations/Entropy.mjs
  35. 17 11
      src/core/operations/FlipImage.mjs
  36. 1198 2
      src/core/operations/FromHTMLEntity.mjs
  37. 71 0
      src/core/operations/GOSTHash.mjs
  38. 52 45
      src/core/operations/GenerateAllHashes.mjs
  39. 17 42
      src/core/operations/GenerateQRCode.mjs
  40. 17 11
      src/core/operations/ImageBrightnessContrast.mjs
  41. 17 11
      src/core/operations/ImageFilter.mjs
  42. 18 11
      src/core/operations/ImageHueSaturationLightness.mjs
  43. 17 11
      src/core/operations/ImageOpacity.mjs
  44. 107 0
      src/core/operations/IndexOfCoincidence.mjs
  45. 18 11
      src/core/operations/InvertImage.mjs
  46. 6 0
      src/core/operations/JSONToCSV.mjs
  47. 27 12
      src/core/operations/NormaliseImage.mjs
  48. 3 2
      src/core/operations/PGPDecryptAndVerify.mjs
  49. 111 0
      src/core/operations/PGPVerify.mjs
  50. 15 57
      src/core/operations/ParseQRCode.mjs
  51. 17 11
      src/core/operations/ResizeImage.mjs
  52. 18 11
      src/core/operations/RotateImage.mjs
  53. 5 4
      src/core/operations/ScanForEmbeddedFiles.mjs
  54. 168 0
      src/core/operations/SharpenImage.mjs
  55. 60 0
      src/core/operations/Streebog.mjs
  56. 1168 2
      src/core/operations/ToHTMLEntity.mjs
  57. 1 1
      src/core/operations/UnescapeString.mjs
  58. 0 265
      src/core/vendor/bzip2.mjs
  59. 2259 0
      src/core/vendor/gost/gostCipher.mjs
  60. 1160 0
      src/core/vendor/gost/gostCoding.mjs
  61. 1653 0
      src/core/vendor/gost/gostCrypto.mjs
  62. 1260 0
      src/core/vendor/gost/gostDigest.mjs
  63. 451 0
      src/core/vendor/gost/gostEngine.mjs
  64. 128 0
      src/core/vendor/gost/gostRandom.mjs
  65. 2023 0
      src/core/vendor/gost/gostSign.mjs
  66. 120 29
      src/web/App.mjs
  67. 0 354
      src/web/InputWaiter.mjs
  68. 62 17
      src/web/Manager.mjs
  69. 0 547
      src/web/OutputWaiter.mjs
  70. 0 239
      src/web/WorkerWaiter.mjs
  71. 232 37
      src/web/html/index.html
  72. 3 1
      src/web/index.js
  73. 485 0
      src/web/static/fonts/bmfonts/Roboto72White.fnt
  74. BIN
      src/web/static/fonts/bmfonts/Roboto72White.png
  75. 488 0
      src/web/static/fonts/bmfonts/RobotoBlack72White.fnt
  76. BIN
      src/web/static/fonts/bmfonts/RobotoBlack72White.png
  77. 103 0
      src/web/static/fonts/bmfonts/RobotoMono72White.fnt
  78. BIN
      src/web/static/fonts/bmfonts/RobotoMono72White.png
  79. 492 0
      src/web/static/fonts/bmfonts/RobotoSlab72White.fnt
  80. BIN
      src/web/static/fonts/bmfonts/RobotoSlab72White.png
  81. 44 8
      src/web/stylesheets/components/_operation.css
  82. 12 4
      src/web/stylesheets/components/_pane.css
  83. 2 0
      src/web/stylesheets/index.css
  84. 4 0
      src/web/stylesheets/layout/_banner.css
  85. 26 0
      src/web/stylesheets/layout/_controls.css
  86. 263 12
      src/web/stylesheets/layout/_io.css
  87. 31 0
      src/web/stylesheets/layout/_modals.css
  88. 2 2
      src/web/stylesheets/layout/_operations.css
  89. 5 5
      src/web/stylesheets/preloader.css
  90. 17 0
      src/web/stylesheets/themes/_classic.css
  91. 17 0
      src/web/stylesheets/themes/_dark.css
  92. 17 0
      src/web/stylesheets/themes/_geocities.css
  93. 147 0
      src/web/stylesheets/themes/_solarizedDark.css
  94. 149 0
      src/web/stylesheets/themes/_solarizedLight.css
  95. 5 2
      src/web/stylesheets/utils/_overrides.css
  96. 2 1
      src/web/waiters/BackgroundWorkerWaiter.mjs
  97. 38 2
      src/web/waiters/BindingsWaiter.mjs
  98. 44 25
      src/web/waiters/ControlsWaiter.mjs
  99. 2 0
      src/web/waiters/HighlighterWaiter.mjs
  100. 1371 0
      src/web/waiters/InputWaiter.mjs

+ 1 - 14
.github/ISSUE_TEMPLATE.md

@@ -1,14 +1 @@
-<!-- Prefix the title above with one of the following: -->
-<!-- Bug report: -->
-<!-- Operation request: -->
-<!-- Feature request: -->
-<!-- Misc: -->
-
-### Summary
-
-
-### Example
-<!-- If describing a bug, tell us what happens instead of the expected behavior -->
-<!-- Include a link that triggers the bug if possible -->
-<!-- If you are requesting a new operation, include example input and output -->
-
+<!-- Prefix the title above with 'Misc:' -->

+ 35 - 0
.github/ISSUE_TEMPLATE/bug_report.md

@@ -0,0 +1,35 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: 'Bug report: <Insert title here>'
+labels: bug
+assignees: ''
+
+---
+
+<!-- Prefix the title above with 'Bug report:' -->
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior or a link to the recipe / input used to cause the bug:
+
+1. Go to '...'
+2. Click on '....'
+3. Scroll down to '....'
+4. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots**
+If applicable, add screenshots to help explain your problem.
+
+**Desktop (if relevant, please complete the following information):**
+ - OS: [e.g. Windows] 
+ - Browser [e.g. chrome, safari]
+ - Version [e.g. 22]
+
+**Additional context**
+Add any other context about the problem here.
+

+ 20 - 0
.github/ISSUE_TEMPLATE/feature_request.md

@@ -0,0 +1,20 @@
+---
+name: Feature request
+about: Suggest an idea for the project
+title: 'Feature request: <Insert title here>'
+labels: feature
+assignees: ''
+
+---
+<!-- Prefix the title above with 'Feature request:' -->
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.

+ 16 - 0
.github/ISSUE_TEMPLATE/operation-request.md

@@ -0,0 +1,16 @@
+---
+name: Operation request
+about: Suggest a new operation
+title: 'Operation request: <Insert title here>'
+labels: operation
+assignees: ''
+
+---
+
+<!-- Prefix the title above with 'Operation request:' -->
+
+## Summary
+
+### Example Input
+
+### Example Output

+ 38 - 0
CHANGELOG.md

@@ -2,6 +2,28 @@
 All major and minor version changes will be documented in this file. Details of patch-level version changes can be found in [commit messages](https://github.com/gchq/CyberChef/commits/master).
 
 
+### [8.38.0] - 2019-07-03
+- 'Streebog' and 'GOST hash' operations added [@MShwed] [@n1474335] | [#530]
+
+### [8.37.0] - 2019-07-03
+- 'CRC-8 Checksum' operation added [@MShwed] | [#591]
+
+### [8.36.0] - 2019-07-03
+- 'PGP Verify' operation added [@artemisbot] | [#585]
+
+### [8.35.0] - 2019-07-03
+- 'Sharpen Image', 'Convert Image Format' and 'Add Text To Image' operations added [@j433866] | [#515]
+
+### [8.34.0] - 2019-06-28
+- Various new visualisations added to the 'Entropy' operation [@MShwed] | [#535]
+- Efficiency improvements made to the 'Entropy' operation for large file support [@n1474335]
+
+### [8.33.0] - 2019-06-27
+- 'Bzip2 Compress' operation added and 'Bzip2 Decompress' operation greatly improved [@artemisbot] | [#531]
+
+### [8.32.0] - 2019-06-27
+- 'Index of Coincidence' operation added [@Ge0rg3] | [#571]
+
 ### [8.31.0] - 2019-04-12
 - The downloadable version of CyberChef is now a .zip file containing separate modules rather than a single .htm file. It is still completely standalone and will not make any external network requests. This change reduces the complexity of the build process significantly. [@n1474335]
 
@@ -130,6 +152,13 @@ All major and minor version changes will be documented in this file. Details of
 
 
 
+[8.38.0]: https://github.com/gchq/CyberChef/releases/tag/v8.38.0
+[8.37.0]: https://github.com/gchq/CyberChef/releases/tag/v8.37.0
+[8.36.0]: https://github.com/gchq/CyberChef/releases/tag/v8.36.0
+[8.35.0]: https://github.com/gchq/CyberChef/releases/tag/v8.35.0
+[8.34.0]: https://github.com/gchq/CyberChef/releases/tag/v8.34.0
+[8.33.0]: https://github.com/gchq/CyberChef/releases/tag/v8.33.0
+[8.32.0]: https://github.com/gchq/CyberChef/releases/tag/v8.32.0
 [8.31.0]: https://github.com/gchq/CyberChef/releases/tag/v8.31.0
 [8.30.0]: https://github.com/gchq/CyberChef/releases/tag/v8.30.0
 [8.29.0]: https://github.com/gchq/CyberChef/releases/tag/v8.29.0
@@ -189,6 +218,8 @@ All major and minor version changes will be documented in this file. Details of
 [@Cynser]: https://github.com/Cynser
 [@anthony-arnold]: https://github.com/anthony-arnold
 [@masq]: https://github.com/masq
+[@Ge0rg3]: https://github.com/Ge0rg3
+[@MShwed]: https://github.com/MShwed
 
 [#95]: https://github.com/gchq/CyberChef/pull/299
 [#173]: https://github.com/gchq/CyberChef/pull/173
@@ -229,6 +260,13 @@ All major and minor version changes will be documented in this file. Details of
 [#489]: https://github.com/gchq/CyberChef/pull/489
 [#496]: https://github.com/gchq/CyberChef/pull/496
 [#506]: https://github.com/gchq/CyberChef/pull/506
+[#515]: https://github.com/gchq/CyberChef/pull/515
 [#516]: https://github.com/gchq/CyberChef/pull/516
 [#525]: https://github.com/gchq/CyberChef/pull/525
+[#530]: https://github.com/gchq/CyberChef/pull/530
+[#531]: https://github.com/gchq/CyberChef/pull/531
 [#533]: https://github.com/gchq/CyberChef/pull/533
+[#535]: https://github.com/gchq/CyberChef/pull/535
+[#571]: https://github.com/gchq/CyberChef/pull/571
+[#585]: https://github.com/gchq/CyberChef/pull/585
+[#591]: https://github.com/gchq/CyberChef/pull/591

+ 2 - 2
README.md

@@ -50,7 +50,7 @@ You can use as many operations as you like in simple or complex ways. Some examp
 
  - Drag and drop
      - Operations can be dragged in and out of the recipe list, or reorganised.
-     - Files up to 500MB can be dragged over the input box to load them directly into the browser.
+     - Files up to 2GB can be dragged over the input box to load them directly into the browser.
  - Auto Bake
      - Whenever you modify the input or the recipe, CyberChef will automatically "bake" for you and produce the output immediately.
      - This can be turned off and operated manually if it is affecting performance (if the input is very large, for instance).
@@ -67,7 +67,7 @@ You can use as many operations as you like in simple or complex ways. Some examp
  - Highlighting
      - When you highlight text in the input or output, the offset and length values will be displayed and, if possible, the corresponding data will be highlighted in the output or input respectively (example: [highlight the word 'question' in the input to see where it appears in the output][11]).
  - Save to file and load from file
-     - You can save the output to a file at any time or load a file by dragging and dropping it into the input field. Files up to around 500MB are supported (depending on your browser), however some operations may take a very long time to run over this much data.
+     - You can save the output to a file at any time or load a file by dragging and dropping it into the input field. Files up to around 2GB are supported (depending on your browser), however some operations may take a very long time to run over this much data.
  - CyberChef is entirely client-side
      - It should be noted that none of your recipe configuration or input (either text or files) is ever sent to the CyberChef web server - all processing is carried out within your browser, on your own computer.
      - Due to this feature, CyberChef can be compiled into a single HTML file. You can download this file and drop it into a virtual machine, share it with other people, or use it independently on your local machine.

+ 0 - 6
babel.config.js

@@ -4,12 +4,6 @@ module.exports = function(api) {
     return {
         "presets": [
             ["@babel/preset-env", {
-                "targets": {
-                    "chrome": 40,
-                    "firefox": 35,
-                    "edge": 14,
-                    "node": "6.5"
-                },
                 "modules": false,
                 "useBuiltIns": "entry",
                 "corejs": 3

Різницю між файлами не показано, бо вона завелика
+ 106 - 602
package-lock.json


+ 41 - 35
package.json

@@ -1,6 +1,6 @@
 {
   "name": "cyberchef",
-  "version": "8.31.4",
+  "version": "8.38.1",
   "description": "The Cyber Swiss Army Knife for encryption, encoding, compression and data analysis.",
   "author": "n1474335 <n1474335@gmail.com>",
   "homepage": "https://gchq.github.io/CyberChef",
@@ -30,29 +30,35 @@
   "main": "build/node/CyberChef.js",
   "module": "src/node/index.mjs",
   "bugs": "https://github.com/gchq/CyberChef/issues",
+  "browserslist": [
+    "Chrome >= 40",
+    "Firefox >= 35",
+    "Edge >= 14",
+    "node >= 6.5"
+  ],
   "devDependencies": {
-    "@babel/core": "^7.4.4",
+    "@babel/core": "^7.4.5",
     "@babel/plugin-transform-runtime": "^7.4.4",
-    "@babel/preset-env": "^7.4.4",
-    "autoprefixer": "^9.5.1",
-    "babel-eslint": "^10.0.1",
-    "babel-loader": "^8.0.5",
+    "@babel/preset-env": "^7.4.5",
+    "autoprefixer": "^9.6.0",
+    "babel-eslint": "^10.0.2",
+    "babel-loader": "^8.0.6",
     "babel-plugin-dynamic-import-node": "^2.2.0",
-    "chromedriver": "^74.0.0",
+    "chromedriver": "^75.0.0",
     "colors": "^1.3.3",
-    "css-loader": "^2.1.1",
-    "eslint": "^5.16.0",
+    "css-loader": "^3.0.0",
+    "eslint": "^6.0.1",
     "exports-loader": "^0.7.0",
-    "file-loader": "^3.0.1",
+    "file-loader": "^4.0.0",
     "grunt": "^1.0.4",
     "grunt-accessibility": "~6.0.0",
     "grunt-chmod": "~1.1.1",
-    "grunt-concurrent": "^2.3.1",
+    "grunt-concurrent": "^3.0.0",
     "grunt-contrib-clean": "~2.0.0",
     "grunt-contrib-connect": "^2.0.0",
     "grunt-contrib-copy": "~1.0.0",
     "grunt-contrib-watch": "^1.1.0",
-    "grunt-eslint": "^21.0.0",
+    "grunt-eslint": "^21.1.0",
     "grunt-exec": "~3.0.0",
     "grunt-jsdoc": "^2.4.0",
     "grunt-webpack": "^3.1.3",
@@ -61,44 +67,43 @@
     "imports-loader": "^0.8.0",
     "ink-docstrap": "^1.3.2",
     "jsdoc-babel": "^0.5.0",
-    "mini-css-extract-plugin": "^0.6.0",
-    "nightwatch": "^1.0.19",
+    "mini-css-extract-plugin": "^0.7.0",
+    "nightwatch": "^1.1.12",
     "node-sass": "^4.12.0",
-    "postcss-css-variables": "^0.12.0",
+    "postcss-css-variables": "^0.13.0",
     "postcss-import": "^12.0.1",
     "postcss-loader": "^3.0.0",
     "prompt": "^1.0.0",
     "sass-loader": "^7.1.0",
     "sitemap": "^2.2.0",
     "style-loader": "^0.23.1",
-    "svg-url-loader": "^2.3.2",
-    "uglifyjs-webpack-plugin": "^2.0.1",
-    "url-loader": "^1.1.2",
-    "webpack": "^4.31.0",
+    "svg-url-loader": "^2.3.3",
+    "url-loader": "^2.0.1",
+    "webpack": "^4.35.0",
     "webpack-bundle-analyzer": "^3.3.2",
-    "webpack-dev-server": "^3.3.1",
+    "webpack-dev-server": "^3.7.2",
     "webpack-node-externals": "^1.7.2",
     "worker-loader": "^2.0.0"
   },
   "dependencies": {
     "@babel/polyfill": "^7.4.4",
-    "@babel/runtime": "^7.4.4",
+    "@babel/runtime": "^7.4.5",
     "arrive": "^2.4.1",
     "babel-plugin-transform-builtin-extend": "1.1.2",
     "bcryptjs": "^2.4.3",
-    "bignumber.js": "^8.1.1",
+    "bignumber.js": "^9.0.0",
     "blakejs": "^1.1.0",
-    "bootstrap": "4.2.1",
+    "bootstrap": "4.3.1",
     "bootstrap-colorpicker": "^2.5.3",
-    "bootstrap-material-design": "^4.1.1",
+    "bootstrap-material-design": "^4.1.2",
     "bson": "^4.0.2",
     "chi-squared": "^1.1.0",
     "clippyjs": "0.0.3",
-    "core-js": "^3.0.1",
+    "core-js": "^3.1.4",
     "crypto-api": "^0.8.3",
     "crypto-js": "^3.1.9-1",
     "ctph.js": "0.0.5",
-    "d3": "^5.9.2",
+    "d3": "^5.9.4",
     "d3-hexbin": "^0.2.2",
     "diff": "^4.0.1",
     "es6-promisify": "^6.0.1",
@@ -106,27 +111,28 @@
     "esmangle": "^1.0.1",
     "esprima": "^4.0.1",
     "exif-parser": "^0.1.12",
-    "file-saver": "^2.0.1",
+    "file-saver": "^2.0.2",
     "geodesy": "^1.1.3",
-    "highlight.js": "^9.15.6",
+    "highlight.js": "^9.15.8",
     "jimp": "^0.6.4",
     "jquery": "3.4.1",
     "js-crc": "^0.2.0",
     "js-sha3": "^0.8.0",
     "jsesc": "^2.5.2",
-    "jsonpath": "^1.0.1",
+    "jsonpath": "^1.0.2",
     "jsonwebtoken": "^8.5.1",
     "jsqr": "^1.2.0",
     "jsrsasign": "8.0.12",
-    "kbpgp": "2.1.0",
+    "kbpgp": "2.1.2",
+    "libbzip2-wasm": "0.0.4",
     "libyara-wasm": "0.0.12",
     "lodash": "^4.17.11",
-    "loglevel": "^1.6.1",
+    "loglevel": "^1.6.3",
     "loglevel-message-prefix": "^3.0.0",
     "moment": "^2.24.0",
     "moment-timezone": "^0.5.25",
     "ngeohash": "^0.6.3",
-    "node-forge": "^0.8.2",
+    "node-forge": "^0.8.5",
     "node-md6": "^0.1.0",
     "nodom": "^2.2.0",
     "notepack.io": "^2.2.0",
@@ -134,12 +140,12 @@
     "otp": "^0.1.3",
     "popper.js": "^1.15.0",
     "qr-image": "^3.2.0",
-    "scryptsy": "^2.0.0",
+    "scryptsy": "^2.1.0",
     "snackbarjs": "^1.1.0",
     "sortablejs": "^1.9.0",
-    "split.js": "^1.5.10",
+    "split.js": "^1.5.11",
     "ssdeep.js": "0.0.2",
-    "ua-parser-js": "^0.7.19",
+    "ua-parser-js": "^0.7.20",
     "utf8": "^3.0.0",
     "vkbeautify": "^0.99.3",
     "xmldom": "^0.1.27",

+ 1 - 7
postcss.config.js

@@ -1,13 +1,7 @@
 module.exports = {
     plugins: [
         require("postcss-import"),
-        require("autoprefixer")({
-            browsers: [
-                "Chrome >= 40",
-                "Firefox >= 35",
-                "Edge >= 14"
-            ]
-        }),
+        require("autoprefixer"),
         require("postcss-css-variables")({
             preserve: true
         }),

+ 18 - 34
src/core/Chef.mjs

@@ -29,8 +29,6 @@ class Chef {
      * @param {Object[]} recipeConfig - The recipe configuration object
      * @param {Object} options - The options object storing various user choices
      * @param {boolean} options.attempHighlight - Whether or not to attempt highlighting
-     * @param {number} progress - The position in the recipe to start from
-     * @param {number} [step] - Whether to only execute one operation in the recipe
      *
      * @returns {Object} response
      * @returns {string} response.result - The output of the recipe
@@ -39,46 +37,20 @@ class Chef {
      * @returns {number} response.duration - The number of ms it took to execute the recipe
      * @returns {number} response.error - The error object thrown by a failed operation (false if no error)
     */
-    async bake(input, recipeConfig, options, progress, step) {
+    async bake(input, recipeConfig, options) {
         log.debug("Chef baking");
         const startTime = new Date().getTime(),
             recipe      = new Recipe(recipeConfig),
             containsFc  = recipe.containsFlowControl(),
             notUTF8     = options && options.hasOwnProperty("treatAsUtf8") && !options.treatAsUtf8;
-        let error = false;
-
-        if (containsFc && isWorkerEnvironment()) self.setOption("attemptHighlight", false);
-
-        // Clean up progress
-        if (progress >= recipeConfig.length) {
-            progress = 0;
-        }
-
-        if (step) {
-            // Unset breakpoint on this step
-            recipe.setBreakpoint(progress, false);
-            // Set breakpoint on next step
-            recipe.setBreakpoint(progress + 1, true);
-        }
-
-        // If the previously run operation presented a different value to its
-        // normal output, we need to recalculate it.
-        if (recipe.lastOpPresented(progress)) {
+        let error = false,
             progress = 0;
-        }
 
-        // If stepping with flow control, we have to start from the beginning
-        // but still want to skip all previous breakpoints
-        if (progress > 0 && containsFc) {
-            recipe.removeBreaksUpTo(progress);
-            progress = 0;
-        }
+        if (containsFc && isWorkerEnvironment()) self.setOption("attemptHighlight", false);
 
-        // If starting from scratch, load data
-        if (progress === 0) {
-            const type = input instanceof ArrayBuffer ? Dish.ARRAY_BUFFER : Dish.STRING;
-            this.dish.set(input, type);
-        }
+        // Load data
+        const type = input instanceof ArrayBuffer ? Dish.ARRAY_BUFFER : Dish.STRING;
+        this.dish.set(input, type);
 
         try {
             progress = await recipe.execute(this.dish, progress);
@@ -197,6 +169,18 @@ class Chef {
         return await newDish.get(type);
     }
 
+    /**
+     * Gets the title of a dish and returns it
+     *
+     * @param {Dish} dish
+     * @param {number} [maxLength=100]
+     * @returns {string}
+     */
+    async getDishTitle(dish, maxLength=100) {
+        const newDish = new Dish(dish);
+        return await newDish.getTitle(maxLength);
+    }
+
 }
 
 export default Chef;

+ 68 - 13
src/core/ChefWorker.js

@@ -25,6 +25,8 @@ self.chef = new Chef();
 
 self.OpModules = OpModules;
 self.OperationConfig = OperationConfig;
+self.inputNum = -1;
+
 
 // Tell the app that the worker has loaded and is ready to operate
 self.postMessage({
@@ -35,6 +37,9 @@ self.postMessage({
 /**
  * Respond to message from parent thread.
  *
+ * inputNum is optional and only used for baking multiple inputs.
+ * Defaults to -1 when one isn't sent with the bake message.
+ *
  * Messages should have the following format:
  * {
  *     action: "bake" | "silentBake",
@@ -43,8 +48,9 @@ self.postMessage({
  *         recipeConfig: {[Object]},
  *         options: {Object},
  *         progress: {number},
- *         step: {boolean}
- *     } | undefined
+ *         step: {boolean},
+ *         [inputNum=-1]: {number}
+ *     }
  * }
  */
 self.addEventListener("message", function(e) {
@@ -62,6 +68,9 @@ self.addEventListener("message", function(e) {
         case "getDishAs":
             getDishAs(r.data);
             break;
+        case "getDishTitle":
+            getDishTitle(r.data);
+            break;
         case "docURL":
             // Used to set the URL of the current document so that scripts can be
             // imported into an inline worker.
@@ -91,30 +100,35 @@ self.addEventListener("message", function(e) {
 async function bake(data) {
     // Ensure the relevant modules are loaded
     self.loadRequiredModules(data.recipeConfig);
-
     try {
+        self.inputNum = (data.inputNum !== undefined) ? data.inputNum : -1;
         const response = await self.chef.bake(
             data.input,          // The user's input
             data.recipeConfig,   // The configuration of the recipe
-            data.options,        // Options set by the user
-            data.progress,       // The current position in the recipe
-            data.step            // Whether or not to take one step or execute the whole recipe
+            data.options         // Options set by the user
         );
 
+        const transferable = (data.input instanceof ArrayBuffer) ? [data.input] : undefined;
         self.postMessage({
             action: "bakeComplete",
             data: Object.assign(response, {
-                id: data.id
+                id: data.id,
+                inputNum: data.inputNum,
+                bakeId: data.bakeId
             })
-        });
+        }, transferable);
+
     } catch (err) {
         self.postMessage({
             action: "bakeError",
-            data: Object.assign(err, {
-                id: data.id
-            })
+            data: {
+                error: err.message || err,
+                id: data.id,
+                inputNum: data.inputNum
+            }
         });
     }
+    self.inputNum = -1;
 }
 
 
@@ -136,13 +150,33 @@ function silentBake(data) {
  */
 async function getDishAs(data) {
     const value = await self.chef.getDishAs(data.dish, data.type);
-
+    const transferable = (data.type === "ArrayBuffer") ? [value] : undefined;
     self.postMessage({
         action: "dishReturned",
         data: {
             value: value,
             id: data.id
         }
+    }, transferable);
+}
+
+
+/**
+ * Gets the dish title
+ *
+ * @param {object} data
+ * @param {Dish} data.dish
+ * @param {number} data.maxLength
+ * @param {number} data.id
+ */
+async function getDishTitle(data) {
+    const title = await self.chef.getDishTitle(data.dish, data.maxLength);
+    self.postMessage({
+        action: "dishReturned",
+        data: {
+            value: title,
+            id: data.id
+        }
     });
 }
 
@@ -193,7 +227,28 @@ self.loadRequiredModules = function(recipeConfig) {
 self.sendStatusMessage = function(msg) {
     self.postMessage({
         action: "statusMessage",
-        data: msg
+        data: {
+            message: msg,
+            inputNum: self.inputNum
+        }
+    });
+};
+
+
+/**
+ * Send progress update to the app.
+ *
+ * @param {number} progress
+ * @param {number} total
+ */
+self.sendProgressMessage = function(progress, total) {
+    self.postMessage({
+        action: "progressMessage",
+        data: {
+            progress: progress,
+            total: total,
+            inputNum: self.inputNum
+        }
     });
 };
 

+ 49 - 0
src/core/Dish.mjs

@@ -8,6 +8,7 @@
 import Utils, { isNodeEnvironment } from "./Utils";
 import DishError from "./errors/DishError";
 import BigNumber from "bignumber.js";
+import { detectFileType } from "./lib/FileType";
 import log from "loglevel";
 
 import {
@@ -199,6 +200,54 @@ class Dish {
         return clone.get(type, notUTF8);
     }
 
+
+    /**
+     * Detects the MIME type of the current dish
+     * @returns {string}
+     */
+    async detectDishType() {
+        const data = new Uint8Array(this.value.slice(0, 2048)),
+            types = detectFileType(data);
+
+        if (!types.length || !types[0].mime || !types[0].mime === "text/plain") {
+            return null;
+        } else {
+            return types[0].mime;
+        }
+    }
+
+
+    /**
+     * Returns the title of the data up to the specified length
+     *
+     * @param {number} maxLength - The maximum title length
+     * @returns {string}
+     */
+    async getTitle(maxLength) {
+        let title = "";
+        let cloned;
+
+        switch (this.type) {
+            case Dish.FILE:
+                title = this.value.name;
+                break;
+            case Dish.LIST_FILE:
+                title = `${this.value.length} file(s)`;
+                break;
+            case Dish.ARRAY_BUFFER:
+            case Dish.BYTE_ARRAY:
+                title = await this.detectDishType();
+                if (title !== null) break;
+                // fall through if no mime type was detected
+            default:
+                cloned = this.clone();
+                cloned.value = cloned.value.slice(0, 256);
+                title = await cloned.get(Dish.STRING);
+        }
+
+        return title.slice(0, maxLength);
+    }
+
     /**
      * Validates that the value is the type that has been specified.
      * May have to disable parts of BYTE_ARRAY validation if it effects performance.

+ 6 - 1
src/core/Recipe.mjs

@@ -200,7 +200,12 @@ class Recipe  {
 
             try {
                 input = await dish.get(op.inputType);
-                log.debug("Executing operation");
+                log.debug(`Executing operation '${op.name}'`);
+
+                if (ENVIRONMENT_IS_WORKER()) {
+                    self.sendStatusMessage(`Baking... (${i+1}/${this.opList.length})`);
+                    self.sendProgressMessage(i + 1, this.opList.length);
+                }
 
                 if (op.flowControl) {
                     // Package up the current state

+ 11 - 2
src/core/Utils.mjs

@@ -200,11 +200,20 @@ class Utils {
      * Utils.parseEscapedChars("\\n");
      */
     static parseEscapedChars(str) {
-        return str.replace(/(\\)?\\([bfnrtv0'"]|x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]{1,6}\})/g, function(m, a, b) {
+        return str.replace(/(\\)?\\([bfnrtv'"]|[0-3][0-7]{2}|[0-7]{1,2}|x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]{1,6}\}|\\)/g, function(m, a, b) {
             if (a === "\\") return "\\"+b;
             switch (b[0]) {
+                case "\\":
+                    return "\\";
                 case "0":
-                    return "\0";
+                case "1":
+                case "2":
+                case "3":
+                case "4":
+                case "5":
+                case "6":
+                case "7":
+                    return String.fromCharCode(parseInt(b, 8));
                 case "b":
                     return "\b";
                 case "t":

+ 9 - 2
src/core/config/Categories.json

@@ -197,8 +197,8 @@
             "Remove null bytes",
             "To Upper case",
             "To Lower case",
-			"To Case Insensitive Regex",
-			"From Case Insensitive Regex",
+            "To Case Insensitive Regex",
+            "From Case Insensitive Regex",
             "Add line numbers",
             "Remove line numbers",
             "To Table",
@@ -302,6 +302,8 @@
             "Snefru",
             "BLAKE2b",
             "BLAKE2s",
+            "GOST hash",
+            "Streebog",
             "SSDEEP",
             "CTPH",
             "Compare SSDEEP hashes",
@@ -316,6 +318,7 @@
             "Fletcher-32 Checksum",
             "Fletcher-64 Checksum",
             "Adler-32 Checksum",
+            "CRC-8 Checksum",
             "CRC-16 Checksum",
             "CRC-32 Checksum",
             "TCP/IP Checksum"
@@ -384,6 +387,9 @@
             "Contain Image",
             "Cover Image",
             "Image Hue/Saturation/Lightness",
+            "Sharpen Image",
+            "Convert Image Format",
+            "Add Text To Image",
             "Hex Density chart",
             "Scatter chart",
             "Series chart",
@@ -395,6 +401,7 @@
         "ops": [
             "Entropy",
             "Frequency distribution",
+            "Index of Coincidence",
             "Chi Square",
             "Disassemble x86",
             "Pseudo-Random Number Generator",

+ 360 - 2
src/core/lib/FileSignatures.mjs

@@ -170,7 +170,7 @@ export const FILE_SIGNATURES = {
             mime: "image/vnd.adobe.photoshop",
             description: "",
             signature: {
-                0: 0x38,
+                0: 0x38, // 8BPS
                 1: 0x42,
                 2: 0x50,
                 3: 0x53,
@@ -185,6 +185,28 @@ export const FILE_SIGNATURES = {
             },
             extractor: null
         },
+        {
+            name: "Photoshop Large Document",
+            extension: "psb",
+            mime: "application/x-photoshop",
+            description: "",
+            signature: {
+                0: 0x38, // 8BPS
+                1: 0x42,
+                2: 0x50,
+                3: 0x53,
+                4: 0x0,
+                5: 0x2,
+                6: 0x0,
+                7: 0x0,
+                8: 0x0,
+                9: 0x0,
+                10: 0x0,
+                11: 0x0,
+                12: 0x0
+            },
+            extractor: null
+        },
         {
             name: "Paint Shop Pro image",
             extension: "psp",
@@ -233,10 +255,114 @@ export const FILE_SIGNATURES = {
                 5: 0x0,
                 6: [0x10, 0x20, 0x30, 0x40, 0x80],
                 7: [0x10, 0x20, 0x30, 0x40, 0x80],
-                9: 0x00,
+                9: 0x0,
                 10: [0x0, 0x1]
             },
             extractor: null
+        },
+        {
+            name: "Radiance High Dynamic Range image",
+            extension: "hdr",
+            mime: "image/vnd.radiance",
+            description: "",
+            signature: {
+                0: 0x23, // #?RADIANCE
+                1: 0x3f,
+                2: 0x52,
+                3: 0x41,
+                4: 0x44,
+                5: 0x49,
+                6: 0x41,
+                7: 0x4e,
+                8: 0x43,
+                9: 0x45,
+                10: 0x0a
+            },
+            extractor: null
+        },
+        {
+            name: "Sony ARW image",
+            extension: "arw",
+            mime: "image/x-raw",
+            description: "",
+            signature: {
+                0: 0x05,
+                1: 0x0,
+                2: 0x0,
+                3: 0x0,
+                4: 0x41,
+                5: 0x57,
+                6: 0x31,
+                7: 0x2e
+            },
+            extractor: null
+        },
+        {
+            name: "Fujifilm Raw Image",
+            extension: "raf",
+            mime: "image/x-raw",
+            description: "",
+            signature: {
+                0: 0x46, // FUJIFILMCCD-RAW
+                1: 0x55,
+                2: 0x4a,
+                3: 0x49,
+                4: 0x46,
+                5: 0x49,
+                6: 0x4c,
+                7: 0x4d,
+                8: 0x43,
+                9: 0x43,
+                10: 0x44,
+                11: 0x2d,
+                12: 0x52,
+                13: 0x41,
+                14: 0x57
+            },
+            extractor: null
+        },
+        {
+            name: "Minolta RAW image",
+            extension: "mrw",
+            mime: "image/x-raw",
+            description: "",
+            signature: {
+                0: 0x0,
+                1: 0x4d, // MRM
+                2: 0x52,
+                3: 0x4d
+            },
+            extractor: null
+        },
+        {
+            name: "Adobe Bridge Thumbnail Cache",
+            extension: "bct",
+            mime: "application/octet-stream",
+            description: "",
+            signature: {
+                0: 0x6c,
+                1: 0x6e,
+                2: 0x62,
+                3: 0x74,
+                4: 0x02,
+                5: 0x0,
+                6: 0x0,
+                7: 0x0
+            },
+            extractor: null
+        },
+        {
+            name: "Microsoft Document Imaging",
+            extension: "mdi",
+            mime: "image/vnd.ms-modi",
+            description: "",
+            signature: {
+                0: 0x45,
+                1: 0x50,
+                2: 0x2a,
+                3: 0x00
+            },
+            extractor: null
         }
     ],
     "Video": [
@@ -534,6 +660,97 @@ export const FILE_SIGNATURES = {
             },
             extractor: null
         },
+        {
+            name: "Audacity",
+            extension: "au",
+            mime: "audio/x-au",
+            description: "",
+            signature: {
+                0: 0x64, // dns.
+                1: 0x6e,
+                2: 0x73,
+                3: 0x2e,
+
+                24: 0x41, // AudacityBlockFile
+                25: 0x75,
+                26: 0x64,
+                27: 0x61,
+                28: 0x63,
+                29: 0x69,
+                30: 0x74,
+                31: 0x79,
+                32: 0x42,
+                33: 0x6c,
+                34: 0x6f,
+                35: 0x63,
+                36: 0x6b,
+                37: 0x46,
+                38: 0x69,
+                39: 0x6c,
+                40: 0x65
+            },
+            extractor: null
+        },
+        {
+            name: "Audacity Block",
+            extension: "auf",
+            mime: "application/octet-stream",
+            description: "",
+            signature: {
+                0: 0x41, // AudacityBlockFile
+                1: 0x75,
+                2: 0x64,
+                3: 0x61,
+                4: 0x63,
+                5: 0x69,
+                6: 0x74,
+                7: 0x79,
+                8: 0x42,
+                9: 0x6c,
+                10: 0x6f,
+                11: 0x63,
+                12: 0x6b,
+                13: 0x46,
+                14: 0x69,
+                15: 0x6c,
+                16: 0x65
+            },
+            extractor: null
+        },
+        {
+            name: "Audio Interchange File",
+            extension: "aif",
+            mime: "audio/x-aiff",
+            description: "",
+            signature: {
+                0: 0x46, // FORM
+                1: 0x4f,
+                2: 0x52,
+                3: 0x4d,
+                8: 0x41, // AIFF
+                9: 0x49,
+                10: 0x46,
+                11: 0x46
+            },
+            extractor: null
+        },
+        {
+            name: "Audio Interchange File (compressed)",
+            extension: "aifc",
+            mime: "audio/x-aifc",
+            description: "",
+            signature: {
+                0: 0x46, // FORM
+                1: 0x4f,
+                2: 0x52,
+                3: 0x4d,
+                8: 0x41, // AIFC
+                9: 0x49,
+                10: 0x46,
+                11: 0x43
+            },
+            extractor: null
+        }
     ],
     "Documents": [
         {
@@ -898,6 +1115,110 @@ export const FILE_SIGNATURES = {
             },
             extractor: null
         },
+        {
+            name: "ARJ Archive",
+            extension: "arj",
+            mime: "application/x-arj-compressed",
+            description: "",
+            signature: {
+                0: 0x60,
+                1: 0xea,
+                8: [0x0, 0x10, 0x14],
+                9: 0x0,
+                10: 0x2
+            },
+            extractor: null
+        },
+        {
+            name: "WinAce Archive",
+            extension: "ace",
+            mime: "application/x-ace-compressed",
+            description: "",
+            signature: {
+                7: 0x2a, // **ACE**
+                8: 0x2a,
+                9: 0x41,
+                10: 0x43,
+                11: 0x45,
+                12: 0x2a,
+                13: 0x2a
+            },
+            extractor: null
+        },
+        {
+            name: "Macintosh BinHex Encoded File",
+            extension: "hqx",
+            mime: "application/mac-binhex",
+            description: "",
+            signature: {
+                11: 0x6d,  // must be converted with BinHex
+                12: 0x75,
+                13: 0x73,
+                14: 0x74,
+                15: 0x20,
+                16: 0x62,
+                17: 0x65,
+                18: 0x20,
+                19: 0x63,
+                20: 0x6f,
+                21: 0x6e,
+                22: 0x76,
+                23: 0x65,
+                24: 0x72,
+                25: 0x74,
+                26: 0x65,
+                27: 0x64,
+                28: 0x20,
+                29: 0x77,
+                30: 0x69,
+                31: 0x74,
+                32: 0x68,
+                33: 0x20,
+                34: 0x42,
+                35: 0x69,
+                36: 0x6e,
+                37: 0x48,
+                38: 0x65,
+                39: 0x78
+            },
+            extractor: null
+        },
+        {
+            name: "ALZip Archive",
+            extension: "alz",
+            mime: "application/octet-stream",
+            description: "",
+            signature: {
+                0: 0x41, // ALZ
+                1: 0x4c,
+                2: 0x5a,
+                3: 0x01,
+                4: 0x0a,
+                5: 0x0,
+                6: 0x0,
+                7: 0x0
+            },
+            extractor: null
+        },
+        {
+            name: "KGB Compressed Archive",
+            extension: "kgb",
+            mime: "application/x-kgb-compressed",
+            description: "",
+            signature: {
+                0: 0x4b, // KGB_arch -
+                1: 0x47,
+                2: 0x42,
+                3: 0x5f,
+                4: 0x61,
+                5: 0x72,
+                6: 0x63,
+                7: 0x68,
+                8: 0x20,
+                9: 0x2d
+            },
+            extractor: null
+        }
     ],
     "Miscellaneous": [
         {
@@ -1041,6 +1362,43 @@ export const FILE_SIGNATURES = {
             },
             extractor: null
         },
+        {
+            name: "BitTorrent link",
+            extension: "torrent",
+            mime: "application/x-bittorrent",
+            description: "",
+            signature: [
+                {
+                    0: 0x64, // d8:announce##:
+                    1: 0x38,
+                    2: 0x3a,
+                    3: 0x61,
+                    4: 0x6e,
+                    5: 0x6e,
+                    6: 0x6f,
+                    7: 0x75,
+                    8: 0x6e,
+                    9: 0x63,
+                    10: 0x65,
+                    11: 0x23,
+                    12: 0x23,
+                    13: 0x3a
+                },
+                {
+                    0: 0x64, // d4:infod
+                    1: 0x34,
+                    2: 0x3a,
+                    3: 0x69,
+                    4: 0x6e,
+                    5: 0x66,
+                    6: 0x6f,
+                    7: 0x64,
+                    8: [0x34, 0x35, 0x36],
+                    9: 0x3a
+                }
+            ],
+            extractor: null
+        }
     ]
 };
 

+ 4 - 2
src/core/lib/Hex.mjs

@@ -12,7 +12,7 @@ import Utils from "../Utils";
 /**
  * Convert a byte array into a hex string.
  *
- * @param {Uint8Array|byteArray} data
+ * @param {byteArray|Uint8Array|ArrayBuffer} data
  * @param {string} [delim=" "]
  * @param {number} [padding=2]
  * @returns {string}
@@ -26,6 +26,7 @@ import Utils from "../Utils";
  */
 export function toHex(data, delim=" ", padding=2) {
     if (!data) return "";
+    if (data instanceof ArrayBuffer) data = new Uint8Array(data);
 
     let output = "";
 
@@ -47,7 +48,7 @@ export function toHex(data, delim=" ", padding=2) {
 /**
  * Convert a byte array into a hex string as efficiently as possible with no options.
  *
- * @param {byteArray} data
+ * @param {byteArray|Uint8Array|ArrayBuffer} data
  * @returns {string}
  *
  * @example
@@ -56,6 +57,7 @@ export function toHex(data, delim=" ", padding=2) {
  */
 export function toHexFast(data) {
     if (!data) return "";
+    if (data instanceof ArrayBuffer) data = new Uint8Array(data);
 
     const output = [];
 

+ 251 - 0
src/core/lib/ImageManipulation.mjs

@@ -0,0 +1,251 @@
+/**
+ * Image manipulation resources
+ *
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import OperationError from "../errors/OperationError";
+
+/**
+ * Gaussian blurs an image.
+ *
+ * @param {jimp} input
+ * @param {number} radius
+ * @param {boolean} fast
+ * @returns {jimp}
+ */
+export function gaussianBlur (input, radius) {
+    try {
+        // From http://blog.ivank.net/fastest-gaussian-blur.html
+        const boxes = boxesForGauss(radius, 3);
+        for (let i = 0; i < 3; i++) {
+            input = boxBlur(input, (boxes[i] - 1) / 2);
+        }
+    } catch (err) {
+        throw new OperationError(`Error blurring image. (${err})`);
+    }
+
+    return input;
+}
+
+/**
+ *
+ * @param {number} radius
+ * @param {number} numBoxes
+ * @returns {Array}
+ */
+function boxesForGauss(radius, numBoxes) {
+    const idealWidth = Math.sqrt((12 * radius * radius / numBoxes) + 1);
+
+    let wl = Math.floor(idealWidth);
+
+    if (wl % 2 === 0) {
+        wl--;
+    }
+
+    const wu = wl + 2;
+
+    const mIdeal = (12 * radius * radius - numBoxes * wl * wl - 4 * numBoxes * wl - 3 * numBoxes) / (-4 * wl - 4);
+    const m = Math.round(mIdeal);
+
+    const sizes = [];
+    for (let i = 0; i < numBoxes; i++) {
+        sizes.push(i < m ? wl : wu);
+    }
+    return sizes;
+}
+
+/**
+ * Applies a box blur effect to the image
+ *
+ * @param {jimp} source
+ * @param {number} radius
+ * @returns {jimp}
+ */
+function boxBlur (source, radius) {
+    const width = source.bitmap.width;
+    const height = source.bitmap.height;
+    let output = source.clone();
+    output = boxBlurH(source, output, width, height, radius);
+    source = boxBlurV(output, source, width, height, radius);
+
+    return source;
+}
+
+/**
+ * Applies the horizontal blur
+ *
+ * @param {jimp} source
+ * @param {jimp} output
+ * @param {number} width
+ * @param {number} height
+ * @param {number} radius
+ * @returns {jimp}
+ */
+function boxBlurH (source, output, width, height, radius) {
+    const iarr = 1 / (radius + radius + 1);
+    for (let i = 0; i < height; i++) {
+        let ti = 0,
+            li = ti,
+            ri = ti + radius;
+        const idx = source.getPixelIndex(ti, i);
+        const firstValRed = source.bitmap.data[idx],
+            firstValGreen = source.bitmap.data[idx + 1],
+            firstValBlue = source.bitmap.data[idx + 2],
+            firstValAlpha = source.bitmap.data[idx + 3];
+
+        const lastIdx = source.getPixelIndex(width - 1, i),
+            lastValRed = source.bitmap.data[lastIdx],
+            lastValGreen = source.bitmap.data[lastIdx + 1],
+            lastValBlue = source.bitmap.data[lastIdx + 2],
+            lastValAlpha = source.bitmap.data[lastIdx + 3];
+
+        let red = (radius + 1) * firstValRed;
+        let green = (radius + 1) * firstValGreen;
+        let blue = (radius + 1) * firstValBlue;
+        let alpha = (radius + 1) * firstValAlpha;
+
+        for (let j = 0; j < radius; j++) {
+            const jIdx = source.getPixelIndex(ti + j, i);
+            red += source.bitmap.data[jIdx];
+            green += source.bitmap.data[jIdx + 1];
+            blue += source.bitmap.data[jIdx + 2];
+            alpha += source.bitmap.data[jIdx + 3];
+        }
+
+        for (let j = 0; j <= radius; j++) {
+            const jIdx = source.getPixelIndex(ri++, i);
+            red += source.bitmap.data[jIdx] - firstValRed;
+            green += source.bitmap.data[jIdx + 1] - firstValGreen;
+            blue += source.bitmap.data[jIdx + 2] - firstValBlue;
+            alpha += source.bitmap.data[jIdx + 3] - firstValAlpha;
+
+            const tiIdx = source.getPixelIndex(ti++, i);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+
+        for (let j = radius + 1; j < width - radius; j++) {
+            const riIdx = source.getPixelIndex(ri++, i);
+            const liIdx = source.getPixelIndex(li++, i);
+            red += source.bitmap.data[riIdx] - source.bitmap.data[liIdx];
+            green += source.bitmap.data[riIdx + 1] - source.bitmap.data[liIdx + 1];
+            blue += source.bitmap.data[riIdx + 2] - source.bitmap.data[liIdx + 2];
+            alpha += source.bitmap.data[riIdx + 3] - source.bitmap.data[liIdx + 3];
+
+            const tiIdx = source.getPixelIndex(ti++, i);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+
+        for (let j = width - radius; j < width; j++) {
+            const liIdx = source.getPixelIndex(li++, i);
+            red += lastValRed - source.bitmap.data[liIdx];
+            green += lastValGreen - source.bitmap.data[liIdx + 1];
+            blue += lastValBlue - source.bitmap.data[liIdx + 2];
+            alpha += lastValAlpha - source.bitmap.data[liIdx + 3];
+
+            const tiIdx = source.getPixelIndex(ti++, i);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+    }
+    return output;
+}
+
+/**
+ * Applies the vertical blur
+ *
+ * @param {jimp} source
+ * @param {jimp} output
+ * @param {number} width
+ * @param {number} height
+ * @param {number} radius
+ * @returns {jimp}
+ */
+function boxBlurV (source, output, width, height, radius) {
+    const iarr = 1 / (radius + radius + 1);
+    for (let i = 0; i < width; i++) {
+        let ti = 0,
+            li = ti,
+            ri = ti + radius;
+
+        const idx = source.getPixelIndex(i, ti);
+
+        const firstValRed = source.bitmap.data[idx],
+            firstValGreen = source.bitmap.data[idx + 1],
+            firstValBlue = source.bitmap.data[idx + 2],
+            firstValAlpha = source.bitmap.data[idx + 3];
+
+        const lastIdx = source.getPixelIndex(i, height - 1),
+            lastValRed = source.bitmap.data[lastIdx],
+            lastValGreen = source.bitmap.data[lastIdx + 1],
+            lastValBlue = source.bitmap.data[lastIdx + 2],
+            lastValAlpha = source.bitmap.data[lastIdx + 3];
+
+        let red = (radius + 1) * firstValRed;
+        let green = (radius + 1) * firstValGreen;
+        let blue = (radius + 1) * firstValBlue;
+        let alpha = (radius + 1) * firstValAlpha;
+
+        for (let j = 0; j < radius; j++) {
+            const jIdx = source.getPixelIndex(i, ti + j);
+            red += source.bitmap.data[jIdx];
+            green += source.bitmap.data[jIdx + 1];
+            blue += source.bitmap.data[jIdx + 2];
+            alpha += source.bitmap.data[jIdx + 3];
+        }
+
+        for (let j = 0; j <= radius; j++) {
+            const riIdx = source.getPixelIndex(i, ri++);
+            red += source.bitmap.data[riIdx] - firstValRed;
+            green += source.bitmap.data[riIdx + 1] - firstValGreen;
+            blue += source.bitmap.data[riIdx + 2] - firstValBlue;
+            alpha += source.bitmap.data[riIdx + 3] - firstValAlpha;
+
+            const tiIdx = source.getPixelIndex(i, ti++);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+
+        for (let j = radius + 1; j < height - radius; j++) {
+            const riIdx = source.getPixelIndex(i, ri++);
+            const liIdx = source.getPixelIndex(i, li++);
+            red += source.bitmap.data[riIdx] - source.bitmap.data[liIdx];
+            green += source.bitmap.data[riIdx + 1] - source.bitmap.data[liIdx + 1];
+            blue += source.bitmap.data[riIdx + 2] - source.bitmap.data[liIdx + 2];
+            alpha += source.bitmap.data[riIdx + 3] - source.bitmap.data[liIdx + 3];
+
+            const tiIdx = source.getPixelIndex(i, ti++);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+
+        for (let j = height - radius; j < height; j++) {
+            const liIdx = source.getPixelIndex(i, li++);
+            red += lastValRed - source.bitmap.data[liIdx];
+            green += lastValGreen - source.bitmap.data[liIdx + 1];
+            blue += lastValBlue - source.bitmap.data[liIdx + 2];
+            alpha += lastValAlpha - source.bitmap.data[liIdx + 3];
+
+            const tiIdx = source.getPixelIndex(i, ti++);
+            output.bitmap.data[tiIdx] = Math.round(red * iarr);
+            output.bitmap.data[tiIdx + 1] = Math.round(green * iarr);
+            output.bitmap.data[tiIdx + 2] = Math.round(blue * iarr);
+            output.bitmap.data[tiIdx + 3] = Math.round(alpha * iarr);
+        }
+    }
+    return output;
+}

+ 11 - 1
src/core/lib/Magic.mjs

@@ -312,6 +312,11 @@ class Magic {
                 return;
             }
 
+            // If the recipe returned an empty buffer, do not continue
+            if (_buffersEqual(output, new ArrayBuffer())) {
+                return;
+            }
+
             const magic = new Magic(output, this.opPatterns),
                 speculativeResults = await magic.speculativeExecution(
                     depth-1, extLang, intensive, [...recipeConfig, opConfig], op.useful, crib);
@@ -395,7 +400,12 @@ class Magic {
         const recipe = new Recipe(recipeConfig);
         try {
             await recipe.execute(dish);
-            return dish.get(Dish.ARRAY_BUFFER);
+            // Return an empty buffer if the recipe did not run to completion
+            if (recipe.lastRunOp === recipe.opList[recipe.opList.length - 1]) {
+                return dish.get(Dish.ARRAY_BUFFER);
+            } else {
+                return new ArrayBuffer();
+            }
         } catch (err) {
             // If there are errors, return an empty buffer
             return new ArrayBuffer();

+ 93 - 0
src/core/lib/QRCode.mjs

@@ -0,0 +1,93 @@
+/**
+ * QR code resources
+ *
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import OperationError from "../errors/OperationError";
+import jsQR from "jsqr";
+import qr from "qr-image";
+import jimp from "jimp";
+import Utils from "../Utils";
+
+/**
+ * Parses a QR code image from an image
+ *
+ * @param {ArrayBuffer} input
+ * @param {boolean} normalise
+ * @returns {string}
+ */
+export async function parseQrCode(input, normalise) {
+    let image;
+    try {
+        image = await jimp.read(input);
+    } catch (err) {
+        throw new OperationError(`Error opening image. (${err})`);
+    }
+
+    try {
+        if (normalise) {
+            image.rgba(false);
+            image.background(0xFFFFFFFF);
+            image.normalize();
+            image.greyscale();
+            image = await image.getBufferAsync(jimp.MIME_JPEG);
+            image = await jimp.read(image);
+        }
+    } catch (err) {
+        throw new OperationError(`Error normalising iamge. (${err})`);
+    }
+
+    const qrData = jsQR(image.bitmap.data, image.getWidth(), image.getHeight());
+    if (qrData) {
+        return qrData.data;
+    } else {
+        throw new OperationError("Could not read a QR code from the image.");
+    }
+}
+
+/**
+ * Generates a QR code from the input string
+ *
+ * @param {string} input
+ * @param {string} format
+ * @param {number} moduleSize
+ * @param {number} margin
+ * @param {string} errorCorrection
+ * @returns {ArrayBuffer}
+ */
+export function generateQrCode(input, format, moduleSize, margin, errorCorrection) {
+    const formats = ["SVG", "EPS", "PDF", "PNG"];
+    if (!formats.includes(format.toUpperCase())) {
+        throw new OperationError("Unsupported QR code format.");
+    }
+
+    let qrImage;
+    try {
+        qrImage = qr.imageSync(input, {
+            type: format,
+            size: moduleSize,
+            margin: margin,
+            "ec_level": errorCorrection.charAt(0).toUpperCase()
+        });
+    } catch (err) {
+        throw new OperationError(`Error generating QR code. (${err})`);
+    }
+
+    if (!qrImage) {
+        throw new OperationError("Error generating QR code.");
+    }
+
+    switch (format) {
+        case "SVG":
+        case "EPS":
+        case "PDF":
+            return Utils.strToArrayBuffer(qrImage);
+        case "PNG":
+            return qrImage.buffer;
+        default:
+            throw new OperationError("Unsupported QR code format.");
+    }
+}

+ 2 - 2
src/core/operations/AESEncrypt.mjs

@@ -65,8 +65,8 @@ class AESEncrypt extends Operation {
      * @throws {OperationError} if invalid key length
      */
     run(input, args) {
-        const key = Utils.convertToByteArray(args[0].string, args[0].option),
-            iv = Utils.convertToByteArray(args[1].string, args[1].option),
+        const key = Utils.convertToByteString(args[0].string, args[0].option),
+            iv = Utils.convertToByteString(args[1].string, args[1].option),
             mode = args[2],
             inputType = args[3],
             outputType = args[4];

+ 266 - 0
src/core/operations/AddTextToImage.mjs

@@ -0,0 +1,266 @@
+/**
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import { isImage } from "../lib/FileType";
+import { toBase64 } from "../lib/Base64";
+import jimp from "jimp";
+
+/**
+ * Add Text To Image operation
+ */
+class AddTextToImage extends Operation {
+
+    /**
+     * AddTextToImage constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Add Text To Image";
+        this.module = "Image";
+        this.description = "Adds text onto an image.<br><br>Text can be horizontally or vertically aligned, or the position can be manually specified.<br>Variants of the Roboto font face are available in any size or colour.";
+        this.infoURL = "";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
+        this.presentType = "html";
+        this.args = [
+            {
+                name: "Text",
+                type: "string",
+                value: ""
+            },
+            {
+                name: "Horizontal align",
+                type: "option",
+                value: ["None", "Left", "Center", "Right"]
+            },
+            {
+                name: "Vertical align",
+                type: "option",
+                value: ["None", "Top", "Middle", "Bottom"]
+            },
+            {
+                name: "X position",
+                type: "number",
+                value: 0
+            },
+            {
+                name: "Y position",
+                type: "number",
+                value: 0
+            },
+            {
+                name: "Size",
+                type: "number",
+                value: 32,
+                min: 8
+            },
+            {
+                name: "Font face",
+                type: "option",
+                value: [
+                    "Roboto",
+                    "Roboto Black",
+                    "Roboto Mono",
+                    "Roboto Slab"
+                ]
+            },
+            {
+                name: "Red",
+                type: "number",
+                value: 255,
+                min: 0,
+                max: 255
+            },
+            {
+                name: "Green",
+                type: "number",
+                value: 255,
+                min: 0,
+                max: 255
+            },
+            {
+                name: "Blue",
+                type: "number",
+                value: 255,
+                min: 0,
+                max: 255
+            },
+            {
+                name: "Alpha",
+                type: "number",
+                value: 255,
+                min: 0,
+                max: 255
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {byteArray}
+     */
+    async run(input, args) {
+        const text = args[0],
+            hAlign = args[1],
+            vAlign = args[2],
+            size = args[5],
+            fontFace = args[6],
+            red = args[7],
+            green = args[8],
+            blue = args[9],
+            alpha = args[10];
+
+        let xPos = args[3],
+            yPos = args[4];
+
+        if (!isImage(new Uint8Array(input))) {
+            throw new OperationError("Invalid file type.");
+        }
+
+        let image;
+        try {
+            image = await jimp.read(input);
+        } catch (err) {
+            throw new OperationError(`Error loading image. (${err})`);
+        }
+        try {
+            if (ENVIRONMENT_IS_WORKER())
+                self.sendStatusMessage("Adding text to image...");
+
+            const fontsMap = {};
+            const fonts = [
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.fnt"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.fnt"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.fnt"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.fnt")
+            ];
+
+            await Promise.all(fonts)
+                .then(fonts => {
+                    fontsMap.Roboto = fonts[0];
+                    fontsMap["Roboto Black"] = fonts[1];
+                    fontsMap["Roboto Mono"] = fonts[2];
+                    fontsMap["Roboto Slab"] = fonts[3];
+                });
+
+
+            // Make Webpack load the png font images
+            await Promise.all([
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/Roboto72White.png"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoSlab72White.png"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoMono72White.png"),
+                import(/* webpackMode: "eager" */ "../../web/static/fonts/bmfonts/RobotoBlack72White.png")
+            ]);
+
+            const font = fontsMap[fontFace];
+
+            // LoadFont needs an absolute url, so append the font name to self.docURL
+            const jimpFont = await jimp.loadFont(self.docURL + "/" + font.default);
+
+            jimpFont.pages.forEach(function(page) {
+                if (page.bitmap) {
+                    // Adjust the RGB values of the image pages to change the font colour.
+                    const pageWidth = page.bitmap.width;
+                    const pageHeight = page.bitmap.height;
+                    for (let ix = 0; ix < pageWidth; ix++) {
+                        for (let iy = 0; iy < pageHeight; iy++) {
+                            const idx = (iy * pageWidth + ix) << 2;
+
+                            const newRed = page.bitmap.data[idx] - (255 - red);
+                            const newGreen = page.bitmap.data[idx + 1] - (255 - green);
+                            const newBlue = page.bitmap.data[idx + 2] - (255 - blue);
+                            const newAlpha = page.bitmap.data[idx + 3] - (255 - alpha);
+
+                            // Make sure the bitmap values don't go below 0 as that makes jimp very unhappy
+                            page.bitmap.data[idx] = (newRed > 0) ? newRed : 0;
+                            page.bitmap.data[idx + 1] = (newGreen > 0) ? newGreen : 0;
+                            page.bitmap.data[idx + 2] = (newBlue > 0) ? newBlue : 0;
+                            page.bitmap.data[idx + 3] = (newAlpha > 0) ? newAlpha : 0;
+                        }
+                    }
+                }
+            });
+
+            // Create a temporary image to hold the rendered text
+            const textImage = new jimp(jimp.measureText(jimpFont, text), jimp.measureTextHeight(jimpFont, text));
+            textImage.print(jimpFont, 0, 0, text);
+
+            // Scale the rendered text image to the correct size
+            const scaleFactor = size / 72;
+            if (size !== 1) {
+                // Use bicubic for decreasing size
+                if (size > 1) {
+                    textImage.scale(scaleFactor, jimp.RESIZE_BICUBIC);
+                } else {
+                    textImage.scale(scaleFactor, jimp.RESIZE_BILINEAR);
+                }
+            }
+
+            // If using the alignment options, calculate the pixel values AFTER the image has been scaled
+            switch (hAlign) {
+                case "Left":
+                    xPos = 0;
+                    break;
+                case "Center":
+                    xPos = (image.getWidth() / 2) - (textImage.getWidth() / 2);
+                    break;
+                case "Right":
+                    xPos = image.getWidth() - textImage.getWidth();
+                    break;
+            }
+
+            switch (vAlign) {
+                case "Top":
+                    yPos = 0;
+                    break;
+                case "Middle":
+                    yPos = (image.getHeight() / 2) - (textImage.getHeight() / 2);
+                    break;
+                case "Bottom":
+                    yPos = image.getHeight() - textImage.getHeight();
+                    break;
+            }
+
+            // Blit the rendered text image onto the original source image
+            image.blit(textImage, xPos, yPos);
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
+        } catch (err) {
+            throw new OperationError(`Error adding text to image. (${err})`);
+        }
+    }
+
+    /**
+     * Displays the blurred image using HTML for web apps
+     *
+     * @param {ArrayBuffer} data
+     * @returns {html}
+     */
+    present(data) {
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
+
+        const type = isImage(dataArray);
+        if (!type) {
+            throw new OperationError("Invalid file type.");
+        }
+
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
+    }
+
+}
+
+export default AddTextToImage;

+ 22 - 13
src/core/operations/BlurImage.mjs

@@ -10,6 +10,7 @@ import { isWorkerEnvironment } from "../Utils";
 import { isImage } from "../lib/FileType";
 import { toBase64 } from "../lib/Base64";
 import jimp from "jimp";
+import { gaussianBlur } from "../lib/ImageManipulation";
 
 /**
  * Blur Image operation
@@ -26,8 +27,8 @@ class BlurImage extends Operation {
         this.module = "Image";
         this.description = "Applies a blur effect to the image.<br><br>Gaussian blur is much slower than fast blur, but produces better results.";
         this.infoURL = "https://wikipedia.org/wiki/Gaussian_blur";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -45,37 +46,44 @@ class BlurImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [blurAmount, blurType] = args;
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
         try {
             switch (blurType){
                 case "Fast":
+                    if (isWorkerEnvironment())
+                        self.sendStatusMessage("Fast blurring image...");
                     image.blur(blurAmount);
                     break;
                 case "Gaussian":
                     if (isWorkerEnvironment())
-                        self.sendStatusMessage("Gaussian blurring image. This may take a while...");
-                    image.gaussian(blurAmount);
+                        self.sendStatusMessage("Gaussian blurring image...");
+                    image = gaussianBlur(image, blurAmount);
                     break;
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error blurring image. (${err})`);
         }
@@ -84,18 +92,19 @@ class BlurImage extends Operation {
     /**
      * Displays the blurred image using HTML for web apps
      *
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 72 - 0
src/core/operations/Bzip2Compress.mjs

@@ -0,0 +1,72 @@
+/**
+ * @author Matt C [me@mitt.dev]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import Bzip2 from "libbzip2-wasm";
+
+/**
+ * Bzip2 Compress operation
+ */
+class Bzip2Compress extends Operation {
+
+    /**
+     * Bzip2Compress constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Bzip2 Compress";
+        this.module = "Compression";
+        this.description = "Bzip2 is a compression library developed by Julian Seward (of GHC fame) that uses the Burrows-Wheeler algorithm. It only supports compressing single files and its compression is slow, however is more effective than Deflate (.gz & .zip).";
+        this.infoURL = "https://wikipedia.org/wiki/Bzip2";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
+        this.args = [
+            {
+                name: "Block size (100s of kb)",
+                type: "number",
+                value: 9,
+                min: 1,
+                max: 9
+            },
+            {
+                name: "Work factor",
+                type: "number",
+                value: 30
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {File}
+     */
+    run(input, args) {
+        const [blockSize, workFactor] = args;
+        if (input.byteLength <= 0) {
+            throw new OperationError("Please provide an input.");
+        }
+        if (ENVIRONMENT_IS_WORKER()) self.sendStatusMessage("Loading Bzip2...");
+        return new Promise((resolve, reject) => {
+            Bzip2().then(bzip2 => {
+                if (ENVIRONMENT_IS_WORKER()) self.sendStatusMessage("Compressing data...");
+                const inpArray = new Uint8Array(input);
+                const bzip2cc = bzip2.compressBZ2(inpArray, blockSize, workFactor);
+                if (bzip2cc.error !== 0) {
+                    reject(new OperationError(bzip2cc.error_msg));
+                } else {
+                    const output = bzip2cc.output;
+                    resolve(output.buffer.slice(output.byteOffset, output.byteLength + output.byteOffset));
+                }
+            });
+        });
+    }
+
+}
+
+export default Bzip2Compress;

+ 29 - 13
src/core/operations/Bzip2Decompress.mjs

@@ -1,12 +1,12 @@
 /**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2016
+ * @author Matt C [me@mitt.dev]
+ * @copyright Crown Copyright 2019
  * @license Apache-2.0
  */
 
 import Operation from "../Operation";
-import bzip2 from "../vendor/bzip2";
 import OperationError from "../errors/OperationError";
+import Bzip2 from "libbzip2-wasm";
 
 /**
  * Bzip2 Decompress operation
@@ -23,9 +23,15 @@ class Bzip2Decompress extends Operation {
         this.module = "Compression";
         this.description = "Decompresses data using the Bzip2 algorithm.";
         this.infoURL = "https://wikipedia.org/wiki/Bzip2";
-        this.inputType = "byteArray";
-        this.outputType = "string";
-        this.args = [];
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
+        this.args = [
+            {
+                name: "Use low-memory, slower decompression algorithm",
+                type: "boolean",
+                value: false
+            }
+        ];
         this.patterns = [
             {
                 "match": "^\\x42\\x5a\\x68",
@@ -41,14 +47,24 @@ class Bzip2Decompress extends Operation {
      * @returns {string}
      */
     run(input, args) {
-        const compressed = new Uint8Array(input);
-
-        try {
-            const bzip2Reader = bzip2.array(compressed);
-            return bzip2.simple(bzip2Reader);
-        } catch (err) {
-            throw new OperationError(err);
+        const [small] = args;
+        if (input.byteLength <= 0) {
+            throw new OperationError("Please provide an input.");
         }
+        if (ENVIRONMENT_IS_WORKER()) self.sendStatusMessage("Loading Bzip2...");
+        return new Promise((resolve, reject) => {
+            Bzip2().then(bzip2 => {
+                if (ENVIRONMENT_IS_WORKER()) self.sendStatusMessage("Decompressing data...");
+                const inpArray = new Uint8Array(input);
+                const bzip2cc = bzip2.decompressBZ2(inpArray, small ? 1 : 0);
+                if (bzip2cc.error !== 0) {
+                    reject(new OperationError(bzip2cc.error_msg));
+                } else {
+                    const output = bzip2cc.output;
+                    resolve(output.buffer.slice(output.byteOffset, output.byteLength + output.byteOffset));
+                }
+            });
+        });
     }
 
 }

+ 157 - 0
src/core/operations/CRC8Checksum.mjs

@@ -0,0 +1,157 @@
+/**
+ * @author mshwed [m@ttshwed.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+
+import { toHexFast } from "../lib/Hex";
+
+/**
+ * CRC-8 Checksum operation
+ */
+class CRC8Checksum extends Operation {
+
+    /**
+     * CRC8Checksum constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "CRC-8 Checksum";
+        this.module = "Crypto";
+        this.description = "A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to raw data.<br><br>The CRC was invented by W. Wesley Peterson in 1961.";
+        this.infoURL = "https://wikipedia.org/wiki/Cyclic_redundancy_check";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "string";
+        this.args = [
+            {
+                "name": "Algorithm",
+                "type": "option",
+                "value": [
+                    "CRC-8",
+                    "CRC-8/CDMA2000",
+                    "CRC-8/DARC",
+                    "CRC-8/DVB-S2",
+                    "CRC-8/EBU",
+                    "CRC-8/I-CODE",
+                    "CRC-8/ITU",
+                    "CRC-8/MAXIM",
+                    "CRC-8/ROHC",
+                    "CRC-8/WCDMA"
+                ]
+            }
+        ];
+    }
+
+    /**
+     * Generates the pre-computed lookup table for byte division
+     *
+     * @param polynomial
+     */
+    calculateCRC8LookupTable(polynomial) {
+        const crc8Table = new Uint8Array(256);
+
+        let currentByte;
+        for (let i = 0; i < 256; i++) {
+            currentByte = i;
+            for (let bit = 0; bit < 8; bit++) {
+                if ((currentByte & 0x80) !== 0) {
+                    currentByte <<= 1;
+                    currentByte ^= polynomial;
+                } else {
+                    currentByte <<= 1;
+                }
+            }
+
+            crc8Table[i] = currentByte;
+        }
+
+        return crc8Table;
+    }
+
+    /**
+     * Calculates the CRC-8 Checksum from an input
+     *
+     * @param {ArrayBuffer} input
+     * @param {number} polynomial
+     * @param {number} initializationValue
+     * @param {boolean} inputReflection
+     * @param {boolean} outputReflection
+     * @param {number} xorOut
+     */
+    calculateCRC8(input, polynomial, initializationValue, inputReflection, outputReflection, xorOut) {
+        const crcSize = 8;
+        const crcTable = this.calculateCRC8LookupTable(polynomial);
+
+        let crc = initializationValue !== 0 ? initializationValue : 0;
+        let currentByte, position;
+
+        input = new Uint8Array(input);
+        for (const inputByte of input) {
+            currentByte = inputReflection ? this.reverseBits(inputByte, crcSize) : inputByte;
+
+            position = (currentByte ^ crc) & 255;
+            crc = crcTable[position];
+        }
+
+        crc = outputReflection ? this.reverseBits(crc, crcSize) : crc;
+
+        if (xorOut !== 0) crc = crc ^ xorOut;
+
+        return toHexFast(new Uint8Array([crc]));
+    }
+
+    /**
+     * Reverse the bits for a given input byte.
+     *
+     * @param {number} input
+     */
+    reverseBits(input, hashSize) {
+        let reversedByte = 0;
+        for (let i = hashSize - 1; i >= 0; i--) {
+            reversedByte |= ((input & 1) << i);
+            input >>= 1;
+        }
+
+        return reversedByte;
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {string}
+     */
+    run(input, args) {
+        const algorithm = args[0];
+
+        switch (algorithm) {
+            case "CRC-8":
+                return this.calculateCRC8(input, 0x7, 0x0, false, false, 0x0);
+            case "CRC-8/CDMA2000":
+                return this.calculateCRC8(input, 0x9B, 0xFF, false, false, 0x0);
+            case "CRC-8/DARC":
+                return this.calculateCRC8(input, 0x39, 0x0, true, true, 0x0);
+            case "CRC-8/DVB-S2":
+                return this.calculateCRC8(input, 0xD5, 0x0, false, false, 0x0);
+            case "CRC-8/EBU":
+                return this.calculateCRC8(input, 0x1D, 0xFF, true, true, 0x0);
+            case "CRC-8/I-CODE":
+                return this.calculateCRC8(input, 0x1D, 0xFD, false, false, 0x0);
+            case "CRC-8/ITU":
+                return this.calculateCRC8(input, 0x7, 0x0, false, false, 0x55);
+            case "CRC-8/MAXIM":
+                return this.calculateCRC8(input, 0x31, 0x0, true, true, 0x0);
+            case "CRC-8/ROHC":
+                return this.calculateCRC8(input, 0x7, 0xFF, true, true, 0x0);
+            case "CRC-8/WCDMA":
+                return this.calculateCRC8(input, 0x9B, 0x0, true, true, 0x0);
+            default:
+                throw new OperationError("Unknown checksum algorithm");
+        }
+    }
+}
+
+export default CRC8Checksum;

+ 30 - 12
src/core/operations/ContainImage.mjs

@@ -26,8 +26,8 @@ class ContainImage extends Operation {
         this.module = "Image";
         this.description = "Scales an image to the specified width and height, maintaining the aspect ratio. The image may be letterboxed.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -73,17 +73,22 @@ class ContainImage extends Operation {
                     "Bezier"
                 ],
                 defaultIndex: 1
+            },
+            {
+                name: "Opaque background",
+                type: "boolean",
+                value: true
             }
         ];
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
-        const [width, height, hAlign, vAlign, alg] = args;
+        const [width, height, hAlign, vAlign, alg, opaqueBg] = args;
 
         const resizeMap = {
             "Nearest Neighbour": jimp.RESIZE_NEAREST_NEIGHBOR,
@@ -102,13 +107,13 @@ class ContainImage extends Operation {
             "Bottom": jimp.VERTICAL_ALIGN_BOTTOM
         };
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -116,8 +121,20 @@ class ContainImage extends Operation {
             if (isWorkerEnvironment())
                 self.sendStatusMessage("Containing image...");
             image.contain(width, height, alignMap[hAlign] | alignMap[vAlign], resizeMap[alg]);
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+
+            if (opaqueBg) {
+                const newImage = await jimp.read(width, height, 0x000000FF);
+                newImage.blit(image, 0, 0);
+                image = newImage;
+            }
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error containing image. (${err})`);
         }
@@ -125,18 +142,19 @@ class ContainImage extends Operation {
 
     /**
      * Displays the contained image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 143 - 0
src/core/operations/ConvertImageFormat.mjs

@@ -0,0 +1,143 @@
+/**
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import { isImage } from "../lib/FileType";
+import { toBase64 } from "../lib/Base64";
+import jimp from "jimp";
+
+/**
+ * Convert Image Format operation
+ */
+class ConvertImageFormat extends Operation {
+
+    /**
+     * ConvertImageFormat constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Convert Image Format";
+        this.module = "Image";
+        this.description = "Converts an image between different formats. Supported formats:<br><ul><li>Joint Photographic Experts Group (JPEG)</li><li>Portable Network Graphics (PNG)</li><li>Bitmap (BMP)</li><li>Tagged Image File Format (TIFF)</li></ul><br>Note: GIF files are supported for input, but cannot be outputted.";
+        this.infoURL = "https://wikipedia.org/wiki/Image_file_formats";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
+        this.presentType = "html";
+        this.args = [
+            {
+                name: "Output Format",
+                type: "option",
+                value: [
+                    "JPEG",
+                    "PNG",
+                    "BMP",
+                    "TIFF"
+                ]
+            },
+            {
+                name: "JPEG Quality",
+                type: "number",
+                value: 80,
+                min: 1,
+                max: 100
+            },
+            {
+                name: "PNG Filter Type",
+                type: "option",
+                value: [
+                    "Auto",
+                    "None",
+                    "Sub",
+                    "Up",
+                    "Average",
+                    "Paeth"
+                ]
+            },
+            {
+                name: "PNG Deflate Level",
+                type: "number",
+                value: 9,
+                min: 0,
+                max: 9
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {byteArray}
+     */
+    async run(input, args) {
+        const [format, jpegQuality, pngFilterType, pngDeflateLevel] = args;
+        const formatMap = {
+            "JPEG": jimp.MIME_JPEG,
+            "PNG": jimp.MIME_PNG,
+            "BMP": jimp.MIME_BMP,
+            "TIFF": jimp.MIME_TIFF
+        };
+
+        const pngFilterMap = {
+            "Auto": jimp.PNG_FILTER_AUTO,
+            "None": jimp.PNG_FILTER_NONE,
+            "Sub": jimp.PNG_FILTER_SUB,
+            "Up": jimp.PNG_FILTER_UP,
+            "Average": jimp.PNG_FILTER_AVERAGE,
+            "Paeth": jimp.PNG_FILTER_PATH // Incorrect spelling in Jimp library
+        };
+
+        const mime = formatMap[format];
+
+        if (!isImage(new Uint8Array(input))) {
+            throw new OperationError("Invalid file format.");
+        }
+        let image;
+        try {
+            image = await jimp.read(input);
+        } catch (err) {
+            throw new OperationError(`Error opening image file. (${err})`);
+        }
+        try {
+            switch (format) {
+                case "JPEG":
+                    image.quality(jpegQuality);
+                    break;
+                case "PNG":
+                    image.filterType(pngFilterMap[pngFilterType]);
+                    image.deflateLevel(pngDeflateLevel);
+                    break;
+            }
+
+            const imageBuffer = await image.getBufferAsync(mime);
+            return imageBuffer.buffer;
+        } catch (err) {
+            throw new OperationError(`Error converting image format. (${err})`);
+        }
+    }
+
+    /**
+     * Displays the converted image using HTML for web apps
+     *
+     * @param {ArrayBuffer} data
+     * @returns {html}
+     */
+    present(data) {
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
+
+        const type = isImage(dataArray);
+        if (!type) {
+            throw new OperationError("Invalid file type.");
+        }
+
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
+    }
+
+}
+
+export default ConvertImageFormat;

+ 17 - 11
src/core/operations/CoverImage.mjs

@@ -26,8 +26,8 @@ class CoverImage extends Operation {
         this.module = "Image";
         this.description = "Scales the image to the given width and height, keeping the aspect ratio. The image may be clipped.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -78,7 +78,7 @@ class CoverImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
@@ -102,13 +102,13 @@ class CoverImage extends Operation {
             "Bottom": jimp.VERTICAL_ALIGN_BOTTOM
         };
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -116,8 +116,13 @@ class CoverImage extends Operation {
             if (isWorkerEnvironment())
                 self.sendStatusMessage("Covering image...");
             image.cover(width, height, alignMap[hAlign] | alignMap[vAlign], resizeMap[alg]);
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error covering image. (${err})`);
         }
@@ -125,18 +130,19 @@ class CoverImage extends Operation {
 
     /**
      * Displays the covered image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 17 - 11
src/core/operations/CropImage.mjs

@@ -26,8 +26,8 @@ class CropImage extends Operation {
         this.module = "Image";
         this.description = "Crops an image to the specified region, or automatically crops edges.<br><br><b><u>Autocrop</u></b><br>Automatically crops same-colour borders from the image.<br><br><u>Autocrop tolerance</u><br>A percentage value for the tolerance of colour difference between pixels.<br><br><u>Only autocrop frames</u><br>Only crop real frames (all sides must have the same border)<br><br><u>Symmetric autocrop</u><br>Force autocrop to be symmetric (top/bottom and left/right are cropped by the same amount)<br><br><u>Autocrop keep border</u><br>The number of pixels of border to leave around the image.";
         this.infoURL = "https://wikipedia.org/wiki/Cropping_(image)";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -87,19 +87,19 @@ class CropImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [xPos, yPos, width, height, autocrop, autoTolerance, autoFrames, autoSymmetric, autoBorder] = args;
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -117,8 +117,13 @@ class CropImage extends Operation {
                 image.crop(xPos, yPos, width, height);
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error cropping image. (${err})`);
         }
@@ -126,18 +131,19 @@ class CropImage extends Operation {
 
     /**
      * Displays the cropped image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 14 - 8
src/core/operations/DetectFileType.mjs

@@ -21,7 +21,12 @@ class DetectFileType extends Operation {
 
         this.name = "Detect File Type";
         this.module = "Default";
-        this.description = "Attempts to guess the MIME (Multipurpose Internet Mail Extensions) type of the data based on 'magic bytes'.<br><br>Currently supports the following file types: 7z, amr, avi, bmp, bz2, class, cr2, crx, dex, dmg, doc, elf, eot, epub, exe, flac, flv, gif, gz, ico, iso, jpg, jxr, m4a, m4v, mid, mkv, mov, mp3, mp4, mpg, ogg, otf, pdf, png, ppt, ps, psd, rar, rtf, sqlite, swf, tar, tar.z, tif, ttf, utf8, vmdk, wav, webm, webp, wmv, woff, woff2, xls, xz, zip.";
+        this.description = "Attempts to guess the MIME (Multipurpose Internet Mail Extensions) type of the data based on 'magic bytes'.<br><br>Currently supports the following file types: " +
+            Object.keys(FILE_SIGNATURES).map(cat =>
+                FILE_SIGNATURES[cat].map(sig =>
+                    sig.extension.split(",")[0]
+                ).join(", ")
+            ).join(", ") + ".";
         this.infoURL = "https://wikipedia.org/wiki/List_of_file_signatures";
         this.inputType = "ArrayBuffer";
         this.outputType = "string";
@@ -52,18 +57,19 @@ class DetectFileType extends Operation {
         if (!types.length) {
             return "Unknown file type. Have you tried checking the entropy of this data to determine whether it might be encrypted or compressed?";
         } else {
-            let output = "";
-
-            types.forEach(type => {
-                output += "File extension: " + type.extension + "\n" +
-                    "MIME type:      " + type.mime + "\n";
+            const results = types.map(type => {
+                let output = `File type:   ${type.name}
+Extension:   ${type.extension}
+MIME type:   ${type.mime}\n`;
 
                 if (type.description && type.description.length) {
-                    output += "\nDescription:    " + type.description + "\n";
+                    output += `Description: ${type.description}\n`;
                 }
+
+                return output;
             });
 
-            return output;
+            return results.join("\n");
         }
     }
 

+ 18 - 11
src/core/operations/DitherImage.mjs

@@ -26,25 +26,25 @@ class DitherImage extends Operation {
         this.module = "Image";
         this.description = "Apply a dither effect to an image.";
         this.infoURL = "https://wikipedia.org/wiki/Dither";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [];
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -52,8 +52,14 @@ class DitherImage extends Operation {
             if (isWorkerEnvironment())
                 self.sendStatusMessage("Applying dither to image...");
             image.dither565();
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error applying dither to image. (${err})`);
         }
@@ -61,18 +67,19 @@ class DitherImage extends Operation {
 
     /**
      * Displays the dithered image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 374 - 41
src/core/operations/Entropy.mjs

@@ -4,8 +4,13 @@
  * @license Apache-2.0
  */
 
+import * as d3temp from "d3";
+import * as nodomtemp from "nodom";
+
 import Operation from "../Operation";
-import Utils from "../Utils";
+
+const d3 = d3temp.default ? d3temp.default : d3temp;
+const nodom = nodomtemp.default ? nodomtemp.default: nodomtemp;
 
 /**
  * Entropy operation
@@ -19,30 +24,45 @@ class Entropy extends Operation {
         super();
 
         this.name = "Entropy";
-        this.module = "Default";
+        this.module = "Charts";
         this.description = "Shannon Entropy, in the context of information theory, is a measure of the rate at which information is produced by a source of data. It can be used, in a broad sense, to detect whether data is likely to be structured or unstructured. 8 is the maximum, representing highly unstructured, 'random' data. English language text usually falls somewhere between 3.5 and 5. Properly encrypted or compressed data should have an entropy of over 7.5.";
         this.infoURL = "https://wikipedia.org/wiki/Entropy_(information_theory)";
-        this.inputType = "byteArray";
-        this.outputType = "number";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "json";
         this.presentType = "html";
-        this.args = [];
+        this.args = [
+            {
+                "name": "Visualisation",
+                "type": "option",
+                "value": ["Shannon scale", "Histogram (Bar)", "Histogram (Line)", "Curve", "Image"]
+            }
+        ];
     }
 
     /**
-     * @param {byteArray} input
-     * @param {Object[]} args
+     * Calculates the frequency of bytes in the input.
+     *
+     * @param {Uint8Array} input
      * @returns {number}
      */
-    run(input, args) {
+    calculateShannonEntropy(input) {
         const prob = [],
-            uniques = input.unique(),
-            str = Utils.byteArrayToChars(input);
+            occurrences = new Array(256).fill(0);
+
+        // Count occurrences of each byte in the input
         let i;
+        for (i = 0; i < input.length; i++) {
+            occurrences[input[i]]++;
+        }
 
-        for (i = 0; i < uniques.length; i++) {
-            prob.push(str.count(Utils.chr(uniques[i])) / input.length);
+        // Store probability list
+        for (i = 0; i < occurrences.length; i++) {
+            if (occurrences[i] > 0) {
+                prob.push(occurrences[i] / input.length);
+            }
         }
 
+        // Calculate Shannon entropy
         let entropy = 0,
             p;
 
@@ -54,44 +74,357 @@ class Entropy extends Operation {
         return -entropy;
     }
 
+    /**
+     * Calculates the scanning entropy of the input
+     *
+     * @param {Uint8Array} inputBytes
+     * @returns {Object}
+     */
+    calculateScanningEntropy(inputBytes) {
+        const entropyData = [];
+        const binWidth = inputBytes.length < 256 ? 8 : 256;
+
+        for (let bytePos = 0; bytePos < inputBytes.length; bytePos += binWidth) {
+            const block = inputBytes.slice(bytePos, bytePos+binWidth);
+            entropyData.push(this.calculateShannonEntropy(block));
+        }
+
+        return { entropyData, binWidth };
+    }
+
+    /**
+     * Calculates the frequency of bytes in the input.
+     *
+     * @param {object} svg
+     * @param {function} xScale
+     * @param {function} yScale
+     * @param {integer} svgHeight
+     * @param {integer} svgWidth
+     * @param {object} margins
+     * @param {string} xTitle
+     * @param {string} yTitle
+     */
+    createAxes(svg, xScale, yScale, svgHeight, svgWidth, margins, title, xTitle, yTitle) {
+        // Axes
+        const yAxis = d3.axisLeft()
+            .scale(yScale);
+
+        const xAxis = d3.axisBottom()
+            .scale(xScale);
+
+        svg.append("g")
+            .attr("transform", `translate(0, ${svgHeight - margins.bottom})`)
+            .call(xAxis);
+
+        svg.append("g")
+            .attr("transform", `translate(${margins.left},0)`)
+            .call(yAxis);
+
+        // Axes labels
+        svg.append("text")
+            .attr("transform", "rotate(-90)")
+            .attr("y", 0 - margins.left)
+            .attr("x", 0 - (svgHeight / 2))
+            .attr("dy", "1em")
+            .style("text-anchor", "middle")
+            .text(yTitle);
+
+        svg.append("text")
+            .attr("transform", `translate(${svgWidth / 2}, ${svgHeight - margins.bottom + 40})`)
+            .style("text-anchor", "middle")
+            .text(xTitle);
+
+        // Add title
+        svg.append("text")
+            .attr("transform", `translate(${svgWidth / 2}, ${margins.top - 10})`)
+            .style("text-anchor", "middle")
+            .text(title);
+    }
+
+    /**
+     * Calculates the frequency of bytes in the input.
+     *
+     * @param {Uint8Array} inputBytes
+     * @returns {number[]}
+     */
+    calculateByteFrequency(inputBytes) {
+        const freq = new Array(256).fill(0);
+        if (inputBytes.length === 0) return freq;
+
+        // Count occurrences of each byte in the input
+        let i;
+        for (i = 0; i < inputBytes.length; i++) {
+            freq[inputBytes[i]]++;
+        }
+
+        for (i = 0; i < freq.length; i++) {
+            freq[i] = freq[i] / inputBytes.length;
+        }
+
+        return freq;
+    }
+
+    /**
+     * Calculates the frequency of bytes in the input.
+     *
+     * @param {number[]} byteFrequency
+     * @returns {HTML}
+     */
+    createByteFrequencyLineHistogram(byteFrequency) {
+        const margins = { top: 30, right: 20, bottom: 50, left: 30 };
+
+        const svgWidth = 500,
+            svgHeight = 500;
+
+        const document = new nodom.Document();
+        let svg = document.createElement("svg");
+
+        svg = d3.select(svg)
+            .attr("width", "100%")
+            .attr("height", "100%")
+            .attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
+
+        const yScale = d3.scaleLinear()
+            .domain([0, d3.max(byteFrequency, d => d)])
+            .range([svgHeight - margins.bottom, margins.top]);
+
+        const xScale = d3.scaleLinear()
+            .domain([0, byteFrequency.length - 1])
+            .range([margins.left, svgWidth - margins.right]);
+
+        const line = d3.line()
+            .x((_, i) => xScale(i))
+            .y(d => yScale(d))
+            .curve(d3.curveMonotoneX);
+
+        svg.append("path")
+            .datum(byteFrequency)
+            .attr("fill", "none")
+            .attr("stroke", "steelblue")
+            .attr("d", line);
+
+        this.createAxes(svg, xScale, yScale, svgHeight, svgWidth, margins, "", "Byte", "Byte Frequency");
+
+        return svg._groups[0][0].outerHTML;
+    }
+
+    /**
+     * Creates a byte frequency histogram
+     *
+     * @param {number[]} byteFrequency
+     * @returns {HTML}
+     */
+    createByteFrequencyBarHistogram(byteFrequency) {
+        const margins = { top: 30, right: 20, bottom: 50, left: 30 };
+
+        const svgWidth = 500,
+            svgHeight = 500,
+            binWidth = 1;
+
+        const document = new nodom.Document();
+        let svg = document.createElement("svg");
+        svg = d3.select(svg)
+            .attr("width", "100%")
+            .attr("height", "100%")
+            .attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
+
+        const yExtent = d3.extent(byteFrequency, d => d);
+        const yScale = d3.scaleLinear()
+            .domain(yExtent)
+            .range([svgHeight - margins.bottom, margins.top]);
+
+        const xScale = d3.scaleLinear()
+            .domain([0, byteFrequency.length - 1])
+            .range([margins.left - binWidth, svgWidth - margins.right]);
+
+        svg.selectAll("rect")
+            .data(byteFrequency)
+            .enter().append("rect")
+            .attr("x", (_, i) => xScale(i) + binWidth)
+            .attr("y", dataPoint => yScale(dataPoint))
+            .attr("width", binWidth)
+            .attr("height", dataPoint => yScale(yExtent[0]) - yScale(dataPoint))
+            .attr("fill", "blue");
+
+        this.createAxes(svg, xScale, yScale, svgHeight, svgWidth, margins, "", "Byte", "Byte Frequency");
+
+        return svg._groups[0][0].outerHTML;
+    }
+
+    /**
+     * Creates a byte frequency histogram
+     *
+     * @param {number[]} entropyData
+     * @returns {HTML}
+     */
+    createEntropyCurve(entropyData) {
+        const margins = { top: 30, right: 20, bottom: 50, left: 30 };
+
+        const svgWidth = 500,
+            svgHeight = 500;
+
+        const document = new nodom.Document();
+        let svg = document.createElement("svg");
+        svg = d3.select(svg)
+            .attr("width", "100%")
+            .attr("height", "100%")
+            .attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
+
+        const yScale = d3.scaleLinear()
+            .domain([0, d3.max(entropyData, d => d)])
+            .range([svgHeight - margins.bottom, margins.top]);
+
+        const xScale = d3.scaleLinear()
+            .domain([0, entropyData.length])
+            .range([margins.left, svgWidth - margins.right]);
+
+        const line = d3.line()
+            .x((_, i) => xScale(i))
+            .y(d => yScale(d))
+            .curve(d3.curveMonotoneX);
+
+        if (entropyData.length > 0) {
+            svg.append("path")
+                .datum(entropyData)
+                .attr("d", line);
+
+            svg.selectAll("path").attr("fill", "none").attr("stroke", "steelblue");
+        }
+
+        this.createAxes(svg, xScale, yScale, svgHeight, svgWidth, margins, "Scanning Entropy", "Block", "Entropy");
+
+        return svg._groups[0][0].outerHTML;
+    }
+
+    /**
+     * Creates an image representation of the entropy
+     *
+     * @param {number[]} entropyData
+     * @returns {HTML}
+     */
+    createEntropyImage(entropyData) {
+        const svgHeight = 100,
+            svgWidth = 100,
+            cellSize = 1,
+            nodes = [];
+
+        for (let i = 0; i < entropyData.length; i++) {
+            nodes.push({
+                x: i % svgWidth,
+                y: Math.floor(i / svgWidth),
+                entropy: entropyData[i]
+            });
+        }
+
+        const document = new nodom.Document();
+        let svg = document.createElement("svg");
+        svg = d3.select(svg)
+            .attr("width", "100%")
+            .attr("height", "100%")
+            .attr("viewBox", `0 0 ${svgWidth} ${svgHeight}`);
+
+        const greyScale = d3.scaleLinear()
+            .domain([0, d3.max(entropyData, d => d)])
+            .range(["#000000", "#FFFFFF"])
+            .interpolate(d3.interpolateRgb);
+
+        svg
+            .selectAll("rect")
+            .data(nodes)
+            .enter().append("rect")
+            .attr("x", d => d.x * cellSize)
+            .attr("y", d => d.y * cellSize)
+            .attr("width", cellSize)
+            .attr("height", cellSize)
+            .style("fill", d => greyScale(d.entropy));
+
+        return svg._groups[0][0].outerHTML;
+    }
+
     /**
      * Displays the entropy as a scale bar for web apps.
      *
      * @param {number} entropy
-     * @returns {html}
+     * @returns {HTML}
      */
-    present(entropy) {
+    createShannonEntropyVisualization(entropy) {
         return `Shannon entropy: ${entropy}
-<br><canvas id='chart-area'></canvas><br>
-- 0 represents no randomness (i.e. all the bytes in the data have the same value) whereas 8, the maximum, represents a completely random string.
-- Standard English text usually falls somewhere between 3.5 and 5.
-- Properly encrypted or compressed data of a reasonable length should have an entropy of over 7.5.
-
-The following results show the entropy of chunks of the input data. Chunks with particularly high entropy could suggest encrypted or compressed sections.
-
-<br><script>
-    var canvas = document.getElementById("chart-area"),
-        parentRect = canvas.parentNode.getBoundingClientRect(),
-        entropy = ${entropy},
-        height = parentRect.height * 0.25;
-
-    canvas.width = parentRect.width * 0.95;
-    canvas.height = height > 150 ? 150 : height;
-
-    CanvasComponents.drawScaleBar(canvas, entropy, 8, [
-        {
-            label: "English text",
-            min: 3.5,
-            max: 5
-        },{
-            label: "Encrypted/compressed",
-            min: 7.5,
-            max: 8
+        <br><canvas id='chart-area'></canvas><br>
+        - 0 represents no randomness (i.e. all the bytes in the data have the same value) whereas 8, the maximum, represents a completely random string.
+        - Standard English text usually falls somewhere between 3.5 and 5.
+        - Properly encrypted or compressed data of a reasonable length should have an entropy of over 7.5.
+
+        The following results show the entropy of chunks of the input data. Chunks with particularly high entropy could suggest encrypted or compressed sections.
+
+        <br><script>
+            var canvas = document.getElementById("chart-area"),
+                parentRect = canvas.parentNode.getBoundingClientRect(),
+                entropy = ${entropy},
+                height = parentRect.height * 0.25;
+
+            canvas.width = parentRect.width * 0.95;
+            canvas.height = height > 150 ? 150 : height;
+
+            CanvasComponents.drawScaleBar(canvas, entropy, 8, [
+                {
+                    label: "English text",
+                    min: 3.5,
+                    max: 5
+                },{
+                    label: "Encrypted/compressed",
+                    min: 7.5,
+                    max: 8
+                }
+            ]);
+        </script>`;
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {json}
+     */
+    run(input, args) {
+        const visualizationType = args[0];
+        input = new Uint8Array(input);
+
+        switch (visualizationType) {
+            case "Histogram (Bar)":
+            case "Histogram (Line)":
+                return this.calculateByteFrequency(input);
+            case "Curve":
+            case "Image":
+                return this.calculateScanningEntropy(input).entropyData;
+            case "Shannon scale":
+            default:
+                return this.calculateShannonEntropy(input);
         }
-    ]);
-</script>`;
     }
 
+    /**
+     * Displays the entropy in a visualisation for web apps.
+     *
+     * @param {json} entropyData
+     * @param {Object[]} args
+     * @returns {html}
+     */
+    present(entropyData, args) {
+        const visualizationType = args[0];
+
+        switch (visualizationType) {
+            case "Histogram (Bar)":
+                return this.createByteFrequencyBarHistogram(entropyData);
+            case "Histogram (Line)":
+                return this.createByteFrequencyLineHistogram(entropyData);
+            case "Curve":
+                return this.createEntropyCurve(entropyData);
+            case "Image":
+                return this.createEntropyImage(entropyData);
+            case "Shannon scale":
+            default:
+                return this.createShannonEntropyVisualization(entropyData);
+        }
+    }
 }
 
 export default Entropy;

+ 17 - 11
src/core/operations/FlipImage.mjs

@@ -26,8 +26,8 @@ class FlipImage extends Operation {
         this.module = "Image";
         this.description = "Flips an image along its X or Y axis.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -39,19 +39,19 @@ class FlipImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [flipAxis] = args;
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid input file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -67,8 +67,13 @@ class FlipImage extends Operation {
                     break;
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error flipping image. (${err})`);
         }
@@ -76,18 +81,19 @@ class FlipImage extends Operation {
 
     /**
      * Displays the flipped image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 1198 - 2
src/core/operations/FromHTMLEntity.mjs

@@ -19,7 +19,7 @@ class FromHTMLEntity extends Operation {
         super();
 
         this.name = "From HTML Entity";
-        this.module = "Default";
+        this.module = "Encodings";
         this.description = "Converts HTML entities back to characters<br><br>e.g. <code>&amp;<span>amp;</span></code> becomes <code>&amp;</code>";
         this.infoURL = "https://wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references";
         this.inputType = "string";
@@ -40,7 +40,7 @@ class FromHTMLEntity extends Operation {
      * @returns {string}
      */
     run(input, args) {
-        const regex = /&(#?x?[a-zA-Z0-9]{1,8});/g;
+        const regex = /&(#?x?[a-zA-Z0-9]{1,20});/g;
         let output = "",
             m,
             i = 0;
@@ -84,11 +84,38 @@ class FromHTMLEntity extends Operation {
  * Lookup table to translate HTML entity codes to their byte values.
  */
 const entityToByte = {
+    "Tab": 9,
+    "NewLine": 10,
+    "excl": 33,
     "quot": 34,
+    "num": 35,
+    "dollar": 36,
+    "percnt": 37,
     "amp": 38,
     "apos": 39,
+    "lpar": 40,
+    "rpar": 41,
+    "ast": 42,
+    "plus": 43,
+    "comma": 44,
+    "period": 46,
+    "sol": 47,
+    "colon": 58,
+    "semi": 59,
     "lt": 60,
+    "equals": 61,
     "gt": 62,
+    "quest": 63,
+    "commat": 64,
+    "lsqb": 91,
+    "bsol": 92,
+    "rsqb": 93,
+    "Hat": 94,
+    "lowbar": 95,
+    "grave": 96,
+    "lcub": 123,
+    "verbar": 124,
+    "rcub": 125,
     "nbsp": 160,
     "iexcl": 161,
     "cent": 162,
@@ -185,14 +212,140 @@ const entityToByte = {
     "yacute": 253,
     "thorn": 254,
     "yuml": 255,
+    "Amacr": 256,
+    "amacr": 257,
+    "Abreve": 258,
+    "abreve": 259,
+    "Aogon": 260,
+    "aogon": 261,
+    "Cacute": 262,
+    "cacute": 263,
+    "Ccirc": 264,
+    "ccirc": 265,
+    "Cdot": 266,
+    "cdot": 267,
+    "Ccaron": 268,
+    "ccaron": 269,
+    "Dcaron": 270,
+    "dcaron": 271,
+    "Dstrok": 272,
+    "dstrok": 273,
+    "Emacr": 274,
+    "emacr": 275,
+    "Edot": 278,
+    "edot": 279,
+    "Eogon": 280,
+    "eogon": 281,
+    "Ecaron": 282,
+    "ecaron": 283,
+    "Gcirc": 284,
+    "gcirc": 285,
+    "Gbreve": 286,
+    "gbreve": 287,
+    "Gdot": 288,
+    "gdot": 289,
+    "Gcedil": 290,
+    "Hcirc": 292,
+    "hcirc": 293,
+    "Hstrok": 294,
+    "hstrok": 295,
+    "Itilde": 296,
+    "itilde": 297,
+    "Imacr": 298,
+    "imacr": 299,
+    "Iogon": 302,
+    "iogon": 303,
+    "Idot": 304,
+    "imath": 305,
+    "IJlig": 306,
+    "ijlig": 307,
+    "Jcirc": 308,
+    "jcirc": 309,
+    "Kcedil": 310,
+    "kcedil": 311,
+    "kgreen": 312,
+    "Lacute": 313,
+    "lacute": 314,
+    "Lcedil": 315,
+    "lcedil": 316,
+    "Lcaron": 317,
+    "lcaron": 318,
+    "Lmidot": 319,
+    "lmidot": 320,
+    "Lstrok": 321,
+    "lstrok": 322,
+    "Nacute": 323,
+    "nacute": 324,
+    "Ncedil": 325,
+    "ncedil": 326,
+    "Ncaron": 327,
+    "ncaron": 328,
+    "napos": 329,
+    "ENG": 330,
+    "eng": 331,
+    "Omacr": 332,
+    "omacr": 333,
+    "Odblac": 336,
+    "odblac": 337,
     "OElig": 338,
     "oelig": 339,
+    "Racute": 340,
+    "racute": 341,
+    "Rcedil": 342,
+    "rcedil": 343,
+    "Rcaron": 344,
+    "rcaron": 345,
+    "Sacute": 346,
+    "sacute": 347,
+    "Scirc": 348,
+    "scirc": 349,
+    "Scedil": 350,
+    "scedil": 351,
     "Scaron": 352,
     "scaron": 353,
+    "Tcedil": 354,
+    "tcedil": 355,
+    "Tcaron": 356,
+    "tcaron": 357,
+    "Tstrok": 358,
+    "tstrok": 359,
+    "Utilde": 360,
+    "utilde": 361,
+    "Umacr": 362,
+    "umacr": 363,
+    "Ubreve": 364,
+    "ubreve": 365,
+    "Uring": 366,
+    "uring": 367,
+    "Udblac": 368,
+    "udblac": 369,
+    "Uogon": 370,
+    "uogon": 371,
+    "Wcirc": 372,
+    "wcirc": 373,
+    "Ycirc": 374,
+    "ycirc": 375,
     "Yuml": 376,
+    "Zacute": 377,
+    "zacute": 378,
+    "Zdot": 379,
+    "zdot": 380,
+    "Zcaron": 381,
+    "zcaron": 382,
     "fnof": 402,
+    "imped": 437,
+    "gacute": 501,
+    "jmath": 567,
     "circ": 710,
+    "caron": 711,
+    "breve": 728,
+    "dot": 729,
+    "ring": 730,
+    "ogon": 731,
     "tilde": 732,
+    "dblac": 733,
+    "DownBreve": 785,
+    "UnderBar": 818,
     "Alpha": 913,
     "Beta": 914,
     "Gamma": 915,
@@ -244,16 +397,124 @@ const entityToByte = {
     "omega": 969,
     "thetasym": 977,
     "upsih": 978,
+    "straightphi": 981,
     "piv": 982,
+    "Gammad": 988,
+    "gammad": 989,
+    "kappav": 1008,
+    "rhov": 1009,
+    "epsi": 1013,
+    "bepsi": 1014,
+    "IOcy": 1025,
+    "DJcy": 1026,
+    "GJcy": 1027,
+    "Jukcy": 1028,
+    "DScy": 1029,
+    "Iukcy": 1030,
+    "YIcy": 1031,
+    "Jsercy": 1032,
+    "LJcy": 1033,
+    "NJcy": 1034,
+    "TSHcy": 1035,
+    "KJcy": 1036,
+    "Ubrcy": 1038,
+    "DZcy": 1039,
+    "Acy": 1040,
+    "Bcy": 1041,
+    "Vcy": 1042,
+    "Gcy": 1043,
+    "Dcy": 1044,
+    "IEcy": 1045,
+    "ZHcy": 1046,
+    "Zcy": 1047,
+    "Icy": 1048,
+    "Jcy": 1049,
+    "Kcy": 1050,
+    "Lcy": 1051,
+    "Mcy": 1052,
+    "Ncy": 1053,
+    "Ocy": 1054,
+    "Pcy": 1055,
+    "Rcy": 1056,
+    "Scy": 1057,
+    "Tcy": 1058,
+    "Ucy": 1059,
+    "Fcy": 1060,
+    "KHcy": 1061,
+    "TScy": 1062,
+    "CHcy": 1063,
+    "SHcy": 1064,
+    "SHCHcy": 1065,
+    "HARDcy": 1066,
+    "Ycy": 1067,
+    "SOFTcy": 1068,
+    "Ecy": 1069,
+    "YUcy": 1070,
+    "YAcy": 1071,
+    "acy": 1072,
+    "bcy": 1073,
+    "vcy": 1074,
+    "gcy": 1075,
+    "dcy": 1076,
+    "iecy": 1077,
+    "zhcy": 1078,
+    "zcy": 1079,
+    "icy": 1080,
+    "jcy": 1081,
+    "kcy": 1082,
+    "lcy": 1083,
+    "mcy": 1084,
+    "ncy": 1085,
+    "ocy": 1086,
+    "pcy": 1087,
+    "rcy": 1088,
+    "scy": 1089,
+    "tcy": 1090,
+    "ucy": 1091,
+    "fcy": 1092,
+    "khcy": 1093,
+    "tscy": 1094,
+    "chcy": 1095,
+    "shcy": 1096,
+    "shchcy": 1097,
+    "hardcy": 1098,
+    "ycy": 1099,
+    "softcy": 1100,
+    "ecy": 1101,
+    "yucy": 1102,
+    "yacy": 1103,
+    "iocy": 1105,
+    "djcy": 1106,
+    "gjcy": 1107,
+    "jukcy": 1108,
+    "dscy": 1109,
+    "iukcy": 1110,
+    "yicy": 1111,
+    "jsercy": 1112,
+    "ljcy": 1113,
+    "njcy": 1114,
+    "tshcy": 1115,
+    "kjcy": 1116,
+    "ubrcy": 1118,
+    "dzcy": 1119,
     "ensp": 8194,
     "emsp": 8195,
+    "emsp13": 8196,
+    "emsp14": 8197,
+    "numsp": 8199,
+    "puncsp": 8200,
     "thinsp": 8201,
+    "hairsp": 8202,
+    "ZeroWidthSpace": 8203,
     "zwnj": 8204,
     "zwj": 8205,
     "lrm": 8206,
     "rlm": 8207,
+    "hyphen": 8208,
     "ndash": 8211,
     "mdash": 8212,
+    "horbar": 8213,
+    "Verbar": 8214,
     "lsquo": 8216,
     "rsquo": 8217,
     "sbquo": 8218,
@@ -263,81 +524,1016 @@ const entityToByte = {
     "dagger": 8224,
     "Dagger": 8225,
     "bull": 8226,
+    "nldr": 8229,
     "hellip": 8230,
     "permil": 8240,
+    "pertenk": 8241,
     "prime": 8242,
     "Prime": 8243,
+    "tprime": 8244,
+    "bprime": 8245,
     "lsaquo": 8249,
     "rsaquo": 8250,
     "oline": 8254,
+    "caret": 8257,
+    "hybull": 8259,
     "frasl": 8260,
+    "bsemi": 8271,
+    "qprime": 8279,
+    "MediumSpace": 8287,
+    "NoBreak": 8288,
+    "ApplyFunction": 8289,
+    "InvisibleTimes": 8290,
+    "InvisibleComma": 8291,
     "euro": 8364,
+    "tdot": 8411,
+    "TripleDot": 8411,
+    "DotDot": 8412,
+    "Copf": 8450,
+    "incare": 8453,
+    "gscr": 8458,
+    "hamilt": 8459,
+    "Hfr": 8460,
+    "quaternions": 8461,
+    "planckh": 8462,
+    "planck": 8463,
+    "Iscr": 8464,
     "image": 8465,
+    "Lscr": 8466,
+    "ell": 8467,
+    "Nopf": 8469,
+    "numero": 8470,
+    "copysr": 8471,
     "weierp": 8472,
+    "Popf": 8473,
+    "rationals": 8474,
+    "Rscr": 8475,
     "real": 8476,
+    "reals": 8477,
+    "rx": 8478,
     "trade": 8482,
+    "integers": 8484,
+    "ohm": 8486,
+    "mho": 8487,
+    "Zfr": 8488,
+    "iiota": 8489,
+    "angst": 8491,
+    "bernou": 8492,
+    "Cfr": 8493,
+    "escr": 8495,
+    "Escr": 8496,
+    "Fscr": 8497,
+    "phmmat": 8499,
+    "order": 8500,
     "alefsym": 8501,
+    "beth": 8502,
+    "gimel": 8503,
+    "daleth": 8504,
+    "CapitalDifferentialD": 8517,
+    "DifferentialD": 8518,
+    "ExponentialE": 8519,
+    "ImaginaryI": 8520,
+    "frac13": 8531,
+    "frac23": 8532,
+    "frac15": 8533,
+    "frac25": 8534,
+    "frac35": 8535,
+    "frac45": 8536,
+    "frac16": 8537,
+    "frac56": 8538,
+    "frac18": 8539,
+    "frac38": 8540,
+    "frac58": 8541,
+    "frac78": 8542,
     "larr": 8592,
     "uarr": 8593,
     "rarr": 8594,
     "darr": 8595,
     "harr": 8596,
+    "varr": 8597,
+    "nwarr": 8598,
+    "nearr": 8599,
+    "searr": 8600,
+    "swarr": 8601,
+    "nlarr": 8602,
+    "nrarr": 8603,
+    "rarrw": 8605,
+    "Larr": 8606,
+    "Uarr": 8607,
+    "Rarr": 8608,
+    "Darr": 8609,
+    "larrtl": 8610,
+    "rarrtl": 8611,
+    "LeftTeeArrow": 8612,
+    "UpTeeArrow": 8613,
+    "map": 8614,
+    "DownTeeArrow": 8615,
+    "larrhk": 8617,
+    "rarrhk": 8618,
+    "larrlp": 8619,
+    "rarrlp": 8620,
+    "harrw": 8621,
+    "nharr": 8622,
+    "lsh": 8624,
+    "rsh": 8625,
+    "ldsh": 8626,
+    "rdsh": 8627,
     "crarr": 8629,
+    "cularr": 8630,
+    "curarr": 8631,
+    "olarr": 8634,
+    "orarr": 8635,
+    "lharu": 8636,
+    "lhard": 8637,
+    "uharr": 8638,
+    "uharl": 8639,
+    "rharu": 8640,
+    "rhard": 8641,
+    "dharr": 8642,
+    "dharl": 8643,
+    "rlarr": 8644,
+    "udarr": 8645,
+    "lrarr": 8646,
+    "llarr": 8647,
+    "uuarr": 8648,
+    "rrarr": 8649,
+    "ddarr": 8650,
+    "lrhar": 8651,
+    "rlhar": 8652,
+    "nlArr": 8653,
+    "nhArr": 8654,
+    "nrArr": 8655,
     "lArr": 8656,
     "uArr": 8657,
     "rArr": 8658,
     "dArr": 8659,
     "hArr": 8660,
+    "vArr": 8661,
+    "nwArr": 8662,
+    "neArr": 8663,
+    "seArr": 8664,
+    "swArr": 8665,
+    "lAarr": 8666,
+    "rAarr": 8667,
+    "zigrarr": 8669,
+    "larrb": 8676,
+    "rarrb": 8677,
+    "duarr": 8693,
+    "loarr": 8701,
+    "roarr": 8702,
+    "hoarr": 8703,
     "forall": 8704,
+    "comp": 8705,
     "part": 8706,
     "exist": 8707,
+    "nexist": 8708,
     "empty": 8709,
     "nabla": 8711,
     "isin": 8712,
     "notin": 8713,
     "ni": 8715,
+    "notni": 8716,
     "prod": 8719,
+    "coprod": 8720,
     "sum": 8721,
     "minus": 8722,
+    "mnplus": 8723,
+    "plusdo": 8724,
+    "setmn": 8726,
     "lowast": 8727,
+    "compfn": 8728,
     "radic": 8730,
     "prop": 8733,
     "infin": 8734,
+    "angrt": 8735,
     "ang": 8736,
+    "angmsd": 8737,
+    "angsph": 8738,
+    "mid": 8739,
+    "nmid": 8740,
+    "par": 8741,
+    "npar": 8742,
     "and": 8743,
     "or": 8744,
     "cap": 8745,
     "cup": 8746,
     "int": 8747,
+    "Int": 8748,
+    "tint": 8749,
+    "conint": 8750,
+    "Conint": 8751,
+    "Cconint": 8752,
+    "cwint": 8753,
+    "cwconint": 8754,
+    "awconint": 8755,
     "there4": 8756,
+    "becaus": 8757,
+    "ratio": 8758,
+    "Colon": 8759,
+    "minusd": 8760,
+    "mDDot": 8762,
+    "homtht": 8763,
     "sim": 8764,
+    "bsim": 8765,
+    "ac": 8766,
+    "acd": 8767,
+    "wreath": 8768,
+    "nsim": 8769,
+    "esim": 8770,
+    "sime": 8771,
+    "nsime": 8772,
     "cong": 8773,
+    "simne": 8774,
+    "ncong": 8775,
     "asymp": 8776,
+    "nap": 8777,
+    "ape": 8778,
+    "apid": 8779,
+    "bcong": 8780,
+    "asympeq": 8781,
+    "bump": 8782,
+    "bumpe": 8783,
+    "esdot": 8784,
+    "eDot": 8785,
+    "efDot": 8786,
+    "erDot": 8787,
+    "colone": 8788,
+    "ecolon": 8789,
+    "ecir": 8790,
+    "cire": 8791,
+    "wedgeq": 8793,
+    "veeeq": 8794,
+    "trie": 8796,
+    "equest": 8799,
     "ne": 8800,
     "equiv": 8801,
+    "nequiv": 8802,
     "le": 8804,
     "ge": 8805,
+    "lE": 8806,
+    "gE": 8807,
+    "lnE": 8808,
+    "gnE": 8809,
+    "Lt": 8810,
+    "Gt": 8811,
+    "twixt": 8812,
+    "NotCupCap": 8813,
+    "nlt": 8814,
+    "ngt": 8815,
+    "nle": 8816,
+    "nge": 8817,
+    "lsim": 8818,
+    "gsim": 8819,
+    "nlsim": 8820,
+    "ngsim": 8821,
+    "lg": 8822,
+    "gl": 8823,
+    "ntlg": 8824,
+    "ntgl": 8825,
+    "pr": 8826,
+    "sc": 8827,
+    "prcue": 8828,
+    "sccue": 8829,
+    "prsim": 8830,
+    "scsim": 8831,
+    "npr": 8832,
+    "nsc": 8833,
     "sub": 8834,
     "sup": 8835,
     "nsub": 8836,
+    "nsup": 8837,
     "sube": 8838,
     "supe": 8839,
+    "nsube": 8840,
+    "nsupe": 8841,
+    "subne": 8842,
+    "supne": 8843,
+    "cupdot": 8845,
+    "uplus": 8846,
+    "sqsub": 8847,
+    "sqsup": 8848,
+    "sqsube": 8849,
+    "sqsupe": 8850,
+    "sqcap": 8851,
+    "sqcup": 8852,
     "oplus": 8853,
+    "ominus": 8854,
     "otimes": 8855,
+    "osol": 8856,
+    "odot": 8857,
+    "ocir": 8858,
+    "oast": 8859,
+    "odash": 8861,
+    "plusb": 8862,
+    "minusb": 8863,
+    "timesb": 8864,
+    "sdotb": 8865,
+    "vdash": 8866,
+    "dashv": 8867,
+    "top": 8868,
     "perp": 8869,
+    "models": 8871,
+    "vDash": 8872,
+    "Vdash": 8873,
+    "Vvdash": 8874,
+    "VDash": 8875,
+    "nvdash": 8876,
+    "nvDash": 8877,
+    "nVdash": 8878,
+    "nVDash": 8879,
+    "prurel": 8880,
+    "vltri": 8882,
+    "vrtri": 8883,
+    "ltrie": 8884,
+    "rtrie": 8885,
+    "origof": 8886,
+    "imof": 8887,
+    "mumap": 8888,
+    "hercon": 8889,
+    "intcal": 8890,
+    "veebar": 8891,
+    "barvee": 8893,
+    "angrtvb": 8894,
+    "lrtri": 8895,
+    "xwedge": 8896,
+    "xvee": 8897,
+    "xcap": 8898,
+    "xcup": 8899,
+    "diam": 8900,
     "sdot": 8901,
+    "sstarf": 8902,
+    "divonx": 8903,
+    "bowtie": 8904,
+    "ltimes": 8905,
+    "rtimes": 8906,
+    "lthree": 8907,
+    "rthree": 8908,
+    "bsime": 8909,
+    "cuvee": 8910,
+    "cuwed": 8911,
+    "Sub": 8912,
+    "Sup": 8913,
+    "Cap": 8914,
+    "Cup": 8915,
+    "fork": 8916,
+    "epar": 8917,
+    "ltdot": 8918,
+    "gtdot": 8919,
+    "Ll": 8920,
+    "Gg": 8921,
+    "leg": 8922,
+    "gel": 8923,
+    "cuepr": 8926,
+    "cuesc": 8927,
+    "nprcue": 8928,
+    "nsccue": 8929,
+    "nsqsube": 8930,
+    "nsqsupe": 8931,
+    "lnsim": 8934,
+    "gnsim": 8935,
+    "prnsim": 8936,
+    "scnsim": 8937,
+    "nltri": 8938,
+    "nrtri": 8939,
+    "nltrie": 8940,
+    "nrtrie": 8941,
     "vellip": 8942,
+    "ctdot": 8943,
+    "utdot": 8944,
+    "dtdot": 8945,
+    "disin": 8946,
+    "isinsv": 8947,
+    "isins": 8948,
+    "isindot": 8949,
+    "notinvc": 8950,
+    "notinvb": 8951,
+    "isinE": 8953,
+    "nisd": 8954,
+    "xnis": 8955,
+    "nis": 8956,
+    "notnivc": 8957,
+    "notnivb": 8958,
+    "barwed": 8965,
+    "Barwed": 8966,
     "lceil": 8968,
     "rceil": 8969,
     "lfloor": 8970,
     "rfloor": 8971,
+    "drcrop": 8972,
+    "dlcrop": 8973,
+    "urcrop": 8974,
+    "ulcrop": 8975,
+    "bnot": 8976,
+    "profline": 8978,
+    "profsurf": 8979,
+    "telrec": 8981,
+    "target": 8982,
+    "ulcorn": 8988,
+    "urcorn": 8989,
+    "dlcorn": 8990,
+    "drcorn": 8991,
+    "frown": 8994,
+    "smile": 8995,
     "lang": 9001,
     "rang": 9002,
+    "cylcty": 9005,
+    "profalar": 9006,
+    "topbot": 9014,
+    "ovbar": 9021,
+    "solbar": 9023,
+    "angzarr": 9084,
+    "lmoust": 9136,
+    "rmoust": 9137,
+    "tbrk": 9140,
+    "bbrk": 9141,
+    "bbrktbrk": 9142,
+    "OverParenthesis": 9180,
+    "UnderParenthesis": 9181,
+    "OverBrace": 9182,
+    "UnderBrace": 9183,
+    "trpezium": 9186,
+    "elinters": 9191,
+    "blank": 9251,
+    "oS": 9416,
+    "boxh": 9472,
+    "boxv": 9474,
+    "boxdr": 9484,
+    "boxdl": 9488,
+    "boxur": 9492,
+    "boxul": 9496,
+    "boxvr": 9500,
+    "boxvl": 9508,
+    "boxhd": 9516,
+    "boxhu": 9524,
+    "boxvh": 9532,
+    "boxH": 9552,
+    "boxV": 9553,
+    "boxdR": 9554,
+    "boxDr": 9555,
+    "boxDR": 9556,
+    "boxdL": 9557,
+    "boxDl": 9558,
+    "boxDL": 9559,
+    "boxuR": 9560,
+    "boxUr": 9561,
+    "boxUR": 9562,
+    "boxuL": 9563,
+    "boxUl": 9564,
+    "boxUL": 9565,
+    "boxvR": 9566,
+    "boxVr": 9567,
+    "boxVR": 9568,
+    "boxvL": 9569,
+    "boxVl": 9570,
+    "boxVL": 9571,
+    "boxHd": 9572,
+    "boxhD": 9573,
+    "boxHD": 9574,
+    "boxHu": 9575,
+    "boxhU": 9576,
+    "boxHU": 9577,
+    "boxvH": 9578,
+    "boxVh": 9579,
+    "boxVH": 9580,
+    "uhblk": 9600,
+    "lhblk": 9604,
+    "block": 9608,
+    "blk14": 9617,
+    "blk12": 9618,
+    "blk34": 9619,
+    "squ": 9633,
+    "squf": 9642,
+    "EmptyVerySmallSquare": 9643,
+    "rect": 9645,
+    "marker": 9646,
+    "fltns": 9649,
+    "xutri": 9651,
+    "utrif": 9652,
+    "utri": 9653,
+    "rtrif": 9656,
+    "rtri": 9657,
+    "xdtri": 9661,
+    "dtrif": 9662,
+    "dtri": 9663,
+    "ltrif": 9666,
+    "ltri": 9667,
     "loz": 9674,
+    "cir": 9675,
+    "tridot": 9708,
+    "xcirc": 9711,
+    "ultri": 9720,
+    "urtri": 9721,
+    "lltri": 9722,
+    "EmptySmallSquare": 9723,
+    "FilledSmallSquare": 9724,
+    "starf": 9733,
+    "bigstar": 9733,
+    "star": 9734,
+    "phone": 9742,
+    "female": 9792,
+    "male": 9794,
     "spades": 9824,
     "clubs": 9827,
     "hearts": 9829,
     "diams": 9830,
+    "sung": 9834,
+    "flat": 9837,
+    "natur": 9838,
+    "sharp": 9839,
+    "check": 10003,
+    "cross": 10007,
+    "malt": 10016,
+    "sext": 10038,
+    "VerticalSeparator": 10072,
+    "lbbrk": 10098,
+    "rbbrk": 10099,
+    "lobrk": 10214,
+    "robrk": 10215,
+    "Lang": 10218,
+    "Rang": 10219,
+    "loang": 10220,
+    "roang": 10221,
+    "xlarr": 10229,
+    "xrarr": 10230,
+    "xharr": 10231,
+    "xlArr": 10232,
+    "xrArr": 10233,
+    "xhArr": 10234,
+    "xmap": 10236,
+    "dzigrarr": 10239,
+    "nvlArr": 10498,
+    "nvrArr": 10499,
+    "nvHarr": 10500,
+    "Map": 10501,
+    "lbarr": 10508,
+    "rbarr": 10509,
+    "lBarr": 10510,
+    "rBarr": 10511,
+    "RBarr": 10512,
+    "DDotrahd": 10513,
+    "UpArrowBar": 10514,
+    "DownArrowBar": 10515,
+    "Rarrtl": 10518,
+    "latail": 10521,
+    "ratail": 10522,
+    "lAtail": 10523,
+    "rAtail": 10524,
+    "larrfs": 10525,
+    "rarrfs": 10526,
+    "larrbfs": 10527,
+    "rarrbfs": 10528,
+    "nwarhk": 10531,
+    "nearhk": 10532,
+    "searhk": 10533,
+    "swarhk": 10534,
+    "nwnear": 10535,
+    "nesear": 10536,
+    "seswar": 10537,
+    "swnwar": 10538,
+    "rarrc": 10547,
+    "cudarrr": 10549,
+    "ldca": 10550,
+    "rdca": 10551,
+    "cudarrl": 10552,
+    "larrpl": 10553,
+    "curarrm": 10556,
+    "cularrp": 10557,
+    "rarrpl": 10565,
+    "harrcir": 10568,
+    "Uarrocir": 10569,
+    "lurdshar": 10570,
+    "ldrushar": 10571,
+    "LeftRightVector": 10574,
+    "RightUpDownVector": 10575,
+    "DownLeftRightVector": 10576,
+    "LeftUpDownVector": 10577,
+    "LeftVectorBar": 10578,
+    "RightVectorBar": 10579,
+    "RightUpVectorBar": 10580,
+    "RightDownVectorBar": 10581,
+    "DownLeftVectorBar": 10582,
+    "DownRightVectorBar": 10583,
+    "LeftUpVectorBar": 10584,
+    "LeftDownVectorBar": 10585,
+    "LeftTeeVector": 10586,
+    "RightTeeVector": 10587,
+    "RightUpTeeVector": 10588,
+    "RightDownTeeVector": 10589,
+    "DownLeftTeeVector": 10590,
+    "DownRightTeeVector": 10591,
+    "LeftUpTeeVector": 10592,
+    "LeftDownTeeVector": 10593,
+    "lHar": 10594,
+    "uHar": 10595,
+    "rHar": 10596,
+    "dHar": 10597,
+    "luruhar": 10598,
+    "ldrdhar": 10599,
+    "ruluhar": 10600,
+    "rdldhar": 10601,
+    "lharul": 10602,
+    "llhard": 10603,
+    "rharul": 10604,
+    "lrhard": 10605,
+    "udhar": 10606,
+    "duhar": 10607,
+    "RoundImplies": 10608,
+    "erarr": 10609,
+    "simrarr": 10610,
+    "larrsim": 10611,
+    "rarrsim": 10612,
+    "rarrap": 10613,
+    "ltlarr": 10614,
+    "gtrarr": 10616,
+    "subrarr": 10617,
+    "suplarr": 10619,
+    "lfisht": 10620,
+    "rfisht": 10621,
+    "ufisht": 10622,
+    "dfisht": 10623,
+    "lopar": 10629,
+    "ropar": 10630,
+    "lbrke": 10635,
+    "rbrke": 10636,
+    "lbrkslu": 10637,
+    "rbrksld": 10638,
+    "lbrksld": 10639,
+    "rbrkslu": 10640,
+    "langd": 10641,
+    "rangd": 10642,
+    "lparlt": 10643,
+    "rpargt": 10644,
+    "gtlPar": 10645,
+    "ltrPar": 10646,
+    "vzigzag": 10650,
+    "vangrt": 10652,
+    "angrtvbd": 10653,
+    "ange": 10660,
+    "range": 10661,
+    "dwangle": 10662,
+    "uwangle": 10663,
+    "angmsdaa": 10664,
+    "angmsdab": 10665,
+    "angmsdac": 10666,
+    "angmsdad": 10667,
+    "angmsdae": 10668,
+    "angmsdaf": 10669,
+    "angmsdag": 10670,
+    "angmsdah": 10671,
+    "bemptyv": 10672,
+    "demptyv": 10673,
+    "cemptyv": 10674,
+    "raemptyv": 10675,
+    "laemptyv": 10676,
+    "ohbar": 10677,
+    "omid": 10678,
+    "opar": 10679,
+    "operp": 10681,
+    "olcross": 10683,
+    "odsold": 10684,
+    "olcir": 10686,
+    "ofcir": 10687,
+    "olt": 10688,
+    "ogt": 10689,
+    "cirscir": 10690,
+    "cirE": 10691,
+    "solb": 10692,
+    "bsolb": 10693,
+    "boxbox": 10697,
+    "trisb": 10701,
+    "rtriltri": 10702,
+    "LeftTriangleBar": 10703,
+    "RightTriangleBar": 10704,
+    "race": 10714,
+    "iinfin": 10716,
+    "infintie": 10717,
+    "nvinfin": 10718,
+    "eparsl": 10723,
+    "smeparsl": 10724,
+    "eqvparsl": 10725,
+    "lozf": 10731,
+    "RuleDelayed": 10740,
+    "dsol": 10742,
+    "xodot": 10752,
+    "xoplus": 10753,
+    "xotime": 10754,
+    "xuplus": 10756,
+    "xsqcup": 10758,
+    "qint": 10764,
+    "fpartint": 10765,
+    "cirfnint": 10768,
+    "awint": 10769,
+    "rppolint": 10770,
+    "scpolint": 10771,
+    "npolint": 10772,
+    "pointint": 10773,
+    "quatint": 10774,
+    "intlarhk": 10775,
+    "pluscir": 10786,
+    "plusacir": 10787,
+    "simplus": 10788,
+    "plusdu": 10789,
+    "plussim": 10790,
+    "plustwo": 10791,
+    "mcomma": 10793,
+    "minusdu": 10794,
+    "loplus": 10797,
+    "roplus": 10798,
+    "Cross": 10799,
+    "timesd": 10800,
+    "timesbar": 10801,
+    "smashp": 10803,
+    "lotimes": 10804,
+    "rotimes": 10805,
+    "otimesas": 10806,
+    "Otimes": 10807,
+    "odiv": 10808,
+    "triplus": 10809,
+    "triminus": 10810,
+    "tritime": 10811,
+    "iprod": 10812,
+    "amalg": 10815,
+    "capdot": 10816,
+    "ncup": 10818,
+    "ncap": 10819,
+    "capand": 10820,
+    "cupor": 10821,
+    "cupcap": 10822,
+    "capcup": 10823,
+    "cupbrcap": 10824,
+    "capbrcup": 10825,
+    "cupcup": 10826,
+    "capcap": 10827,
+    "ccups": 10828,
+    "ccaps": 10829,
+    "ccupssm": 10832,
+    "And": 10835,
+    "Or": 10836,
+    "andand": 10837,
+    "oror": 10838,
+    "orslope": 10839,
+    "andslope": 10840,
+    "andv": 10842,
+    "orv": 10843,
+    "andd": 10844,
+    "ord": 10845,
+    "wedbar": 10847,
+    "sdote": 10854,
+    "simdot": 10858,
+    "congdot": 10861,
+    "easter": 10862,
+    "apacir": 10863,
+    "apE": 10864,
+    "eplus": 10865,
+    "pluse": 10866,
+    "Esim": 10867,
+    "Colone": 10868,
+    "Equal": 10869,
+    "eDDot": 10871,
+    "equivDD": 10872,
+    "ltcir": 10873,
+    "gtcir": 10874,
+    "ltquest": 10875,
+    "gtquest": 10876,
+    "les": 10877,
+    "ges": 10878,
+    "lesdot": 10879,
+    "gesdot": 10880,
+    "lesdoto": 10881,
+    "gesdoto": 10882,
+    "lesdotor": 10883,
+    "gesdotol": 10884,
+    "lap": 10885,
+    "gap": 10886,
+    "lne": 10887,
+    "gne": 10888,
+    "lnap": 10889,
+    "gnap": 10890,
+    "lEg": 10891,
+    "gEl": 10892,
+    "lsime": 10893,
+    "gsime": 10894,
+    "lsimg": 10895,
+    "gsiml": 10896,
+    "lgE": 10897,
+    "glE": 10898,
+    "lesges": 10899,
+    "gesles": 10900,
+    "els": 10901,
+    "egs": 10902,
+    "elsdot": 10903,
+    "egsdot": 10904,
+    "el": 10905,
+    "eg": 10906,
+    "siml": 10909,
+    "simg": 10910,
+    "simlE": 10911,
+    "simgE": 10912,
+    "LessLess": 10913,
+    "GreaterGreater": 10914,
+    "glj": 10916,
+    "gla": 10917,
+    "ltcc": 10918,
+    "gtcc": 10919,
+    "lescc": 10920,
+    "gescc": 10921,
+    "smt": 10922,
+    "lat": 10923,
+    "smte": 10924,
+    "late": 10925,
+    "bumpE": 10926,
+    "pre": 10927,
+    "sce": 10928,
+    "prE": 10931,
+    "scE": 10932,
+    "prnE": 10933,
+    "scnE": 10934,
+    "prap": 10935,
+    "scap": 10936,
+    "prnap": 10937,
+    "scnap": 10938,
+    "Pr": 10939,
+    "Sc": 10940,
+    "subdot": 10941,
+    "supdot": 10942,
+    "subplus": 10943,
+    "supplus": 10944,
+    "submult": 10945,
+    "supmult": 10946,
+    "subedot": 10947,
+    "supedot": 10948,
+    "subE": 10949,
+    "supE": 10950,
+    "subsim": 10951,
+    "supsim": 10952,
+    "subnE": 10955,
+    "supnE": 10956,
+    "csub": 10959,
+    "csup": 10960,
+    "csube": 10961,
+    "csupe": 10962,
+    "subsup": 10963,
+    "supsub": 10964,
+    "subsub": 10965,
+    "supsup": 10966,
+    "suphsub": 10967,
+    "supdsub": 10968,
+    "forkv": 10969,
+    "topfork": 10970,
+    "mlcp": 10971,
+    "Dashv": 10980,
+    "Vdashl": 10982,
+    "Barv": 10983,
+    "vBar": 10984,
+    "vBarv": 10985,
+    "Vbar": 10987,
+    "Not": 10988,
+    "bNot": 10989,
+    "rnmid": 10990,
+    "cirmid": 10991,
+    "midcir": 10992,
+    "topcir": 10993,
+    "nhpar": 10994,
+    "parsim": 10995,
+    "parsl": 11005,
+    "fflig": 64256,
+    "filig": 64257,
+    "fllig": 64258,
+    "ffilig": 64259,
+    "ffllig": 64260,
+    "Ascr": 119964,
+    "Cscr": 119966,
+    "Dscr": 119967,
+    "Gscr": 119970,
+    "Jscr": 119973,
+    "Kscr": 119974,
+    "Nscr": 119977,
+    "Oscr": 119978,
+    "Pscr": 119979,
+    "Qscr": 119980,
+    "Sscr": 119982,
+    "Tscr": 119983,
+    "Uscr": 119984,
+    "Vscr": 119985,
+    "Wscr": 119986,
+    "Xscr": 119987,
+    "Yscr": 119988,
+    "Zscr": 119989,
+    "ascr": 119990,
+    "bscr": 119991,
+    "cscr": 119992,
+    "dscr": 119993,
+    "fscr": 119995,
+    "hscr": 119997,
+    "iscr": 119998,
+    "jscr": 119999,
+    "kscr": 120000,
+    "lscr": 120001,
+    "mscr": 120002,
+    "nscr": 120003,
+    "pscr": 120005,
+    "qscr": 120006,
+    "rscr": 120007,
+    "sscr": 120008,
+    "tscr": 120009,
+    "uscr": 120010,
+    "vscr": 120011,
+    "wscr": 120012,
+    "xscr": 120013,
+    "yscr": 120014,
+    "zscr": 120015,
+    "Afr": 120068,
+    "Bfr": 120069,
+    "Dfr": 120071,
+    "Efr": 120072,
+    "Ffr": 120073,
+    "Gfr": 120074,
+    "Jfr": 120077,
+    "Kfr": 120078,
+    "Lfr": 120079,
+    "Mfr": 120080,
+    "Nfr": 120081,
+    "Ofr": 120082,
+    "Pfr": 120083,
+    "Qfr": 120084,
+    "Sfr": 120086,
+    "Tfr": 120087,
+    "Ufr": 120088,
+    "Vfr": 120089,
+    "Wfr": 120090,
+    "Xfr": 120091,
+    "Yfr": 120092,
+    "afr": 120094,
+    "bfr": 120095,
+    "cfr": 120096,
+    "dfr": 120097,
+    "efr": 120098,
+    "ffr": 120099,
+    "gfr": 120100,
+    "hfr": 120101,
+    "ifr": 120102,
+    "jfr": 120103,
+    "kfr": 120104,
+    "lfr": 120105,
+    "mfr": 120106,
+    "nfr": 120107,
+    "ofr": 120108,
+    "pfr": 120109,
+    "qfr": 120110,
+    "rfr": 120111,
+    "sfr": 120112,
+    "tfr": 120113,
+    "ufr": 120114,
+    "vfr": 120115,
+    "wfr": 120116,
+    "xfr": 120117,
+    "yfr": 120118,
+    "zfr": 120119,
+    "Aopf": 120120,
+    "Bopf": 120121,
+    "Dopf": 120123,
+    "Eopf": 120124,
+    "Fopf": 120125,
+    "Gopf": 120126,
+    "Iopf": 120128,
+    "Jopf": 120129,
+    "Kopf": 120130,
+    "Lopf": 120131,
+    "Mopf": 120132,
+    "Oopf": 120134,
+    "Sopf": 120138,
+    "Topf": 120139,
+    "Uopf": 120140,
+    "Vopf": 120141,
+    "Wopf": 120142,
+    "Xopf": 120143,
+    "Yopf": 120144,
+    "aopf": 120146,
+    "bopf": 120147,
+    "copf": 120148,
+    "dopf": 120149,
+    "eopf": 120150,
+    "fopf": 120151,
+    "gopf": 120152,
+    "hopf": 120153,
+    "iopf": 120154,
+    "jopf": 120155,
+    "kopf": 120156,
+    "lopf": 120157,
+    "mopf": 120158,
+    "nopf": 120159,
+    "oopf": 120160,
+    "popf": 120161,
+    "qopf": 120162,
+    "ropf": 120163,
+    "sopf": 120164,
+    "topf": 120165,
+    "uopf": 120166,
+    "vopf": 120167,
+    "wopf": 120168,
+    "xopf": 120169,
+    "yopf": 120170,
+    "zopf": 120171
 };
 
 export default FromHTMLEntity;

+ 71 - 0
src/core/operations/GOSTHash.mjs

@@ -0,0 +1,71 @@
+/**
+ * @author n1474335 [n1474335@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import GostDigest from "../vendor/gost/gostDigest";
+import {toHexFast} from "../lib/Hex";
+
+/**
+ * GOST hash operation
+ */
+class GOSTHash extends Operation {
+
+    /**
+     * GOSTHash constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "GOST hash";
+        this.module = "Hashing";
+        this.description = "The GOST hash function, defined in the standards GOST R 34.11-94 and GOST 34.311-95 is a 256-bit cryptographic hash function. It was initially defined in the Russian national standard GOST R 34.11-94 <i>Information Technology – Cryptographic Information Security – Hash Function</i>. The equivalent standard used by other member-states of the CIS is GOST 34.311-95.<br><br>This function must not be confused with a different Streebog hash function, which is defined in the new revision of the standard GOST R 34.11-2012.<br><br>The GOST hash function is based on the GOST block cipher.";
+        this.infoURL = "https://wikipedia.org/wiki/GOST_(hash_function)";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "string";
+        this.args = [
+            {
+                "name": "S-Box",
+                "type": "option",
+                "value": [
+                    "D-A",
+                    "D-SC",
+                    "E-TEST",
+                    "E-A",
+                    "E-B",
+                    "E-C",
+                    "E-D",
+                    "E-SC",
+                    "E-Z",
+                    "D-TEST"
+                ]
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {string}
+     */
+    run(input, args) {
+        try {
+            const sBox = args[1];
+            const gostDigest = new GostDigest({
+                name: "GOST R 34.11",
+                version: 1994,
+                sBox: sBox
+            });
+
+            return toHexFast(gostDigest.digest(input));
+        } catch (err) {
+            throw new OperationError(err);
+        }
+    }
+
+}
+
+export default GOSTHash;

+ 52 - 45
src/core/operations/GenerateAllHashes.mjs

@@ -26,10 +26,13 @@ import Fletcher16Checksum from "./Fletcher16Checksum";
 import Fletcher32Checksum from "./Fletcher32Checksum";
 import Fletcher64Checksum from "./Fletcher64Checksum";
 import Adler32Checksum from "./Adler32Checksum";
+import CRC8Checksum from "./CRC8Checksum";
 import CRC16Checksum from "./CRC16Checksum";
 import CRC32Checksum from "./CRC32Checksum";
 import BLAKE2b from "./BLAKE2b";
 import BLAKE2s from "./BLAKE2s";
+import Streebog from "./Streebog";
+import GOSTHash from "./GOSTHash";
 
 /**
  * Generate all hashes operation
@@ -60,52 +63,56 @@ class GenerateAllHashes extends Operation {
         const arrayBuffer = input,
             str = Utils.arrayBufferToStr(arrayBuffer, false),
             byteArray = new Uint8Array(arrayBuffer),
-            output = "MD2:         " + (new MD2()).run(arrayBuffer, []) +
-                "\nMD4:         " + (new MD4()).run(arrayBuffer, []) +
-                "\nMD5:         " + (new MD5()).run(arrayBuffer, []) +
-                "\nMD6:         " + (new MD6()).run(str, []) +
-                "\nSHA0:        " + (new SHA0()).run(arrayBuffer, []) +
-                "\nSHA1:        " + (new SHA1()).run(arrayBuffer, []) +
-                "\nSHA2 224:    " + (new SHA2()).run(arrayBuffer, ["224"]) +
-                "\nSHA2 256:    " + (new SHA2()).run(arrayBuffer, ["256"]) +
-                "\nSHA2 384:    " + (new SHA2()).run(arrayBuffer, ["384"]) +
-                "\nSHA2 512:    " + (new SHA2()).run(arrayBuffer, ["512"]) +
-                "\nSHA3 224:    " + (new SHA3()).run(arrayBuffer, ["224"]) +
-                "\nSHA3 256:    " + (new SHA3()).run(arrayBuffer, ["256"]) +
-                "\nSHA3 384:    " + (new SHA3()).run(arrayBuffer, ["384"]) +
-                "\nSHA3 512:    " + (new SHA3()).run(arrayBuffer, ["512"]) +
-                "\nKeccak 224:  " + (new Keccak()).run(arrayBuffer, ["224"]) +
-                "\nKeccak 256:  " + (new Keccak()).run(arrayBuffer, ["256"]) +
-                "\nKeccak 384:  " + (new Keccak()).run(arrayBuffer, ["384"]) +
-                "\nKeccak 512:  " + (new Keccak()).run(arrayBuffer, ["512"]) +
-                "\nShake 128:   " + (new Shake()).run(arrayBuffer, ["128", 256]) +
-                "\nShake 256:   " + (new Shake()).run(arrayBuffer, ["256", 512]) +
-                "\nRIPEMD-128:  " + (new RIPEMD()).run(arrayBuffer, ["128"]) +
-                "\nRIPEMD-160:  " + (new RIPEMD()).run(arrayBuffer, ["160"]) +
-                "\nRIPEMD-256:  " + (new RIPEMD()).run(arrayBuffer, ["256"]) +
-                "\nRIPEMD-320:  " + (new RIPEMD()).run(arrayBuffer, ["320"]) +
-                "\nHAS-160:     " + (new HAS160()).run(arrayBuffer, []) +
-                "\nWhirlpool-0: " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool-0"]) +
-                "\nWhirlpool-T: " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool-T"]) +
-                "\nWhirlpool:   " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool"]) +
-                "\nBLAKE2b-128: " + (new BLAKE2b).run(arrayBuffer, ["128", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2b-160: " + (new BLAKE2b).run(arrayBuffer, ["160", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2b-256: " + (new BLAKE2b).run(arrayBuffer, ["256", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2b-384: " + (new BLAKE2b).run(arrayBuffer, ["384", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2b-512: " + (new BLAKE2b).run(arrayBuffer, ["512", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2s-128: " + (new BLAKE2s).run(arrayBuffer, ["128", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2s-160: " + (new BLAKE2s).run(arrayBuffer, ["160", "Hex", {string: "", option: "UTF8"}]) +
-                "\nBLAKE2s-256: " + (new BLAKE2s).run(arrayBuffer, ["256", "Hex", {string: "", option: "UTF8"}]) +
-                "\nSSDEEP:      " + (new SSDEEP()).run(str) +
-                "\nCTPH:        " + (new CTPH()).run(str) +
+            output = "MD2:          " + (new MD2()).run(arrayBuffer, []) +
+                "\nMD4:          " + (new MD4()).run(arrayBuffer, []) +
+                "\nMD5:          " + (new MD5()).run(arrayBuffer, []) +
+                "\nMD6:          " + (new MD6()).run(str, []) +
+                "\nSHA0:         " + (new SHA0()).run(arrayBuffer, []) +
+                "\nSHA1:         " + (new SHA1()).run(arrayBuffer, []) +
+                "\nSHA2 224:     " + (new SHA2()).run(arrayBuffer, ["224"]) +
+                "\nSHA2 256:     " + (new SHA2()).run(arrayBuffer, ["256"]) +
+                "\nSHA2 384:     " + (new SHA2()).run(arrayBuffer, ["384"]) +
+                "\nSHA2 512:     " + (new SHA2()).run(arrayBuffer, ["512"]) +
+                "\nSHA3 224:     " + (new SHA3()).run(arrayBuffer, ["224"]) +
+                "\nSHA3 256:     " + (new SHA3()).run(arrayBuffer, ["256"]) +
+                "\nSHA3 384:     " + (new SHA3()).run(arrayBuffer, ["384"]) +
+                "\nSHA3 512:     " + (new SHA3()).run(arrayBuffer, ["512"]) +
+                "\nKeccak 224:   " + (new Keccak()).run(arrayBuffer, ["224"]) +
+                "\nKeccak 256:   " + (new Keccak()).run(arrayBuffer, ["256"]) +
+                "\nKeccak 384:   " + (new Keccak()).run(arrayBuffer, ["384"]) +
+                "\nKeccak 512:   " + (new Keccak()).run(arrayBuffer, ["512"]) +
+                "\nShake 128:    " + (new Shake()).run(arrayBuffer, ["128", 256]) +
+                "\nShake 256:    " + (new Shake()).run(arrayBuffer, ["256", 512]) +
+                "\nRIPEMD-128:   " + (new RIPEMD()).run(arrayBuffer, ["128"]) +
+                "\nRIPEMD-160:   " + (new RIPEMD()).run(arrayBuffer, ["160"]) +
+                "\nRIPEMD-256:   " + (new RIPEMD()).run(arrayBuffer, ["256"]) +
+                "\nRIPEMD-320:   " + (new RIPEMD()).run(arrayBuffer, ["320"]) +
+                "\nHAS-160:      " + (new HAS160()).run(arrayBuffer, []) +
+                "\nWhirlpool-0:  " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool-0"]) +
+                "\nWhirlpool-T:  " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool-T"]) +
+                "\nWhirlpool:    " + (new Whirlpool()).run(arrayBuffer, ["Whirlpool"]) +
+                "\nBLAKE2b-128:  " + (new BLAKE2b).run(arrayBuffer, ["128", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2b-160:  " + (new BLAKE2b).run(arrayBuffer, ["160", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2b-256:  " + (new BLAKE2b).run(arrayBuffer, ["256", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2b-384:  " + (new BLAKE2b).run(arrayBuffer, ["384", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2b-512:  " + (new BLAKE2b).run(arrayBuffer, ["512", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2s-128:  " + (new BLAKE2s).run(arrayBuffer, ["128", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2s-160:  " + (new BLAKE2s).run(arrayBuffer, ["160", "Hex", {string: "", option: "UTF8"}]) +
+                "\nBLAKE2s-256:  " + (new BLAKE2s).run(arrayBuffer, ["256", "Hex", {string: "", option: "UTF8"}]) +
+                "\nStreebog-256: " + (new Streebog).run(arrayBuffer, ["256"]) +
+                "\nStreebog-512: " + (new Streebog).run(arrayBuffer, ["512"]) +
+                "\nGOST:         " + (new GOSTHash).run(arrayBuffer, ["D-A"]) +
+                "\nSSDEEP:       " + (new SSDEEP()).run(str) +
+                "\nCTPH:         " + (new CTPH()).run(str) +
                 "\n\nChecksums:" +
-                "\nFletcher-8:  " + (new Fletcher8Checksum).run(byteArray, []) +
-                "\nFletcher-16: " + (new Fletcher16Checksum).run(byteArray, []) +
-                "\nFletcher-32: " + (new Fletcher32Checksum).run(byteArray, []) +
-                "\nFletcher-64: " + (new Fletcher64Checksum).run(byteArray, []) +
-                "\nAdler-32:    " + (new Adler32Checksum).run(byteArray, []) +
-                "\nCRC-16:      " + (new CRC16Checksum).run(str, []) +
-                "\nCRC-32:      " + (new CRC32Checksum).run(str, []);
+                "\nFletcher-8:   " + (new Fletcher8Checksum).run(byteArray, []) +
+                "\nFletcher-16:  " + (new Fletcher16Checksum).run(byteArray, []) +
+                "\nFletcher-32:  " + (new Fletcher32Checksum).run(byteArray, []) +
+                "\nFletcher-64:  " + (new Fletcher64Checksum).run(byteArray, []) +
+                "\nAdler-32:     " + (new Adler32Checksum).run(byteArray, []) +
+                "\nCRC-8:        " + (new CRC8Checksum).run(arrayBuffer, ["CRC-8"]) +
+                "\nCRC-16:       " + (new CRC16Checksum).run(arrayBuffer, []) +
+                "\nCRC-32:       " + (new CRC32Checksum).run(arrayBuffer, []);
 
         return output;
     }

+ 17 - 42
src/core/operations/GenerateQRCode.mjs

@@ -6,7 +6,7 @@
 
 import Operation from "../Operation";
 import OperationError from "../errors/OperationError";
-import qr from "qr-image";
+import { generateQrCode } from "../lib/QRCode";
 import { toBase64 } from "../lib/Base64";
 import { isImage } from "../lib/FileType";
 import Utils from "../Utils";
@@ -27,7 +27,7 @@ class GenerateQRCode extends Operation {
         this.description = "Generates a Quick Response (QR) code from the input text.<br><br>A QR code is a type of matrix barcode (or two-dimensional barcode) first designed in 1994 for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached.";
         this.infoURL = "https://wikipedia.org/wiki/QR_code";
         this.inputType = "string";
-        this.outputType = "byteArray";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -38,12 +38,14 @@ class GenerateQRCode extends Operation {
             {
                 "name": "Module size (px)",
                 "type": "number",
-                "value": 5
+                "value": 5,
+                "min": 1
             },
             {
                 "name": "Margin (num modules)",
                 "type": "number",
-                "value": 2
+                "value": 2,
+                "min": 0
             },
             {
                 "name": "Error correction",
@@ -57,61 +59,34 @@ class GenerateQRCode extends Operation {
     /**
      * @param {string} input
      * @param {Object[]} args
-     * @returns {byteArray}
+     * @returns {ArrayBuffer}
      */
     run(input, args) {
         const [format, size, margin, errorCorrection] = args;
 
-        // Create new QR image from the input data, and convert it to a buffer
-        const qrImage = qr.imageSync(input, {
-            type: format,
-            size: size,
-            margin: margin,
-            "ec_level": errorCorrection.charAt(0).toUpperCase()
-        });
-
-        if (qrImage == null) {
-            throw new OperationError("Error generating QR code.");
-        }
-
-        switch (format) {
-            case "SVG":
-            case "EPS":
-            case "PDF":
-                return [...Buffer.from(qrImage)];
-            case "PNG":
-                // Return the QR image buffer as a byte array
-                return [...qrImage];
-            default:
-                throw new OperationError("Unsupported QR code format.");
-        }
+        return generateQrCode(input, format, size, margin, errorCorrection);
     }
 
     /**
      * Displays the QR image using HTML for web apps
      *
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data, args) {
-        if (!data.length) return "";
-
-        const [format] = args;
-
+        if (!data.byteLength && !data.length) return "";
+        const dataArray = new Uint8Array(data),
+            [format] = args;
         if (format === "PNG") {
-            let dataURI = "data:";
-            const mime = isImage(data);
-            if (mime){
-                dataURI += mime + ";";
-            } else {
-                throw new OperationError("Invalid PNG file generated by QR image");
+            const type = isImage(dataArray);
+            if (!type) {
+                throw new OperationError("Invalid file type.");
             }
-            dataURI += "base64," + toBase64(data);
 
-            return `<img src="${dataURI}">`;
+            return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
         }
 
-        return Utils.byteArrayToChars(data);
+        return Utils.arrayBufferToStr(data);
     }
 
 }

+ 17 - 11
src/core/operations/ImageBrightnessContrast.mjs

@@ -26,8 +26,8 @@ class ImageBrightnessContrast extends Operation {
         this.module = "Image";
         this.description = "Adjust the brightness or contrast of an image.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -48,19 +48,19 @@ class ImageBrightnessContrast extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [brightness, contrast] = args;
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -76,8 +76,13 @@ class ImageBrightnessContrast extends Operation {
                 image.contrast(contrast / 100);
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error adjusting image brightness or contrast. (${err})`);
         }
@@ -85,18 +90,19 @@ class ImageBrightnessContrast extends Operation {
 
     /**
      * Displays the image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 17 - 11
src/core/operations/ImageFilter.mjs

@@ -26,8 +26,8 @@ class ImageFilter extends Operation {
         this.module = "Image";
         this.description = "Applies a greyscale or sepia filter to an image.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -42,19 +42,19 @@ class ImageFilter extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [filterType] = args;
-        if (!isImage(input)){
+        if (!isImage(new Uint8Array(input))){
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -67,8 +67,13 @@ class ImageFilter extends Operation {
                 image.sepia();
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error applying filter to image. (${err})`);
         }
@@ -76,18 +81,19 @@ class ImageFilter extends Operation {
 
     /**
      * Displays the blurred image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 18 - 11
src/core/operations/ImageHueSaturationLightness.mjs

@@ -26,8 +26,8 @@ class ImageHueSaturationLightness extends Operation {
         this.module = "Image";
         this.description = "Adjusts the hue / saturation / lightness (HSL) values of an image.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -55,20 +55,20 @@ class ImageHueSaturationLightness extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [hue, saturation, lightness] = args;
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -103,8 +103,14 @@ class ImageHueSaturationLightness extends Operation {
                     }
                 ]);
             }
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error adjusting image hue / saturation / lightness. (${err})`);
         }
@@ -112,18 +118,19 @@ class ImageHueSaturationLightness extends Operation {
 
     /**
      * Displays the image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 }
 

+ 17 - 11
src/core/operations/ImageOpacity.mjs

@@ -26,8 +26,8 @@ class ImageOpacity extends Operation {
         this.module = "Image";
         this.description = "Adjust the opacity of an image.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -41,19 +41,19 @@ class ImageOpacity extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [opacity] = args;
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -62,8 +62,13 @@ class ImageOpacity extends Operation {
                 self.sendStatusMessage("Changing image opacity...");
             image.opacity(opacity / 100);
 
-            const imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error changing image opacity. (${err})`);
         }
@@ -71,18 +76,19 @@ class ImageOpacity extends Operation {
 
     /**
      * Displays the image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 107 - 0
src/core/operations/IndexOfCoincidence.mjs

@@ -0,0 +1,107 @@
+/**
+ * @author George O [georgeomnet+cyberchef@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import Utils from "../Utils";
+
+/**
+ * Index of Coincidence operation
+ */
+class IndexOfCoincidence extends Operation {
+
+    /**
+     * IndexOfCoincidence constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Index of Coincidence";
+        this.module = "Default";
+        this.description = "Index of Coincidence (IC) is the probability of two randomly selected characters being the same. This can be used to determine whether text is readable or random, with English text having an IC of around 0.066. IC can therefore be a sound method to automate frequency analysis.";
+        this.infoURL = "https://wikipedia.org/wiki/Index_of_coincidence";
+        this.inputType = "string";
+        this.outputType = "number";
+        this.presentType = "html";
+        this.args = [];
+    }
+
+    /**
+     * @param {string} input
+     * @param {Object[]} args
+     * @returns {number}
+     */
+    run(input, args) {
+        const text = input.toLowerCase().replace(/[^a-z]/g, ""),
+            frequencies = new Array(26).fill(0),
+            alphabet = Utils.expandAlphRange("a-z");
+        let coincidence = 0.00,
+            density = 0.00,
+            result = 0.00,
+            i;
+
+        for (i=0; i < alphabet.length; i++) {
+            frequencies[i] = text.count(alphabet[i]);
+        }
+
+        for (i=0; i < frequencies.length; i++) {
+            coincidence += frequencies[i] * (frequencies[i] - 1);
+        }
+
+        density = frequencies.sum();
+
+        // Ensure that we don't divide by 0
+        if (density < 2) density = 2;
+
+        result = coincidence / (density * (density - 1));
+
+        return result;
+    }
+
+    /**
+     * Displays the IC as a scale bar for web apps.
+     *
+     * @param {number} ic
+     * @returns {html}
+     */
+    present(ic) {
+        return `Index of Coincidence: ${ic}
+Normalized: ${ic * 26}
+<br><canvas id='chart-area'></canvas><br>
+- 0 represents complete randomness (all characters are unique), whereas 1 represents no randomness (all characters are identical).
+- English text generally has an IC of between 0.67 to 0.78.
+- 'Random' text is determined by the probability that each letter occurs the same number of times as another.
+
+The graph shows the IC of the input data. A low IC generally means that the text is random, compressed or encrypted.
+
+<script type='application/javascript'>
+  var canvas = document.getElementById("chart-area"),
+      parentRect = canvas.parentNode.getBoundingClientRect(),
+      ic = ${ic};
+
+  canvas.width = parentRect.width * 0.95;
+  canvas.height = parentRect.height * 0.25;
+
+  ic = ic > 0.25 ? 0.25 : ic;
+
+  CanvasComponents.drawScaleBar(canvas, ic, 0.25, [
+    {
+      label: "English text",
+      min: 0.05,
+      max: 0.08
+    },
+    {
+      label: "> 0.25",
+      min: 0.24,
+      max: 0.25
+    }
+  ]);
+</script>
+     `;
+    }
+
+}
+
+export default IndexOfCoincidence;

+ 18 - 11
src/core/operations/InvertImage.mjs

@@ -26,25 +26,25 @@ class InvertImage extends Operation {
         this.module = "Image";
         this.description = "Invert the colours of an image.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [];
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid input file format.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -52,8 +52,14 @@ class InvertImage extends Operation {
             if (isWorkerEnvironment())
                 self.sendStatusMessage("Inverting image...");
             image.invert();
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error inverting image. (${err})`);
         }
@@ -61,18 +67,19 @@ class InvertImage extends Operation {
 
     /**
      * Displays the inverted image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 6 - 0
src/core/operations/JSONToCSV.mjs

@@ -51,6 +51,10 @@ class JSONToCSV extends Operation {
         this.rowDelim = rowDelim;
         const self = this;
 
+        if (!(input instanceof Array)) {
+            input = [input];
+        }
+
         try {
             // If the JSON is an array of arrays, this is easy
             if (input[0] instanceof Array) {
@@ -89,6 +93,8 @@ class JSONToCSV extends Operation {
      * @returns {string}
      */
     escapeCellContents(data) {
+        if (typeof data === "number") data = data.toString();
+
         // Double quotes should be doubled up
         data = data.replace(/"/g, '""');
 

+ 27 - 12
src/core/operations/NormaliseImage.mjs

@@ -25,44 +25,59 @@ class NormaliseImage extends Operation {
         this.module = "Image";
         this.description = "Normalise the image colours.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType=  "html";
         this.args = [];
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
-        const image = await jimp.read(Buffer.from(input));
+        let image;
+        try {
+            image = await jimp.read(input);
+        } catch (err) {
+            throw new OperationError(`Error opening image file. (${err})`);
+        }
 
-        image.normalize();
+        try {
+            image.normalize();
 
-        const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-        return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
+        } catch (err) {
+            throw new OperationError(`Error normalising image. (${err})`);
+        }
     }
 
     /**
      * Displays the normalised image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 3 - 2
src/core/operations/PGPDecryptAndVerify.mjs

@@ -93,7 +93,7 @@ class PGPDecryptAndVerify extends Operation {
                             text += `${signer.username} `;
                         }
                         if (signer.comment) {
-                            text += `${signer.comment} `;
+                            text += `(${signer.comment}) `;
                         }
                         if (signer.email) {
                             text += `<${signer.email}>`;
@@ -101,8 +101,9 @@ class PGPDecryptAndVerify extends Operation {
                         text += "\n";
                     }
                     text += [
+                        `PGP key ID: ${km.get_pgp_short_key_id()}`,
                         `PGP fingerprint: ${km.get_pgp_fingerprint().toString("hex")}`,
-                        `Signed on ${new Date(ds.sig.hashed_subpackets[0].time * 1000).toUTCString()}`,
+                        `Signed on ${new Date(ds.sig.when_generated() * 1000).toUTCString()}`,
                         "----------------------------------\n"
                     ].join("\n");
                     text += unboxedLiterals.toString();

+ 111 - 0
src/core/operations/PGPVerify.mjs

@@ -0,0 +1,111 @@
+/**
+ * @author Matt C [me@mitt.dev]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+
+import kbpgp from "kbpgp";
+import { ASP, importPublicKey } from "../lib/PGP";
+import * as es6promisify from "es6-promisify";
+const promisify = es6promisify.default ? es6promisify.default.promisify : es6promisify.promisify;
+
+/**
+ * PGP Verify operation
+ */
+class PGPVerify extends Operation {
+
+    /**
+     * PGPVerify constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "PGP Verify";
+        this.module = "PGP";
+        this.description = [
+            "Input: the ASCII-armoured encrypted PGP message you want to verify.",
+            "<br><br>",
+            "Argument: the ASCII-armoured PGP public key of the signer",
+            "<br><br>",
+            "This operation uses PGP to decrypt a clearsigned message.",
+            "<br><br>",
+            "Pretty Good Privacy is an encryption standard (OpenPGP) used for encrypting, decrypting, and signing messages.",
+            "<br><br>",
+            "This function uses the Keybase implementation of PGP.",
+        ].join("\n");
+        this.infoURL = "https://wikipedia.org/wiki/Pretty_Good_Privacy";
+        this.inputType = "string";
+        this.outputType = "string";
+        this.args = [
+            {
+                "name": "Public key of signer",
+                "type": "text",
+                "value": ""
+            }
+        ];
+    }
+
+    /**
+     * @param {string} input
+     * @param {Object[]} args
+     * @returns {string}
+     */
+    async run(input, args) {
+        const signedMessage = input,
+            [publicKey] = args,
+            keyring = new kbpgp.keyring.KeyRing();
+        let unboxedLiterals;
+
+        if (!publicKey) throw new OperationError("Enter the public key of the signer.");
+        const pubKey = await importPublicKey(publicKey);
+        keyring.add_key_manager(pubKey);
+
+        try {
+            unboxedLiterals = await promisify(kbpgp.unbox)({
+                armored: signedMessage,
+                keyfetch: keyring,
+                asp: ASP
+            });
+            const ds = unboxedLiterals[0].get_data_signer();
+            if (ds) {
+                const km = ds.get_key_manager();
+                if (km) {
+                    const signer = km.get_userids_mark_primary()[0].components;
+                    let text = "Signed by ";
+                    if (signer.email || signer.username || signer.comment) {
+                        if (signer.username) {
+                            text += `${signer.username} `;
+                        }
+                        if (signer.comment) {
+                            text += `(${signer.comment}) `;
+                        }
+                        if (signer.email) {
+                            text += `<${signer.email}>`;
+                        }
+                        text += "\n";
+                    }
+                    text += [
+                        `PGP key ID: ${km.get_pgp_short_key_id()}`,
+                        `PGP fingerprint: ${km.get_pgp_fingerprint().toString("hex")}`,
+                        `Signed on ${new Date(ds.sig.when_generated() * 1000).toUTCString()}`,
+                        "----------------------------------\n"
+                    ].join("\n");
+                    text += unboxedLiterals.toString();
+                    return text.trim();
+                } else {
+                    throw new OperationError("Could not identify a key manager.");
+                }
+            } else {
+                throw new OperationError("The data does not appear to be signed.");
+            }
+        } catch (err) {
+            throw new OperationError(`Couldn't verify message: ${err}`);
+        }
+    }
+
+}
+
+export default PGPVerify;

+ 15 - 57
src/core/operations/ParseQRCode.mjs

@@ -6,9 +6,8 @@
 
 import Operation from "../Operation";
 import OperationError from "../errors/OperationError";
-import { isImage } from "../lib/FileType";
-import jsqr from "jsqr";
-import jimp from "jimp";
+import { isImage } from "../lib/FileType.mjs";
+import { parseQrCode } from "../lib/QRCode";
 
 /**
  * Parse QR Code operation
@@ -25,7 +24,7 @@ class ParseQRCode extends Operation {
         this.module = "Image";
         this.description = "Reads an image file and attempts to detect and read a Quick Response (QR) code from the image.<br><br><u>Normalise Image</u><br>Attempts to normalise the image before parsing it to improve detection of a QR code.";
         this.infoURL = "https://wikipedia.org/wiki/QR_code";
-        this.inputType = "byteArray";
+        this.inputType = "ArrayBuffer";
         this.outputType = "string";
         this.args = [
             {
@@ -34,69 +33,28 @@ class ParseQRCode extends Operation {
                 "value": false
             }
         ];
+        this.patterns = [
+            {
+                "match": "^(?:\\xff\\xd8\\xff|\\x89\\x50\\x4e\\x47|\\x47\\x49\\x46|.{8}\\x57\\x45\\x42\\x50|\\x42\\x4d)",
+                "flags": "",
+                "args": [false],
+                "useful": true
+            }
+        ];
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {string}
      */
     async run(input, args) {
         const [normalise] = args;
 
-        // Make sure that the input is an image
-        if (!isImage(input)) throw new OperationError("Invalid file type.");
-
-        let image = input;
-
-        if (normalise) {
-            // Process the image to be easier to read by jsqr
-            // Disables the alpha channel
-            // Sets the image default background to white
-            // Normalises the image colours
-            // Makes the image greyscale
-            // Converts image to a JPEG
-            image = await new Promise((resolve, reject) => {
-                jimp.read(Buffer.from(input))
-                    .then(image => {
-                        image
-                            .rgba(false)
-                            .background(0xFFFFFFFF)
-                            .normalize()
-                            .greyscale()
-                            .getBuffer(jimp.MIME_JPEG, (error, result) => {
-                                resolve(result);
-                            });
-                    })
-                    .catch(err => {
-                        reject(new OperationError("Error reading the image file."));
-                    });
-            });
+        if (!isImage(new Uint8Array(input))) {
+            throw new OperationError("Invalid file type.");
         }
-
-        if (image instanceof OperationError) {
-            throw image;
-        }
-
-        return new Promise((resolve, reject) => {
-            jimp.read(Buffer.from(image))
-                .then(image => {
-                    if (image.bitmap != null) {
-                        const qrData = jsqr(image.bitmap.data, image.getWidth(), image.getHeight());
-                        if (qrData != null) {
-                            resolve(qrData.data);
-                        } else {
-                            reject(new OperationError("Couldn't read a QR code from the image."));
-                        }
-                    } else {
-                        reject(new OperationError("Error reading the image file."));
-                    }
-                })
-                .catch(err => {
-                    reject(new OperationError("Error reading the image file."));
-                });
-        });
-
+        return await parseQrCode(input, normalise);
     }
 
 }

+ 17 - 11
src/core/operations/ResizeImage.mjs

@@ -26,8 +26,8 @@ class ResizeImage extends Operation {
         this.module = "Image";
         this.description = "Resizes an image to the specified width and height values.";
         this.infoURL = "https://wikipedia.org/wiki/Image_scaling";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -68,7 +68,7 @@ class ResizeImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
@@ -87,13 +87,13 @@ class ResizeImage extends Operation {
             "Bezier": jimp.RESIZE_BEZIER
         };
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -111,8 +111,13 @@ class ResizeImage extends Operation {
                 image.resize(width, height, resizeMap[resizeAlg]);
             }
 
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error resizing image. (${err})`);
         }
@@ -120,18 +125,19 @@ class ResizeImage extends Operation {
 
     /**
      * Displays the resized image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 18 - 11
src/core/operations/RotateImage.mjs

@@ -26,8 +26,8 @@ class RotateImage extends Operation {
         this.module = "Image";
         this.description = "Rotates an image by the specified number of degrees.";
         this.infoURL = "";
-        this.inputType = "byteArray";
-        this.outputType = "byteArray";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
         this.presentType = "html";
         this.args = [
             {
@@ -39,20 +39,20 @@ class RotateImage extends Operation {
     }
 
     /**
-     * @param {byteArray} input
+     * @param {ArrayBuffer} input
      * @param {Object[]} args
      * @returns {byteArray}
      */
     async run(input, args) {
         const [degrees] = args;
 
-        if (!isImage(input)) {
+        if (!isImage(new Uint8Array(input))) {
             throw new OperationError("Invalid file type.");
         }
 
         let image;
         try {
-            image = await jimp.read(Buffer.from(input));
+            image = await jimp.read(input);
         } catch (err) {
             throw new OperationError(`Error loading image. (${err})`);
         }
@@ -60,8 +60,14 @@ class RotateImage extends Operation {
             if (isWorkerEnvironment())
                 self.sendStatusMessage("Rotating image...");
             image.rotate(degrees);
-            const imageBuffer = await image.getBufferAsync(jimp.AUTO);
-            return [...imageBuffer];
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
         } catch (err) {
             throw new OperationError(`Error rotating image. (${err})`);
         }
@@ -69,18 +75,19 @@ class RotateImage extends Operation {
 
     /**
      * Displays the rotated image using HTML for web apps
-     * @param {byteArray} data
+     * @param {ArrayBuffer} data
      * @returns {html}
      */
     present(data) {
-        if (!data.length) return "";
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
 
-        const type = isImage(data);
+        const type = isImage(dataArray);
         if (!type) {
             throw new OperationError("Invalid file type.");
         }
 
-        return `<img src="data:${type};base64,${toBase64(data)}">`;
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
     }
 
 }

+ 5 - 4
src/core/operations/ScanForEmbeddedFiles.mjs

@@ -55,12 +55,13 @@ class ScanForEmbeddedFiles extends Operation {
         if (types.length) {
             types.forEach(type => {
                 numFound++;
-                output += "\nOffset " + type.offset + " (0x" + Utils.hex(type.offset) + "):\n" +
-                    "  File extension: " + type.fileDetails.extension + "\n" +
-                    "  MIME type:      " + type.fileDetails.mime + "\n";
+                output += `\nOffset ${type.offset} (0x${Utils.hex(type.offset)}):
+  File type:   ${type.fileDetails.name}
+  Extension:   ${type.fileDetails.extension}
+  MIME type:   ${type.fileDetails.mime}\n`;
 
                 if (type.fileDetails.description && type.fileDetails.description.length) {
-                    output += "  Description:    " + type.fileDetails.description + "\n";
+                    output += `  Description: ${type.fileDetails.description}\n`;
                 }
             });
         }

+ 168 - 0
src/core/operations/SharpenImage.mjs

@@ -0,0 +1,168 @@
+/**
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import { isImage } from "../lib/FileType";
+import { toBase64 } from "../lib/Base64";
+import { gaussianBlur } from "../lib/ImageManipulation";
+import jimp from "jimp";
+
+/**
+ * Sharpen Image operation
+ */
+class SharpenImage extends Operation {
+
+    /**
+     * SharpenImage constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Sharpen Image";
+        this.module = "Image";
+        this.description = "Sharpens an image (Unsharp mask)";
+        this.infoURL = "https://wikipedia.org/wiki/Unsharp_masking";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "ArrayBuffer";
+        this.presentType = "html";
+        this.args = [
+            {
+                name: "Radius",
+                type: "number",
+                value: 2,
+                min: 1
+            },
+            {
+                name: "Amount",
+                type: "number",
+                value: 1,
+                min: 0,
+                step: 0.1
+            },
+            {
+                name: "Threshold",
+                type: "number",
+                value: 10,
+                min: 0,
+                max: 100
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {byteArray}
+     */
+    async run(input, args) {
+        const [radius, amount, threshold] = args;
+
+        if (!isImage(new Uint8Array(input))){
+            throw new OperationError("Invalid file type.");
+        }
+
+        let image;
+        try {
+            image = await jimp.read(input);
+        } catch (err) {
+            throw new OperationError(`Error loading image. (${err})`);
+        }
+
+        try {
+            if (ENVIRONMENT_IS_WORKER())
+                self.sendStatusMessage("Sharpening image... (Cloning image)");
+            const blurMask = image.clone();
+
+            if (ENVIRONMENT_IS_WORKER())
+                self.sendStatusMessage("Sharpening image... (Blurring cloned image)");
+            const blurImage = gaussianBlur(image.clone(), radius, 3);
+
+
+            if (ENVIRONMENT_IS_WORKER())
+                self.sendStatusMessage("Sharpening image... (Creating unsharp mask)");
+            blurMask.scan(0, 0, blurMask.bitmap.width, blurMask.bitmap.height, function(x, y, idx) {
+                const blurRed = blurImage.bitmap.data[idx];
+                const blurGreen = blurImage.bitmap.data[idx + 1];
+                const blurBlue = blurImage.bitmap.data[idx + 2];
+
+                const normalRed = this.bitmap.data[idx];
+                const normalGreen = this.bitmap.data[idx + 1];
+                const normalBlue = this.bitmap.data[idx + 2];
+
+                // Subtract blurred pixel value from normal image
+                this.bitmap.data[idx] = (normalRed > blurRed) ? normalRed - blurRed : 0;
+                this.bitmap.data[idx + 1] = (normalGreen > blurGreen) ? normalGreen - blurGreen : 0;
+                this.bitmap.data[idx + 2] = (normalBlue > blurBlue) ? normalBlue - blurBlue : 0;
+            });
+
+            if (ENVIRONMENT_IS_WORKER())
+                self.sendStatusMessage("Sharpening image... (Merging with unsharp mask)");
+            image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) {
+                let maskRed = blurMask.bitmap.data[idx];
+                let maskGreen = blurMask.bitmap.data[idx + 1];
+                let maskBlue = blurMask.bitmap.data[idx + 2];
+
+                const normalRed = this.bitmap.data[idx];
+                const normalGreen = this.bitmap.data[idx + 1];
+                const normalBlue = this.bitmap.data[idx + 2];
+
+                // Calculate luminance
+                const maskLuminance = (0.2126 * maskRed + 0.7152 * maskGreen + 0.0722 * maskBlue);
+                const normalLuminance = (0.2126 * normalRed + 0.7152 * normalGreen + 0.0722 * normalBlue);
+
+                let luminanceDiff;
+                if (maskLuminance > normalLuminance) {
+                    luminanceDiff = maskLuminance - normalLuminance;
+                } else {
+                    luminanceDiff = normalLuminance - maskLuminance;
+                }
+
+                // Scale mask colours by amount
+                maskRed = maskRed * amount;
+                maskGreen = maskGreen * amount;
+                maskBlue = maskBlue * amount;
+
+                // Only change pixel value if the difference is higher than threshold
+                if ((luminanceDiff / 255) * 100 >= threshold) {
+                    this.bitmap.data[idx] = (normalRed + maskRed) <= 255 ? normalRed + maskRed : 255;
+                    this.bitmap.data[idx + 1] = (normalGreen + maskGreen) <= 255 ? normalGreen + maskGreen : 255;
+                    this.bitmap.data[idx + 2] = (normalBlue + maskBlue) <= 255 ? normalBlue + maskBlue : 255;
+                }
+            });
+
+            let imageBuffer;
+            if (image.getMIME() === "image/gif") {
+                imageBuffer = await image.getBufferAsync(jimp.MIME_PNG);
+            } else {
+                imageBuffer = await image.getBufferAsync(jimp.AUTO);
+            }
+            return imageBuffer.buffer;
+        } catch (err) {
+            throw new OperationError(`Error sharpening image. (${err})`);
+        }
+    }
+
+    /**
+     * Displays the sharpened image using HTML for web apps
+     * @param {ArrayBuffer} data
+     * @returns {html}
+     */
+    present(data) {
+        if (!data.byteLength) return "";
+        const dataArray = new Uint8Array(data);
+
+        const type = isImage(dataArray);
+        if (!type) {
+            throw new OperationError("Invalid file type.");
+        }
+
+        return `<img src="data:${type};base64,${toBase64(dataArray)}">`;
+    }
+
+}
+
+export default SharpenImage;

+ 60 - 0
src/core/operations/Streebog.mjs

@@ -0,0 +1,60 @@
+/**
+ * @author mshwed [m@ttshwed.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+import Operation from "../Operation";
+import OperationError from "../errors/OperationError";
+import GostDigest from "../vendor/gost/gostDigest";
+import {toHexFast} from "../lib/Hex";
+
+/**
+ * Streebog operation
+ */
+class Streebog extends Operation {
+
+    /**
+     * Streebog constructor
+     */
+    constructor() {
+        super();
+
+        this.name = "Streebog";
+        this.module = "Hashing";
+        this.description = "Streebog is a cryptographic hash function defined in the Russian national standard GOST R 34.11-2012 <i>Information Technology \u2013 Cryptographic Information Security \u2013 Hash Function</i>. It was created to replace an obsolete GOST hash function defined in the old standard GOST R 34.11-94, and as an asymmetric reply to SHA-3 competition by the US National Institute of Standards and Technology.";
+        this.infoURL = "https://wikipedia.org/wiki/Streebog";
+        this.inputType = "ArrayBuffer";
+        this.outputType = "string";
+        this.args = [
+            {
+                "name": "Size",
+                "type": "option",
+                "value": ["256", "512"]
+            }
+        ];
+    }
+
+    /**
+     * @param {ArrayBuffer} input
+     * @param {Object[]} args
+     * @returns {string}
+     */
+    run(input, args) {
+        try {
+            const length = parseInt(args[0], 10);
+            const gostDigest = new GostDigest({
+                name: "GOST R 34.11",
+                version: 2012,
+                length: length
+            });
+
+            return toHexFast(gostDigest.digest(input));
+        } catch (err) {
+            throw new OperationError(err);
+        }
+    }
+
+}
+
+export default Streebog;

+ 1168 - 2
src/core/operations/ToHTMLEntity.mjs

@@ -19,7 +19,7 @@ class ToHTMLEntity extends Operation {
         super();
 
         this.name = "To HTML Entity";
-        this.module = "Default";
+        this.module = "Encodings";
         this.description = "Converts characters to HTML entities<br><br>e.g. <code>&amp;</code> becomes <code>&amp;<span>amp;</span></code>";
         this.infoURL = "https://wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references";
         this.inputType = "string";
@@ -33,7 +33,7 @@ class ToHTMLEntity extends Operation {
             {
                 "name": "Convert to",
                 "type": "option",
-                "value": ["Named entities where possible", "Numeric entities", "Hex entities"]
+                "value": ["Named entities", "Numeric entities", "Hex entities"]
             }
         ];
     }
@@ -87,11 +87,38 @@ class ToHTMLEntity extends Operation {
  * Lookup table to translate byte values to their HTML entity codes.
  */
 const byteToEntity = {
+    9: "&Tab;",
+    10: "&NewLine;",
+    33: "&excl;",
     34: "&quot;",
+    35: "&num;",
+    36: "&dollar;",
+    37: "&percnt;",
     38: "&amp;",
     39: "&apos;",
+    40: "&lpar;",
+    41: "&rpar;",
+    42: "&ast;",
+    43: "&plus;",
+    44: "&comma;",
+    46: "&period;",
+    47: "&sol;",
+    58: "&colon;",
+    59: "&semi;",
     60: "&lt;",
+    61: "&equals;",
     62: "&gt;",
+    63: "&quest;",
+    64: "&commat;",
+    91: "&lsqb;",
+    92: "&bsol;",
+    93: "&rsqb;",
+    94: "&Hat;",
+    95: "&lowbar;",
+    96: "&grave;",
+    123: "&lcub;",
+    124: "&verbar;",
+    125: "&rcub;",
     160: "&nbsp;",
     161: "&iexcl;",
     162: "&cent;",
@@ -188,14 +215,139 @@ const byteToEntity = {
     253: "&yacute;",
     254: "&thorn;",
     255: "&yuml;",
+    256: "&Amacr;",
+    257: "&amacr;",
+    258: "&Abreve;",
+    259: "&abreve;",
+    260: "&Aogon;",
+    261: "&aogon;",
+    262: "&Cacute;",
+    263: "&cacute;",
+    264: "&Ccirc;",
+    265: "&ccirc;",
+    266: "&Cdot;",
+    267: "&cdot;",
+    268: "&Ccaron;",
+    269: "&ccaron;",
+    270: "&Dcaron;",
+    271: "&dcaron;",
+    272: "&Dstrok;",
+    273: "&dstrok;",
+    274: "&Emacr;",
+    275: "&emacr;",
+    278: "&Edot;",
+    279: "&edot;",
+    280: "&Eogon;",
+    281: "&eogon;",
+    282: "&Ecaron;",
+    283: "&ecaron;",
+    284: "&Gcirc;",
+    285: "&gcirc;",
+    286: "&Gbreve;",
+    287: "&gbreve;",
+    288: "&Gdot;",
+    289: "&gdot;",
+    290: "&Gcedil;",
+    292: "&Hcirc;",
+    293: "&hcirc;",
+    294: "&Hstrok;",
+    295: "&hstrok;",
+    296: "&Itilde;",
+    297: "&itilde;",
+    298: "&Imacr;",
+    299: "&imacr;",
+    302: "&Iogon;",
+    303: "&iogon;",
+    304: "&Idot;",
+    305: "&imath;",
+    306: "&IJlig;",
+    307: "&ijlig;",
+    308: "&Jcirc;",
+    309: "&jcirc;",
+    310: "&Kcedil;",
+    311: "&kcedil;",
+    312: "&kgreen;",
+    313: "&Lacute;",
+    314: "&lacute;",
+    315: "&Lcedil;",
+    316: "&lcedil;",
+    317: "&Lcaron;",
+    318: "&lcaron;",
+    319: "&Lmidot;",
+    320: "&lmidot;",
+    321: "&Lstrok;",
+    322: "&lstrok;",
+    323: "&Nacute;",
+    324: "&nacute;",
+    325: "&Ncedil;",
+    326: "&ncedil;",
+    327: "&Ncaron;",
+    328: "&ncaron;",
+    329: "&napos;",
+    330: "&ENG;",
+    331: "&eng;",
+    332: "&Omacr;",
+    333: "&omacr;",
+    336: "&Odblac;",
+    337: "&odblac;",
     338: "&OElig;",
     339: "&oelig;",
+    340: "&Racute;",
+    341: "&racute;",
+    342: "&Rcedil;",
+    343: "&rcedil;",
+    344: "&Rcaron;",
+    345: "&rcaron;",
+    346: "&Sacute;",
+    347: "&sacute;",
+    348: "&Scirc;",
+    349: "&scirc;",
+    350: "&Scedil;",
+    351: "&scedil;",
     352: "&Scaron;",
     353: "&scaron;",
+    354: "&Tcedil;",
+    355: "&tcedil;",
+    356: "&Tcaron;",
+    357: "&tcaron;",
+    358: "&Tstrok;",
+    359: "&tstrok;",
+    360: "&Utilde;",
+    361: "&utilde;",
+    362: "&Umacr;",
+    363: "&umacr;",
+    364: "&Ubreve;",
+    365: "&ubreve;",
+    366: "&Uring;",
+    367: "&uring;",
+    368: "&Udblac;",
+    369: "&udblac;",
+    370: "&Uogon;",
+    371: "&uogon;",
+    372: "&Wcirc;",
+    373: "&wcirc;",
+    374: "&Ycirc;",
+    375: "&ycirc;",
     376: "&Yuml;",
+    377: "&Zacute;",
+    378: "&zacute;",
+    379: "&Zdot;",
+    380: "&zdot;",
+    381: "&Zcaron;",
+    382: "&zcaron;",
     402: "&fnof;",
+    437: "&imped;",
+    501: "&gacute;",
+    567: "&jmath;",
     710: "&circ;",
+    711: "&caron;",
+    728: "&breve;",
+    729: "&dot;",
+    730: "&ring;",
+    731: "&ogon;",
     732: "&tilde;",
+    785: "&DownBreve;",
+    818: "&UnderBar;",
     913: "&Alpha;",
     914: "&Beta;",
     915: "&Gamma;",
@@ -247,16 +399,124 @@ const byteToEntity = {
     969: "&omega;",
     977: "&thetasym;",
     978: "&upsih;",
+    981: "&straightphi;",
     982: "&piv;",
+    988: "&Gammad;",
+    989: "&gammad;",
+    1008: "&kappav;",
+    1009: "&rhov;",
+    1013: "&epsi;,",
+    1014: "&bepsi;",
+    1025: "&IOcy;",
+    1026: "&DJcy;",
+    1027: "&GJcy;",
+    1028: "&Jukcy;",
+    1029: "&DScy;",
+    1030: "&Iukcy;",
+    1031: "&YIcy;",
+    1032: "&Jsercy;",
+    1033: "&LJcy;",
+    1034: "&NJcy;",
+    1035: "&TSHcy;",
+    1036: "&KJcy;",
+    1038: "&Ubrcy;",
+    1039: "&DZcy;",
+    1040: "&Acy;",
+    1041: "&Bcy;",
+    1042: "&Vcy;",
+    1043: "&Gcy;",
+    1044: "&Dcy;",
+    1045: "&IEcy;",
+    1046: "&ZHcy;",
+    1047: "&Zcy;",
+    1048: "&Icy;",
+    1049: "&Jcy;",
+    1050: "&Kcy;",
+    1051: "&Lcy;",
+    1052: "&Mcy;",
+    1053: "&Ncy;",
+    1054: "&Ocy;",
+    1055: "&Pcy;",
+    1056: "&Rcy;",
+    1057: "&Scy;",
+    1058: "&Tcy;",
+    1059: "&Ucy;",
+    1060: "&Fcy;",
+    1061: "&KHcy;",
+    1062: "&TScy;",
+    1063: "&CHcy;",
+    1064: "&SHcy;",
+    1065: "&SHCHcy;",
+    1066: "&HARDcy;",
+    1067: "&Ycy;",
+    1068: "&SOFTcy;",
+    1069: "&Ecy;",
+    1070: "&YUcy;",
+    1071: "&YAcy;",
+    1072: "&acy;",
+    1073: "&bcy;",
+    1074: "&vcy;",
+    1075: "&gcy;",
+    1076: "&dcy;",
+    1077: "&iecy;",
+    1078: "&zhcy;",
+    1079: "&zcy;",
+    1080: "&icy;",
+    1081: "&jcy;",
+    1082: "&kcy;",
+    1083: "&lcy;",
+    1084: "&mcy;",
+    1085: "&ncy;",
+    1086: "&ocy;",
+    1087: "&pcy;",
+    1088: "&rcy;",
+    1089: "&scy;",
+    1090: "&tcy;",
+    1091: "&ucy;",
+    1092: "&fcy;",
+    1093: "&khcy;",
+    1094: "&tscy;",
+    1095: "&chcy;",
+    1096: "&shcy;",
+    1097: "&shchcy;",
+    1098: "&hardcy;",
+    1099: "&ycy;",
+    1100: "&softcy;",
+    1101: "&ecy;",
+    1102: "&yucy;",
+    1103: "&yacy;",
+    1105: "&iocy;",
+    1106: "&djcy;",
+    1107: "&gjcy;",
+    1108: "&jukcy;",
+    1109: "&dscy;",
+    1110: "&iukcy;",
+    1111: "&yicy;",
+    1112: "&jsercy;",
+    1113: "&ljcy;",
+    1114: "&njcy;",
+    1115: "&tshcy;",
+    1116: "&kjcy;",
+    1118: "&ubrcy;",
+    1119: "&dzcy;",
     8194: "&ensp;",
     8195: "&emsp;",
+    8196: "&emsp13;",
+    8197: "&emsp14;",
+    8199: "&numsp;",
+    8200: "&puncsp;",
     8201: "&thinsp;",
+    8202: "&hairsp;",
+    8203: "&ZeroWidthSpace;",
     8204: "&zwnj;",
     8205: "&zwj;",
     8206: "&lrm;",
     8207: "&rlm;",
+    8208: "&hyphen;",
     8211: "&ndash;",
     8212: "&mdash;",
+    8213: "&horbar;",
+    8214: "&Verbar;",
     8216: "&lsquo;",
     8217: "&rsquo;",
     8218: "&sbquo;",
@@ -266,81 +526,987 @@ const byteToEntity = {
     8224: "&dagger;",
     8225: "&Dagger;",
     8226: "&bull;",
+    8229: "&nldr;",
     8230: "&hellip;",
     8240: "&permil;",
+    8241: "&pertenk;",
     8242: "&prime;",
     8243: "&Prime;",
+    8244: "&tprime;",
+    8245: "&bprime;",
     8249: "&lsaquo;",
     8250: "&rsaquo;",
     8254: "&oline;",
+    8257: "&caret;",
+    8259: "&hybull;",
     8260: "&frasl;",
+    8271: "&bsemi;",
+    8279: "&qprime;",
+    8287: "&MediumSpace;",
+    8288: "&NoBreak;",
+    8289: "&ApplyFunction;",
+    8290: "&InvisibleTimes;",
+    8291: "&InvisibleComma;",
     8364: "&euro;",
+    8411: "&tdot;",
+    8412: "&DotDot;",
+    8450: "&Copf;",
+    8453: "&incare;",
+    8458: "&gscr;",
+    8459: "&hamilt;",
+    8460: "&Hfr;",
+    8461: "&quaternions;",
+    8462: "&planckh;",
+    8463: "&planck;",
+    8464: "&Iscr;",
     8465: "&image;",
+    8466: "&Lscr;",
+    8467: "&ell;",
+    8469: "&Nopf;",
+    8470: "&numero;",
+    8471: "&copysr;",
     8472: "&weierp;",
+    8473: "&Popf;",
+    8474: "&rationals;",
+    8475: "&Rscr;",
     8476: "&real;",
+    8477: "&reals;",
+    8478: "&rx;",
     8482: "&trade;",
+    8484: "&integers;",
+    8486: "&ohm;",
+    8487: "&mho;",
+    8488: "&Zfr;",
+    8489: "&iiota;",
+    8491: "&angst;",
+    8492: "&bernou;",
+    8493: "&Cfr;",
+    8495: "&escr;",
+    8496: "&Escr;",
+    8497: "&Fscr;",
+    8499: "&phmmat;",
+    8500: "&order;",
     8501: "&alefsym;",
+    8502: "&beth;",
+    8503: "&gimel;",
+    8504: "&daleth;",
+    8517: "&CapitalDifferentialD;",
+    8518: "&DifferentialD;",
+    8519: "&ExponentialE;",
+    8520: "&ImaginaryI;",
+    8531: "&frac13;",
+    8532: "&frac23;",
+    8533: "&frac15;",
+    8534: "&frac25;",
+    8535: "&frac35;",
+    8536: "&frac45;",
+    8537: "&frac16;",
+    8538: "&frac56;",
+    8539: "&frac18;",
+    8540: "&frac38;",
+    8541: "&frac58;",
+    8542: "&frac78;",
     8592: "&larr;",
     8593: "&uarr;",
     8594: "&rarr;",
     8595: "&darr;",
     8596: "&harr;",
+    8597: "&varr;",
+    8598: "&nwarr;",
+    8599: "&nearr;",
+    8600: "&searr;",
+    8601: "&swarr;",
+    8602: "&nlarr;",
+    8603: "&nrarr;",
+    8605: "&rarrw;",
+    8606: "&Larr;",
+    8607: "&Uarr;",
+    8608: "&Rarr;",
+    8609: "&Darr;",
+    8610: "&larrtl;",
+    8611: "&rarrtl;",
+    8612: "&LeftTeeArrow;",
+    8613: "&UpTeeArrow;",
+    8614: "&map;",
+    8615: "&DownTeeArrow;",
+    8617: "&larrhk;",
+    8618: "&rarrhk;",
+    8619: "&larrlp;",
+    8620: "&rarrlp;",
+    8621: "&harrw;",
+    8622: "&nharr;",
+    8624: "&lsh;",
+    8625: "&rsh;",
+    8626: "&ldsh;",
+    8627: "&rdsh;",
     8629: "&crarr;",
+    8630: "&cularr;",
+    8631: "&curarr;",
+    8634: "&olarr;",
+    8635: "&orarr;",
+    8636: "&lharu;",
+    8637: "&lhard;",
+    8638: "&uharr;",
+    8639: "&uharl;",
+    8640: "&rharu;",
+    8641: "&rhard;",
+    8642: "&dharr;",
+    8643: "&dharl;",
+    8644: "&rlarr;",
+    8645: "&udarr;",
+    8646: "&lrarr;",
+    8647: "&llarr;",
+    8648: "&uuarr;",
+    8649: "&rrarr;",
+    8650: "&ddarr;",
+    8651: "&lrhar;",
+    8652: "&rlhar;;",
+    8653: "&nlArr;",
+    8654: "&nhArr;",
+    8655: "&nrArr;",
     8656: "&lArr;",
     8657: "&uArr;",
     8658: "&rArr;",
     8659: "&dArr;",
     8660: "&hArr;",
+    8661: "&vArr;",
+    8662: "&nwArr;",
+    8663: "&neArr;",
+    8664: "&seArr;",
+    8665: "&swArr;",
+    8666: "&lAarr;",
+    8667: "&rAarr;",
+    8669: "&zigrarr;",
+    8676: "&larrb;",
+    8677: "&rarrb;",
+    8693: "&duarr;",
+    8701: "&loarr;",
+    8702: "&roarr;",
+    8703: "&hoarr;",
     8704: "&forall;",
+    8705: "&comp;",
     8706: "&part;",
     8707: "&exist;",
+    8708: "&nexist;",
     8709: "&empty;",
     8711: "&nabla;",
     8712: "&isin;",
     8713: "&notin;",
     8715: "&ni;",
+    8716: "&notni;",
     8719: "&prod;",
+    8720: "&coprod;",
     8721: "&sum;",
     8722: "&minus;",
+    8723: "&mnplus;",
+    8724: "&plusdo;",
+    8726: "&setmn;",
     8727: "&lowast;",
+    8728: "&compfn;",
     8730: "&radic;",
     8733: "&prop;",
     8734: "&infin;",
+    8735: "&angrt;",
     8736: "&ang;",
+    8737: "&angmsd;",
+    8738: "&angsph;",
+    8739: "&mid;",
+    8740: "&nmid;",
+    8741: "&par;",
+    8742: "&npar;",
     8743: "&and;",
     8744: "&or;",
     8745: "&cap;",
     8746: "&cup;",
     8747: "&int;",
+    8748: "&Int;",
+    8749: "&tint;",
+    8750: "&conint;",
+    8751: "&Conint;",
+    8752: "&Cconint;",
+    8753: "&cwint;",
+    8754: "&cwconint;",
+    8755: "&awconint;",
     8756: "&there4;",
+    8757: "&becaus;",
+    8758: "&ratio;",
+    8759: "&Colon;",
+    8760: "&minusd;",
+    8762: "&mDDot;",
+    8763: "&homtht;",
     8764: "&sim;",
+    8765: "&bsim;",
+    8766: "&ac;",
+    8767: "&acd;",
+    8768: "&wreath;",
+    8769: "&nsim;",
+    8770: "&esim;",
+    8771: "&sime;",
+    8772: "&nsime;",
     8773: "&cong;",
+    8774: "&simne;",
+    8775: "&ncong;",
     8776: "&asymp;",
+    8777: "&nap;",
+    8778: "&ape;",
+    8779: "&apid;",
+    8780: "&bcong;",
+    8781: "&asympeq;",
+    8782: "&bump;",
+    8783: "&bumpe;",
+    8784: "&esdot;",
+    8785: "&eDot;",
+    8786: "&efDot;",
+    8787: "&erDot;",
+    8788: "&colone;",
+    8789: "&ecolon;",
+    8790: "&ecir;",
+    8791: "&cire;",
+    8793: "&wedgeq;",
+    8794: "&veeeq;",
+    8796: "&trie;",
+    8799: "&equest;",
     8800: "&ne;",
     8801: "&equiv;",
+    8802: "&nequiv;",
     8804: "&le;",
     8805: "&ge;",
+    8806: "&lE;",
+    8807: "&gE;",
+    8808: "&lnE;",
+    8809: "&gnE;",
+    8810: "&Lt;",
+    8811: "&Gt;",
+    8812: "&twixt;",
+    8813: "&NotCupCap;",
+    8814: "&nlt;",
+    8815: "&ngt;",
+    8816: "&nle;",
+    8817: "&nge;;",
+    8818: "&lsim;",
+    8819: "&gsim;",
+    8820: "&nlsim;",
+    8821: "&ngsim;",
+    8822: "&lg;",
+    8823: "&gl;",
+    8824: "&ntlg;",
+    8825: "&ntgl;",
+    8826: "&pr;",
+    8827: "&sc;",
+    8828: "&prcue;",
+    8829: "&sccue;",
+    8830: "&prsim;",
+    8831: "&scsim;",
+    8832: "&npr;",
+    8833: "&nsc;",
     8834: "&sub;",
     8835: "&sup;",
     8836: "&nsub;",
+    8837: "&nsup;",
     8838: "&sube;",
     8839: "&supe;",
+    8840: "&nsube;",
+    8841: "&nsupe;",
+    8842: "&subne;",
+    8843: "&supne;",
+    8845: "&cupdot;",
+    8846: "&uplus;",
+    8847: "&sqsub;",
+    8848: "&sqsup;",
+    8849: "&sqsube;",
+    8850: "&sqsupe;",
+    8851: "&sqcap;",
+    8852: "&sqcup;",
     8853: "&oplus;",
+    8854: "&ominus;",
     8855: "&otimes;",
+    8856: "&osol;",
+    8857: "&odot;",
+    8858: "&ocir;",
+    8859: "&oast;",
+    8861: "&odash;",
+    8862: "&plusb;",
+    8863: "&minusb;",
+    8864: "&timesb;",
+    8865: "&sdotb;",
+    8866: "&vdash;",
+    8867: "&dashv;",
+    8868: "&top;",
     8869: "&perp;",
+    8871: "&models;",
+    8872: "&vDash;",
+    8873: "&Vdash;",
+    8874: "&Vvdash;",
+    8875: "&VDash;",
+    8876: "&nvdash;",
+    8877: "&nvDash;",
+    8878: "&nVdash;",
+    8879: "&nVDash;",
+    8880: "&prurel;",
+    8882: "&vltri;",
+    8883: "&vrtri;",
+    8884: "&ltrie;",
+    8885: "&rtrie;",
+    8886: "&origof;",
+    8887: "&imof;",
+    8888: "&mumap;",
+    8889: "&hercon;",
+    8890: "&intcal;",
+    8891: "&veebar;",
+    8893: "&barvee;",
+    8894: "&angrtvb;",
+    8895: "&lrtri;",
+    8896: "&xwedge;",
+    8897: "&xvee;",
+    8898: "&xcap;",
+    8899: "&xcup;",
+    8900: "&diam;",
     8901: "&sdot;",
+    8902: "&sstarf;",
+    8903: "&divonx;",
+    8904: "&bowtie;",
+    8905: "&ltimes;",
+    8906: "&rtimes;",
+    8907: "&lthree;",
+    8908: "&rthree;",
+    8909: "&bsime;",
+    8910: "&cuvee;",
+    8911: "&cuwed;",
+    8912: "&Sub;",
+    8913: "&Sup;",
+    8914: "&Cap;",
+    8915: "&Cup;",
+    8916: "&fork;",
+    8917: "&epar;",
+    8918: "&ltdot;",
+    8919: "&gtdot;",
+    8920: "&Ll;",
+    8921: "&Gg;",
+    8922: "&leg;",
+    8923: "&gel;",
+    8926: "&cuepr;",
+    8927: "&cuesc;",
+    8928: "&nprcue;",
+    8929: "&nsccue;",
+    8930: "&nsqsube;",
+    8931: "&nsqsupe;",
+    8934: "&lnsim;",
+    8935: "&gnsim;",
+    8936: "&prnsim;",
+    8937: "&scnsim;",
+    8938: "&nltri;",
+    8939: "&nrtri;",
+    8940: "&nltrie;",
+    8941: "&nrtrie;",
     8942: "&vellip;",
+    8943: "&ctdot;",
+    8944: "&utdot;",
+    8945: "&dtdot;",
+    8946: "&disin;",
+    8947: "&isinsv;",
+    8948: "&isins;",
+    8949: "&isindot;",
+    8950: "&notinvc;",
+    8951: "&notinvb;",
+    8953: "&isinE;",
+    8954: "&nisd;",
+    8955: "&xnis;",
+    8956: "&nis;",
+    8957: "&notnivc;",
+    8958: "&notnivb;",
+    8965: "&barwed;",
+    8966: "&Barwed;",
     8968: "&lceil;",
     8969: "&rceil;",
     8970: "&lfloor;",
     8971: "&rfloor;",
+    8972: "&drcrop;",
+    8973: "&dlcrop;",
+    8974: "&urcrop;",
+    8975: "&ulcrop;",
+    8976: "&bnot;",
+    8978: "&profline;",
+    8979: "&profsurf;",
+    8981: "&telrec;",
+    8982: "&target;",
+    8988: "&ulcorn;",
+    8989: "&urcorn;",
+    8990: "&dlcorn;",
+    8991: "&drcorn;",
+    8994: "&frown;",
+    8995: "&smile;",
     9001: "&lang;",
     9002: "&rang;",
+    9005: "&cylcty;",
+    9006: "&profalar;",
+    9014: "&topbot;",
+    9021: "&ovbar;",
+    9023: "&solbar;",
+    9084: "&angzarr;",
+    9136: "&lmoust;",
+    9137: "&rmoust;",
+    9140: "&tbrk;",
+    9141: "&bbrk;",
+    9142: "&bbrktbrk;",
+    9180: "&OverParenthesis;",
+    9181: "&UnderParenthesis;",
+    9182: "&OverBrace;",
+    9183: "&UnderBrace;",
+    9186: "&trpezium;",
+    9191: "&elinters;",
+    9251: "&blank;",
+    9416: "&oS;",
+    9472: "&boxh;",
+    9474: "&boxv;",
+    9484: "&boxdr;",
+    9488: "&boxdl;",
+    9492: "&boxur;",
+    9496: "&boxul;",
+    9500: "&boxvr;",
+    9508: "&boxvl;",
+    9516: "&boxhd;",
+    9524: "&boxhu;",
+    9532: "&boxvh;",
+    9552: "&boxH;",
+    9553: "&boxV;",
+    9554: "&boxdR;",
+    9555: "&boxDr;",
+    9556: "&boxDR;",
+    9557: "&boxdL;",
+    9558: "&boxDl;",
+    9559: "&boxDL;",
+    9560: "&boxuR;",
+    9561: "&boxUr;",
+    9562: "&boxUR;",
+    9563: "&boxuL;",
+    9564: "&boxUl;",
+    9565: "&boxUL;",
+    9566: "&boxvR;",
+    9567: "&boxVr;",
+    9568: "&boxVR;",
+    9569: "&boxvL;",
+    9570: "&boxVl;",
+    9571: "&boxVL;",
+    9572: "&boxHd;",
+    9573: "&boxhD;",
     9674: "&loz;",
+    9675: "&cir;",
+    9708: "&tridot;",
+    9711: "&xcirc;",
+    9720: "&ultri;",
+    9721: "&urtri;",
+    9722: "&lltri;",
+    9723: "&EmptySmallSquare;",
+    9724: "&FilledSmallSquare;",
+    9733: "&starf;",
+    9734: "&star;",
+    9742: "&phone;",
+    9792: "&female;",
+    9794: "&male;",
     9824: "&spades;",
     9827: "&clubs;",
     9829: "&hearts;",
     9830: "&diams;",
+    9834: "&sung;",
+    9837: "&flat;",
+    9838: "&natur;",
+    9839: "&sharp;",
+    10003: "&check;",
+    10007: "&cross;",
+    10016: "&malt;",
+    10038: "&sext;",
+    10072: "&VerticalSeparator;",
+    10098: "&lbbrk;",
+    10099: "&rbbrk;",
+    10214: "&lobrk;",
+    10215: "&robrk;",
+    10216: "&lang;",
+    10217: "&rang;",
+    10218: "&Lang;",
+    10219: "&Rang;",
+    10220: "&loang;",
+    10221: "&roang;",
+    10229: "&xlarr;",
+    10230: "&xrarr;",
+    10231: "&xharr;",
+    10232: "&xlArr;",
+    10233: "&xrArr;",
+    10234: "&xhArr;",
+    10236: "&xmap;",
+    10239: "&dzigrarr;",
+    10498: "&nvlArr;",
+    10499: "&nvrArr;",
+    10500: "&nvHarr;",
+    10501: "&Map;",
+    10508: "&lbarr;",
+    10509: "&rbarr;",
+    10510: "&lBarr;",
+    10511: "&rBarr;",
+    10512: "&RBarr;",
+    10513: "&DDotrahd;",
+    10514: "&UpArrowBar;",
+    10515: "&DownArrowBar;",
+    10518: "&Rarrtl;",
+    10521: "&latail;",
+    10522: "&ratail;",
+    10523: "&lAtail;",
+    10524: "&rAtail;",
+    10525: "&larrfs;",
+    10526: "&rarrfs;",
+    10527: "&larrbfs;",
+    10528: "&rarrbfs;",
+    10531: "&nwarhk;",
+    10532: "&nearhk;",
+    10533: "&searhk;",
+    10534: "&swarhk;",
+    10535: "&nwnear;",
+    10536: "&nesear;",
+    10537: "&seswar;",
+    10538: "&swnwar;",
+    10547: "&rarrc;",
+    10549: "&cudarrr;",
+    10550: "&ldca;",
+    10551: "&rdca;",
+    10552: "&cudarrl;",
+    10553: "&larrpl;",
+    10556: "&curarrm;",
+    10557: "&cularrp;",
+    10565: "&rarrpl;",
+    10568: "&harrcir;",
+    10569: "&Uarrocir;",
+    10570: "&lurdshar;",
+    10571: "&ldrushar;",
+    10574: "&LeftRightVector;",
+    10575: "&RightUpDownVector;",
+    10576: "&DownLeftRightVector;",
+    10577: "&LeftUpDownVector;",
+    10578: "&LeftVectorBar;",
+    10579: "&RightVectorBar;",
+    10580: "&RightUpVectorBar;",
+    10581: "&RightDownVectorBar;",
+    10582: "&DownLeftVectorBar;",
+    10583: "&DownRightVectorBar;",
+    10584: "&LeftUpVectorBar;",
+    10585: "&LeftDownVectorBar;",
+    10586: "&LeftTeeVector;",
+    10587: "&RightTeeVector;",
+    10588: "&RightUpTeeVector;",
+    10589: "&RightDownTeeVector;",
+    10590: "&DownLeftTeeVector;",
+    10591: "&DownRightTeeVector;",
+    10592: "&LeftUpTeeVector;",
+    10593: "&LeftDownTeeVector;",
+    10594: "&lHar;",
+    10595: "&uHar;",
+    10596: "&rHar;",
+    10597: "&dHar;",
+    10598: "&luruhar;",
+    10599: "&ldrdhar;",
+    10600: "&ruluhar;",
+    10601: "&rdldhar;",
+    10602: "&lharul;",
+    10603: "&llhard;",
+    10604: "&rharul;",
+    10605: "&lrhard;",
+    10606: "&udhar;",
+    10607: "&duhar;",
+    10608: "&RoundImplies;",
+    10609: "&erarr;",
+    10610: "&simrarr;",
+    10611: "&larrsim;",
+    10612: "&rarrsim;",
+    10613: "&rarrap;",
+    10614: "&ltlarr;",
+    10616: "&gtrarr;",
+    10617: "&subrarr;",
+    10619: "&suplarr;",
+    10620: "&lfisht;",
+    10621: "&rfisht;",
+    10622: "&ufisht;",
+    10623: "&dfisht;",
+    10629: "&lopar;",
+    10630: "&ropar;",
+    10635: "&lbrke;",
+    10636: "&rbrke;",
+    10637: "&lbrkslu;",
+    10638: "&rbrksld;",
+    10639: "&lbrksld;",
+    10640: "&rbrkslu;",
+    10641: "&langd;",
+    10642: "&rangd;",
+    10643: "&lparlt;",
+    10644: "&rpargt;",
+    10645: "&gtlPar;",
+    10646: "&ltrPar;",
+    10650: "&vzigzag;",
+    10652: "&vangrt;",
+    10653: "&angrtvbd;",
+    10660: "&ange;",
+    10661: "&range;",
+    10662: "&dwangle;",
+    10663: "&uwangle;",
+    10664: "&angmsdaa;",
+    10665: "&angmsdab;",
+    10666: "&angmsdac;",
+    10667: "&angmsdad;",
+    10668: "&angmsdae;",
+    10669: "&angmsdaf;",
+    10670: "&angmsdag;",
+    10671: "&angmsdah;",
+    10672: "&bemptyv;",
+    10673: "&demptyv;",
+    10674: "&cemptyv;",
+    10675: "&raemptyv;",
+    10676: "&laemptyv;",
+    10677: "&ohbar;",
+    10678: "&omid;",
+    10679: "&opar;",
+    10681: "&operp;",
+    10683: "&olcross;",
+    10684: "&odsold;",
+    10686: "&olcir;",
+    10687: "&ofcir;",
+    10688: "&olt;",
+    10689: "&ogt;",
+    10690: "&cirscir;",
+    10691: "&cirE;",
+    10692: "&solb;",
+    10693: "&bsolb;",
+    10697: "&boxbox;",
+    10701: "&trisb;",
+    10702: "&rtriltri;",
+    10703: "&LeftTriangleBar;",
+    10704: "&RightTriangleBar;",
+    10714: "&race;",
+    10716: "&iinfin;",
+    10717: "&infintie;",
+    10718: "&nvinfin;",
+    10723: "&eparsl;",
+    10724: "&smeparsl;",
+    10725: "&eqvparsl;",
+    10731: "&lozf;",
+    10740: "&RuleDelayed;",
+    10742: "&dsol;",
+    10752: "&xodot;",
+    10753: "&xoplus;",
+    10754: "&xotime;",
+    10756: "&xuplus;",
+    10758: "&xsqcup;",
+    10764: "&qint;",
+    10765: "&fpartint;",
+    10768: "&cirfnint;",
+    10769: "&awint;",
+    10770: "&rppolint;",
+    10771: "&scpolint;",
+    10772: "&npolint;",
+    10773: "&pointint;",
+    10774: "&quatint;",
+    10775: "&intlarhk;",
+    10786: "&pluscir;",
+    10787: "&plusacir;",
+    10788: "&simplus;",
+    10789: "&plusdu;",
+    10790: "&plussim;",
+    10791: "&plustwo;",
+    10793: "&mcomma;",
+    10794: "&minusdu;",
+    10797: "&loplus;",
+    10798: "&roplus;",
+    10799: "&Cross;",
+    10800: "&timesd;",
+    10801: "&timesbar;",
+    10803: "&smashp;",
+    10804: "&lotimes;",
+    10805: "&rotimes;",
+    10806: "&otimesas;",
+    10807: "&Otimes;",
+    10808: "&odiv;",
+    10809: "&triplus;",
+    10810: "&triminus;",
+    10811: "&tritime;",
+    10812: "&iprod;",
+    10815: "&amalg;",
+    10816: "&capdot;",
+    10818: "&ncup;",
+    10819: "&ncap;",
+    10820: "&capand;",
+    10821: "&cupor;",
+    10822: "&cupcap;",
+    10823: "&capcup;",
+    10824: "&cupbrcap;",
+    10825: "&capbrcup;",
+    10826: "&cupcup;",
+    10827: "&capcap;",
+    10828: "&ccups;",
+    10829: "&ccaps;",
+    10832: "&ccupssm;",
+    10835: "&And;",
+    10836: "&Or;",
+    10837: "&andand;",
+    10838: "&oror;",
+    10839: "&orslope;",
+    10840: "&andslope;",
+    10842: "&andv;",
+    10843: "&orv;",
+    10844: "&andd;",
+    10845: "&ord;",
+    10847: "&wedbar;",
+    10854: "&sdote;",
+    10858: "&simdot;",
+    10861: "&congdot;",
+    10862: "&easter;",
+    10863: "&apacir;",
+    10864: "&apE;",
+    10865: "&eplus;",
+    10866: "&pluse;",
+    10867: "&Esim;",
+    10868: "&Colone;",
+    10869: "&Equal;",
+    10871: "&eDDot;",
+    10872: "&equivDD;",
+    10873: "&ltcir;",
+    10874: "&gtcir;",
+    10875: "&ltquest;",
+    10876: "&gtquest;",
+    10877: "&les;",
+    10878: "&ges;",
+    10879: "&lesdot;",
+    10880: "&gesdot;",
+    10881: "&lesdoto;",
+    10882: "&gesdoto;",
+    10883: "&lesdotor;",
+    10884: "&gesdotol;",
+    10885: "&lap;",
+    10886: "&gap;",
+    10887: "&lne;",
+    10888: "&gne;",
+    10889: "&lnap;",
+    10890: "&gnap;",
+    10891: "&lEg;",
+    10892: "&gEl;",
+    10893: "&lsime;",
+    10894: "&gsime;",
+    10895: "&lsimg;",
+    10896: "&gsiml;",
+    10897: "&lgE;",
+    10898: "&glE;",
+    10899: "&lesges;",
+    10900: "&gesles;",
+    10901: "&els;",
+    10902: "&egs;",
+    10903: "&elsdot;",
+    10904: "&egsdot;",
+    10905: "&el;",
+    10906: "&eg;",
+    10909: "&siml;",
+    10910: "&simg;",
+    10911: "&simlE;",
+    10912: "&simgE;",
+    10913: "&LessLess;",
+    10914: "&GreaterGreater;",
+    10916: "&glj;",
+    10917: "&gla;",
+    10918: "&ltcc;",
+    10919: "&gtcc;",
+    10920: "&lescc;",
+    10921: "&gescc;",
+    10922: "&smt;",
+    10923: "&lat;",
+    10924: "&smte;",
+    10925: "&late;",
+    10926: "&bumpE;",
+    10927: "&pre;",
+    10928: "&sce;",
+    10931: "&prE;",
+    10932: "&scE;",
+    10933: "&prnE;",
+    10934: "&scnE;",
+    10935: "&prap;",
+    10936: "&scap;",
+    10937: "&prnap;",
+    10938: "&scnap;",
+    10939: "&Pr;",
+    10940: "&Sc;",
+    10941: "&subdot;",
+    10942: "&supdot;",
+    10943: "&subplus;",
+    10944: "&supplus;",
+    10945: "&submult;",
+    10946: "&supmult;",
+    10947: "&subedot;",
+    10948: "&supedot;",
+    10949: "&subE;",
+    10950: "&supE;",
+    10951: "&subsim;",
+    10952: "&supsim;",
+    10955: "&subnE;",
+    10956: "&supnE;",
+    10959: "&csub;",
+    10960: "&csup;",
+    10961: "&csube;",
+    10962: "&csupe;",
+    10963: "&subsup;",
+    10964: "&supsub;",
+    10965: "&subsub;",
+    10966: "&supsup;",
+    10967: "&suphsub;",
+    10968: "&supdsub;",
+    10969: "&forkv;",
+    10970: "&topfork;",
+    10971: "&mlcp;",
+    10980: "&Dashv;",
+    10982: "&Vdashl;",
+    10983: "&Barv;",
+    10984: "&vBar;",
+    10985: "&vBarv;",
+    10987: "&Vbar;",
+    10988: "&Not;",
+    10989: "&bNot;",
+    10990: "&rnmid;",
+    10991: "&cirmid;",
+    10992: "&midcir;",
+    10993: "&topcir;",
+    10994: "&nhpar;",
+    10995: "&parsim;",
+    11005: "&parsl;",
+    64256: "&fflig;",
+    64257: "&filig;",
+    64258: "&fllig;",
+    64259: "&ffilig;",
+    64260: "&ffllig;",
+    119964: "&Ascr;",
+    119966: "&Cscr;",
+    119967: "&Dscr;",
+    119970: "&Gscr;",
+    119973: "&Jscr;",
+    119974: "&Kscr;",
+    119977: "&Nscr;",
+    119978: "&Oscr;",
+    119979: "&Pscr;",
+    119980: "&Qscr;",
+    119982: "&Sscr;",
+    119983: "&Tscr;",
+    119984: "&Uscr;",
+    119985: "&Vscr;",
+    119986: "&Wscr;",
+    119987: "&Xscr;",
+    119988: "&Yscr;",
+    119989: "&Zscr;",
+    119990: "&ascr;",
+    119991: "&bscr;",
+    119992: "&cscr;",
+    119993: "&dscr;",
+    119995: "&fscr;",
+    119997: "&hscr;",
+    119998: "&iscr;",
+    119999: "&jscr;",
+    120000: "&kscr;",
+    120001: "&lscr;",
+    120002: "&mscr;",
+    120003: "&nscr;",
+    120005: "&pscr;",
+    120006: "&qscr;",
+    120007: "&rscr;",
+    120008: "&sscr;",
+    120009: "&tscr;",
+    120010: "&uscr;",
+    120011: "&vscr;",
+    120012: "&wscr;",
+    120013: "&xscr;",
+    120014: "&yscr;",
+    120015: "&zscr;",
+    120068: "&Afr;",
+    120069: "&Bfr;",
+    120071: "&Dfr;",
+    120072: "&Efr;",
+    120073: "&Ffr;",
+    120074: "&Gfr;",
+    120077: "&Jfr;",
+    120078: "&Kfr;",
+    120079: "&Lfr;",
+    120080: "&Mfr;",
+    120081: "&Nfr;",
+    120082: "&Ofr;",
+    120083: "&Pfr;",
+    120084: "&Qfr;",
+    120086: "&Sfr;",
+    120087: "&Tfr;",
+    120088: "&Ufr;",
+    120089: "&Vfr;",
+    120090: "&Wfr;",
+    120091: "&Xfr;",
+    120092: "&Yfr;",
+    120094: "&afr;",
+    120095: "&bfr;",
+    120096: "&cfr;",
+    120097: "&dfr;",
+    120098: "&efr;",
+    120099: "&ffr;",
+    120100: "&gfr;",
+    120101: "&hfr;",
+    120102: "&ifr;",
+    120103: "&jfr;",
+    120104: "&kfr;",
+    120105: "&lfr;",
+    120106: "&mfr;",
+    120107: "&nfr;",
+    120108: "&ofr;",
+    120109: "&pfr;",
+    120110: "&qfr;",
+    120111: "&rfr;",
+    120112: "&sfr;",
+    120113: "&tfr;",
+    120114: "&ufr;",
+    120115: "&vfr;",
+    120116: "&wfr;",
+    120117: "&xfr;",
+    120118: "&yfr;",
+    120119: "&zfr;",
+    120120: "&Aopf;",
+    120121: "&Bopf;",
+    120123: "&Dopf;",
+    120124: "&Eopf;",
+    120125: "&Fopf;",
+    120126: "&Gopf;",
+    120128: "&Iopf;",
+    120129: "&Jopf;",
+    120130: "&Kopf;",
+    120131: "&Lopf;",
+    120132: "&Mopf;",
+    120134: "&Oopf;",
+    120138: "&Sopf;",
+    120139: "&Topf;",
+    120140: "&Uopf;",
+    120141: "&Vopf;",
+    120142: "&Wopf;",
+    120143: "&Xopf;",
+    120144: "&Yopf;",
+    120146: "&aopf;",
+    120147: "&bopf;",
+    120148: "&copf;",
+    120149: "&dopf;",
+    120150: "&eopf;",
+    120151: "&fopf;",
+    120152: "&gopf;",
+    120153: "&hopf;",
+    120154: "&iopf;",
+    120155: "&jopf;",
+    120156: "&kopf;",
+    120157: "&lopf;",
+    120158: "&mopf;",
+    120159: "&nopf;",
+    120160: "&oopf;",
+    120161: "&popf;",
+    120162: "&qopf;",
+    120163: "&ropf;",
+    120164: "&sopf;",
+    120165: "&topf;",
+    120166: "&uopf;",
+    120167: "&vopf;",
+    120168: "&wopf;",
+    120169: "&xopf;",
+    120170: "&yopf;",
+    120171: "&zopf;"
 };
 
 export default ToHTMLEntity;

+ 1 - 1
src/core/operations/UnescapeString.mjs

@@ -20,7 +20,7 @@ class UnescapeString extends Operation {
 
         this.name = "Unescape string";
         this.module = "Default";
-        this.description = "Unescapes characters in a string that have been escaped. For example, <code>Don\\'t stop me now</code> becomes <code>Don't stop me now</code>.<br><br>Supports the following escape sequences:<ul><li><code>\\n</code> (Line feed/newline)</li><li><code>\\r</code> (Carriage return)</li><li><code>\\t</code> (Horizontal tab)</li><li><code>\\b</code> (Backspace)</li><li><code>\\f</code> (Form feed)</li><li><code>\\xnn</code> (Hex, where n is 0-f)</li><li><code>\\\\</code> (Backslash)</li><li><code>\\'</code> (Single quote)</li><li><code>\\&quot;</code> (Double quote)</li><li><code>\\unnnn</code> (Unicode character)</li><li><code>\\u{nnnnnn}</code> (Unicode code point)</li></ul>";
+        this.description = "Unescapes characters in a string that have been escaped. For example, <code>Don\\'t stop me now</code> becomes <code>Don't stop me now</code>.<br><br>Supports the following escape sequences:<ul><li><code>\\n</code> (Line feed/newline)</li><li><code>\\r</code> (Carriage return)</li><li><code>\\t</code> (Horizontal tab)</li><li><code>\\b</code> (Backspace)</li><li><code>\\f</code> (Form feed)</li><li><code>\\nnn</code> (Octal, where n is 0-7)</li><li><code>\\xnn</code> (Hex, where n is 0-f)</li><li><code>\\\\</code> (Backslash)</li><li><code>\\'</code> (Single quote)</li><li><code>\\&quot;</code> (Double quote)</li><li><code>\\unnnn</code> (Unicode character)</li><li><code>\\u{nnnnnn}</code> (Unicode code point)</li></ul>";
         this.infoURL = "https://wikipedia.org/wiki/Escape_sequence";
         this.inputType = "string";
         this.outputType = "string";

+ 0 - 265
src/core/vendor/bzip2.mjs

@@ -1,265 +0,0 @@
-/** @license
-========================================================================
-  bzip2.js - a small bzip2 decompression implementation
-  
-  Copyright 2011 by antimatter15 (antimatter15@gmail.com)
-  
-  Based on micro-bunzip by Rob Landley (rob@landley.net).
-
-  Copyright (c) 2011 by antimatter15 (antimatter15@gmail.com).
-
-  Permission is hereby granted, free of charge, to any person obtaining a
-  copy of this software and associated documentation files (the "Software"),
-  to deal in the Software without restriction, including without limitation
-  the rights to use, copy, modify, merge, publish, distribute, sublicense,
-  and/or sell copies of the Software, and to permit persons to whom the
-  Software is furnished to do so, subject to the following conditions:
-  
-  The above copyright notice and this permission notice shall be included
-  in all copies or substantial portions of the Software.
-  
-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
-  THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-*/
-"use strict";
-
-var bzip2 = {};
-
-bzip2.array = function(bytes){
-  var bit = 0, byte = 0;
-  var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
-  return function(n){
-    var result = 0;
-    while(n > 0){
-      var left = 8 - bit;
-      if(n >= left){
-        result <<= left;
-        result |= (BITMASK[left] & bytes[byte++]);
-        bit = 0;
-        n -= left;
-      }else{
-        result <<= n;
-        result |= ((bytes[byte] & (BITMASK[n] << (8 - n - bit))) >> (8 - n - bit));
-        bit += n;
-        n = 0;
-      }
-    }
-    return result
-  }
-}
-
-bzip2.simple = function(bits){
-  var size = bzip2.header(bits);
-  var all = '', chunk = '';
-  do{
-    all += chunk;
-    chunk = bzip2.decompress(bits, size);
-  }while(chunk != -1);
-  return all;
-}
-
-bzip2.header = function(bits){
-  if(bits(8*3) != 4348520) throw "No magic number found";
-  var i = bits(8) - 48;
-  if(i < 1 || i > 9) throw "Not a BZIP archive";
-  return i;
-};
-
-
-//takes a function for reading the block data (starting with 0x314159265359)
-//a block size (0-9) (optional, defaults to 9)
-//a length at which to stop decompressing and return the output
-bzip2.decompress = function(bits, size, len){
-  var MAX_HUFCODE_BITS = 20;
-  var MAX_SYMBOLS = 258;
-  var SYMBOL_RUNA = 0;
-  var SYMBOL_RUNB = 1;
-  var GROUP_SIZE = 50;
-  
-  var bufsize = 100000 * size;
-  for(var h = '', i = 0; i < 6; i++) h += bits(8).toString(16);
-  if(h == "177245385090") return -1; //last block
-  if(h != "314159265359") throw "Not valid bzip data";
-  bits(32); //ignore CRC codes
-  if(bits(1)) throw "Unsupported obsolete version";
-  var origPtr = bits(24);
-  if(origPtr > bufsize) throw "Initial position larger than buffer size";
-  var t = bits(16);
-  var symToByte = new Uint8Array(256), 
-      symTotal = 0;
-  for (i = 0; i < 16; i++) {
-    if(t & (1 << (15 - i))) {
-      var k = bits(16);
-      for(j = 0; j < 16; j++){
-        if(k & (1 << (15 - j))){
-          symToByte[symTotal++] = (16 * i) + j;
-        }
-      }
-    }
-  }
-
-  var groupCount = bits(3);
-  if(groupCount < 2 || groupCount > 6) throw "Error 1";
-  var nSelectors = bits(15);
-  if(nSelectors == 0) throw "Error";
-  var mtfSymbol = []; //TODO: possibly replace JS array with typed arrays
-  for(var i = 0; i < groupCount; i++) mtfSymbol[i] = i;
-  var selectors = new Uint8Array(32768);
-  
-  for(var i = 0; i < nSelectors; i++){
-    for(var j = 0; bits(1); j++) if(j >= groupCount) throw "Error 2"; 
-    var uc = mtfSymbol[j];
-    mtfSymbol.splice(j, 1); //this is a probably inefficient MTF transform
-    mtfSymbol.splice(0, 0, uc);
-    selectors[i] = uc;
-  }
-  
-  var symCount = symTotal + 2;
-  var groups = [];
-  for(var j = 0; j < groupCount; j++){
-    var length = new Uint8Array(MAX_SYMBOLS), 
-        temp = new Uint8Array(MAX_HUFCODE_BITS+1);
-    t = bits(5); //lengths
-    for(var i = 0; i < symCount; i++){
-      while(true){
-        if (t < 1 || t > MAX_HUFCODE_BITS) throw "Error 3";
-        if(!bits(1)) break;
-        if(!bits(1)) t++;
-        else t--;
-      }
-      length[i] = t;
-    }
-    var  minLen,  maxLen;
-    minLen = maxLen = length[0];
-    for(var i = 1; i < symCount; i++){
-      if(length[i] > maxLen) maxLen = length[i];
-      else if(length[i] < minLen) minLen = length[i];
-    }
-    var hufGroup;
-    hufGroup = groups[j] = {};
-    hufGroup.permute = new Uint32Array(MAX_SYMBOLS);
-    hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 1);
-    hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
-    hufGroup.minLen = minLen;
-    hufGroup.maxLen = maxLen;
-    var base = hufGroup.base.subarray(1);
-    var limit = hufGroup.limit.subarray(1);
-    var pp = 0;
-    for(var i = minLen; i <= maxLen; i++)
-      for(var t = 0; t < symCount; t++) 
-      if(length[t] == i) hufGroup.permute[pp++] = t;
-      for(i = minLen; i <= maxLen; i++) temp[i] = limit[i] = 0;
-      for(i = 0; i < symCount; i++) temp[length[i]]++;
-      pp = t = 0;
-      for(i = minLen; i < maxLen; i++) {
-        pp += temp[i];
-        limit[i] = pp - 1;
-        pp <<= 1;
-        base[i+1] = pp - (t += temp[i]);
-      }
-      limit[maxLen]=pp+temp[maxLen]-1;
-      base[minLen]=0;
-  }
-  var byteCount = new Uint32Array(256);
-  for(var i = 0; i < 256; i++) mtfSymbol[i] = i;
-  var runPos, count, symCount, selector;
-  runPos = count = symCount = selector = 0;
-  var buf = new Uint32Array(bufsize);
-  while(true){
-    if(!(symCount--)){
-      symCount = GROUP_SIZE - 1;
-      if(selector >= nSelectors) throw "Error 4";
-      hufGroup = groups[selectors[selector++]];
-      base = hufGroup.base.subarray(1);
-      limit = hufGroup.limit.subarray(1);
-    }
-    i = hufGroup.minLen;
-    j = bits(i);
-    while(true){
-      if(i > hufGroup.maxLen) throw "Error 5";
-      if(j <= limit[i]) break;
-      i++;
-      j = (j << 1) | bits(1);
-    }
-    j -= base[i];
-    if(j < 0 || j >= MAX_SYMBOLS) throw "Error 6";
-    var nextSym = hufGroup.permute[j];
-    if (nextSym == SYMBOL_RUNA || nextSym == SYMBOL_RUNB) {
-      if(!runPos){
-        runPos = 1;
-        t = 0;
-      }
-      if(nextSym == SYMBOL_RUNA) t += runPos;
-      else t += 2 * runPos;
-      runPos <<= 1;
-      continue;
-    }
-    if(runPos){
-      runPos = 0;
-      if(count + t >= bufsize) throw "Error 7";
-      uc = symToByte[mtfSymbol[0]];
-      byteCount[uc] += t;
-      while(t--) buf[count++] = uc;
-    }
-    if(nextSym > symTotal) break;
-    if(count >= bufsize) throw "Error 8";
-    i = nextSym -1;
-    uc = mtfSymbol[i];
-    mtfSymbol.splice(i, 1);
-    mtfSymbol.splice(0, 0, uc);
-    uc = symToByte[uc];
-    byteCount[uc]++;
-    buf[count++] = uc;
-  }
-  if(origPtr < 0 || origPtr >= count) throw "Error 9";
-  var j = 0;
-  for(var i = 0; i < 256; i++){
-    k = j + byteCount[i];
-    byteCount[i] = j;
-    j = k;
-  }
-  for(var i = 0; i < count; i++){
-    uc = buf[i] & 0xff;
-    buf[byteCount[uc]] |= (i << 8);
-    byteCount[uc]++;
-  }
-  var pos = 0, current = 0, run = 0;
-  if(count) {
-    pos = buf[origPtr];
-    current = (pos & 0xff);
-    pos >>= 8;
-    run = -1;
-  }
-  count = count;
-  var output = '';
-  var copies, previous, outbyte;
-  if(!len) len = Infinity;
-  while(count){
-    count--;
-    previous = current;
-    pos = buf[pos];
-    current = pos & 0xff;
-    pos >>= 8;
-    if(run++ == 3){
-      copies = current;
-      outbyte = previous;
-      current = -1;
-    }else{
-      copies = 1;
-      outbyte = current;
-    }
-    while(copies--){
-      output += (String.fromCharCode(outbyte));
-      if(!--len) return output;
-    }
-    if(current != previous) run = 0;
-  }
-  return output;
-}
-
-export default bzip2;

+ 2259 - 0
src/core/vendor/gost/gostCipher.mjs

@@ -0,0 +1,2259 @@
+/**
+ * GOST 28147-89/GOST R 34.12-2015/GOST R 32.13-2015 Encryption Algorithm
+ * 1.76
+ * 2014-2016, Rudolf Nickolaev. All rights reserved.
+ * 
+ * Exported for CyberChef by mshwed [m@ttshwed.com]
+ */
+
+/*
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+import GostRandom from './gostRandom';
+
+import crypto from 'crypto'
+
+/*
+* Initial parameters and common algortithms of GOST 28147-89 
+* 
+* http://tools.ietf.org/html/rfc5830
+* 
+*/ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+var rootCrypto = crypto;
+var CryptoOperationData = ArrayBuffer;
+var SyntaxError = Error,
+        DataError = Error,
+        NotSupportedError = Error;
+/*
+* Check supported
+* This implementation support only Little Endian arhitecture
+*/
+
+var littleEndian = (function () {
+    var buffer = new CryptoOperationData(2);
+    new DataView(buffer).setInt16(0, 256, true);
+    return new Int16Array(buffer)[0] === 256;
+})();
+
+// Default initial vector
+var defaultIV = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
+
+// Predefined sBox collection
+var sBoxes = {
+    'E-TEST': [
+        0x4, 0x2, 0xF, 0x5, 0x9, 0x1, 0x0, 0x8, 0xE, 0x3, 0xB, 0xC, 0xD, 0x7, 0xA, 0x6,
+        0xC, 0x9, 0xF, 0xE, 0x8, 0x1, 0x3, 0xA, 0x2, 0x7, 0x4, 0xD, 0x6, 0x0, 0xB, 0x5,
+        0xD, 0x8, 0xE, 0xC, 0x7, 0x3, 0x9, 0xA, 0x1, 0x5, 0x2, 0x4, 0x6, 0xF, 0x0, 0xB,
+        0xE, 0x9, 0xB, 0x2, 0x5, 0xF, 0x7, 0x1, 0x0, 0xD, 0xC, 0x6, 0xA, 0x4, 0x3, 0x8,
+        0x3, 0xE, 0x5, 0x9, 0x6, 0x8, 0x0, 0xD, 0xA, 0xB, 0x7, 0xC, 0x2, 0x1, 0xF, 0x4,
+        0x8, 0xF, 0x6, 0xB, 0x1, 0x9, 0xC, 0x5, 0xD, 0x3, 0x7, 0xA, 0x0, 0xE, 0x2, 0x4,
+        0x9, 0xB, 0xC, 0x0, 0x3, 0x6, 0x7, 0x5, 0x4, 0x8, 0xE, 0xF, 0x1, 0xA, 0x2, 0xD,
+        0xC, 0x6, 0x5, 0x2, 0xB, 0x0, 0x9, 0xD, 0x3, 0xE, 0x7, 0xA, 0xF, 0x4, 0x1, 0x8
+    ],
+    'E-A': [
+        0x9, 0x6, 0x3, 0x2, 0x8, 0xB, 0x1, 0x7, 0xA, 0x4, 0xE, 0xF, 0xC, 0x0, 0xD, 0x5,
+        0x3, 0x7, 0xE, 0x9, 0x8, 0xA, 0xF, 0x0, 0x5, 0x2, 0x6, 0xC, 0xB, 0x4, 0xD, 0x1,
+        0xE, 0x4, 0x6, 0x2, 0xB, 0x3, 0xD, 0x8, 0xC, 0xF, 0x5, 0xA, 0x0, 0x7, 0x1, 0x9,
+        0xE, 0x7, 0xA, 0xC, 0xD, 0x1, 0x3, 0x9, 0x0, 0x2, 0xB, 0x4, 0xF, 0x8, 0x5, 0x6,
+        0xB, 0x5, 0x1, 0x9, 0x8, 0xD, 0xF, 0x0, 0xE, 0x4, 0x2, 0x3, 0xC, 0x7, 0xA, 0x6,
+        0x3, 0xA, 0xD, 0xC, 0x1, 0x2, 0x0, 0xB, 0x7, 0x5, 0x9, 0x4, 0x8, 0xF, 0xE, 0x6,
+        0x1, 0xD, 0x2, 0x9, 0x7, 0xA, 0x6, 0x0, 0x8, 0xC, 0x4, 0x5, 0xF, 0x3, 0xB, 0xE,
+        0xB, 0xA, 0xF, 0x5, 0x0, 0xC, 0xE, 0x8, 0x6, 0x2, 0x3, 0x9, 0x1, 0x7, 0xD, 0x4
+    ],
+    'E-B': [
+        0x8, 0x4, 0xB, 0x1, 0x3, 0x5, 0x0, 0x9, 0x2, 0xE, 0xA, 0xC, 0xD, 0x6, 0x7, 0xF,
+        0x0, 0x1, 0x2, 0xA, 0x4, 0xD, 0x5, 0xC, 0x9, 0x7, 0x3, 0xF, 0xB, 0x8, 0x6, 0xE,
+        0xE, 0xC, 0x0, 0xA, 0x9, 0x2, 0xD, 0xB, 0x7, 0x5, 0x8, 0xF, 0x3, 0x6, 0x1, 0x4,
+        0x7, 0x5, 0x0, 0xD, 0xB, 0x6, 0x1, 0x2, 0x3, 0xA, 0xC, 0xF, 0x4, 0xE, 0x9, 0x8,
+        0x2, 0x7, 0xC, 0xF, 0x9, 0x5, 0xA, 0xB, 0x1, 0x4, 0x0, 0xD, 0x6, 0x8, 0xE, 0x3,
+        0x8, 0x3, 0x2, 0x6, 0x4, 0xD, 0xE, 0xB, 0xC, 0x1, 0x7, 0xF, 0xA, 0x0, 0x9, 0x5,
+        0x5, 0x2, 0xA, 0xB, 0x9, 0x1, 0xC, 0x3, 0x7, 0x4, 0xD, 0x0, 0x6, 0xF, 0x8, 0xE,
+        0x0, 0x4, 0xB, 0xE, 0x8, 0x3, 0x7, 0x1, 0xA, 0x2, 0x9, 0x6, 0xF, 0xD, 0x5, 0xC
+    ],
+    'E-C': [
+        0x1, 0xB, 0xC, 0x2, 0x9, 0xD, 0x0, 0xF, 0x4, 0x5, 0x8, 0xE, 0xA, 0x7, 0x6, 0x3,
+        0x0, 0x1, 0x7, 0xD, 0xB, 0x4, 0x5, 0x2, 0x8, 0xE, 0xF, 0xC, 0x9, 0xA, 0x6, 0x3,
+        0x8, 0x2, 0x5, 0x0, 0x4, 0x9, 0xF, 0xA, 0x3, 0x7, 0xC, 0xD, 0x6, 0xE, 0x1, 0xB,
+        0x3, 0x6, 0x0, 0x1, 0x5, 0xD, 0xA, 0x8, 0xB, 0x2, 0x9, 0x7, 0xE, 0xF, 0xC, 0x4,
+        0x8, 0xD, 0xB, 0x0, 0x4, 0x5, 0x1, 0x2, 0x9, 0x3, 0xC, 0xE, 0x6, 0xF, 0xA, 0x7,
+        0xC, 0x9, 0xB, 0x1, 0x8, 0xE, 0x2, 0x4, 0x7, 0x3, 0x6, 0x5, 0xA, 0x0, 0xF, 0xD,
+        0xA, 0x9, 0x6, 0x8, 0xD, 0xE, 0x2, 0x0, 0xF, 0x3, 0x5, 0xB, 0x4, 0x1, 0xC, 0x7,
+        0x7, 0x4, 0x0, 0x5, 0xA, 0x2, 0xF, 0xE, 0xC, 0x6, 0x1, 0xB, 0xD, 0x9, 0x3, 0x8
+    ],
+    'E-D': [
+        0xF, 0xC, 0x2, 0xA, 0x6, 0x4, 0x5, 0x0, 0x7, 0x9, 0xE, 0xD, 0x1, 0xB, 0x8, 0x3,
+        0xB, 0x6, 0x3, 0x4, 0xC, 0xF, 0xE, 0x2, 0x7, 0xD, 0x8, 0x0, 0x5, 0xA, 0x9, 0x1,
+        0x1, 0xC, 0xB, 0x0, 0xF, 0xE, 0x6, 0x5, 0xA, 0xD, 0x4, 0x8, 0x9, 0x3, 0x7, 0x2,
+        0x1, 0x5, 0xE, 0xC, 0xA, 0x7, 0x0, 0xD, 0x6, 0x2, 0xB, 0x4, 0x9, 0x3, 0xF, 0x8,
+        0x0, 0xC, 0x8, 0x9, 0xD, 0x2, 0xA, 0xB, 0x7, 0x3, 0x6, 0x5, 0x4, 0xE, 0xF, 0x1,
+        0x8, 0x0, 0xF, 0x3, 0x2, 0x5, 0xE, 0xB, 0x1, 0xA, 0x4, 0x7, 0xC, 0x9, 0xD, 0x6,
+        0x3, 0x0, 0x6, 0xF, 0x1, 0xE, 0x9, 0x2, 0xD, 0x8, 0xC, 0x4, 0xB, 0xA, 0x5, 0x7,
+        0x1, 0xA, 0x6, 0x8, 0xF, 0xB, 0x0, 0x4, 0xC, 0x3, 0x5, 0x9, 0x7, 0xD, 0x2, 0xE
+    ],
+    'E-SC': [
+        0x3, 0x6, 0x1, 0x0, 0x5, 0x7, 0xd, 0x9, 0x4, 0xb, 0x8, 0xc, 0xe, 0xf, 0x2, 0xa,
+        0x7, 0x1, 0x5, 0x2, 0x8, 0xb, 0x9, 0xc, 0xd, 0x0, 0x3, 0xa, 0xf, 0xe, 0x4, 0x6,
+        0xf, 0x1, 0x4, 0x6, 0xc, 0x8, 0x9, 0x2, 0xe, 0x3, 0x7, 0xa, 0xb, 0xd, 0x5, 0x0,
+        0x3, 0x4, 0xf, 0xc, 0x5, 0x9, 0xe, 0x0, 0x6, 0x8, 0x7, 0xa, 0x1, 0xb, 0xd, 0x2,
+        0x6, 0x9, 0x0, 0x7, 0xb, 0x8, 0x4, 0xc, 0x2, 0xe, 0xa, 0xf, 0x1, 0xd, 0x5, 0x3,
+        0x6, 0x1, 0x2, 0xf, 0x0, 0xb, 0x9, 0xc, 0x7, 0xd, 0xa, 0x5, 0x8, 0x4, 0xe, 0x3,
+        0x0, 0x2, 0xe, 0xc, 0x9, 0x1, 0x4, 0x7, 0x3, 0xf, 0x6, 0x8, 0xa, 0xd, 0xb, 0x5,
+        0x5, 0x2, 0xb, 0x8, 0x4, 0xc, 0x7, 0x1, 0xa, 0x6, 0xe, 0x0, 0x9, 0x3, 0xd, 0xf
+    ],
+    'E-Z': [// This is default S-box in according to draft of new standard
+        0xc, 0x4, 0x6, 0x2, 0xa, 0x5, 0xb, 0x9, 0xe, 0x8, 0xd, 0x7, 0x0, 0x3, 0xf, 0x1,
+        0x6, 0x8, 0x2, 0x3, 0x9, 0xa, 0x5, 0xc, 0x1, 0xe, 0x4, 0x7, 0xb, 0xd, 0x0, 0xf,
+        0xb, 0x3, 0x5, 0x8, 0x2, 0xf, 0xa, 0xd, 0xe, 0x1, 0x7, 0x4, 0xc, 0x9, 0x6, 0x0,
+        0xc, 0x8, 0x2, 0x1, 0xd, 0x4, 0xf, 0x6, 0x7, 0x0, 0xa, 0x5, 0x3, 0xe, 0x9, 0xb,
+        0x7, 0xf, 0x5, 0xa, 0x8, 0x1, 0x6, 0xd, 0x0, 0x9, 0x3, 0xe, 0xb, 0x4, 0x2, 0xc,
+        0x5, 0xd, 0xf, 0x6, 0x9, 0x2, 0xc, 0xa, 0xb, 0x7, 0x8, 0x1, 0x4, 0x3, 0xe, 0x0,
+        0x8, 0xe, 0x2, 0x5, 0x6, 0x9, 0x1, 0xc, 0xf, 0x4, 0xb, 0x0, 0xd, 0xa, 0x3, 0x7,
+        0x1, 0x7, 0xe, 0xd, 0x0, 0x5, 0x8, 0x3, 0x4, 0xf, 0xa, 0x6, 0x9, 0xc, 0xb, 0x2
+    ],
+    //S-box for digest
+    'D-TEST': [
+        0x4, 0xA, 0x9, 0x2, 0xD, 0x8, 0x0, 0xE, 0x6, 0xB, 0x1, 0xC, 0x7, 0xF, 0x5, 0x3,
+        0xE, 0xB, 0x4, 0xC, 0x6, 0xD, 0xF, 0xA, 0x2, 0x3, 0x8, 0x1, 0x0, 0x7, 0x5, 0x9,
+        0x5, 0x8, 0x1, 0xD, 0xA, 0x3, 0x4, 0x2, 0xE, 0xF, 0xC, 0x7, 0x6, 0x0, 0x9, 0xB,
+        0x7, 0xD, 0xA, 0x1, 0x0, 0x8, 0x9, 0xF, 0xE, 0x4, 0x6, 0xC, 0xB, 0x2, 0x5, 0x3,
+        0x6, 0xC, 0x7, 0x1, 0x5, 0xF, 0xD, 0x8, 0x4, 0xA, 0x9, 0xE, 0x0, 0x3, 0xB, 0x2,
+        0x4, 0xB, 0xA, 0x0, 0x7, 0x2, 0x1, 0xD, 0x3, 0x6, 0x8, 0x5, 0x9, 0xC, 0xF, 0xE,
+        0xD, 0xB, 0x4, 0x1, 0x3, 0xF, 0x5, 0x9, 0x0, 0xA, 0xE, 0x7, 0x6, 0x8, 0x2, 0xC,
+        0x1, 0xF, 0xD, 0x0, 0x5, 0x7, 0xA, 0x4, 0x9, 0x2, 0x3, 0xE, 0x6, 0xB, 0x8, 0xC
+    ],
+    'D-A': [
+        0xA, 0x4, 0x5, 0x6, 0x8, 0x1, 0x3, 0x7, 0xD, 0xC, 0xE, 0x0, 0x9, 0x2, 0xB, 0xF,
+        0x5, 0xF, 0x4, 0x0, 0x2, 0xD, 0xB, 0x9, 0x1, 0x7, 0x6, 0x3, 0xC, 0xE, 0xA, 0x8,
+        0x7, 0xF, 0xC, 0xE, 0x9, 0x4, 0x1, 0x0, 0x3, 0xB, 0x5, 0x2, 0x6, 0xA, 0x8, 0xD,
+        0x4, 0xA, 0x7, 0xC, 0x0, 0xF, 0x2, 0x8, 0xE, 0x1, 0x6, 0x5, 0xD, 0xB, 0x9, 0x3,
+        0x7, 0x6, 0x4, 0xB, 0x9, 0xC, 0x2, 0xA, 0x1, 0x8, 0x0, 0xE, 0xF, 0xD, 0x3, 0x5,
+        0x7, 0x6, 0x2, 0x4, 0xD, 0x9, 0xF, 0x0, 0xA, 0x1, 0x5, 0xB, 0x8, 0xE, 0xC, 0x3,
+        0xD, 0xE, 0x4, 0x1, 0x7, 0x0, 0x5, 0xA, 0x3, 0xC, 0x8, 0xF, 0x6, 0x2, 0x9, 0xB,
+        0x1, 0x3, 0xA, 0x9, 0x5, 0xB, 0x4, 0xF, 0x8, 0x6, 0x7, 0xE, 0xD, 0x0, 0x2, 0xC
+    ],
+    'D-SC': [
+        0xb, 0xd, 0x7, 0x0, 0x5, 0x4, 0x1, 0xf, 0x9, 0xe, 0x6, 0xa, 0x3, 0xc, 0x8, 0x2,
+        0x1, 0x2, 0x7, 0x9, 0xd, 0xb, 0xf, 0x8, 0xe, 0xc, 0x4, 0x0, 0x5, 0x6, 0xa, 0x3,
+        0x5, 0x1, 0xd, 0x3, 0xf, 0x6, 0xc, 0x7, 0x9, 0x8, 0xb, 0x2, 0x4, 0xe, 0x0, 0xa,
+        0xd, 0x1, 0xb, 0x4, 0x9, 0xc, 0xe, 0x0, 0x7, 0x5, 0x8, 0xf, 0x6, 0x2, 0xa, 0x3,
+        0x2, 0xd, 0xa, 0xf, 0x9, 0xb, 0x3, 0x7, 0x8, 0xc, 0x5, 0xe, 0x6, 0x0, 0x1, 0x4,
+        0x0, 0x4, 0x6, 0xc, 0x5, 0x3, 0x8, 0xd, 0xa, 0xb, 0xf, 0x2, 0x1, 0x9, 0x7, 0xe,
+        0x1, 0x3, 0xc, 0x8, 0xa, 0x6, 0xb, 0x0, 0x2, 0xe, 0x7, 0x9, 0xf, 0x4, 0x5, 0xd,
+        0xa, 0xb, 0x6, 0x0, 0x1, 0x3, 0x4, 0x7, 0xe, 0xd, 0x5, 0xf, 0x8, 0x2, 0x9, 0xc
+    ]
+};
+
+var C = new Uint8Array([
+    0x69, 0x00, 0x72, 0x22, 0x64, 0xC9, 0x04, 0x23,
+    0x8D, 0x3A, 0xDB, 0x96, 0x46, 0xE9, 0x2A, 0xC4,
+    0x18, 0xFE, 0xAC, 0x94, 0x00, 0xED, 0x07, 0x12,
+    0xC0, 0x86, 0xDC, 0xC2, 0xEF, 0x4C, 0xA9, 0x2B
+]);
+
+function signed(x) {
+    return x >= 0x80000000 ? x - 0x100000000 : x;
+}
+
+function unsigned(x) {
+    return x < 0 ? x + 0x100000000 : x;
+}
+
+// Set random values into Uint8Arry
+// Random generator
+function randomSeed(e) {
+    GostRandom = GostRandom || root.GostRandom;
+    var randomSource = GostRandom ? new (GostRandom || root.GostRandom) : rootCrypto;
+    if (randomSource.getRandomValues)
+        randomSource.getRandomValues(e);
+    else
+        throw new NotSupportedError('Random generator not found');
+}
+
+// Get buffer
+function buffer(d) {
+    if (d instanceof CryptoOperationData)
+        return d;
+    else if (d && d.buffer && d.buffer instanceof CryptoOperationData)
+        return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ?
+                d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;
+    else
+        throw new DataError('CryptoOperationData required');
+}
+
+// Get byte array
+function byteArray(d) {
+    return new Uint8Array(buffer(d));
+}
+
+// Clone byte array
+function cloneArray(d) {
+    return new Uint8Array(byteArray(d));
+}
+
+
+// Get int32 array
+function intArray(d) {
+    return new Int32Array(buffer(d));
+}
+
+// Swap bytes for version 2015
+function swap32(b) {
+    return ((b & 0xff) << 24)
+            | ((b & 0xff00) << 8)
+            | ((b >> 8) & 0xff00)
+            | ((b >> 24) & 0xff);
+}
+
+// </editor-fold>
+
+/*
+    * Initial parameters and common algortithms of GOST R 34.12-15 
+    * Algorithm "Kuznechik" 128bit
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+// Default initial vector
+var defaultIV128 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+
+// Mult table for R function
+var multTable = (function () {
+
+    // Multiply two numbers in the GF(2^8) finite field defined 
+    // by the polynomial x^8 + x^7 + x^6 + x + 1 = 0 */
+    function gmul(a, b) {
+        var p = 0, counter, carry;
+        for (counter = 0; counter < 8; counter++) {
+            if (b & 1)
+                p ^= a;
+            carry = a & 0x80; // detect if x^8 term is about to be generated 
+            a = (a << 1) & 0xff;
+            if (carry)
+                a ^= 0xc3; // replace x^8 with x^7 + x^6 + x + 1 
+            b >>= 1;
+        }
+        return p & 0xff;
+    }
+
+    // It is required only this values for R function
+    //       0   1   2    3    4    5    6    7
+    var x = [1, 16, 32, 133, 148, 192, 194, 251];
+    var m = [];
+    for (var i = 0; i < 8; i++) {
+        m[i] = [];
+        for (var j = 0; j < 256; j++)
+            m[i][j] = gmul(x[i], j);
+    }
+    return m;
+})();
+
+// 148, 32, 133, 16, 194, 192, 1, 251, 1, 192, 194, 16, 133, 32, 148, 1
+var kB = [4, 2, 3, 1, 6, 5, 0, 7, 0, 5, 6, 1, 3, 2, 4, 0];
+
+// R - function
+function funcR(d) {
+    var sum = 0;
+    for (var i = 0; i < 16; i++)
+        sum ^= multTable[kB[i]][d[i]];
+
+    for (var i = 16; i > 0; --i)
+        d[i] = d[i - 1];
+    d[0] = sum;
+}
+
+function funcReverseR(d) {
+    var tmp = d[0];
+    for (var i = 0; i < 15; i++)
+        d[i] = d[i + 1];
+    d[15] = tmp;
+
+    var sum = 0;
+    for (i = 0; i < 16; i++)
+        sum ^= multTable[kB[i]][d[i]];
+    d[15] = sum;
+}
+
+// Nonlinear transformation
+var kPi = [
+    252, 238, 221, 17, 207, 110, 49, 22, 251, 196, 250, 218, 35, 197, 4, 77,
+    233, 119, 240, 219, 147, 46, 153, 186, 23, 54, 241, 187, 20, 205, 95, 193,
+    249, 24, 101, 90, 226, 92, 239, 33, 129, 28, 60, 66, 139, 1, 142, 79,
+    5, 132, 2, 174, 227, 106, 143, 160, 6, 11, 237, 152, 127, 212, 211, 31,
+    235, 52, 44, 81, 234, 200, 72, 171, 242, 42, 104, 162, 253, 58, 206, 204,
+    181, 112, 14, 86, 8, 12, 118, 18, 191, 114, 19, 71, 156, 183, 93, 135,
+    21, 161, 150, 41, 16, 123, 154, 199, 243, 145, 120, 111, 157, 158, 178, 177,
+    50, 117, 25, 61, 255, 53, 138, 126, 109, 84, 198, 128, 195, 189, 13, 87,
+    223, 245, 36, 169, 62, 168, 67, 201, 215, 121, 214, 246, 124, 34, 185, 3,
+    224, 15, 236, 222, 122, 148, 176, 188, 220, 232, 40, 80, 78, 51, 10, 74,
+    167, 151, 96, 115, 30, 0, 98, 68, 26, 184, 56, 130, 100, 159, 38, 65,
+    173, 69, 70, 146, 39, 94, 85, 47, 140, 163, 165, 125, 105, 213, 149, 59,
+    7, 88, 179, 64, 134, 172, 29, 247, 48, 55, 107, 228, 136, 217, 231, 137,
+    225, 27, 131, 73, 76, 63, 248, 254, 141, 83, 170, 144, 202, 216, 133, 97,
+    32, 113, 103, 164, 45, 43, 9, 91, 203, 155, 37, 208, 190, 229, 108, 82,
+    89, 166, 116, 210, 230, 244, 180, 192, 209, 102, 175, 194, 57, 75, 99, 182
+];
+
+var kReversePi = (function () {
+    var m = [];
+    for (var i = 0, n = kPi.length; i < n; i++)
+        m[kPi[i]] = i;
+    return m;
+})();
+
+function funcS(d) {
+    for (var i = 0; i < 16; ++i)
+        d[i] = kPi[d[i]];
+}
+
+function funcReverseS(d) {
+    for (var i = 0; i < 16; ++i)
+        d[i] = kReversePi[d[i]];
+}
+
+function funcX(a, b) {
+    for (var i = 0; i < 16; ++i)
+        a[i] ^= b[i];
+}
+
+function funcL(d) {
+    for (var i = 0; i < 16; ++i)
+        funcR(d);
+}
+
+function funcReverseL(d) {
+    for (var i = 0; i < 16; ++i)
+        funcReverseR(d);
+}
+
+function funcLSX(a, b) {
+    funcX(a, b);
+    funcS(a);
+    funcL(a);
+}
+
+function funcReverseLSX(a, b) {
+    funcX(a, b);
+    funcReverseL(a);
+    funcReverseS(a);
+}
+
+function funcF(inputKey, inputKeySecond, iterationConst) {
+    var tmp = new Uint8Array(inputKey);
+    funcLSX(inputKey, iterationConst);
+    funcX(inputKey, inputKeySecond);
+    inputKeySecond.set(tmp);
+}
+
+function funcC(number, d) {
+    for (var i = 0; i < 15; i++)
+        d[i] = 0;
+    d[15] = number;
+    funcL(d);
+}
+
+// </editor-fold>
+
+/**
+ * Key schedule for GOST R 34.12-15 128bits
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method keySchedule
+ * @param {type} k
+ * @returns {Uint8Array}
+ */
+function keySchedule128(k) // <editor-fold defaultstate="collapsed">
+{
+    var keys = new Uint8Array(160), c = new Uint8Array(16);
+    keys.set(byteArray(k));
+    for (var j = 0; j < 4; j++) {
+        var j0 = 32 * j, j1 = 32 * (j + 1);
+        keys.set(new Uint8Array(keys.buffer, j0, 32), j1);
+        for (var i = 1; i < 9; i++) {
+            funcC(j * 8 + i, c);
+            funcF(new Uint8Array(keys.buffer, j1, 16),
+                    new Uint8Array(keys.buffer, j1 + 16, 16), c);
+        }
+    }
+    return keys;
+} // </editor-fold>
+
+/**
+ * GOST R 34.12-15 128 bits encrypt/decrypt process 
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method round
+ * @param {Uint8Array} k Scheduled key
+ * @param {Uint8Array} d Data
+ * @param {number} ofs Offsec
+ * @param {number} e true - decrypt
+ */
+function process128(k, d, ofs, e) // <editor-fold defaultstate="collapsed">
+{
+    ofs = ofs || d.byteOffset;
+    var r = new Uint8Array(d.buffer, ofs, 16);
+    if (e) {
+        for (var i = 0; i < 9; i++)
+            funcReverseLSX(r, new Uint8Array(k.buffer, (9 - i) * 16, 16));
+
+        funcX(r, new Uint8Array(k.buffer, 0, 16));
+    } else {
+        for (var i = 0; i < 9; i++)
+            funcLSX(r, new Uint8Array(k.buffer, 16 * i, 16));
+
+        funcX(r, new Uint8Array(k.buffer, 16 * 9, 16));
+    }
+} // </editor-fold>
+
+/**
+ * One GOST encryption round
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method round
+ * @param {Int8Array} S sBox
+ * @param {Int32Array} m 2x32 bits cipher block 
+ * @param {Int32Array} k 32 bits key[i] 
+ */
+function round(S, m, k) // <editor-fold defaultstate="collapsed">
+{
+    var cm = (m[0] + k) & 0xffffffff;
+
+    var om = S[  0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4);
+    om |= S[ 16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4);
+    om |= S[ 32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4);
+    om |= S[ 48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4);
+    om |= S[ 64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4);
+    om |= S[ 80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4);
+    om |= S[ 96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4);
+    om |= S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4);
+    cm = om << 11 | om >>> (32 - 11);
+
+    cm ^= m[1];
+    m[1] = m[0];
+    m[0] = cm;
+
+} // </editor-fold>
+
+/**
+ * Process encrypt/decrypt block with key K using GOST 28147-89
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method process
+ * @param k {Int32Array} 8x32 bits key 
+ * @param d {Int32Array} 8x8 bits cipher block 
+ * @param ofs {number} offset
+ */
+function process89(k, d, ofs) // <editor-fold defaultstate="collapsed">
+{
+    ofs = ofs || d.byteOffset;
+    var s = this.sBox,
+            m = new Int32Array(d.buffer, ofs, 2);
+
+    for (var i = 0; i < 32; i++)
+        round(s, m, k[i]);
+
+    var r = m[0];
+    m[0] = m[1];
+    m[1] = r;
+} // </editor-fold>
+
+/**
+ * Process encrypt/decrypt block with key K using GOST R 34.12-15 64bit block
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method process
+ * @param k {Int32Array} 8x32 bits key 
+ * @param d {Int32Array} 8x8 bits cipher block 
+ * @param ofs {number} offset
+ */
+function process15(k, d, ofs) // <editor-fold defaultstate="collapsed">
+{
+    ofs = ofs || d.byteOffset;
+    var s = this.sBox,
+            m = new Int32Array(d.buffer, ofs, 2),
+            r = swap32(m[0]);
+    m[0] = swap32(m[1]);
+    m[1] = r;
+
+    for (var i = 0; i < 32; i++)
+        round(s, m, k[i]);
+
+    m[0] = swap32(m[0]);
+    m[1] = swap32(m[1]);
+} // </editor-fold>
+
+/**
+ * Key keySchedule algorithm for GOST 28147-89 64bit cipher
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method process
+ * @param k {Uint8Array} 8 bit key array
+ * @param e {boolean}  true - decrypt
+ * @returns {Int32Array} keyScheduled 32-bit key
+ */
+function keySchedule89(k, e) // <editor-fold defaultstate="collapsed">
+{
+    var sch = new Int32Array(32),
+            key = new Int32Array(buffer(k));
+
+    for (var i = 0; i < 8; i++)
+        sch[i] = key[i];
+
+    if (e) {
+        for (var i = 0; i < 8; i++)
+            sch[i + 8] = sch[7 - i];
+
+        for (var i = 0; i < 8; i++)
+            sch[i + 16] = sch[7 - i];
+    } else {
+        for (var i = 0; i < 8; i++)
+            sch[i + 8] = sch[i];
+
+        for (var i = 0; i < 8; i++)
+            sch[i + 16] = sch[i];
+    }
+
+    for (var i = 0; i < 8; i++)
+        sch[i + 24] = sch[7 - i];
+
+    return sch;
+} // </editor-fold>
+
+/**
+ * Key keySchedule algorithm for GOST R 34.12-15 64bit cipher
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method process
+ * @param k {Uint8Array} 8 bit key array
+ * @param e {boolean}  true - decrypt
+ * @returns {Int32Array} keyScheduled 32-bit key
+ */
+function keySchedule15(k, e) // <editor-fold defaultstate="collapsed">
+{
+    var sch = new Int32Array(32),
+            key = new Int32Array(buffer(k));
+
+    for (var i = 0; i < 8; i++)
+        sch[i] = swap32(key[i]);
+
+    if (e) {
+        for (var i = 0; i < 8; i++)
+            sch[i + 8] = sch[7 - i];
+
+        for (var i = 0; i < 8; i++)
+            sch[i + 16] = sch[7 - i];
+    } else {
+        for (var i = 0; i < 8; i++)
+            sch[i + 8] = sch[i];
+
+        for (var i = 0; i < 8; i++)
+            sch[i + 16] = sch[i];
+    }
+
+    for (var i = 0; i < 8; i++)
+        sch[i + 24] = sch[7 - i];
+
+    return sch;
+} // </editor-fold>
+
+/**
+ * Key schedule for RC2
+ * 
+ * https://tools.ietf.org/html/rfc2268
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method keySchedule
+ * @param {Uint8Array} k
+ * @returns {Uint16Array}
+ */
+var keyScheduleRC2 = (function () // <editor-fold defaultstate="collapsed">
+{
+    // an array of "random" bytes based on the digits of PI = 3.14159...
+    var PITABLE = new Uint8Array([
+        0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
+        0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
+        0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
+        0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
+        0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
+        0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
+        0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
+        0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
+        0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
+        0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
+        0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
+        0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
+        0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
+        0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
+        0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
+        0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad
+    ]);
+
+    return function (k)
+    {
+        var key = new Uint8Array(buffer(k)),
+                T = Math.min(key.length, 128),
+                T1 = this.effectiveLength,
+                T8 = Math.floor((T1 + 7) / 8),
+                TM = 0xff % Math.pow(2, 8 + T1 - 8 * T8);
+
+        var L = new Uint8Array(128), K = new Uint16Array(L.buffer);
+        for (var i = 0; i < T; i++)
+            L[i] = key[i];
+        for (var i = T; i < 128; i++)
+            L[i] = PITABLE[(L[i - 1] + L[i - T]) % 256];
+        L[128 - T8] = PITABLE[L[128 - T8] & TM];
+        for (var i = 127 - T8; i >= 0; --i)
+            L[i] = PITABLE[L[i + 1] ^ L[i + T8]];
+        return K;
+    };
+} // </editor-fold>
+)();
+
+/**
+ * RC2 encrypt/decrypt process 
+ * 
+ * https://tools.ietf.org/html/rfc2268
+ * 
+ * @memberOf GostCipher
+ * @private
+ * @instance
+ * @method round
+ * @param {CryptoOperationData} k Scheduled key
+ * @param {CryptoOperationData} d Data
+ * @param {number} ofs Offsec
+ * @param {number} e true - decrypt
+ */
+var processRC2 = (function () // <editor-fold defaultstate="collapsed">
+{
+    var K, j, R = new Uint16Array(4),
+            s = new Uint16Array([1, 2, 3, 5]), reverse;
+
+    function rol(R, s) {
+        return (R << s | R >>> (16 - s)) & 0xffff;
+    }
+
+    function ror(R, s) {
+        return (R >>> s | R << (16 - s)) & 0xffff;
+    }
+
+    function mix(i) {
+        if (reverse) {
+            R[i] = ror(R[i], s[i]);
+            R[i] = R[i] - K[j] - (R[(i + 3) % 4] & R[(i + 2) % 4]) - ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
+            j = j - 1;
+        } else {
+            R[i] = R[i] + K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
+            j = j + 1;
+            R[i] = rol(R[i], s[i]);
+        }
+    }
+
+    function mash(i) {
+        if (reverse) {
+            R[i] = R[i] - K[R[(i + 3) % 4] & 63];
+        } else {
+            R[i] = R[i] + K[R[(i + 3) % 4] & 63];
+        }
+    }
+
+    function perform(method, count) {
+        count = count || 1;
+        for (var j = 0; j < count; j++) {
+            if (reverse) {
+                for (var i = 3; i >= 0; --i)
+                    method(i);
+            } else {
+                for (var i = 0; i < 4; i++)
+                    method(i);
+            }
+        }
+    }
+
+    return function (k, d, ofs, e) {
+        reverse = e;
+        //  1. Initialize words R[0], ..., R[3] to contain the 64-bit
+        //     ciphertext value.
+        R = new Uint16Array(d.buffer, ofs || d.byteOffset, 4);
+        //  2. Expand the key, so that words K[0], ..., K[63] become
+        //     defined.
+        K = k;
+        //  3. Initialize j to zero (enc) j to 63 (dec).
+        j = e ? 63 : 0;
+        //  4. Perform five mixing rounds.
+        perform(mix, 5);
+        //  5. Perform one mashing round.
+        perform(mash);
+        //  6. Perform six mixing rounds.
+        perform(mix, 6);
+        //  7. Perform one mashing round.
+        perform(mash);
+        //  8. Perform five mixing rounds.
+        perform(mix, 5);
+    };
+} // </editor-fold>
+)();
+
+/**
+ * Algorithm name GOST 28147-ECB<br><br>
+ * 
+ * encryptECB (K, D) is D, encrypted with key k using GOST 28147/GOST R 34.13 in 
+ * "prostaya zamena" (Electronic Codebook, ECB) mode. 
+ * @memberOf GostCipher
+ * @method encrypt
+ * @instance
+ * @param k {CryptoOperationData} 8x32 bit key 
+ * @param d {CryptoOperationData} 8 bits message
+ * @return {CryptoOperationData} result
+ */
+function encryptECB(k, d) // <editor-fold defaultstate="collapsed">
+{
+    var p = this.pad(byteArray(d)),
+            n = this.blockSize,
+            b = p.byteLength / n,
+            key = this.keySchedule(k);
+
+    for (var i = 0; i < b; i++)
+        this.process(key, p, n * i);
+
+    return p.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-ECB<br><br>
+ * 
+ * decryptECB (K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13 in   
+ * "prostaya zamena"  (Electronic Codebook, ECB) mode.
+ * 
+ * @memberOf GostCipher
+ * @method decrypt
+ * @instance
+ * @param k {CryptoOperationData} 8x32 bits key 
+ * @param d {CryptoOperationData} 8 bits message
+ * @return {CryptoOperationData} result
+ */
+function decryptECB(k, d) // <editor-fold defaultstate="collapsed">
+{
+    var p = cloneArray(d),
+            n = this.blockSize,
+            b = p.byteLength / n,
+            key = this.keySchedule(k, 1);
+
+    for (var i = 0; i < b; i++)
+        this.process(key, p, n * i, 1);
+
+    return this.unpad(p).buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CFB<br><br>
+ * 
+ * encryptCFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie s obratnoj svyaziyu" (Cipher Feedback, CFB) mode, and IV is   
+ * used as the initialization vector.
+ * 
+ * @memberOf GostCipher
+ * @method encrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function encryptCFB(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            c = cloneArray(d),
+            m = s.length,
+            t = new Uint8Array(m),
+            b = this.shiftBits >> 3,
+            cb = c.length, r = cb % b, q = (cb - r) / b,
+            key = this.keySchedule(k);
+
+    for (var i = 0; i < q; i++) {
+
+        for (var j = 0; j < m; j++)
+            t[j] = s[j];
+
+        this.process(key, s);
+
+        for (var j = 0; j < b; j++)
+            c[i * b + j] ^= s[j];
+
+        for (var j = 0; j < m - b; j++)
+            s[j] = t[b + j];
+
+        for (var j = 0; j < b; j++)
+            s[m - b + j] = c[i * b + j];
+
+        k = this.keyMeshing(k, s, i, key);
+    }
+
+    if (r > 0) {
+        this.process(key, s);
+
+        for (var i = 0; i < r; i++)
+            c[q * b + i] ^= s[i];
+    }
+    return c.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CFB<br><br>
+ * 
+ * decryptCFB (IV, K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie s obratnoj svyaziyu po shifrotekstu" (Cipher Feedback, CFB) mode, and IV is   
+ * used as the initialization vector.
+ * 
+ * @memberOf GostCipher
+ * @method decrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function decryptCFB(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            c = cloneArray(d),
+            m = s.length,
+            t = new Uint8Array(m),
+            b = this.shiftBits >> 3,
+            cb = c.length, r = cb % b, q = (cb - r) / b,
+            key = this.keySchedule(k);
+
+    for (var i = 0; i < q; i++) {
+
+        for (var j = 0; j < m; j++)
+            t[j] = s[j];
+
+        this.process(key, s);
+
+        for (var j = 0; j < b; j++) {
+            t[j] = c[i * b + j];
+            c[i * b + j] ^= s[j];
+        }
+
+        for (var j = 0; j < m - b; j++)
+            s[j] = t[b + j];
+
+        for (var j = 0; j < b; j++)
+            s[m - b + j] = t[j];
+
+        k = this.keyMeshing(k, s, i, key);
+    }
+
+    if (r > 0) {
+        this.process(key, s);
+
+        for (var i = 0; i < r; i++)
+            c[q * b + i] ^= s[i];
+    }
+    return c.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-OFB<br><br>
+ * 
+ * encryptOFB/decryptOFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie s obratnoj svyaziyu po vyhodu" (Output Feedback, OFB) mode, and IV is   
+ * used as the initialization vector.
+ * 
+ * @memberOf GostCipher
+ * @method encrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv 8x8 optional bits initial vector
+ * @return {CryptoOperationData} result
+ */
+/**
+ * Algorithm name GOST 28147-OFB<br><br>
+ * 
+ * encryptOFB/decryptOFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie s obratnoj svyaziyu po vyhodu" (Output Feedback, OFB) mode, and IV is   
+ * used as the initialization vector.
+ * 
+ * @memberOf GostCipher
+ * @method decrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function processOFB(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            c = cloneArray(d),
+            m = s.length,
+            t = new Uint8Array(m),
+            b = this.shiftBits >> 3,
+            p = new Uint8Array(b),
+            cb = c.length, r = cb % b, q = (cb - r) / b,
+            key = this.keySchedule(k);
+
+    for (var i = 0; i < q; i++) {
+
+        for (var j = 0; j < m; j++)
+            t[j] = s[j];
+
+        this.process(key, s);
+
+        for (var j = 0; j < b; j++)
+            p[j] = s[j];
+
+        for (var j = 0; j < b; j++)
+            c[i * b + j] ^= s[j];
+
+        for (var j = 0; j < m - b; j++)
+            s[j] = t[b + j];
+
+        for (var j = 0; j < b; j++)
+            s[m - b + j] = p[j];
+
+        k = this.keyMeshing(k, s, i, key);
+    }
+
+    if (r > 0) {
+        this.process(key, s);
+
+        for (var i = 0; i < r; i++)
+            c[q * b + i] ^= s[i];
+    }
+    return c.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CTR<br><br>
+ * 
+ * encryptCTR/decryptCTR (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie" (Counter Mode-CTR) mode, and IV is used as the   
+ * initialization vector.
+ * @memberOf GostCipher
+ * @method encrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv 8x8 optional bits initial vector
+ * @return {CryptoOperationData} result
+ */
+/**
+ * Algorithm name GOST 28147-CTR<br><br>
+ * 
+ * encryptCTR/decryptCTR (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "gammirovanie" (Counter Mode-CTR) mode, and IV is used as the   
+ * initialization vector.
+ * @memberOf GostCipher
+ * @method decrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function processCTR89(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            c = cloneArray(d),
+            b = this.blockSize,
+            t = new Int8Array(b),
+            cb = c.length, r = cb % b, q = (cb - r) / b,
+            key = this.keySchedule(k),
+            syn = new Int32Array(s.buffer);
+
+    this.process(key, s);
+
+    for (var i = 0; i < q; i++) {
+        syn[0] = (syn[0] + 0x1010101) & 0xffffffff;
+        // syn[1] = signed(unsigned((syn[1] + 0x1010104) & 0xffffffff) % 0xffffffff);
+        var tmp = unsigned(syn[1]) + 0x1010104; // Special thanks to Ilya Matveychikov
+        syn[1] = signed(tmp < 0x100000000 ? tmp : tmp - 0xffffffff);
+
+        for (var j = 0; j < b; j++)
+            t[j] = s[j];
+
+        this.process(key, syn);
+
+        for (var j = 0; j < b; j++)
+            c[i * b + j] ^= s[j];
+
+        for (var j = 0; j < b; j++)
+            s[j] = t[j];
+
+        k = this.keyMeshing(k, s, i, key);
+    }
+    if (r > 0) {
+        syn[0] = (syn[0] + 0x1010101) & 0xffffffff;
+        // syn[1] = signed(unsigned((syn[1] + 0x1010104) & 0xffffffff) % 0xffffffff);
+        var tmp = unsigned(syn[1]) + 0x1010104; // Special thanks to Ilya Matveychikov
+        syn[1] = signed(tmp < 0x100000000 ? tmp : tmp - 0xffffffff);
+
+        this.process(key, syn);
+
+        for (var i = 0; i < r; i++)
+            c[q * b + i] ^= s[i];
+    }
+    return c.buffer;
+} // </editor-fold>
+
+function processCTR15(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var c = cloneArray(d),
+            n = this.blockSize,
+            b = this.shiftBits >> 3,
+            cb = c.length, r = cb % b, q = (cb - r) / b,
+            s = new Uint8Array(n),
+            t = new Int32Array(n),
+            key = this.keySchedule(k);
+
+    s.set(iv || this.iv);
+    for (var i = 0; i < q; i++) {
+
+        for (var j = 0; j < n; j++)
+            t[j] = s[j];
+
+        this.process(key, s);
+
+        for (var j = 0; j < b; j++)
+            c[b * i + j] ^= s[j];
+
+        for (var j = 0; j < n; j++)
+            s[j] = t[j];
+
+        for (var j = n - 1; i >= 0; --i) {
+            if (s[j] > 0xfe) {
+                s[j] -= 0xfe;
+            } else {
+                s[j]++;
+                break;
+            }
+        }
+    }
+
+    if (r > 0) {
+        this.process(key, s);
+        for (var j = 0; j < r; j++)
+            c[b * q + j] ^= s[j];
+    }
+
+    return c.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CBC<br><br>
+ * 
+ * encryptCBC (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13   
+ * in "Prostaya zamena s zatsepleniem" (Cipher-Block-Chaining, CBC) mode and IV is used as the initialization 
+ * vector.
+ * 
+ * @memberOf GostCipher
+ * @method encrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function encryptCBC(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            n = this.blockSize,
+            m = s.length,
+            c = this.pad(byteArray(d)),
+            key = this.keySchedule(k);
+
+    for (var i = 0, b = c.length / n; i < b; i++) {
+
+        for (var j = 0; j < n; j++)
+            s[j] ^= c[i * n + j];
+
+        this.process(key, s);
+
+        for (var j = 0; j < n; j++)
+            c[i * n + j] = s[j];
+
+        if (m !== n) {
+            for (var j = 0; j < m - n; j++)
+                s[j] = s[n + j];
+
+            for (var j = 0; j < n; j++)
+                s[j + m - n] = c[i * n + j];
+        }
+
+        k = this.keyMeshing(k, s, i, key);
+    }
+
+    return c.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CBC<br><br>
+ * 
+ * decryptCBC (IV, K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13   
+ * in "Prostaya zamena s zatsepleniem" (Cipher-Block-Chaining, CBC) mode and IV is used as the initialization 
+ * vector.
+ * 
+ * @memberOf GostCipher
+ * @method decrypt
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function decryptCBC(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var s = new Uint8Array(iv || this.iv),
+            n = this.blockSize,
+            m = s.length,
+            c = cloneArray(d),
+            next = new Uint8Array(n),
+            key = this.keySchedule(k, 1);
+
+    for (var i = 0, b = c.length / n; i < b; i++) {
+
+        for (var j = 0; j < n; j++)
+            next[j] = c[i * n + j];
+
+        this.process(key, c, i * n, 1);
+
+        for (var j = 0; j < n; j++)
+            c[i * n + j] ^= s[j];
+
+        if (m !== n) {
+            for (var j = 0; j < m - n; j++)
+                s[j] = s[n + j];
+        }
+
+        for (var j = 0; j < n; j++)
+            s[j + m - n] = next[j];
+
+        k = this.keyMeshing(k, s, i, key, 1);
+    }
+
+    return this.unpad(c).buffer;
+} // </editor-fold>
+
+/**
+ * The generateKey method returns a new generated key.
+ * 
+ * @memberOf GostCipher
+ * @method generateKey
+ * @instance
+ * @return {CryptoOperationData} result
+ */
+
+function generateKey() // <editor-fold defaultstate="collapsed">
+{
+    // Simple generate 256 bit random seed
+    var k = new Uint8Array(this.keySize);
+    randomSeed(k);
+    return k.buffer;
+} // </editor-fold>
+
+
+/**
+ * makeIMIT (K, D) is the 32-bit result of the GOST 28147/GOST R 34.13 in   
+ * "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV   
+ * as initialization vector.  Note that the standard specifies its use   
+ * in this mode only with an initialization vector of zero.
+ * 
+ * @memberOf GostCipher
+ * @method processMAC
+ * @private
+ * @instance
+ * @param {Int32Array} key 8x32 bits key 
+ * @param {Int32Array} s 8x8 sum array
+ * @param {Uint8Array} d 8 bits array with data 
+ * @return {Uint8Array} result
+ */
+function processMAC89(key, s, d) // <editor-fold defaultstate="collapsed">
+{
+    var c = zeroPad.call(this, byteArray(d)),
+            n = this.blockSize,
+            q = c.length / n,
+            sBox = this.sBox,
+            sum = new Int32Array(s.buffer);
+
+    for (var i = 0; i < q; i++) {
+
+        for (var j = 0; j < n; j++)
+            s[j] ^= c[i * n + j];
+
+        for (var j = 0; j < 16; j++) // 1-16 steps
+            round(sBox, sum, key[j]);
+    }
+} // </editor-fold>
+
+function processKeyMAC15(s) // <editor-fold defaultstate="collapsed">
+{
+    var t = 0, n = s.length;
+    for (var i = n - 1; i >= 0; --i) {
+        var t1 = s[i] >>> 7;
+        s[i] = (s[i] << 1) & 0xff | t;
+        t = t1;
+    }
+    if (t !== 0) {
+        if (n === 16)
+            s[15] ^= 0x87;
+        else
+            s[7] ^= 0x1b;
+    }
+} // </editor-fold>
+
+function processMAC15(key, s, d) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize,
+            sBox = this.sBox, c = byteArray(d),
+            r = new Uint8Array(n);
+    // R
+    this.process(key, r);
+    // K1
+    processKeyMAC15(r);
+    if (d.byteLength % n !== 0) {
+        c = bitPad.call(this, byteArray(d));
+        // K2
+        processKeyMAC15(r);
+    }
+
+    for (var i = 0, q = c.length / n; i < q; i++) {
+
+        for (var j = 0; j < n; j++)
+            s[j] ^= c[i * n + j];
+
+        if (i === q - 1) {// Last block
+            for (var j = 0; j < n; j++)
+                s[j] ^= r[j];
+        }
+
+        this.process(key, s);
+    }
+} // </editor-fold>
+
+/**
+ * signMAC (K, D, IV) is the 32-bit result of the GOST 28147/GOST R 34.13 in   
+ * "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV   
+ * as initialization vector.  Note that the standard specifies its use   
+ * in this mode only with an initialization vector of zero.
+ * 
+ * @memberOf GostCipher
+ * @method sign
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv initial vector
+ * @return {CryptoOperationData} result
+ */
+function signMAC(k, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var key = this.keySchedule(k),
+            s = new Uint8Array(iv || this.iv),
+            m = Math.ceil(this.macLength >> 3) || this.blockSize >> 1;
+
+    this.processMAC(key, s, d);
+
+    var mac = new Uint8Array(m); // mac size
+    mac.set(new Uint8Array(s.buffer, 0, m));
+    return mac.buffer;
+} // </editor-fold>
+
+/**
+ * verifyMAC (K, M, D, IV) the 32-bit result verification of the GOST 28147/GOST R 34.13 in   
+ * "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV   
+ * as initialization vector.  Note that the standard specifies its use   
+ * in this mode only with an initialization vector of zero.
+ * 
+ * @memberOf GostCipher
+ * @method verify
+ * @instance
+ * @param {CryptoOperationData} k 8x32 bits key 
+ * @param {CryptoOperationData} m 8 bits array with signature
+ * @param {CryptoOperationData} d 8 bits array with data 
+ * @param {CryptoOperationData} iv 8x8 optional bits initial vector
+ * @return {boolen} MAC verified = true
+ */
+function verifyMAC(k, m, d, iv) // <editor-fold defaultstate="collapsed">
+{
+    var mac = new Uint8Array(signMAC.call(this, k, d, iv)),
+            test = byteArray(m);
+    if (mac.length !== test.length)
+        return false;
+    for (var i = 0, n = mac.length; i < n; i++)
+        if (mac[i] !== test[i])
+            return false;
+    return true;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-KW<br><br>
+ * 
+ * This algorithm encrypts GOST 28147-89 CEK with a GOST 28147/GOST R 34.13 KEK.
+ * Ref. rfc4357 6.1 GOST 28147-89 Key Wrap
+ * Note: This algorithm MUST NOT be used with a KEK produced by VKO GOST   
+ * R 34.10-94, because such a KEK is constant for every sender-recipient   
+ * pair.  Encrypting many different content encryption keys on the same   
+ * constant KEK may reveal that KEK.
+ * 
+ * @memberOf GostCipher
+ * @method wrapKey
+ * @instance
+ * @param {CryptoOperationData} kek Key encryption key
+ * @param {CryptoOperationData} cek Content encryption key
+ * @returns {CryptoOperationData} Encrypted cek
+ */
+function wrapKeyGOST(kek, cek) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize, k = this.keySize, len = k + (n >> 1);
+    // 1) For a unique symmetric KEK, generate 8 octets at random and call 
+    // the result UKM.  For a KEK, produced by VKO GOST R 34.10-2001, use 
+    // the UKM that was used for key derivation.    
+    if (!this.ukm) 
+        throw new DataError('UKM must be defined');
+    var ukm = new Uint8Array(this.ukm);
+    // 2) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK, CEK).       
+    // Call the result CEK_MAC. 
+    var mac = signMAC.call(this, kek, cek, ukm);
+    // 3) Encrypt the CEK in ECB mode using the KEK.  Call the ciphertext CEK_ENC.
+    var enc = encryptECB.call(this, kek, cek);
+    // 4) The wrapped content-encryption key is (UKM | CEK_ENC | CEK_MAC).
+    var r = new Uint8Array(len);
+    r.set(new Uint8Array(enc), 0);
+    r.set(new Uint8Array(mac), k);
+    return r.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-KW<br><br>
+ * 
+ *  This algorithm decrypts GOST 28147-89 CEK with a GOST 28147 KEK.
+ *  Ref. rfc4357 6.2 GOST 28147-89 Key Unwrap
+ *  
+ * @memberOf GostCipher
+ * @method unwrapKey
+ * @instance
+ * @param {type} kek Key encryption key
+ * @param {type} data Content encryption key
+ * @return {CryptoOperationData} result
+ */
+function unwrapKeyGOST(kek, data) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize, k = this.keySize, len = k + (n >> 1);
+    // 1) If the wrapped content-encryption key is not 44 octets, then error.
+    var d = buffer(data);
+    if (d.byteLength !== len)
+        throw new DataError('Wrapping key size must be ' + len + ' bytes');
+    // 2) Decompose the wrapped content-encryption key into UKM, CEK_ENC, and CEK_MAC.  
+    // UKM is the most significant (first) 8 octets. CEK_ENC is next 32 octets, 
+    // and CEK_MAC is the least significant (last) 4 octets.    
+    if (!this.ukm)
+        throw new DataError('UKM must be defined');
+    var ukm = new Uint8Array(this.ukm),
+            enc = new Uint8Array(d, 0, k),
+            mac = new Uint8Array(d, k, n >> 1);
+    // 3) Decrypt CEK_ENC in ECB mode using the KEK.  Call the output CEK.
+    var cek = decryptECB.call(this, kek, enc);
+    // 4) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK, CEK), 
+    // compare the result with CEK_MAC.  If they are not equal, then error.
+    var check = verifyMAC.call(this, kek, mac, cek, ukm);
+    if (!check)
+        throw new DataError('Error verify MAC of wrapping key');
+    return cek;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CPKW<br><br>
+ * 
+ * Given a random 64-bit UKM and a GOST 28147 key K, this algorithm   
+ * creates a new GOST 28147-89 key K(UKM).
+ * Ref. rfc4357 6.3 CryptoPro KEK Diversification Algorithm
+ * 
+ * @memberOf GostCipher
+ * @method diversify
+ * @instance
+ * @private
+ * @param {CryptoOperationData} kek Key encryption key
+ * @param {CryptoOperationData} ukm Random generated value
+ * @returns {CryptoOperationData} Diversified kek
+ */
+function diversifyKEK(kek, ukm) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize;
+
+    // 1) Let K[0] = K;    
+    var k = intArray(kek);
+    // 2) UKM is split into components a[i,j]:       
+    //    UKM = a[0]|..|a[7] (a[i] - byte, a[i,0]..a[i,7] - it’s bits) 
+    var a = [];
+    for (var i = 0; i < n; i++) {
+        a[i] = [];
+        for (var j = 0; j < 8; j++) {
+            a[i][j] = (ukm[i] >>> j) & 0x1;
+        }
+    }
+    // 3) Let i be 0.    
+    // 4) K[1]..K[8] are calculated by repeating the following algorithm       
+    //    eight times:     
+    for (var i = 0; i < n; i++) {
+        //     A) K[i] is split into components k[i,j]:
+        //        K[i] = k[i,0]|k[i,1]|..|k[i,7] (k[i,j] - 32-bit integer)
+        //     B) Vector S[i] is calculated:        
+        //        S[i] = ((a[i,0]*k[i,0] + ... + a[i,7]*k[i,7]) mod 2^32) |        
+        //         (((~a[i,0])*k[i,0] + ... + (~a[i,7])*k[i,7]) mod 2^32);     
+        var s = new Int32Array(2);
+        for (var j = 0; j < 8; j++) {
+            if (a[i][j])
+                s[0] = (s[0] + k[j]) & 0xffffffff;
+            else
+                s[1] = (s[1] + k[j]) & 0xffffffff;
+        }
+        //     C) K[i+1] = encryptCFB (S[i], K[i], K[i])
+        var iv = new Uint8Array(s.buffer);
+        k = new Int32Array(encryptCFB.call(this, k, k, iv));
+        //     D) i = i + 1
+    }
+    // 5) Let K(UKM) be K[8].
+    return k;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CPKW<br><br>
+ * 
+ * This algorithm encrypts GOST 28147-89 CEK with a GOST 28147 KEK.   
+ * It can be used with any KEK (e.g., produced by VKO GOST R 34.10-94 or   
+ * VKO GOST R 34.10-2001) because a unique UKM is used to diversify the KEK.
+ * Ref. rfc4357 6.3  CryptoPro Key Wrap
+ * 
+ * @memberOf GostCipher
+ * @method wrapKey
+ * @instance
+ * @param {CryptoOperationData} kek Key encryption key
+ * @param {CryptoOperationData} cek Content encryption key
+ * @returns {CryptoOperationData} Encrypted cek
+ */
+function wrapKeyCP(kek, cek) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize, k = this.keySize, len = k + (n >> 1);
+    // 1) For a unique symmetric KEK or a KEK produced by VKO GOST R       
+    // 34.10-94, generate 8 octets at random.  Call the result UKM.  For       
+    // a KEK, produced by VKO GOST R 34.10-2001, use the UKM that was       
+    // used for key derivation.
+    if (!this.ukm) 
+        throw new DataError('UKM must be defined');
+    var ukm = new Uint8Array(this.ukm);
+    // 2) Diversify KEK, using the CryptoPro KEK Diversification Algorithm,       
+    // described in Section 6.5.  Call the result KEK(UKM).
+    var dek = diversifyKEK.call(this, kek, ukm);
+    // 3) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK(UKM),       
+    // CEK).  Call the result CEK_MAC.    
+    var mac = signMAC.call(this, dek, cek, ukm);
+    // 4) Encrypt CEK in ECB mode using KEK(UKM).  Call the ciphertext       
+    // CEK_ENC.    
+    var enc = encryptECB.call(this, dek, cek);
+    // 5) The wrapped content-encryption key is (UKM | CEK_ENC | CEK_MAC).
+    var r = new Uint8Array(len);
+    r.set(new Uint8Array(enc), 0);
+    r.set(new Uint8Array(mac), k);
+    return r.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CPKW<br><br>
+ * 
+ * This algorithm encrypts GOST 28147-89 CEK with a GOST 28147 KEK. 
+ * Ref. rfc4357 6.4 CryptoPro Key Unwrap
+ *
+ * @memberOf GostCipher
+ * @method unwrapKey
+ * @instance
+ * @param {CryptoOperationData} kek Key encryption key
+ * @param {CryptoOperationData} data Encrypted content encryption keu
+ * @return {CryptoOperationData} result Decrypted content encryption keu
+ */
+function unwrapKeyCP(kek, data) // <editor-fold defaultstate="collapsed">
+{
+    var n = this.blockSize, k = this.keySize, len = k + (n >> 1);
+    // 1) If the wrapped content-encryption key is not 44 octets, then error.    
+    var d = buffer(data);
+    if (d.byteLength !== len)
+        throw new DataError('Wrapping key size must be ' + len + ' bytes');
+    // 2) Decompose the wrapped content-encryption key into UKM, CEK_ENC,       
+    // and CEK_MAC.  UKM is the most significant (first) 8 octets.       
+    // CEK_ENC is next 32 octets, and CEK_MAC is the least significant       
+    // (last) 4 octets.    
+    if (!this.ukm)
+        throw new DataError('UKM must be defined');
+    var ukm = new Uint8Array(this.ukm),
+            enc = new Uint8Array(d, 0, k),
+            mac = new Uint8Array(d, k, n >> 1);
+    // 3) Diversify KEK using the CryptoPro KEK Diversification Algorithm,       
+    // described in section 6.5.  Call the result KEK(UKM).    
+    var dek = diversifyKEK.call(this, kek, ukm);
+    // 4) Decrypt CEK_ENC in ECB mode using KEK(UKM).  Call the output CEK.    
+    var cek = decryptECB.call(this, dek, enc);
+    // 5) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK(UKM),       
+    // CEK), compare the result with CEK_MAC.  If they are not equal, 
+    // then it is an error.
+    var check = verifyMAC.call(this, dek, mac, cek, ukm);
+    if (!check)
+        throw new DataError('Error verify MAC of wrapping key');
+    return cek;
+} // </editor-fold>
+
+/**
+ * SignalCom master key packing algorithm
+ * 
+ * kek stored in 3 files - kek.opq, mk.db3, masks.db3
+ * kek.opq - always 36 bytes length = 32 bytes encrypted kek + 4 bytes mac of decrypted kek
+ * mk.db3 - 6 bytes header (1 byte magic code 0x22 + 1 byte count of masks + 4 bytes mac of 
+ * xor summarizing masks value) + attached masks 
+ * masks.db3 - detached masks. 
+ * Total length  of attached + detached masks = 32 bits * count of masks
+ * Default value of count 8 = (7 attached + 1 detached). But really no reason for such 
+ * separation - all masks xor summarizing - order is not matter.
+ * Content of file rand.opq can used as ukm. Don't forget change file content after using. 
+ * 
+ * For usb-token files has names: 
+ * a001 - mk.db3, b001 - masks.db3, c001 - kek.opq, d001 - rand.opq
+ * For windows registry
+ * 00000001 - mk.db3, 00000002 - masks.db3, 00000003 - key.opq, 00000004 - rand.opq, 
+ * 00000006 - keys\00000001.key, 0000000A - certificate
+ * 
+ * @memberOf GostCipher
+ * @method packKey
+ * @instance
+ * @private
+ * @param {CryptoOperationData} unpacked - clear main key 32 bytes
+ * @param {CryptoOperationData} ukm - random vector for packing - 32 bytes * (count of masks - 1)
+ * @returns {CryptoOperationData} packed master key - concatination of mk.db3 + masks.db3
+ */
+function packKeySC(unpacked, ukm) // <editor-fold defaultstate="collapsed">
+{
+    var m = this.blockSize >> 1, k = this.keySize;
+    var mcount = 8;
+    var key = new Uint8Array(buffer(unpacked));
+    if (key.byteLength !== k)
+        throw new DataError('Wrong cleartext size ' + key.byteLength + ' bytes');
+    // Check or generate UKM
+    ukm = ukm || this.ukm;
+    if (ukm) {
+        ukm = new Uint8Array(buffer(ukm));
+        if (ukm.byteLength > 0 && ukm.byteLength % k === 0)
+            mcount = ukm.byteLength / k + 1;
+        else
+            throw new DataError('Wrong rand size ' + ukm.byteLength + ' bytes');
+    } else
+        randomSeed(ukm = new Uint8Array((mcount - 1) * k));
+    // Output array
+    var d = new Uint8Array(mcount * k + m + 2), b = d.buffer;
+    // Calculate MAC
+    var zero32 = new Uint8Array(k);
+    var mac = signMAC.call(this, key, zero32);
+    d[0] = 0x22; // Magic code
+    d[1] = mcount; // Count of masks
+    d.set(new Uint8Array(mac), 2);
+    d.set(ukm, k + m + 2);
+    for (var i = 1; i < mcount; i++) {
+        var mask = new Uint8Array(b, 2 + m + k * i);
+        for (var j = 0; j < k; j++)
+            key[j] ^= mask[j];
+    }
+    d.set(key, m + 2);
+    return d.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-SCKW<br><br>
+ * 
+ * SignalCom master key unpacking algorithm
+ * 
+ * @memberOf GostCipher
+ * @method unpackKey
+ * @instance
+ * @private
+ * @param {CryptoOperationData} packed - concatination of mk.db3 + masks.db3
+ * @returns {CryptoOperationData} unpacked master key
+ */
+function unpackKeySC(packed) // <editor-fold defaultstate="collapsed">
+{
+    var m = this.blockSize >> 1, k = this.keySize;
+    var b = buffer(packed);
+    // Unpack master key
+    var magic = new Uint8Array(b, 0, 1)[0];
+    if (magic !== 0x22)
+        throw new DataError('Invalid magic number');
+    var mcount = new Uint8Array(b, 1, 1)[0];
+    var mac = new Uint8Array(b, 2, m); // MAC for summarized mask
+    // Compute packKey xor summing for all masks
+    var key = new Uint8Array(k);
+    for (var i = 0; i < mcount; i++) {
+        var mask = new Uint8Array(b, 2 + m + k * i, k);
+        for (var j = 0; j < k; j++)
+            key[j] ^= mask[j];
+    }
+    // Test MAC for packKey with default sBox on zero 32 bytes array
+    var zero32 = new Uint8Array(k);
+    var test = verifyMAC.call(this, key, mac, zero32);
+    if (!test) {
+        // Try to use different sBoxes
+        var names = ['E-A', 'E-B', 'E-C', 'E-D', 'E-SC'];
+        for (var i = 0, n = names.length; i < n; i++) {
+            this.sBox = sBoxes[names[i]];
+            test = verifyMAC.call(this, key, mac, zero32);
+            if (test)
+                break;
+        }
+    }
+    if (!test)
+        throw new DataError('Invalid main key MAC');
+    return key.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-SCKW<br><br>
+ * 
+ * SignalCom Key Wrapping algorithm
+ * 
+ * @memberOf GostCipher
+ * @method wrapKey
+ * @instance
+ * @param {CryptoOperationData} kek - clear kek or concatination of mk.db3 + masks.db3
+ * @param {CryptoOperationData} cek - key for wrapping 
+ * @returns {CryptoOperationData} wrapped key - file kek.opq
+ */
+function wrapKeySC(kek, cek) // <editor-fold defaultstate="collapsed">
+{
+    var m = this.blockSize >> 1, n = this.keySize;
+    var k = buffer(kek);
+    var c = buffer(cek);
+    if (k.byteLength !== n)
+        k = unpackKeySC.call(this, k);
+    var enc = encryptECB.call(this, k, c);
+    var mac = signMAC.call(this, k, c);
+    var d = new Uint8Array(m + n);
+    d.set(new Uint8Array(enc), 0);
+    d.set(new Uint8Array(mac), n);
+    return d.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-SCKW<br><br>
+ * 
+ * SignalCom Key UnWrapping algorithm
+ * 
+ * @memberOf GostCipher
+ * @method unwrapKey
+ * @instance
+ * @param {CryptoOperationData} kek - concatination of files mk.db3 + masks.db3 or clear kek 
+ * @param {CryptoOperationData} cek - wrapping key - file kek.opq
+ * @return {CryptoOperationData} result
+ */
+function unwrapKeySC(kek, cek) // <editor-fold defaultstate="collapsed">
+{
+    var m = this.blockSize >> 1, n = this.keySize;
+    var k = buffer(kek);
+    var c = buffer(cek);
+    if (k.byteLength !== n)
+        k = unpackKeySC.call(this, k);
+    var enc = new Uint8Array(c, 0, n); // Encrypted kek
+    var mac = new Uint8Array(c, n, m); // MAC for clear kek
+    var d = decryptECB.call(this, k, enc);
+    if (!verifyMAC.call(this, k, mac, d))
+        throw new DataError('Invalid key MAC');
+    return d;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-SCKW<br><br>
+ * 
+ * SignalCom master key generation for wrapping
+ * 
+ * @memberOf GostCipher
+ * @method generateKey
+ * @instance
+ * @return {CryptoOperationData} result
+ */
+function generateWrappingKeySC() // <editor-fold defaultstate="collapsed">
+{
+    return packKeySC.call(this, generateKey.call(this));
+} // </editor-fold>
+
+function maskKey(mask, key, inverse, keySize) // <editor-fold defaultstate="collapsed">
+{
+    var k = keySize / 4, 
+            m32 = new Int32Array(buffer(mask)),
+            k32 = new Int32Array(buffer(key)), 
+            r32 = new Int32Array(k);
+    if (inverse)
+        for (var i = 0; i < k; i++) 
+            r32[i] = (k32[i] + m32[i]) & 0xffffffff;
+    else
+        for (var i = 0; i < k; i++) 
+            r32[i] = (k32[i] - m32[i]) & 0xffffffff;
+    return r32.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-MASK<br><br>
+ * 
+ * This algorithm wrap key mask
+ * 
+ * @memberOf GostCipher
+ * @method wrapKey
+ * @instance
+ * @param {CryptoOperationData} mask The mask
+ * @param {CryptoOperationData} key The key
+ * @returns {CryptoOperationData} The masked key
+ */
+function wrapKeyMask(mask, key) // <editor-fold defaultstate="collapsed">
+{
+    return maskKey(mask, key, this.procreator === 'VN', this.keySize);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CPKW<br><br>
+ * 
+ * This algorithm unwrap key mask
+ *
+ * @memberOf GostCipher
+ * @method unwrapKey
+ * @instance
+ * @param {CryptoOperationData} mask The mask
+ * @param {CryptoOperationData} key The masked key
+ * @return {CryptoOperationData} result The key
+ */
+function unwrapKeyMask(mask, key) // <editor-fold defaultstate="collapsed">
+{
+    return maskKey(mask, key, this.procreator !== 'VN', this.keySize);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-CPKM<br><br>
+ * 
+ * Key meshing in according to rfc4357 2.3.2. CryptoPro Key Meshing
+ * 
+ * @memberOf GostCipher
+ * @method keyMeshing
+ * @instance
+ * @private
+ * @param {(Uint8Array|CryptoOperationData)} k 8x8 bit key 
+ * @param {Uint8Array} s 8x8 bit sync (iv)
+ * @param {Integer} i block index
+ * @param {Int32Array} key 8x32 bit key schedule 
+ * @param {boolean} e true - decrypt
+ * @returns CryptoOperationData next 8x8 bit key
+ */
+function keyMeshingCP(k, s, i, key, e) // <editor-fold defaultstate="collapsed">
+{
+    if ((i + 1) * this.blockSize % 1024 === 0) { // every 1024 octets
+        // K[i+1] = decryptECB (K[i], C);
+        k = decryptECB.call(this, k, C);
+        // IV0[i+1] = encryptECB (K[i+1],IVn[i])
+        s.set(new Uint8Array(encryptECB.call(this, k, s)));
+        // restore key schedule
+        key.set(this.keySchedule(k, e));
+    }
+    return k;
+} // </editor-fold>
+
+/**
+ *  Null Key Meshing in according to rfc4357 2.3.1
+ * 
+ * @memberOf GostCipher
+ * @method keyMeshing
+ * @instance
+ * @private
+ * @param {(Uint8Array|CryptoOperationData)} k 8x8 bit key 
+ */
+function noKeyMeshing(k) // <editor-fold defaultstate="collapsed">
+{
+    return k;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-NoPadding<br><br>
+ * 
+ * No padding.
+ * 
+ * @memberOf GostCipher
+ * @method padding
+ * @instance
+ * @private
+ * @param {Uint8Array} d array with source data
+ * @returns {Uint8Array} result
+ */
+function noPad(d) // <editor-fold defaultstate="collapsed">
+{
+    return new Uint8Array(d);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-PKCS5Padding<br><br>
+ * 
+ *  PKCS#5 padding: 8-x remaining bytes are filled with the value of      
+ *  8-x.  If there’s no incomplete block, one extra block filled with      
+ *  value 8 is added
+ * 
+ * @memberOf GostCipher
+ * @method padding
+ * @instance
+ * @private
+ * @param {Uint8Array} d array with source data
+ * @returns {Uint8Array} result
+ */
+function pkcs5Pad(d) // <editor-fold defaultstate="collapsed">
+{
+    var n = d.byteLength,
+            nb = this.blockSize,
+            q = nb - n % nb,
+            m = Math.ceil((n + 1) / nb) * nb,
+            r = new Uint8Array(m);
+    r.set(d);
+    for (var i = n; i < m; i++)
+        r[i] = q;
+    return r;
+} // </editor-fold>
+
+function pkcs5Unpad(d) // <editor-fold defaultstate="collapsed">
+{
+    var m = d.byteLength,
+            nb = this.blockSize,
+            q = d[m - 1],
+            n = m - q;
+    if (q > nb)
+        throw DataError('Invalid padding');
+    var r = new Uint8Array(n);
+    if (n > 0)
+        r.set(new Uint8Array(d.buffer, 0, n));
+    return r;
+} // </editor-fold>
+
+
+/**
+ * Algorithm name GOST 28147-ZeroPadding<br><br>
+ * 
+ * Zero padding: 8-x remaining bytes are filled with zero
+ * 
+ * @memberOf GostCipher
+ * @method padding
+ * @instance
+ * @private
+ * @param {Uint8Array} d array with source data
+ * @returns {Uint8Array} result
+ */
+function zeroPad(d) // <editor-fold defaultstate="collapsed">
+{
+    var n = d.byteLength,
+            nb = this.blockSize,
+            m = Math.ceil(n / nb) * nb,
+            r = new Uint8Array(m);
+    r.set(d);
+    for (var i = n; i < m; i++)
+        r[i] = 0;
+    return r;
+} // </editor-fold>
+
+
+/**
+ * Algorithm name GOST 28147-BitPadding<br><br>
+ * 
+ * Bit padding: P* = P || 1 || 000...0 If there’s no incomplete block, 
+ * one extra block filled with 1 || 000...0
+ * 
+ * @memberOf GostCipher
+ * @method padding
+ * @instance
+ * @private
+ * @param {Uint8Array} d array with source data
+ * @returns {Uint8Array} result
+ */
+function bitPad(d) // <editor-fold defaultstate="collapsed"> 
+{
+    var n = d.byteLength,
+            nb = this.blockSize,
+            m = Math.ceil((n + 1) / nb) * nb,
+            r = new Uint8Array(m);
+    r.set(d);
+    r[n] = 1;
+    for (var i = n + 1; i < m; i++)
+        r[i] = 0;
+    return r;
+} // </editor-fold>
+
+function bitUnpad(d) // <editor-fold defaultstate="collapsed"> 
+{
+    var m = d.byteLength,
+            n = m;
+    while (n > 1 && d[n - 1] === 0)
+        n--;
+    if (d[n - 1] !== 1)
+        throw DataError('Invalid padding');
+    n--;
+    var r = new Uint8Array(n);
+    if (n > 0)
+        r.set(new Uint8Array(d.buffer, 0, n));
+    return r;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST 28147-RandomPadding<br><br>
+ * 
+ * Random padding: 8-x remaining bytes of the last block are set to      
+ * random.
+ * 
+ * @memberOf GostCipher
+ * @method padding
+ * @instance
+ * @private
+ * @param {Uint8Array} d array with source data
+ * @returns {Uint8Array} result
+ */
+function randomPad(d) // <editor-fold defaultstate="collapsed">
+{
+    var n = d.byteLength,
+            nb = this.blockSize,
+            q = nb - n % nb,
+            m = Math.ceil(n / nb) * nb,
+            r = new Uint8Array(m), e = new Uint8Array(r.buffer, n, q);
+    r.set(d);
+    randomSeed(e);
+    return r;
+} // </editor-fold>
+
+/**
+ * GOST 28147-89 Encryption Algorithm<br><br> 
+ * 
+ * References {@link http://tools.ietf.org/html/rfc5830}<br><br>
+ * 
+ * When keys and initialization vectors are converted to/from byte arrays, 
+ * little-endian byte order is assumed.<br><br>
+ * 
+ * Normalized algorithm identifier common parameters:
+ * 
+ *  <ul>
+ *      <li><b>name</b> Algorithm name 'GOST 28147' or 'GOST R 34.12'</li>
+ *      <li><b>version</b> Algorithm version, number
+ *          <ul>
+ *              <li><b>1989</b> Current version of standard</li>
+ *              <li><b>2015</b> New draft version of standard</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>length</b> Block length
+ *          <ul>
+ *              <li><b>64</b> 64 bits length (default)</li>
+ *              <li><b>128</b> 128 bits length (only for version 2015)</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>mode</b> Algorithm mode, string
+ *          <ul>
+ *              <li><b>ES</b> Encryption mode (default)</li>
+ *              <li><b>MAC</b> "imitovstavka" (MAC) mode</li>
+ *              <li><b>KW</b> Key wrapping mode</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>sBox</b> Paramset sBox for GOST 28147-89, string. Used only if version = 1989</li>
+ *  </ul>
+ *  
+ * Supported algorithms, modes and parameters:
+ * 
+ *  <ul>
+ *      <li>Encript/Decrypt mode (ES)
+ *          <ul>
+ *              <li><b>block</b> Block mode, string. Default ECB</li>
+ *              <li><b>keyMeshing</b> Key meshing mode, string. Default NO</li>
+ *              <li><b>padding</b> Padding mode, string. Default NO for CFB and CTR modes, or ZERO for others</li>
+ *              <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
+ *          </ul>
+ *      </li>
+ *      <li>Sign/Verify mode (MAC)
+ *          <ul>
+ *              <li><b>macLength</b> Length of mac in bits (default - 32 bits)</li>
+ *              <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
+ *          </ul>
+ *      </li>
+ *      <li>Wrap/Unwrap key mode (KW)
+ *          <ul>
+ *              <li><b>keyWrapping</b> Mode of keywrapping, string. Default NO - standard GOST key wrapping</li>
+ *              <li><b>ukm</b> {@link CryptoOperationData} User key material. Default - random generated value</li>
+ *          </ul>
+ *      </li>
+ *  </ul>
+ *      
+ * Supported paramters values:
+ *      
+ *  <ul>
+ *      <li>Block modes (parameter 'block')
+ *          <ul>
+ *              <li><b>ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+ *              <li><b>CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
+ *              <li><b>OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
+ *              <li><b>CTR</b> "gammirovanie" (counter) mode</li>
+ *              <li><b>CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+ *          </ul>
+ *      </li>
+ *      <li>Key meshing modes (parameter 'keyMeshing')
+ *          <ul>
+ *              <li><b>NO</b> No key wrapping (default)</li>
+ *              <li><b>CP</b> CryptoPor Key key meshing</li>
+ *          </ul>
+ *      </li>
+ *      <li>Padding modes (parameter 'padding')
+ *          <ul>
+ *              <li><b>NO</b> No padding only for CFB, OFB and CTR modes</li>
+ *              <li><b>PKCS5</b> PKCS#5 padding mode</li>
+ *              <li><b>ZERO</b> Zero bits padding mode</li>
+ *              <li><b>RANDOM</b> Random bits padding mode</li>
+ *              <li><b>BIT</b> One bit padding mode</li>
+ *          </ul>
+ *      </li>
+ *      <li>Wrapping key modes (parameter 'keyWrapping')
+ *          <ul>
+ *              <li><b>NO</b> Ref. rfc4357 6.1 GOST 28147-89 Key wrapping</li>
+ *              <li><b>CP</b> CryptoPro Key wrapping mode</li>
+ *              <li><b>SC</b> SignalCom Key wrapping mode</li>
+ *          </ul>
+ *      </li>
+ *  </ul>
+ * 
+ * @class GostCipher
+ * @param {AlgorithmIndentifier} algorithm WebCryptoAPI algorithm identifier
+ */
+function GostCipher(algorithm) // <editor-fold defaultstate="collapsed">
+{
+    // Check little endian support
+    if (!littleEndian)
+        throw new NotSupportedError('Big endian platform not supported');
+    algorithm = algorithm || {};
+    this.keySize = 32;
+    this.blockLength = algorithm.length || 64;
+    this.blockSize = this.blockLength >> 3;
+
+    this.name = (algorithm.name || (algorithm.version === 1 ? 'RC2' :
+            algorithm.version === 1989 ? 'GOST 28147' : 'GOST R 34.12')) +
+            (algorithm.version > 4 ? '-' + ((algorithm.version || 1989) % 100) : '') + '-' +
+            (this.blockLength === 64 ? '' : this.blockLength + '-') +
+            ((algorithm.mode === 'MAC') ? 'MAC-' + (algorithm.macLength || this.blockLength >> 1) :
+                    (algorithm.mode === 'KW' || algorithm.keyWrapping) ?
+                    ((algorithm.keyWrapping || 'NO') !== 'NO' ? algorithm.keyWrapping : '') + 'KW' :
+                    (algorithm.block || 'ECB') + ((algorithm.block === 'CFB' || algorithm.block === 'OFB' ||
+                    (algorithm.block === 'CTR' && algorithm.version === 2015)) &&
+                    algorithm.shiftBits && algorithm.shiftBits !== this.blockLength ? '-' + algorithm.shiftBits : '') +
+                    (algorithm.padding ? '-' + (algorithm.padding || (algorithm.block === 'CTR' ||
+                            algorithm.block === 'CFB' || algorithm.block === 'OFB' ? 'NO' : 'ZERO')) + 'PADDING' : '') +
+                    ((algorithm.keyMeshing || 'NO') !== 'NO' ? '-CPKEYMESHING' : '')) +
+            (algorithm.procreator ? '/' + algorithm.procreator : '') +
+            (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : '');
+
+    // Algorithm procreator
+    this.procreator = algorithm.procreator;
+    
+    switch (algorithm.version || 1989) {
+        case 1:
+            this.process = processRC2;
+            this.keySchedule = keyScheduleRC2;
+            this.blockLength = 64;
+            this.effectiveLength = algorithm.length || 32;
+            this.keySize = 8 * Math.ceil(this.effectiveLength / 8); // Max 128
+            this.blockSize = this.blockLength >> 3;
+            break;
+        case 2015:
+            this.version = 2015;
+            if (this.blockLength === 64) {
+                this.process = process15;
+                this.keySchedule = keySchedule15;
+            } else if (this.blockLength === 128) {
+                this.process = process128;
+                this.keySchedule = keySchedule128;
+            } else
+                throw new DataError('Invalid block length');
+            this.processMAC = processMAC15;
+            break;
+        case 1989:
+            this.version = 1989;
+            this.process = process89;
+            this.processMAC = processMAC89;
+            this.keySchedule = keySchedule89;
+            if (this.blockLength !== 64)
+                throw new DataError('Invalid block length');
+            break;
+        default:
+            throw new NotSupportedError('Algorithm version ' + algorithm.version + ' not supported');
+    }
+
+    switch (algorithm.mode || (algorithm.keyWrapping && 'KW') || 'ES') {
+
+        case 'ES':
+            switch (algorithm.block || 'ECB') {
+                case 'ECB':
+                    this.encrypt = encryptECB;
+                    this.decrypt = decryptECB;
+                    break;
+                case 'CTR':
+                    if (this.version === 1989) {
+                        this.encrypt = processCTR89;
+                        this.decrypt = processCTR89;
+                    } else {
+                        this.encrypt = processCTR15;
+                        this.decrypt = processCTR15;
+                        this.shiftBits = algorithm.shiftBits || this.blockLength;
+                    }
+                    break
+                case 'CBC':
+                    this.encrypt = encryptCBC;
+                    this.decrypt = decryptCBC;
+                    break
+                case 'CFB':
+                    this.encrypt = encryptCFB;
+                    this.decrypt = decryptCFB;
+                    this.shiftBits = algorithm.shiftBits || this.blockLength;
+                    break;
+                case 'OFB':
+                    this.encrypt = processOFB;
+                    this.decrypt = processOFB;
+                    this.shiftBits = algorithm.shiftBits || this.blockLength;
+                    break;
+                default:
+                    throw new NotSupportedError('Block mode ' + algorithm.block + ' not supported');
+            }
+            switch (algorithm.keyMeshing) {
+                case 'CP':
+                    this.keyMeshing = keyMeshingCP;
+                    break;
+                default:
+                    this.keyMeshing = noKeyMeshing;
+            }
+            if (this.encrypt === encryptECB || this.encrypt === encryptCBC) {
+                switch (algorithm.padding) {
+                    case 'PKCS5P':
+                        this.pad = pkcs5Pad;
+                        this.unpad = pkcs5Unpad;
+                        break;
+                    case 'RANDOM':
+                        this.pad = randomPad;
+                        this.unpad = noPad;
+                        break;
+                    case 'BIT':
+                        this.pad = bitPad;
+                        this.unpad = bitUnpad;
+                        break;
+                    default:
+                        this.pad = zeroPad;
+                        this.unpad = noPad;
+                }
+            } else {
+                this.pad = noPad;
+                this.unpad = noPad;
+            }
+            this.generateKey = generateKey;
+            break;
+        case 'MAC':
+            this.sign = signMAC;
+            this.verify = verifyMAC;
+            this.generateKey = generateKey;
+            this.macLength = algorithm.macLength || (this.blockLength >> 1);
+            this.pad = noPad;
+            this.unpad = noPad;
+            this.keyMeshing = noKeyMeshing;
+            break;
+        case 'KW':
+            this.pad = noPad;
+            this.unpad = noPad;
+            this.keyMeshing = noKeyMeshing;
+            switch (algorithm.keyWrapping) {
+                case 'CP':
+                    this.wrapKey = wrapKeyCP;
+                    this.unwrapKey = unwrapKeyCP;
+                    this.generateKey = generateKey;
+                    this.shiftBits = algorithm.shiftBits || this.blockLength;
+                    break;
+                case 'SC':
+                    this.wrapKey = wrapKeySC;
+                    this.unwrapKey = unwrapKeySC;
+                    this.generateKey = generateWrappingKeySC;
+                    break;
+                default:
+                    this.wrapKey = wrapKeyGOST;
+                    this.unwrapKey = unwrapKeyGOST;
+                    this.generateKey = generateKey;
+            }
+            break;
+        case 'MASK':
+            this.wrapKey = wrapKeyMask;
+            this.unwrapKey = unwrapKeyMask;
+            this.generateKey = generateKey;
+            break;
+        default:
+            throw new NotSupportedError('Mode ' + algorithm.mode + ' not supported');
+    }
+
+    // Define sBox parameter
+    var sBox = algorithm.sBox, sBoxName;
+    if (!sBox)
+        sBox = this.version === 2015 ? sBoxes['E-Z'] : this.procreator === 'SC' ? sBoxes['E-SC'] : sBoxes['E-A'];
+    else if (typeof sBox === 'string') {
+        sBoxName = sBox.toUpperCase();
+        sBox = sBoxes[sBoxName];
+        if (!sBox)
+            throw new SyntaxError('Unknown sBox name: ' + algorithm.sBox);
+    } else if (!sBox.length || sBox.length !== sBoxes['E-Z'].length)
+        throw new SyntaxError('Length of sBox must be ' + sBoxes['E-Z'].length);
+    this.sBox = sBox;
+    // Initial vector
+    if (algorithm.iv) {
+        this.iv = new Uint8Array(algorithm.iv);
+        if (this.iv.byteLength !== this.blockSize && this.version === 1989)
+            throw new SyntaxError('Length of iv must be ' + this.blockLength + ' bits');
+        else if (this.iv.byteLength !== this.blockSize >> 1 && this.encrypt === processCTR15)
+            throw new SyntaxError('Length of iv must be ' + this.blockLength >> 1 + ' bits');
+        else if (this.iv.byteLength % this.blockSize !== 0 && this.encrypt !== processCTR15)
+            throw new SyntaxError('Length of iv must be a multiple of ' + this.blockLength + ' bits');
+    } else
+        this.iv = this.blockLength === 128 ? defaultIV128 : defaultIV;
+    // User key material
+    if (algorithm.ukm) {
+        this.ukm = new Uint8Array(algorithm.ukm);
+        if (this.ukm.byteLength * 8 !== this.blockLength)
+            throw new SyntaxError('Length of ukm must be ' + this.blockLength + ' bits');
+    }
+} // </editor-fold>
+
+export default GostCipher;

+ 1160 - 0
src/core/vendor/gost/gostCoding.mjs

@@ -0,0 +1,1160 @@
+/**
+ * Coding algorithms: Base64, Hex, Int16, Chars, BER and PEM
+ * version 1.76
+ * 2014-2016, Rudolf Nickolaev. All rights reserved.
+ * 
+ * Exported for CyberChef by mshwed [m@ttshwed.com]
+ */
+
+/*
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * THIS SOfTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES Of MERCHANTABILITY AND fITNESS fOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * fOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT Of SUBSTITUTE GOODS OR
+ * SERVICES; LOSS Of USE, DATA, OR PROfITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY Of LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT Of THE USE
+ * Of THIS SOfTWARE, EVEN If ADVISED Of THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+import gostCrypto from './gostCrypto';
+
+/**
+ * The Coding interface provides string converting methods: Base64, Hex, 
+ * Int16, Chars, BER and PEM
+ * @class GostCoding
+ * 
+ */ // <editor-fold defaultstate="collapsed">
+var root = {};
+var DataError = Error;
+var CryptoOperationData = ArrayBuffer;
+var Date = Date;
+
+function buffer(d) {
+    if (d instanceof CryptoOperationData)
+        return d;
+    else if (d && d.buffer && d.buffer instanceof CryptoOperationData)
+        return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ?
+                d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;
+    else
+        throw new DataError('CryptoOperationData required');
+} // </editor-fold>
+
+function GostCoding() {
+}
+
+/**
+ * BASE64 conversion
+ * 
+ * @class GostCoding.Base64
+ */
+var Base64 = {// <editor-fold defaultstate="collapsed">
+    /**
+     * Base64.decode convert BASE64 string s to CryptoOperationData
+     * 
+     * @memberOf GostCoding.Base64
+     * @param {String} s BASE64 encoded string value
+     * @returns {CryptoOperationData} Binary decoded data
+     */
+    decode: function (s) {
+        s = s.replace(/[^A-Za-z0-9\+\/]/g, '');
+        var n = s.length,
+                k = n * 3 + 1 >> 2, r = new Uint8Array(k);
+
+        for (var m3, m4, u24 = 0, j = 0, i = 0; i < n; i++) {
+            m4 = i & 3;
+            var c = s.charCodeAt(i);
+
+            c = c > 64 && c < 91 ?
+                    c - 65 : c > 96 && c < 123 ?
+                    c - 71 : c > 47 && c < 58 ?
+                    c + 4 : c === 43 ?
+                    62 : c === 47 ?
+                    63 : 0;
+
+            u24 |= c << 18 - 6 * m4;
+            if (m4 === 3 || n - i === 1) {
+                for (m3 = 0; m3 < 3 && j < k; m3++, j++) {
+                    r[j] = u24 >>> (16 >>> m3 & 24) & 255;
+                }
+                u24 = 0;
+
+            }
+        }
+        return r.buffer;
+    },
+    /**
+     * Base64.encode(data) convert CryptoOperationData data to BASE64 string
+     * 
+     * @memberOf GostCoding.Base64
+     * @param {CryptoOperationData} data Bynary data for encoding
+     * @returns {String} BASE64 encoded data
+     */
+    encode: function (data) {
+        var slen = 8, d = new Uint8Array(buffer(data));
+        var m3 = 2, s = '';
+        for (var n = d.length, u24 = 0, i = 0; i < n; i++) {
+            m3 = i % 3;
+            if (i > 0 && (i * 4 / 3) % (12 * slen) === 0)
+                s += '\r\n';
+            u24 |= d[i] << (16 >>> m3 & 24);
+            if (m3 === 2 || n - i === 1) {
+                for (var j = 18; j >= 0; j -= 6) {
+                    var c = u24 >>> j & 63;
+                    c = c < 26 ? c + 65 : c < 52 ? c + 71 : c < 62 ? c - 4 :
+                            c === 62 ? 43 : c === 63 ? 47 : 65;
+                    s += String.fromCharCode(c);
+                }
+                u24 = 0;
+            }
+        }
+        return s.substr(0, s.length - 2 + m3) + (m3 === 2 ? '' : m3 === 1 ? '=' : '==');
+    } // </editor-fold>
+};
+
+/**
+ * BASE64 conversion
+ * 
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.Base64
+ */
+GostCoding.prototype.Base64 = Base64;
+
+/**
+ * Text string conversion <br>
+ * Methods support charsets: ascii, win1251, utf8, utf16 (ucs2, unicode), utf32 (ucs4)
+ * 
+ * @class GostCoding.Chars
+ */
+var Chars = (function () { // <editor-fold defaultstate="collapsed">
+
+    var _win1251_ = {
+        0x402: 0x80, 0x403: 0x81, 0x201A: 0x82, 0x453: 0x83, 0x201E: 0x84, 0x2026: 0x85, 0x2020: 0x86, 0x2021: 0x87,
+        0x20AC: 0x88, 0x2030: 0x89, 0x409: 0x8A, 0x2039: 0x8B, 0x40A: 0x8C, 0x40C: 0x8D, 0x40B: 0x8E, 0x40f: 0x8f,
+        0x452: 0x90, 0x2018: 0x91, 0x2019: 0x92, 0x201C: 0x93, 0x201D: 0x94, 0x2022: 0x95, 0x2013: 0x96, 0x2014: 0x97,
+        0x2122: 0x99, 0x459: 0x9A, 0x203A: 0x9B, 0x45A: 0x9C, 0x45C: 0x9D, 0x45B: 0x9E, 0x45f: 0x9f,
+        0xA0: 0xA0, 0x40E: 0xA1, 0x45E: 0xA2, 0x408: 0xA3, 0xA4: 0xA4, 0x490: 0xA5, 0xA6: 0xA6, 0xA7: 0xA7,
+        0x401: 0xA8, 0xA9: 0xA9, 0x404: 0xAA, 0xAB: 0xAB, 0xAC: 0xAC, 0xAD: 0xAD, 0xAE: 0xAE, 0x407: 0xAf,
+        0xB0: 0xB0, 0xB1: 0xB1, 0x406: 0xB2, 0x456: 0xB3, 0x491: 0xB4, 0xB5: 0xB5, 0xB6: 0xB6, 0xB7: 0xB7,
+        0x451: 0xB8, 0x2116: 0xB9, 0x454: 0xBA, 0xBB: 0xBB, 0x458: 0xBC, 0x405: 0xBD, 0x455: 0xBE, 0x457: 0xBf
+    };
+    var _win1251back_ = {};
+    for (var from in _win1251_) {
+        var to = _win1251_[from];
+        _win1251back_[to] = from;
+    }
+
+    return {
+        /**
+         * Chars.decode(s, charset) convert string s with defined charset to CryptoOperationData 
+         * 
+         * @memberOf GostCoding.Chars
+         * @param {string} s Javascript string
+         * @param {string} charset Charset, default 'win1251'
+         * @returns {CryptoOperationData} Decoded binary data
+         */
+        decode: function (s, charset) {
+            charset = (charset || 'win1251').toLowerCase().replace('-', '');
+            var r = [];
+            for (var i = 0, j = s.length; i < j; i++) {
+                var c = s.charCodeAt(i);
+                if (charset === 'utf8') {
+                    if (c < 0x80) {
+                        r.push(c);
+                    } else if (c < 0x800) {
+                        r.push(0xc0 + (c >>> 6));
+                        r.push(0x80 + (c & 63));
+                    } else if (c < 0x10000) {
+                        r.push(0xe0 + (c >>> 12));
+                        r.push(0x80 + (c >>> 6 & 63));
+                        r.push(0x80 + (c & 63));
+                    } else if (c < 0x200000) {
+                        r.push(0xf0 + (c >>> 18));
+                        r.push(0x80 + (c >>> 12 & 63));
+                        r.push(0x80 + (c >>> 6 & 63));
+                        r.push(0x80 + (c & 63));
+                    } else if (c < 0x4000000) {
+                        r.push(0xf8 + (c >>> 24));
+                        r.push(0x80 + (c >>> 18 & 63));
+                        r.push(0x80 + (c >>> 12 & 63));
+                        r.push(0x80 + (c >>> 6 & 63));
+                        r.push(0x80 + (c & 63));
+                    } else {
+                        r.push(0xfc + (c >>> 30));
+                        r.push(0x80 + (c >>> 24 & 63));
+                        r.push(0x80 + (c >>> 18 & 63));
+                        r.push(0x80 + (c >>> 12 & 63));
+                        r.push(0x80 + (c >>> 6 & 63));
+                        r.push(0x80 + (c & 63));
+                    }
+                } else if (charset === 'unicode' || charset === 'ucs2' || charset === 'utf16') {
+                    if (c < 0xD800 || (c >= 0xE000 && c <= 0x10000)) {
+                        r.push(c >>> 8);
+                        r.push(c & 0xff);
+                    } else if (c >= 0x10000 && c < 0x110000) {
+                        c -= 0x10000;
+                        var first = ((0xffc00 & c) >> 10) + 0xD800;
+                        var second = (0x3ff & c) + 0xDC00;
+                        r.push(first >>> 8);
+                        r.push(first & 0xff);
+                        r.push(second >>> 8);
+                        r.push(second & 0xff);
+                    }
+                } else if (charset === 'utf32' || charset === 'ucs4') {
+                    r.push(c >>> 24 & 0xff);
+                    r.push(c >>> 16 & 0xff);
+                    r.push(c >>> 8 & 0xff);
+                    r.push(c & 0xff);
+                } else if (charset === 'win1251') {
+                    if (c >= 0x80) {
+                        if (c >= 0x410 && c < 0x450) // А..Яа..я
+                            c -= 0x350;
+                        else
+                            c = _win1251_[c] || 0;
+                    }
+                    r.push(c);
+                } else
+                    r.push(c & 0xff);
+            }
+            return new Uint8Array(r).buffer;
+        },
+        /**
+         * Chars.encode(data, charset) convert CryptoOperationData data to string with defined charset
+         * 
+         * @memberOf GostCoding.Chars
+         * @param {CryptoOperationData} data Binary data
+         * @param {string} charset Charset, default win1251
+         * @returns {string} Encoded javascript string
+         */
+        encode: function (data, charset) {
+            charset = (charset || 'win1251').toLowerCase().replace('-', '');
+            var r = [], d = new Uint8Array(buffer(data));
+            for (var i = 0, n = d.length; i < n; i++) {
+                var c = d[i];
+                if (charset === 'utf8') {
+                    c = c >= 0xfc && c < 0xfe && i + 5 < n ? // six bytes
+                            (c - 0xfc) * 1073741824 + (d[++i] - 0x80 << 24) + (d[++i] - 0x80 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80
+                            : c >> 0xf8 && c < 0xfc && i + 4 < n ? // five bytes 
+                            (c - 0xf8 << 24) + (d[++i] - 0x80 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80
+                            : c >> 0xf0 && c < 0xf8 && i + 3 < n ? // four bytes 
+                            (c - 0xf0 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80
+                            : c >= 0xe0 && c < 0xf0 && i + 2 < n ? // three bytes 
+                            (c - 0xe0 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80
+                            : c >= 0xc0 && c < 0xe0 && i + 1 < n ? // two bytes 
+                            (c - 0xc0 << 6) + d[++i] - 0x80
+                            : c; // one byte 
+                } else if (charset === 'unicode' || charset === 'ucs2' || charset === 'utf16') {
+                    c = (c << 8) + d[++i];
+                    if (c >= 0xD800 && c < 0xE000) {
+                        var first = (c - 0xD800) << 10;
+                        c = d[++i];
+                        c = (c << 8) + d[++i];
+                        var second = c - 0xDC00;
+                        c = first + second + 0x10000;
+                    }
+                } else if (charset === 'utf32' || charset === 'ucs4') {
+                    c = (c << 8) + d[++i];
+                    c = (c << 8) + d[++i];
+                    c = (c << 8) + d[++i];
+                } else if (charset === 'win1251') {
+                    if (c >= 0x80) {
+                        if (c >= 0xC0 && c < 0x100)
+                            c += 0x350; // А..Яа..я
+                        else
+                            c = _win1251back_[c] || 0;
+                    }
+                }
+                r.push(String.fromCharCode(c));
+            }
+            return r.join('');
+        }
+    }; // </editor-fold>
+})();
+
+/**
+ * Text string conversion
+ * 
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.Chars
+ */
+GostCoding.prototype.Chars = Chars;
+
+/**
+ * HEX conversion
+ * 
+ * @class GostCoding.Hex
+ */
+var Hex = {// <editor-fold defaultstate="collapsed">
+    /**
+     * Hex.decode(s, endean) convert HEX string s to CryptoOperationData in endean mode
+     * 
+     * @memberOf GostCoding.Hex
+     * @param {string} s Hex encoded string
+     * @param {boolean} endean Little or Big Endean, default Little
+     * @returns {CryptoOperationData} Decoded binary data
+     */
+    decode: function (s, endean) {
+        s = s.replace(/[^A-fa-f0-9]/g, '');
+        var n = Math.ceil(s.length / 2), r = new Uint8Array(n);
+        s = (s.length % 2 > 0 ? '0' : '') + s;
+        if (endean && ((typeof endean !== 'string') ||
+                (endean.toLowerCase().indexOf('little') < 0)))
+            for (var i = 0; i < n; i++)
+                r[i] = parseInt(s.substr((n - i - 1) * 2, 2), 16);
+        else
+            for (var i = 0; i < n; i++)
+                r[i] = parseInt(s.substr(i * 2, 2), 16);
+        return r.buffer;
+    },
+    /**
+     * Hex.encode(data, endean) convert CryptoOperationData data to HEX string in endean mode
+     * 
+     * @memberOf GostCoding.Hex 
+     * @param {CryptoOperationData} data Binary data
+     * @param {boolean} endean Little/Big Endean, default Little
+     * @returns {string} Hex decoded string
+     */
+    encode: function (data, endean) {
+        var s = [], d = new Uint8Array(buffer(data)), n = d.length;
+        if (endean && ((typeof endean !== 'string') ||
+                (endean.toLowerCase().indexOf('little') < 0)))
+            for (var i = 0; i < n; i++) {
+                var j = n - i - 1;
+                s[j] = (j > 0 && j % 32 === 0 ? '\r\n' : '') +
+                        ('00' + d[i].toString(16)).slice(-2);
+            }
+        else
+            for (var i = 0; i < n; i++)
+                s[i] = (i > 0 && i % 32 === 0 ? '\r\n' : '') +
+                        ('00' + d[i].toString(16)).slice(-2);
+        return s.join('');
+    } // </editor-fold>
+};
+
+/**
+ *  HEX conversion
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.Hex
+ */
+GostCoding.prototype.Hex = Hex;
+
+/**
+ * String hex-encoded integer conversion
+ * 
+ * @class GostCoding.Int16
+ */
+var Int16 = {// <editor-fold defaultstate="collapsed">
+    /**
+     * Int16.decode(s) convert hex big insteger s to CryptoOperationData
+     * 
+     * @memberOf GostCoding.Int16 
+     * @param {string} s Int16 string 
+     * @returns {CryptoOperationData} Decoded binary data
+     */
+    decode: function (s) {
+        s = (s || '').replace(/[^\-A-fa-f0-9]/g, '');
+        if (s.length === 0)
+            s = '0';
+        // Signature
+        var neg = false;
+        if (s.charAt(0) === '-') {
+            neg = true;
+            s = s.substring(1);
+        }
+        // Align 2 chars
+        while (s.charAt(0) === '0' && s.length > 1)
+            s = s.substring(1);
+        s = (s.length % 2 > 0 ? '0' : '') + s;
+        // Padding for singanuture
+        // '800000' - 'ffffff' - for positive
+        // '800001' - 'ffffff' - for negative
+        if ((!neg && !/^[0-7]/.test(s)) ||
+                (neg && !/^[0-7]|8[0]+$/.test(s)))
+            s = '00' + s;
+        // Convert hex
+        var n = s.length / 2, r = new Uint8Array(n), t = 0;
+        for (var i = n - 1; i >= 0; --i) {
+            var c = parseInt(s.substr(i * 2, 2), 16);
+            if (neg && (c + t > 0)) {
+                c = 256 - c - t;
+                t = 1;
+            }
+            r[i] = c;
+        }
+        return r.buffer;
+    },
+    /**
+     * Int16.encode(data) convert CryptoOperationData data to big integer hex string
+     * 
+     * @memberOf GostCoding.Int16
+     * @param {CryptoOperationData} data Binary data
+     * @returns {string} Int16 encoded string
+     */
+    encode: function (data) {
+        var d = new Uint8Array(buffer(data)), n = d.length;
+        if (d.length === 0)
+            return '0x00';
+        var s = [], neg = d[0] > 0x7f, t = 0;
+        for (var i = n - 1; i >= 0; --i) {
+            var v = d[i];
+            if (neg && (v + t > 0)) {
+                v = 256 - v - t;
+                t = 1;
+            }
+            s[i] = ('00' + v.toString(16)).slice(-2);
+        }
+        s = s.join('');
+        while (s.charAt(0) === '0')
+            s = s.substring(1);
+        return (neg ? '-' : '') + '0x' + s;
+    } // </editor-fold>
+};
+
+/**
+ * String hex-encoded integer conversion
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.Int16
+ */
+GostCoding.prototype.Int16 = Int16;
+
+/**
+ * BER, DER, CER conversion
+ * 
+ * @class GostCoding.BER
+ */
+var BER = (function () { // <editor-fold defaultstate="collapsed">
+
+    // Predefenition block
+    function encodeBER(source, format, onlyContent) {
+        // Correct primitive type
+        var object = source.object;
+        if (object === undefined)
+            object = source;
+
+        // Determinate tagClass
+        var tagClass = source.tagClass = source.tagClass || 0; // Universial default
+
+        // Determinate tagNumber. Use only for Universal class
+        if (tagClass === 0) {
+            var tagNumber = source.tagNumber;
+            if (typeof tagNumber === 'undefined') {
+                if (typeof object === 'string') {
+                    if (object === '')   // NULL
+                        tagNumber = 0x05;
+                    else if (/^\-?0x[0-9a-fA-F]+$/.test(object)) // INTEGER
+                        tagNumber = 0x02;
+                    else if (/^(\d+\.)+\d+$/.test(object)) // OID
+                        tagNumber = 0x06;
+                    else if (/^[01]+$/.test(object)) // BIT STRING
+                        tagNumber = 0x03;
+                    else if (/^(true|false)$/.test(object)) // BOOLEAN
+                        tagNumber = 0x01;
+                    else if (/^[0-9a-fA-F]+$/.test(object)) // OCTET STRING
+                        tagNumber = 0x04;
+                    else
+                        tagNumber = 0x13; // Printable string (later can be changed to UTF8String)
+                } else if (typeof object === 'number') { // INTEGER
+                    tagNumber = 0x02;
+                } else if (typeof object === 'boolean') { // BOOLEAN
+                    tagNumber = 0x01;
+                } else if (object instanceof Array) { // SEQUENCE
+                    tagNumber = 0x10;
+                } else if (object instanceof Date) { // GeneralizedTime
+                    tagNumber = 0x18;
+                } else if (object instanceof CryptoOperationData || (object && object.buffer instanceof CryptoOperationData)) {
+                    tagNumber = 0x04;
+                } else
+                    throw new DataError('Unrecognized type for ' + object);
+            }
+        }
+
+        // Determinate constructed
+        var tagConstructed = source.tagConstructed;
+        if (typeof tagConstructed === 'undefined')
+            tagConstructed = source.tagConstructed = object instanceof Array;
+
+        // Create content
+        var content;
+        if (object instanceof CryptoOperationData || (object && object.buffer instanceof CryptoOperationData)) { // Direct
+            content = new Uint8Array(buffer(object));
+            if (tagNumber === 0x03) { // BITSTRING
+                // Set unused bits
+                var a = new Uint8Array(buffer(content));
+                content = new Uint8Array(a.length + 1);
+                content[0] = 0; // No unused bits
+                content.set(a, 1);
+            }
+        } else if (tagConstructed) { // Sub items coding
+            if (object instanceof Array) {
+                var bytelen = 0, ba = [], offset = 0;
+                for (var i = 0, n = object.length; i < n; i++) {
+                    ba[i] = encodeBER(object[i], format);
+                    bytelen += ba[i].length;
+                }
+                if (tagNumber === 0x11)
+                    ba.sort(function (a, b) { // Sort order for SET components
+                        for (var i = 0, n = Math.min(a.length, b.length); i < n; i++) {
+                            var r = a[i] - b[i];
+                            if (r !== 0)
+                                return r;
+                        }
+                        return a.length - b.length;
+                    });
+                if (format === 'CER') { // final for CER 00 00
+                    ba[n] = new Uint8Array(2);
+                    bytelen += 2;
+                }
+                content = new Uint8Array(bytelen);
+                for (var i = 0, n = ba.length; i < n; i++) {
+                    content.set(ba[i], offset);
+                    offset = offset + ba[i].length;
+                }
+            } else
+                throw new DataError('Constracted block can\'t be primitive');
+        } else {
+            switch (tagNumber) {
+                // 0x00: // EOC
+                case 0x01: // BOOLEAN
+                    content = new Uint8Array(1);
+                    content[0] = object ? 0xff : 0;
+                    break;
+                case 0x02: // INTEGER
+                case 0x0a: // ENUMIRATED
+                    content = Int16.decode(
+                            typeof object === 'number' ? object.toString(16) : object);
+                    break;
+                case 0x03: // BIT STRING
+                    if (typeof object === 'string') {
+                        var unusedBits = 7 - (object.length + 7) % 8;
+                        var n = Math.ceil(object.length / 8);
+                        content = new Uint8Array(n + 1);
+                        content[0] = unusedBits;
+                        for (var i = 0; i < n; i++) {
+                            var c = 0;
+                            for (var j = 0; j < 8; j++) {
+                                var k = i * 8 + j;
+                                c = (c << 1) + (k < object.length ? (object.charAt(k) === '1' ? 1 : 0) : 0);
+                            }
+                            content[i + 1] = c;
+                        }
+                    }
+                    break;
+                case 0x04:
+                    content = Hex.decode(
+                            typeof object === 'number' ? object.toString(16) : object);
+                    break;
+                    // case 0x05: // NULL
+                case 0x06: // OBJECT IDENTIFIER
+                    var a = object.match(/\d+/g), r = [];
+                    for (var i = 1; i < a.length; i++) {
+                        var n = +a[i], r1 = [];
+                        if (i === 1)
+                            n = n + a[0] * 40;
+                        do {
+                            r1.push(n & 0x7F);
+                            n = n >>> 7;
+                        } while (n);
+                        // reverse order
+                        for (j = r1.length - 1; j >= 0; --j)
+                            r.push(r1[j] + (j === 0 ? 0x00 : 0x80));
+                    }
+                    content = new Uint8Array(r);
+                    break;
+                    // case 0x07: // ObjectDescriptor
+                    // case 0x08: // EXTERNAL
+                    // case 0x09: // REAL
+                    // case 0x0A: // ENUMERATED
+                    // case 0x0B: // EMBEDDED PDV
+                case 0x0C: // UTF8String
+                    content = Chars.decode(object, 'utf8');
+                    break;
+                    // case 0x10: // SEQUENCE
+                    // case 0x11: // SET
+                case 0x12: // NumericString
+                case 0x16: // IA5String // ASCII
+                case 0x13: // PrintableString // ASCII subset
+                case 0x14: // TeletexString // aka T61String
+                case 0x15: // VideotexString
+                case 0x19: // GraphicString
+                case 0x1A: // VisibleString // ASCII subset
+                case 0x1B: // GeneralString
+                    // Reflect on character encoding
+                    for (var i = 0, n = object.length; i < n; i++)
+                        if (object.charCodeAt(i) > 255)
+                            tagNumber = 0x0C;
+                    if (tagNumber === 0x0C)
+                        content = Chars.decode(object, 'utf8');
+                    else
+                        content = Chars.decode(object, 'ascii');
+                    break;
+                case 0x17: // UTCTime
+                case 0x18: // GeneralizedTime
+                    var result = object.original;
+                    if (!result) {
+                        var date = new Date(object);
+                        date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); // to UTC
+                        var ms = tagNumber === 0x18 ? date.getMilliseconds().toString() : ''; // Milliseconds, remove trailing zeros
+                        while (ms.length > 0 && ms.charAt(ms.length - 1) === '0')
+                            ms = ms.substring(0, ms.length - 1);
+                        if (ms.length > 0)
+                            ms = '.' + ms;
+                        result = (tagNumber === 0x17 ? date.getYear().toString().slice(-2) : date.getFullYear().toString()) +
+                                ('00' + (date.getMonth() + 1)).slice(-2) +
+                                ('00' + date.getDate()).slice(-2) +
+                                ('00' + date.getHours()).slice(-2) +
+                                ('00' + date.getMinutes()).slice(-2) +
+                                ('00' + date.getSeconds()).slice(-2) + ms + 'Z';
+                    }
+                    content = Chars.decode(result, 'ascii');
+                    break;
+                case 0x1C: // UniversalString
+                    content = Chars.decode(object, 'utf32');
+                    break;
+                case 0x1E: // BMPString
+                    content = Chars.decode(object, 'utf16');
+                    break;
+            }
+        }
+
+        if (!content)
+            content = new Uint8Array(0);
+        if (content instanceof CryptoOperationData)
+            content = new Uint8Array(content);
+
+        if (!tagConstructed && format === 'CER') {
+            // Encoding CER-form for string types
+            var k;
+            switch (tagNumber) {
+                case 0x03: // BIT_STRING
+                    k = 1; // ingnore unused bit for bit string
+                case 0x04: // OCTET_STRING
+                case 0x0C: // UTF8String
+                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
+                case 0x1E: // BMPString
+                    k = k || 0;
+                    // Split content on 1000 octet len parts 
+                    var size = 1000;
+                    var bytelen = 0, ba = [], offset = 0;
+                    for (var i = k, n = content.length; i < n; i += size - k) {
+                        ba[i] = encodeBER({
+                            object: new Unit8Array(content.buffer, i, Math.min(size - k, n - i)),
+                            tagNumber: tagNumber,
+                            tagClass: 0,
+                            tagConstructed: false
+                        }, format);
+                        bytelen += ba[i].length;
+                    }
+                    ba[n] = new Uint8Array(2); // final for CER 00 00
+                    bytelen += 2;
+                    content = new Uint8Array(bytelen);
+                    for (var i = 0, n = ba.length; i < n; i++) {
+                        content.set(ba[i], offset);
+                        offset = offset + ba[i].length;
+                    }
+            }
+        }
+
+        // Restore tagNumber for all classes
+        if (tagClass === 0)
+            source.tagNumber = tagNumber;
+        else
+            source.tagNumber = tagNumber = source.tagNumber || 0;
+        source.content = content;
+
+        if (onlyContent)
+            return content;
+
+        // Create header
+        // tagNumber
+        var ha = [], first = tagClass === 3 ? 0xC0 : tagClass === 2 ? 0x80 :
+                tagClass === 1 ? 0x40 : 0x00;
+        if (tagConstructed)
+            first |= 0x20;
+        if (tagNumber < 0x1F) {
+            first |= tagNumber & 0x1F;
+            ha.push(first);
+        } else {
+            first |= 0x1F;
+            ha.push(first);
+            var n = tagNumber, ha1 = [];
+            do {
+                ha1.push(n & 0x7F);
+                n = n >>> 7;
+            } while (n)
+            // reverse order
+            for (var j = ha1.length - 1; j >= 0; --j)
+                ha.push(ha1[j] + (j === 0 ? 0x00 : 0x80));
+        }
+        // Length
+        if (tagConstructed && format === 'CER') {
+            ha.push(0x80);
+        } else {
+            var len = content.length;
+            if (len > 0x7F) {
+                var l2 = len, ha2 = [];
+                do {
+                    ha2.push(l2 & 0xff);
+                    l2 = l2 >>> 8;
+                } while (l2);
+                ha.push(ha2.length + 0x80); // reverse order
+                for (var j = ha2.length - 1; j >= 0; --j)
+                    ha.push(ha2[j]);
+            } else {
+                // simple len
+                ha.push(len);
+            }
+        }
+        var header = source.header = new Uint8Array(ha);
+
+        // Result - complete buffer
+        var block = new Uint8Array(header.length + content.length);
+        block.set(header, 0);
+        block.set(content, header.length);
+        return block;
+    }
+
+    function decodeBER(source, offset) {
+
+        // start pos
+        var pos = offset || 0, start = pos;
+        var tagNumber, tagClass, tagConstructed,
+                content, header, buffer, sub, len;
+
+        if (source.object) {
+            // Ready from source
+            tagNumber = source.tagNumber;
+            tagClass = source.tagClass;
+            tagConstructed = source.tagConstructed;
+            content = source.content;
+            header = source.header;
+            buffer = source.object instanceof CryptoOperationData ?
+                    new Uint8Array(source.object) : null;
+            sub = source.object instanceof Array ? source.object : null;
+            len = buffer && buffer.length || null;
+        } else {
+            // Decode header
+            var d = source;
+
+            // Read tag
+            var buf = d[pos++];
+            tagNumber = buf & 0x1f;
+            tagClass = buf >> 6;
+            tagConstructed = (buf & 0x20) !== 0;
+            if (tagNumber === 0x1f) { // long tag
+                tagNumber = 0;
+                do {
+                    if (tagNumber > 0x1fffffffffff80)
+                        throw new DataError('Convertor not supported tag number more then (2^53 - 1) at position ' + offset);
+                    buf = d[pos++];
+                    tagNumber = (tagNumber << 7) + (buf & 0x7f);
+                } while (buf & 0x80);
+            }
+
+            // Read len        
+            buf = d[pos++];
+            len = buf & 0x7f;
+            if (len !== buf) {
+                if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
+                    throw new DataError('Length over 48 bits not supported at position ' + offset);
+                if (len === 0)
+                    len = null; // undefined
+                else {
+                    buf = 0;
+                    for (var i = 0; i < len; ++i)
+                        buf = (buf << 8) + d[pos++];
+                    len = buf;
+                }
+            }
+
+            start = pos;
+            sub = null;
+
+            if (tagConstructed) {
+                // must have valid content
+                sub = [];
+                if (len !== null) {
+                    // definite length
+                    var end = start + len;
+                    while (pos < end) {
+                        var s = decodeBER(d, pos);
+                        sub.push(s);
+                        pos += s.header.length + s.content.length;
+                    }
+                    if (pos !== end)
+                        throw new DataError('Content size is not correct for container starting at offset ' + start);
+                } else {
+                    // undefined length
+                    try {
+                        for (; ; ) {
+                            var s = decodeBER(d, pos);
+                            pos += s.header.length + s.content.length;
+                            if (s.tagClass === 0x00 && s.tagNumber === 0x00)
+                                break;
+                            sub.push(s);
+                        }
+                        len = pos - start;
+                    } catch (e) {
+                        throw new DataError('Exception ' + e + ' while decoding undefined length content at offset ' + start);
+                    }
+                }
+            }
+
+            // Header and content
+            header = new Uint8Array(d.buffer, offset, start - offset);
+            content = new Uint8Array(d.buffer, start, len);
+            buffer = content;
+        }
+
+        // Constructed types - check for string concationation
+        if (sub !== null && tagClass === 0) {
+            var k;
+            switch (tagNumber) {
+                case 0x03: // BIT_STRING
+                    k = 1; // ingnore unused bit for bit string
+                case 0x04: // OCTET_STRING
+                case 0x0C: // UTF8String
+                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
+                case 0x1E: // BMPString
+                    k = k || 0;
+                    // Concatination
+                    if (sub.length === 0)
+                        throw new DataError('No constructed encoding content of string type at offset ' + start);
+                    len = k;
+                    for (var i = 0, n = sub.length; i < n; i++) {
+                        var s = sub[i];
+                        if (s.tagClass !== tagClass || s.tagNumber !== tagNumber || s.tagConstructed)
+                            throw new DataError('Invalid constructed encoding of string type at offset ' + start);
+                        len += s.content.length - k;
+                    }
+                    buffer = new Uint8Array(len);
+                    for (var i = 0, n = sub.length, j = k; i < n; i++) {
+                        var s = sub[i];
+                        if (k > 0)
+                            buffer.set(s.content.subarray(1), j);
+                        else
+                            buffer.set(s.content, j);
+                        j += s.content.length - k;
+                    }
+                    tagConstructed = false; // follow not required
+                    sub = null;
+                    break;
+            }
+        }
+        // Primitive types
+        var object = '';
+        if (sub === null) {
+            if (len === null)
+                throw new DataError('Invalid tag with undefined length at offset ' + start);
+
+            if (tagClass === 0) {
+                switch (tagNumber) {
+                    case 0x01: // BOOLEAN
+                        object = buffer[0] !== 0;
+                        break;
+                    case 0x02: // INTEGER
+                    case 0x0a: // ENUMIRATED
+                        if (len > 6) {
+                            object = Int16.encode(buffer);
+                        } else {
+                            var v = buffer[0];
+                            if (buffer[0] > 0x7f)
+                                v = v - 256;
+                            for (var i = 1; i < len; i++)
+                                v = v * 256 + buffer[i];
+                            object = v;
+                        }
+                        break;
+                    case 0x03: // BIT_STRING
+                        if (len > 5) { // Content buffer
+                            object = new Uint8Array(buffer.subarray(1)).buffer;
+                        } else { // Max bit mask only for 32 bit
+                            var unusedBit = buffer[0],
+                                    skip = unusedBit, s = [];
+                            for (var i = len - 1; i >= 1; --i) {
+                                var b = buffer[i];
+                                for (var j = skip; j < 8; ++j)
+                                    s.push((b >> j) & 1 ? '1' : '0');
+                                skip = 0;
+                            }
+                            object = s.reverse().join('');
+                        }
+                        break;
+                    case 0x04: // OCTET_STRING
+                        object = new Uint8Array(buffer).buffer;
+                        break;
+                        //  case 0x05: // NULL
+                    case 0x06: // OBJECT_IDENTIFIER
+                        var s = '',
+                                n = 0,
+                                bits = 0;
+                        for (var i = 0; i < len; ++i) {
+                            var v = buffer[i];
+                            n = (n << 7) + (v & 0x7F);
+                            bits += 7;
+                            if (!(v & 0x80)) { // finished
+                                if (s === '') {
+                                    var m = n < 80 ? n < 40 ? 0 : 1 : 2;
+                                    s = m + "." + (n - m * 40);
+                                } else
+                                    s += "." + n.toString();
+                                n = 0;
+                                bits = 0;
+                            }
+                        }
+                        if (bits > 0)
+                            throw new DataError('Incompleted OID at offset ' + start);
+                        object = s;
+                        break;
+                        //case 0x07: // ObjectDescriptor
+                        //case 0x08: // EXTERNAL
+                        //case 0x09: // REAL
+                        //case 0x0A: // ENUMERATED
+                        //case 0x0B: // EMBEDDED_PDV
+                    case 0x10: // SEQUENCE
+                    case 0x11: // SET
+                        object = [];
+                        break;
+                    case 0x0C: // UTF8String
+                        object = Chars.encode(buffer, 'utf8');
+                        break;
+                    case 0x12: // NumericString
+                    case 0x13: // PrintableString
+                    case 0x14: // TeletexString
+                    case 0x15: // VideotexString
+                    case 0x16: // IA5String
+                    case 0x19: // GraphicString
+                    case 0x1A: // VisibleString
+                    case 0x1B: // GeneralString
+                        object = Chars.encode(buffer, 'ascii');
+                        break;
+                    case 0x1C: // UniversalString
+                        object = Chars.encode(buffer, 'utf32');
+                        break;
+                    case 0x1E: // BMPString
+                        object = Chars.encode(buffer, 'utf16');
+                        break;
+                    case 0x17: // UTCTime
+                    case 0x18: // GeneralizedTime
+                        var shortYear = tagNumber === 0x17;
+                        var s = Chars.encode(buffer, 'ascii'),
+                                m = (shortYear ?
+                                        /^(\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)?)?$/ :
+                                        /^(\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)?)?$/).exec(s);
+                        if (!m)
+                            throw new DataError('Unrecognized time format "' + s + '" at offset ' + start);
+                        if (shortYear) {
+                            // Where YY is greater than or equal to 50, the year SHALL be interpreted as 19YY; and
+                            // Where YY is less than 50, the year SHALL be interpreted as 20YY                                
+                            m[1] = +m[1];
+                            m[1] += (m[1] < 50) ? 2000 : 1900;
+                        }
+                        var dt = new Date(m[1], +m[2] - 1, +m[3], +(m[4] || '0'), +(m[5] || '0'), +(m[6] || '0'), +(m[7] || '0')),
+                                tz = dt.getTimezoneOffset();
+                        if (m[8] || tagNumber === 0x17) {
+                            if (m[8].toUpperCase() !== 'Z' && m[9]) {
+                                tz = tz + parseInt(m[9]);
+                            }
+                            dt.setMinutes(dt.getMinutes() - tz);
+                        }
+                        dt.original = s;
+                        object = dt;
+                        break;
+                }
+            } else // OCTET_STRING
+                object = new Uint8Array(buffer).buffer;
+        } else
+            object = sub;
+
+        // result
+        return {
+            tagConstructed: tagConstructed,
+            tagClass: tagClass,
+            tagNumber: tagNumber,
+            header: header,
+            content: content,
+            object: object
+        };
+    }
+
+    return {
+        /**
+         * BER.decode(object, format) convert javascript object to ASN.1 format CryptoOperationData<br><br>
+         * If object has members tagNumber, tagClass and tagConstructed
+         * it is clear define encoding rules. Else method use defaul rules:
+         * <ul>
+         *   <li>Empty string or null - NULL</li>
+         *   <li>String starts with '0x' and has 0-9 and a-f characters - INTEGER</li>
+         *   <li>String like d.d.d.d (d - set of digits) - OBJECT IDENTIFIER</li>
+         *   <li>String with characters 0 and 1 - BIT STRING</li>
+         *   <li>Strings 'true' or 'false' - BOOLEAN</li>
+         *   <li>String has only 0-9 and a-f characters - OCTET STRING</li>
+         *   <li>String has only characters with code 0-255 - PrintableString</li>
+         *   <li>Other strings - UTF8String</li>
+         *   <li>Number - INTEGER</li>
+         *   <li>Date - GeneralizedTime</li>
+         *   <li>Boolean - SEQUENCE</li>
+         *   <li>CryptoOperationData - OCTET STRING</li>
+         * </ul>
+         * SEQUENCE or SET arrays recursively encoded for each item.<br>
+         * OCTET STRING and BIT STRING can presents as array with one item. 
+         * It means encapsulates encoding for child element.<br>
+         * 
+         * If CONTEXT or APPLICATION classes item presents as array with one 
+         * item we use EXPLICIT encoding for element, else IMPLICIT encoding.<br>
+         * 
+         * @memberOf GostCoding.BER
+         * @param {Object} object Object to encoding
+         * @param {string} format Encoding rule: 'DER' or 'CER', default 'DER'
+         * @param {boolean} onlyContent Encode content only, without header
+         * @returns {CryptoOperationData} BER encoded data
+         */
+        encode: function (object, format, onlyContent) {
+            return encodeBER(object, format, onlyContent).buffer;
+        },
+        /**
+         * BER.encode(data) convert ASN.1 format CryptoOperationData data to javascript object<br><br>
+         * 
+         * Conversion rules to javascript object:
+         *  <ul>
+         *      <li>BOOLEAN - Boolean object</li>
+         *      <li>INTEGER, ENUMIRATED - Integer object if len <= 6 (48 bits) else Int16 encoded string</li>
+         *      <li>BIT STRING - Integer object if len <= 5 (w/o unsedBit octet - 32 bits) else String like '10111100' or  Array with one item in case of incapsulates encoding</li>
+         *      <li>OCTET STRING - Hex encoded string or Array with one item in case of incapsulates encoding</li>
+         *      <li>OBJECT IDENTIFIER - String with object identifier</li>
+         *      <li>SEQUENCE, SET - Array of encoded items</li>
+         *      <li>UTF8String, NumericString, PrintableString, TeletexString, VideotexString, 
+         *          IA5String, GraphicString, VisibleString, GeneralString, UniversalString,
+         *          BMPString - encoded String</li>
+         *      <li>UTCTime, GeneralizedTime - Date</li>
+         *  </ul>
+         * @memberOf GostCoding.BER
+         * @param {(CryptoOperationData|GostCoding.BER)} data Binary data to decode
+         * @returns {Object} Javascript object with result of decoding
+         */
+        decode: function (data) {
+            return decodeBER(data.object ? data : new Uint8Array(buffer(data)), 0);
+        }
+    }; // </editor-fold>
+})();
+
+/**
+ * BER, DER, CER conversion
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.BER
+ */
+GostCoding.prototype.BER = BER;
+
+/**
+ * PEM conversion
+ * @class GostCoding.PEM
+ */
+var PEM = {// <editor-fold defaultstate="collapsed">
+    /**
+     * PEM.encode(data, name) encode CryptoOperationData to PEM format with name label
+     * 
+     * @memberOf GostCoding.PEM
+     * @param {(Object|CryptoOperationData)} data Java script object or BER-encoded binary data
+     * @param {string} name Name of PEM object: 'certificate', 'private key' etc.
+     * @returns {string} Encoded object
+     */
+    encode: function (data, name) {
+        return (name ? '-----BEGIN ' + name.toUpperCase() + '-----\r\n' : '') +
+                Base64.encode(data instanceof CryptoOperationData ? data : BER.encode(data)) +
+                (name ? '\r\n-----END ' + name.toUpperCase() + '-----' : '');
+    },
+    /**
+     * PEM.decode(s, name, deep) decode PEM format s labeled name to CryptoOperationData or javascript object in according to deep parameter
+     * 
+     * @memberOf GostCoding.PEM
+     * @param {string} s PEM encoded string
+     * @param {string} name Name of PEM object: 'certificate', 'private key' etc.
+     * @param {boolean} deep If true method do BER-decoding, else only BASE64 decoding
+     * @param {integer} index Index of decoded value
+     * @returns {(Object|CryptoOperationData)} Decoded javascript object if deep=true, else CryptoOperationData for father BER decoding
+     */
+    decode: function (s, name, deep, index) {
+        // Try clear base64
+        var re1 = /([A-Za-z0-9\+\/\s\=]+)/g,
+                valid = re1.exec(s);
+        if (valid[1].length !== s.length)
+            valid = false;
+        if (!valid && name) {
+            // Try with the name
+            var re2 = new RegExp(
+                    '-----\\s?BEGIN ' + name.toUpperCase() +
+                    '-----([A-Za-z0-9\\+\\/\\s\\=]+)-----\\s?END ' +
+                    name.toUpperCase() + '-----', 'g');
+            valid = re2.exec(s);
+        }
+        if (!valid) {
+            // Try with some name
+            var re3 = new RegExp(
+                    '-----\\s?BEGIN [A-Z0-9\\s]+' +
+                    '-----([A-Za-z0-9\\+\\/\\s\\=]+)-----\\s?END ' +
+                    '[A-Z0-9\\s]+-----', 'g');
+            valid = re3.exec(s);
+        }
+        var r = valid && valid[1 + (index || 0)];
+        if (!r)
+            throw new DataError('Not valid PEM format');
+        var out = Base64.decode(r);
+        if (deep)
+            out = BER.decode(out);
+        return out;
+    } // </editor-fold>
+};
+
+/**
+ * PEM conversion
+ * @memberOf GostCoding
+ * @insnance
+ * @type GostCoding.PEM
+ */
+GostCoding.prototype.PEM = PEM;
+
+if (gostCrypto)
+    /**
+     * Coding algorithms: Base64, Hex, Int16, Chars, BER and PEM
+     * 
+     * @memberOf gostCrypto
+     * @type GostCoding
+     */
+    gostCrypto.coding = new GostCoding();
+
+export default GostCoding;

+ 1653 - 0
src/core/vendor/gost/gostCrypto.mjs

@@ -0,0 +1,1653 @@
+/**
+ * Implementation Web Crypto interfaces for GOST algorithms
+ * 1.76
+ * 2014-2016, Rudolf Nickolaev. All rights reserved.
+ * 
+ * Exported for CyberChef by mshwed [m@ttshwed.com]
+ */
+
+/* 
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+import GostRandom from './gostRandom';
+import gostEngine from './gostEngine';
+
+import crypto from 'crypto'
+
+/*
+* Algorithm normalization
+* 
+*/ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+root.gostEngine = gostEngine;
+
+var rootCrypto = crypto
+
+var SyntaxError = Error,
+        DataError = Error,
+        NotSupportedError = Error,
+        OperationError = Error,
+        InvalidStateError = Error,
+        InvalidAccessError = Error;
+
+// Normalize algorithm
+function normalize(algorithm, method) {
+    if (typeof algorithm === 'string' || algorithm instanceof String)
+        algorithm = {name: algorithm};
+    var name = algorithm.name;
+    if (!name)
+        throw new SyntaxError('Algorithm name not defined');
+    // Extract algorithm modes from name
+    var modes = name.split('/'), modes = modes[0].split('-').concat(modes.slice(1));
+    // Normalize the name with default modes
+    var na = {};
+    name = modes[0].replace(/[\.\s]/g, '');
+    modes = modes.slice(1);
+    if (name.indexOf('28147') >= 0) {
+        na = {
+            name: 'GOST 28147',
+            version: 1989,
+            mode: (algorithm.mode || (// ES, MAC, KW
+                    (method === 'sign' || method === 'verify') ? 'MAC' :
+                    (method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
+            length: algorithm.length || 64
+        };
+    } else if (name.indexOf('3412') >= 0) {
+        na = {
+            name: 'GOST R 34.12',
+            version: 2015,
+            mode: (algorithm.mode || (// ES, MAC, KW
+                    (method === 'sign' || method === 'verify') ? 'MAC' :
+                    (method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
+            length: algorithm.length || 64 // 128
+        };
+    } else if (name.indexOf('3411') >= 0) {
+        na = {
+            name: 'GOST R 34.11',
+            version: 2012, // 1994
+            mode: (algorithm.mode || (// HASH, KDF, HMAC, PBKDF2, PFXKDF, CPKDF
+                    (method === 'deriveKey' || method === 'deriveBits') ? 'KDF' :
+                    (method === 'sign' || method === 'verify') ? 'HMAC' : 'HASH')).toUpperCase(),
+            length: algorithm.length || 256 // 512
+        };
+    } else if (name.indexOf('3410') >= 0) {
+        na = {
+            name: 'GOST R 34.10',
+            version: 2012, // 1994, 2001
+            mode: (algorithm.mode || (// SIGN, DH, MASK
+                    (method === 'deriveKey' || method === 'deriveBits') ? 'DH' : 'SIGN')).toUpperCase(),
+            length: algorithm.length || 256 // 512
+        };
+    } else if (name.indexOf('SHA') >= 0) {
+        na = {
+            name: 'SHA',
+            version: (algorithm.length || 160) === 160 ? 1 : 2, // 1, 2
+            mode: (algorithm.mode || (// HASH, KDF, HMAC, PBKDF2, PFXKDF
+                    (method === 'deriveKey' || method === 'deriveBits') ? 'KDF' :
+                    (method === 'sign' || method === 'verify') ? 'HMAC' : 'HASH')).toUpperCase(),
+            length: algorithm.length || 160
+        };
+    } else if (name.indexOf('RC2') >= 0) {
+        na = {
+            name: 'RC2',
+            version: 1,
+            mode: (algorithm.mode || (// ES, MAC, KW
+                    (method === 'sign' || method === 'verify') ? 'MAC' :
+                    (method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
+            length: algorithm.length || 32 // 1 - 1024
+        };
+    } else if (name.indexOf('PBKDF2') >= 0) {
+        na = normalize(algorithm.hash, 'digest');
+        na.mode = 'PBKDF2';
+    } else if (name.indexOf('PFXKDF') >= 0) {
+        na = normalize(algorithm.hash, 'digest');
+        na.mode = 'PFXKDF';
+    } else if (name.indexOf('CPKDF') >= 0) {
+        na = normalize(algorithm.hash, 'digest');
+        na.mode = 'CPKDF';
+    } else if (name.indexOf('HMAC') >= 0) {
+        na = normalize(algorithm.hash, 'digest');
+        na.mode = 'HMAC';
+    } else
+        throw new NotSupportedError('Algorithm not supported');
+
+    // Compile modes
+    modes.forEach(function (mode) {
+        mode = mode.toUpperCase();
+        if (/^[0-9]+$/.test(mode)) {
+            if ((['8', '16', '32'].indexOf(mode) >= 0) || (na.length === '128' && mode === '64')) { // Shift bits
+                if (na.mode === 'ES')
+                    na.shiftBits = parseInt(mode);
+                else if (na.mode === 'MAC')
+                    na.macLength = parseInt(mode);
+                else
+                    throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
+            } else if (['89', '94', '01', '12', '15', '1989', '1994', '2001', '2012', '2015'].indexOf(mode) >= 0) { // GOST Year
+                var version = parseInt(mode);
+                version = version < 1900 ? (version < 80 ? 2000 + version : 1900 + version) : version;
+                na.version = version;
+            } else if (['1'].indexOf(mode) >= 0 && na.name === 'SHA') { // SHA-1
+                na.version = 1;
+                na.length = 160;
+            } else if (['256', '384', '512'].indexOf(mode) >= 0 && na.name === 'SHA') { // SHA-2
+                na.version = 2;
+                na.length = parseInt(mode);
+            } else if (['40', '128'].indexOf(mode) >= 0 && na.name === 'RC2') { // RC2
+                na.version = 1;
+                na.length = parseInt(mode); // key size
+            } else if (['64', '128', '256', '512'].indexOf(mode) >= 0) // block size
+                na.length = parseInt(mode);
+            else if (['1000', '2000'].indexOf(mode) >= 0) // Iterations
+                na.iterations = parseInt(mode);
+            // Named Paramsets
+        } else if (['E-TEST', 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC', 'E-Z', 'D-TEST', 'D-A', 'D-SC'].indexOf(mode) >= 0) {
+            na.sBox = mode;
+        } else if (['S-TEST', 'S-A', 'S-B', 'S-C', 'S-D', 'X-A', 'X-B', 'X-C'].indexOf(mode) >= 0) {
+            na.namedParam = mode;
+        } else if (['S-256-TEST', 'S-256-A', 'S-256-B', 'S-256-C', 'P-256', 'T-512-TEST', 'T-512-A',
+            'T-512-B', 'X-256-A', 'X-256-B', 'T-256-TEST', 'T-256-A', 'T-256-B', 'S-256-B', 'T-256-C', 'S-256-C'].indexOf(mode) >= 0) {
+            na.namedCurve = mode;
+        } else if (['SC', 'CP', 'VN'].indexOf(mode) >= 0) {
+            na.procreator = mode;
+
+            // Encription GOST 28147 or GOST R 34.12
+        } else if (na.name === 'GOST 28147' || na.name === 'GOST R 34.12' || na.name === 'RC2') {
+            if (['ES', 'MAC', 'KW', 'MASK'].indexOf(mode) >= 0) {
+                na.mode = mode;
+            } else if (['ECB', 'CFB', 'OFB', 'CTR', 'CBC'].indexOf(mode) >= 0) {
+                na.mode = 'ES';
+                na.block = mode;
+            } else if (['CPKW', 'NOKW', 'SCKW'].indexOf(mode) >= 0) {
+                na.mode = 'KW';
+                na.keyWrapping = mode.replace('KW', '');
+            } else if (['ZEROPADDING', 'PKCS5PADDING', 'NOPADDING', 'RANDOMPADDING', 'BITPADDING'].indexOf(mode) >= 0) {
+                na.padding = mode.replace('PADDING', '');
+            } else if (['NOKM', 'CPKM'].indexOf(mode) >= 0) {
+                na.keyMeshing = mode.replace('KM', '');
+            } else
+                throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
+
+            // Digesting GOST 34.11
+        } else if (na.name === 'GOST R 34.11' || na.name === 'SHA') {
+            if (['HASH', 'KDF', 'HMAC', 'PBKDF2', 'PFXKDF', 'CPKDF'].indexOf(mode) >= 0)
+                na.mode = mode;
+            else
+                throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
+
+            // Signing GOST 34.10
+        } else if (na.name === 'GOST R 34.10') {
+            var hash = mode.replace(/[\.\s]/g, '');
+            if (hash.indexOf('GOST') >= 0 && hash.indexOf('3411') >= 0)
+                na.hash = mode;
+            else if (['SIGN', 'DH', 'MASK'].indexOf(mode))
+                na.mode = mode;
+            else
+                throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
+        }
+    });
+
+    // Procreator
+    na.procreator = algorithm.procreator || na.procreator || 'CP';
+
+    // Key size
+    switch (na.name) {
+        case 'GOST R 34.10':
+            na.keySize = na.length / (na.version === 1994 ? 4 : 8);
+            break;
+        case 'GOST R 34.11':
+            na.keySize = 32;
+            break;
+        case 'GOST 28147':
+        case 'GOST R 34.12':
+            na.keySize = 32;
+            break;
+        case 'RC2':
+            na.keySize = Math.ceil(na.length / 8);
+            break;
+        case 'SHA':
+            na.keySize = na.length / 8;
+            break;
+    }
+
+    // Encrypt additional modes 
+    if (na.mode === 'ES') {
+        if (algorithm.block)
+            na.block = algorithm.block; // ECB, CFB, OFB, CTR, CBC
+        if (na.block)
+            na.block = na.block.toUpperCase();
+        if (algorithm.padding)
+            na.padding = algorithm.padding; // NO, ZERO, PKCS5, RANDOM, BIT
+        if (na.padding)
+            na.padding = na.padding.toUpperCase();
+        if (algorithm.shiftBits)
+            na.shiftBits = algorithm.shiftBits; // 8, 16, 32, 64
+        if (algorithm.keyMeshing)
+            na.keyMeshing = algorithm.keyMeshing; // NO, CP
+        if (na.keyMeshing)
+            na.keyMeshing = na.keyMeshing.toUpperCase();
+        // Default values
+        if (method !== 'importKey' && method !== 'generateKey') {
+            na.block = na.block || 'ECB';
+            na.padding = na.padding || (na.block === 'CBC' || na.block === 'ECB' ? 'ZERO' : 'NO');
+            if (na.block === 'CFB' || na.block === 'OFB')
+                na.shiftBits = na.shiftBits || na.length;
+            na.keyMeshing = na.keyMeshing || 'NO';
+        }
+    }
+    if (na.mode === 'KW') {
+        if (algorithm.keyWrapping)
+            na.keyWrapping = algorithm.keyWrapping; // NO, CP, SC
+        if (na.keyWrapping)
+            na.keyWrapping = na.keyWrapping.toUpperCase();
+        if (method !== 'importKey' && method !== 'generateKey')
+            na.keyWrapping = na.keyWrapping || 'NO';
+    }
+
+    // Paramsets
+    ['sBox', 'namedParam', 'namedCurve', 'curve', 'param', 'modulusLength'].forEach(function (name) {
+        algorithm[name] && (na[name] = algorithm[name]);
+    });
+    // Default values
+    if (method !== 'importKey' && method !== 'generateKey') {
+        if (na.name === 'GOST 28147') {
+            na.sBox = na.sBox || (na.procreator === 'SC' ? 'E-SC' : 'E-A'); // 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC'
+        } else if (na.name === 'GOST R 34.12' && na.length === 64) {
+            na.sBox = 'E-Z';
+        } else if (na.name === 'GOST R 34.11' && na.version === 1994) {
+            na.sBox = na.sBox || (na.procreator === 'SC' ? 'D-SC' : 'D-A'); // 'D-SC'
+        } else if (na.name === 'GOST R 34.10' && na.version === 1994) {
+            na.namedParam = na.namedParam || (na.mode === 'DH' ? 'X-A' : 'S-A'); // 'S-B', 'S-C', 'S-D', 'X-B', 'X-C'
+        } else if (na.name === 'GOST R 34.10' && na.version === 2001) {
+            na.namedCurve = na.namedCurve || (na.length === 256 ?
+                    na.procreator === 'SC' ? 'P-256' : (na.mode === 'DH' ? 'X-256-A' : 'S-256-A') : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
+                    na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
+        } else if (na.name === 'GOST R 34.10' && na.version === 2012) {
+            na.namedCurve = na.namedCurve || (na.length === 256 ?
+                    na.procreator === 'SC' ? 'P-256' : (na.mode === 'DH' ? 'X-256-A' : 'S-256-A') : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
+                    na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
+        }
+    }
+
+    // Vectors
+    switch (na.mode) {
+        case 'DH':
+            algorithm.ukm && (na.ukm = algorithm.ukm);
+            algorithm['public'] && (na['public'] = algorithm['public']);
+            break;
+        case 'SIGN':
+        case 'KW':
+            algorithm.ukm && (na.ukm = algorithm.ukm);
+            break;
+        case 'ES':
+        case 'MAC':
+            algorithm.iv && (na.iv = algorithm.iv);
+            break;
+        case 'KDF':
+            algorithm.label && (na.label = algorithm.label);
+            algorithm.contex && (na.context = algorithm.contex);
+            break;
+        case 'PBKDF2':
+            algorithm.salt && (na.salt = algorithm.salt);
+            algorithm.iterations && (na.iterations = algorithm.iterations);
+            algorithm.diversifier && (na.diversifier = algorithm.diversifier);
+            break;
+        case 'PFXKDF':
+            algorithm.salt && (na.salt = algorithm.salt);
+            algorithm.iterations && (na.iterations = algorithm.iterations);
+            algorithm.diversifier && (na.diversifier = algorithm.diversifier);
+            break;
+        case 'CPKDF':
+            algorithm.salt && (na.salt = algorithm.salt);
+            algorithm.iterations && (na.iterations = algorithm.iterations);
+            break;
+    }
+
+    // Verification method and modes
+    if (method && (
+            ((na.mode !== 'ES' && na.mode !== 'SIGN' && na.mode !== 'MAC' &&
+                    na.mode !== 'HMAC' && na.mode !== 'KW' && na.mode !== 'DH'
+                    && na.mode !== 'MASK') &&
+                    (method === 'generateKey')) ||
+            ((na.mode !== 'ES') &&
+                    (method === 'encrypt' || method === 'decrypt')) ||
+            ((na.mode !== 'SIGN' && na.mode !== 'MAC' && na.mode !== 'HMAC') &&
+                    (method === 'sign' || method === 'verify')) ||
+            ((na.mode !== 'HASH') &&
+                    (method === 'digest')) ||
+            ((na.mode !== 'KW' && na.mode !== 'MASK') &&
+                    (method === 'wrapKey' || method === 'unwrapKey')) ||
+            ((na.mode !== 'DH' && na.mode !== 'PBKDF2' && na.mode !== 'PFXKDF' &&
+                    na.mode !== 'CPKDF' && na.mode !== 'KDF') &&
+                    (method === 'deriveKey' || method === 'deriveBits'))))
+        throw new NotSupportedError('Algorithm mode ' + na.mode + ' not valid for method ' + method);
+
+    // Normalize hash algorithm
+    algorithm.hash && (na.hash = algorithm.hash);
+    if (na.hash) {
+        if ((typeof na.hash === 'string' || na.hash instanceof String)
+                && na.procreator)
+            na.hash = na.hash + '/' + na.procreator;
+        na.hash = normalize(na.hash, 'digest');
+    }
+
+    // Algorithm object identirifer
+    algorithm.id && (na.id = algorithm.id);
+
+    return na;
+}
+
+// Check for possibility use native crypto.subtle
+function checkNative(algorithm) {
+    if (!rootCrypto || !rootCrypto.subtle || !algorithm)
+        return false;
+    // Prepare name
+    var name = (typeof algorithm === 'string' || algorithm instanceof String) ?
+            name = algorithm : algorithm.name;
+    if (!name)
+        return false;
+    name = name.toUpperCase();
+    // Digest algorithm for key derivation
+    if ((name.indexOf('KDF') >= 0 || name.indexOf('HMAC') >= 0) && algorithm.hash)
+        return checkNative(algorithm.hash);
+    // True if no supported names
+    return name.indexOf('GOST') === -1 &&
+            name.indexOf('SHA-1') === -1 &&
+            name.indexOf('RC2') === -1 &&
+            name.indexOf('?DES') === -1;
+}
+// </editor-fold>
+
+/*
+    * Key conversion methods
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+// Check key parameter
+function checkKey(key, method) {
+    if (!key.algorithm)
+        throw new SyntaxError('Key algorithm not defined');
+
+    if (!key.algorithm.name)
+        throw new SyntaxError('Key algorithm name not defined');
+
+    var name = key.algorithm.name,
+            gostCipher = name === 'GOST 28147' || name === 'GOST R 34.12' || name === 'RC2',
+            gostDigest = name === 'GOST R 34.11' || name === 'SHA',
+            gostSign = name === 'GOST R 34.10';
+
+    if (!gostCipher && !gostSign && !gostDigest)
+        throw new NotSupportedError('Key algorithm ' + name + ' is unsupproted');
+
+    if (!key.type)
+        throw new SyntaxError('Key type not defined');
+
+    if (((gostCipher || gostDigest) && key.type !== 'secret') ||
+            (gostSign && !(key.type === 'public' || key.type === 'private')))
+        throw new DataError('Key type ' + key.type + ' is not valid for algorithm ' + name);
+
+    if (!key.usages || !key.usages.indexOf)
+        throw new SyntaxError('Key usages not defined');
+
+    for (var i = 0, n = key.usages.length; i < n; i++) {
+        var md = key.usages[i];
+        if (((md === 'encrypt' || md === 'decrypt') && key.type !== 'secret') ||
+                (md === 'sign' && key.type === 'public') ||
+                (md === 'verify' && key.type === 'private'))
+            throw new InvalidStateError('Key type ' + key.type + ' is not valid for ' + md);
+    }
+
+    if (method)
+        if (key.usages.indexOf(method) === -1)
+            throw new InvalidAccessError('Key usages is not contain method ' + method);
+
+    if (!key.buffer)
+        throw new SyntaxError('Key buffer is not defined');
+
+    var size = key.buffer.byteLength * 8, keySize = 8 * key.algorithm.keySize;
+    if ((key.type === 'secret' && size !== (keySize || 256) &&
+            (key.usages.indexOf('encrypt') >= 0 || key.usages.indexOf('decrypt') >= 0)) ||
+            (key.type === 'private' && !(size === 256 || size === 512)) ||
+            (key.type === 'public' && !(size === 512 || size === 1024)))
+        throw new SyntaxError('Key buffer has wrong size ' + size + ' bit');
+}
+
+// Extract key and enrich cipher algorithm
+function extractKey(method, algorithm, key) {
+    checkKey(key, method);
+    if (algorithm) {
+        var params;
+        switch (algorithm.mode) {
+            case 'ES':
+                params = ['sBox', 'keyMeshing', 'padding', 'block'];
+                break;
+            case 'SIGN':
+                params = ['namedCurve', 'namedParam', 'sBox', 'curve', 'param', 'modulusLength'];
+                break;
+            case 'MAC':
+                params = ['sBox'];
+                break;
+            case 'KW':
+                params = ['keyWrapping', 'ukm'];
+                break;
+            case 'DH':
+                params = ['namedCurve', 'namedParam', 'sBox', 'ukm', 'curve', 'param', 'modulusLength'];
+                break;
+            case 'KDF':
+                params = ['context', 'label'];
+                break;
+            case 'PBKDF2':
+                params = ['sBox', 'iterations', 'salt'];
+                break;
+            case 'PFXKDF':
+                params = ['sBox', 'iterations', 'salt', 'diversifier'];
+                break;
+            case 'CPKDF':
+                params = ['sBox', 'salt'];
+                break;
+        }
+        if (params)
+            params.forEach(function (name) {
+                key.algorithm[name] && (algorithm[name] = key.algorithm[name]);
+            });
+    }
+    return key.buffer;
+}
+
+// Make key definition
+function convertKey(algorithm, extractable, keyUsages, keyData, keyType) {
+    var key = {
+        type: keyType || (algorithm.name === 'GOST R 34.10' ? 'private' : 'secret'),
+        extractable: extractable || 'false',
+        algorithm: algorithm,
+        usages: keyUsages || [],
+        buffer: keyData
+    };
+    checkKey(key);
+    return key;
+}
+
+function convertKeyPair(publicAlgorithm, privateAlgorithm, extractable, keyUsages, publicBuffer, privateBuffer) {
+
+    if (!keyUsages || !keyUsages.indexOf)
+        throw new SyntaxError('Key usages not defined');
+
+    var publicUsages = keyUsages.filter(function (value) {
+        return value !== 'sign';
+    });
+    var privateUsages = keyUsages.filter(function (value) {
+        return value !== 'verify';
+    });
+
+    return {
+        publicKey: convertKey(publicAlgorithm, extractable, publicUsages, publicBuffer, 'public'),
+        privateKey: convertKey(privateAlgorithm, extractable, privateUsages, privateBuffer, 'private')
+    };
+}
+
+// Swap bytes in buffer
+function swapBytes(src) {
+    if (src instanceof CryptoOperationData)
+        src = new Uint8Array(src);
+    var dst = new Uint8Array(src.length);
+    for (var i = 0, n = src.length; i < n; i++)
+        dst[n - i - 1] = src[i];
+    return dst.buffer;
+}
+// </editor-fold>
+
+/**
+ * Promise stub object (not fulfill specification, only for internal use)
+ * Class not defined if Promise class already defined in root context<br><br>
+ * 
+ * The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:
+ *  <ul>
+ *      <li>pending: initial state, not fulfilled or rejected.</li>
+ *      <li>fulfilled: successful operation</li>
+ *      <li>rejected: failed operation.</li>
+ *  </ul>
+ * Another term describing the state is settled: the Promise is either fulfilled or rejected, but not pending.<br><br>
+ * @class Promise
+ * @global
+ * @param {function} executor Function object with two arguments resolve and reject. 
+ * The first argument fulfills the promise, the second argument rejects it. 
+ * We can call these functions, once our operation is completed.
+ */ // <editor-fold defaultstate="collapsed">
+if (!Promise) {
+
+    root.Promise = (function () {
+
+        function mswrap(value) {
+            if (value && value.oncomplete === null && value.onerror === null) {
+                return new Promise(function (resolve, reject) {
+                    value.oncomplete = function () {
+                        resolve(value.result);
+                    };
+                    value.onerror = function () {
+                        reject(new OperationError(value.toString()));
+                    };
+                });
+            } else
+                return value;
+        }
+
+        function Promise(executor) {
+
+            var state = 'pending', result,
+                    resolveQueue = [], rejectQueue = [];
+
+            function call(callback) {
+                try {
+                    callback();
+                } catch (e) {
+                }
+            }
+
+            try {
+                executor(function (value) {
+                    if (state === 'pending') {
+                        state = 'fulfilled';
+                        result = value;
+                        resolveQueue.forEach(call);
+                    }
+                }, function (reason) {
+                    if (state === 'pending') {
+                        state = 'rejected';
+                        result = reason;
+                        rejectQueue.forEach(call);
+                    }
+                });
+            } catch (error) {
+                if (state === 'pending') {
+                    state = 'rejected';
+                    result = error;
+                    rejectQueue.forEach(call);
+                }
+            }
+            /**
+             * The then() method returns a Promise. It takes two arguments, both are 
+             * callback functions for the success and failure cases of the Promise.
+             * 
+             * @method then
+             * @memberOf Promise
+             * @instance
+             * @param {function} onFulfilled A Function called when the Promise is fulfilled. This function has one argument, the fulfillment value.
+             * @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
+             * @returns {Promise} 
+             */
+            this.then = function (onFulfilled, onRejected) {
+
+                return new Promise(function (resolve, reject) {
+
+                    function asyncOnFulfilled() {
+                        var value;
+                        try {
+                            value = onFulfilled ? onFulfilled(result) : result;
+                        } catch (error) {
+                            reject(error);
+                            return;
+                        }
+                        value = mswrap(value);
+                        if (value && value.then && value.then.call) {
+                            value.then(resolve, reject);
+                        } else {
+                            resolve(value);
+                        }
+                    }
+
+                    function asyncOnRejected() {
+                        var reason;
+                        try {
+                            reason = onRejected ? onRejected(result) : result;
+                        } catch (error) {
+                            reject(error);
+                            return;
+                        }
+                        reason = mswrap(reason);
+                        if (reason && reason.then && reason.then.call) {
+                            reason.then(resolve, reject);
+                        } else {
+                            reject(reason);
+                        }
+                    }
+
+                    if (state === 'fulfilled') {
+                        asyncOnFulfilled();
+                    } else if (state === 'rejected') {
+                        asyncOnRejected();
+                    } else {
+                        resolveQueue.push(asyncOnFulfilled);
+                        rejectQueue.push(asyncOnRejected);
+                    }
+
+                });
+
+            };
+            /**
+             * The catch() method returns a Promise and deals with rejected cases only. 
+             * It behaves the same as calling Promise.prototype.then(undefined, onRejected).
+             * 
+             * @method catch
+             * @memberOf Promise
+             * @instance
+             * @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
+             * @returns {Promise} 
+             */
+            this['catch'] = function (onRejected) {
+                return this.then(undefined, onRejected);
+            };
+        }
+
+        /**
+         * The Promise.all(iterable) method returns a promise that resolves when all 
+         * of the promises in the iterable argument have resolved.<br><br>
+         * 
+         * The result is passed as an array of values from all the promises. 
+         * If something passed in the iterable array is not a promise, it's converted to 
+         * one by Promise.resolve. If any of the passed in promises rejects, the 
+         * all Promise immediately rejects with the value of the promise that rejected, 
+         * discarding all the other promises whether or not they have resolved.
+         * 
+         * @method all
+         * @memberOf Promise
+         * @static
+         * @param {KeyUsages} promises Array with promises.
+         * @returns {Promise}
+         */
+        Promise.all = function (promises) {
+            return new Promise(function (resolve, reject) {
+                var result = [], count = 0;
+                function asyncResolve(k) {
+                    count++;
+                    return function (data) {
+                        result[k] = data;
+                        count--;
+                        if (count === 0)
+                            resolve(result);
+                    };
+                }
+
+                function asyncReject(reason) {
+                    if (count > 0)
+                        reject(reason);
+                    count = 0;
+                }
+
+                for (var i = 0, n = promises.length; i < n; i++) {
+                    var data = promises[i];
+                    if (data.then && data.then.call)
+                        data.then(asyncResolve(i), asyncReject);
+                    else
+                        result[i] = data;
+                }
+
+                if (count === 0)
+                    resolve(result);
+            });
+        };
+
+        return Promise;
+    })();
+} // </editor-fold>
+
+/*
+    * Worker executor
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+var baseUrl = '', nameSuffix = '';
+// Try to define from DOM model
+if (typeof document !== 'undefined') {
+    (function () {
+        var regs = /^(.*)gostCrypto(.*)\.js$/i;
+        var list = document.querySelectorAll('script');
+        for (var i = 0, n = list.length; i < n; i++) {
+            var value = list[i].getAttribute('src');
+            var test = regs.exec(value);
+            if (test) {
+                baseUrl = test[1];
+                nameSuffix = test[2];
+            }
+        }
+    })();
+}
+
+// Local importScripts procedure for include dependens
+function importScripts() {
+    for (var i = 0, n = arguments.length; i < n; i++) {
+        var name = arguments[i].split('.'),
+                src = baseUrl + name[0] + nameSuffix + '.' + name[1];
+        var el = document.querySelector('script[src="' + src + '"]');
+        if (!el) {
+            el = document.createElement('script');
+            el.setAttribute('src', src);
+            document.head.appendChild(el);
+        }
+    }
+}
+
+// Create Worker
+var worker = false, tasks = [], sequence = 0;
+// Worker will create only for first child process and
+// Gost implementation libraries not yet loaded
+if (!root.importScripts && !root.gostEngine) {
+
+    try {
+        worker = new Worker(baseUrl + 'gostEngine' + nameSuffix + '.js');
+
+        // Result of opertion
+        worker.onmessage = function (event) {
+            // Find task
+            var id = event.data.id;
+            for (var i = 0, n = tasks.length; i < n; i++)
+                if (tasks[i].id === id)
+                    break;
+            if (i < n) {
+                var task = tasks[i];
+                tasks.splice(i, 1);
+                // Reject if error or resolve with result
+                if (event.data.error)
+                    task.reject(new OperationError(event.data.error));
+                else
+                    task.resolve(event.data.result);
+            }
+        };
+
+        // Worker error - reject all waiting tasks
+        worker.onerror = function (event) {
+            for (var i = 0, n = tasks.length; i < n; i++)
+                tasks[i].reject(event.error);
+            tasks = [];
+        };
+
+    } catch (e) {
+        // Worker is't supported
+        worker = false;
+    }
+}
+
+if (!root.importScripts) {
+    // This procedure emulate load dependents as in Worker
+    root.importScripts = importScripts;
+
+}
+
+if (!worker) {
+    // Import main module
+    // Reason: we are already in worker process or Worker interface is not 
+    // yet supported
+    root.gostEngine || require('./gostEngine');
+}
+
+// Executor for any method
+function execute(algorithm, method, args) {
+    return new Promise(function (resolve, reject) {
+        try {
+            if (worker) {
+                var id = ++sequence;
+                tasks.push({
+                    id: id,
+                    resolve: resolve,
+                    reject: reject
+                });
+                worker.postMessage({
+                    id: id, algorithm: algorithm,
+                    method: method, args: args
+                });
+            } else {
+                if (root.gostEngine)
+                    resolve(root.gostEngine.execute(algorithm, method, args));
+                else
+                    reject(new OperationError('Module gostEngine not found'));
+            }
+        } catch (error) {
+            reject(error);
+        }
+    });
+}
+
+// Self resolver
+function call(callback) {
+    try {
+        callback();
+    } catch (e) {
+    }
+}
+
+// </editor-fold>
+
+/*
+    * WebCrypto common class references
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+/**
+ * The Algorithm object is a dictionary object [WebIDL] which is used to 
+ * specify an algorithm and any additional parameters required to fully 
+ * specify the desired operation.<br>
+ * <pre>
+ *  dictionary Algorithm {
+ *      DOMString name;
+ *  };
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
+ * @class Algorithm
+ * @param {DOMString} name The name of the registered algorithm to use.
+ */
+
+/**
+ * AlgorithmIdentifier - Algorithm or DOMString name of algorithm<br>
+ * <pre>
+ *  typedef (Algorithm or DOMString) AlgorithmIdentifier;
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
+ * @class AlgorithmIdentifier
+ */
+
+/**
+ * The KeyAlgorithm interface represents information about the contents of a 
+ * given Key object.
+ * <pre>
+ *  interface KeyAlgorithm {
+ *      readonly attribute DOMString name
+ *  };
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-algorithm-interface}
+ * @class KeyAlgorithm 
+ * @param {DOMString} name The name of the algorithm used to generate the Key
+ */
+
+/**
+ * The type of a key. The recognized key type values are "public", "private" 
+ * and "secret". Opaque keying material, including that used for symmetric 
+ * algorithms, is represented by "secret", while keys used as part of asymmetric 
+ * algorithms composed of public/private keypairs will be either "public" or "private".
+ * <pre>
+ *  typedef DOMString KeyType;
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
+ * @class KeyType
+ */
+
+/**
+ * Sequence of operation type that may be performed using a key. The recognized 
+ * key usage values are "encrypt", "decrypt", "sign", "verify", "deriveKey", 
+ * "deriveBits", "wrapKey" and "unwrapKey".
+ * <pre>
+ *  typedef DOMString[] KeyUsages;
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
+ * @class KeyUsages
+ */
+
+/**
+ * The Key object represents an opaque reference to keying material that is 
+ * managed by the user agent.<br>
+ * This specification provides a uniform interface for many different kinds of 
+ * keying material managed by the user agent. This may include keys that have 
+ * been generated by the user agent, derived from other keys by the user agent, 
+ * imported to the user agent through user actions or using this API, 
+ * pre-provisioned within software or hardware to which the user agent has 
+ * access or made available to the user agent in other ways. The term key refers 
+ * broadly to any keying material including actual keys for cryptographic 
+ * operations and secret values obtained within key derivation or exchange operations.<br>
+ * The Key object is not required to directly interface with the underlying key 
+ * storage mechanism, and may instead simply be a reference for the user agent 
+ * to understand how to obtain the keying material when needed, eg. when performing 
+ * a cryptographic operation.
+ * <pre>
+ *  interface Key {
+ *      readonly attribute KeyType type;
+ *      readonly attribute boolean extractable;
+ *      readonly attribute KeyAlgorithm algorithm;
+ *      readonly attribute KeyUsages usages;
+ *  };     
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
+ * @class Key
+ * @param {KeyType} type The type of a key. The recognized key type values are "public", "private" and "secret".
+ * @param {boolean} extractable Whether or not the raw keying material may be exported by the application.
+ * @param {KeyAlgorithm} algorithm The Algorithm used to generate the key.
+ * @param {KeyUsages} usages Key usage array: type of operation that may be performed using a key. 
+ */
+
+/**
+ * The KeyPair interface represents an asymmetric key pair that is comprised of both public and private keys.
+ * <pre>
+ *  interface KeyPair {
+ *      readonly attribute Key publicKey;
+ *      readonly attribute Key privateKey;
+ *  };     
+ * </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#keypair}
+ * @class KeyPair
+ * @param {Key} privateKey Private key
+ * @param {Key} publicKey Public key
+ */
+
+/**
+ * Specifies a serialization format for a key. The recognized key format values are:
+ *  <ul>
+ *      <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
+ *      <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
+ *      <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
+ *      <li>'jwk' - The key is represented as JSON according to the JSON Web Key format.</li>
+ *  </ul>
+ *  <pre>
+ *  typedef DOMString KeyFormat;
+ *  </pre>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
+ *  @class KeyFormat
+ */
+
+/**
+ * Binary data 
+ *  <pre>
+ *  typedef (ArrayBuffer or ArrayBufferView) CryptoOperationData;
+ *  </pre>
+ * @class CryptoOperationData
+ */
+var CryptoOperationData = ArrayBuffer;
+
+/**
+ * DER-encoded ArrayBuffer or PEM-encoded DOMString constains ASN.1 object<br>
+ * <pre>
+ *  typedef (ArrayBuffer or DOMString) FormatedData;
+ * </pre>
+ * @class FormatedData
+ */
+// </editor-fold>
+
+/**
+ * The gostCrypto provide general purpose cryptographic functionality for
+ * GOST standards including a cryptographically strong pseudo-random number 
+ * generator seeded with truly random values.
+ * 
+ * @namespace gostCrypto
+ */
+var gostCrypto = {};
+
+/**
+ * The SubtleCrypto class provides low-level cryptographic primitives and algorithms.
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#subtlecrypto-interface}
+ * 
+ * @class SubtleCrypto
+ */ // <editor-fold>
+function SubtleCrypto() {
+}
+
+/**
+ * The encrypt method returns a new Promise object that will encrypt data 
+ * using the specified algorithm identifier with the supplied Key.
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-encrypt}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST 28147-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+ *      <li><b>GOST 28147-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
+ *      <li><b>GOST 28147-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
+ *      <li><b>GOST 28147-CTR</b> "gammirovanie" (counter) mode</li>
+ *      <li><b>GOST 28147-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+ *      <li><b>GOST R 34.12-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+ *      <li><b>GOST R 34.12-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
+ *      <li><b>GOST R 34.12-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
+ *      <li><b>GOST R 34.12-CTR</b> "gammirovanie" (counter) mode</li>
+ *      <li><b>GOST R 34.12-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+ *  </ul>
+ *  For more information see {@link GostCipher} 
+ * 
+ * @memberOf SubtleCrypto
+ * @method encrypt
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} key Key object
+ * @param {CryptoOperationData} data Operation data
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.encrypt = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.encrypt(algorithm, key, data);
+
+        algorithm = normalize(algorithm, 'encrypt');
+        return execute(algorithm, 'encrypt',
+                [extractKey('encrypt', algorithm, key), data]);
+    });
+}; // </editor-fold>
+
+/**
+ * The decrypt method returns a new Promise object that will decrypt data 
+ * using the specified algorithm identifier with the supplied Key. 
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-decrypt}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST 28147-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+ *      <li><b>GOST 28147-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
+ *      <li><b>GOST 28147-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
+ *      <li><b>GOST 28147-CTR</b> "gammirovanie" (counter) mode</li>
+ *      <li><b>GOST 28147-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+ *      <li><b>GOST R 34.12-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+ *      <li><b>GOST R 34.12-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
+ *      <li><b>GOST R 34.12-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
+ *      <li><b>GOST R 34.12-CTR</b> "gammirovanie" (counter) mode</li>
+ *      <li><b>GOST R 34.12-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+ *  </ul>
+ *  For additional modes see {@link GostCipher} 
+ * 
+ * @memberOf SubtleCrypto
+ * @method decrypt
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} key Key object
+ * @param {CryptoOperationData} data Operation data
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.decrypt = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.decrypt(algorithm, key, data);
+
+        algorithm = normalize(algorithm, 'decrypt');
+        return execute(algorithm, 'decrypt',
+                [extractKey('decrypt', algorithm, key), data]);
+    });
+}; // </editor-fold>
+
+/**
+ * The sign method returns a new Promise object that will sign data using 
+ * the specified algorithm identifier with the supplied Key.
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-sign}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-94</b> GOST Signature</li>
+ *      <li><b>GOST R 34.10-94/GOST R 34.11-94</b> GOST Signature with Hash</li>
+ *      <li><b>GOST R 34.10</b> ECGOST Signature</li>
+ *      <li><b>GOST R 34.10/GOST R 34.11-94</b> ECGOST Signature with Old-Style Hash</li>
+ *      <li><b>GOST R 34.10/GOST R 34.11</b> ECGOST Signature with Streebog Hash</li>
+ *      <li><b>GOST 28147-MAC</b> MAC base on GOST 28147</li>
+ *      <li><b>GOST R 34.12-MAC</b> MAC base on GOST R 43.12</li>
+ *      <li><b>GOST R 34.11-HMAC</b> HMAC base on GOST 34.11</li>
+ *      <li><b>SHA-HMAC</b> HMAC base on SHA</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}
+ * 
+ * @memberOf SubtleCrypto
+ * @method sign
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} key Key object 
+ * @param {CryptoOperationData} data Operation data
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.sign = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.sign(algorithm, key, data);
+
+        algorithm = normalize(algorithm, 'sign');
+        var value = execute(algorithm, 'sign',
+                [extractKey('sign', algorithm, key), data]).then(function (data) {
+            if (algorithm.procreator === 'SC' && algorithm.mode === 'SIGN') {
+                data = gostCrypto.asn1.GostSignature.encode(data);
+            }
+            return data;
+        });
+        return value;
+    });
+}; // </editor-fold>
+
+/**
+ * The verify method returns a new Promise object that will verify data 
+ * using the specified algorithm identifier with the supplied Key.
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-verify}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-94</b> GOST Signature</li>
+ *      <li><b>GOST R 34.10-94/GOST R 34.11-94</b> GOST Signature with Hash</li>
+ *      <li><b>GOST R 34.10</b> ECGOST Signature</li>
+ *      <li><b>GOST R 34.10/GOST R 34.11-94</b> ECGOST Signature with Old-Style Hash</li>
+ *      <li><b>GOST R 34.10/GOST R 34.11</b> ECGOST Signature with Streebog Hash</li>
+ *      <li><b>GOST 28147-MAC</b> MAC base on GOST 28147</li>
+ *      <li><b>GOST R 34.12-MAC</b> MAC base on GOST R 34.12</li>
+ *      <li><b>GOST R 34.11-HMAC</b> HMAC base on GOST 34.11</li>
+ *      <li><b>SHA-HMAC</b> HMAC base on SHA</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}
+ * 
+ * @memberOf SubtleCrypto
+ * @method verify
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} key Key object
+ * @param {CryptoOperationData} signature Signature data
+ * @param {CryptoOperationData} data Operation data
+ * @returns {Promise} Promise that resolves with boolean value of verification result
+ */
+SubtleCrypto.prototype.verify = function (algorithm, key, signature, data) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.verify(algorithm, key, signature, data);
+
+        algorithm = normalize(algorithm, 'verify');
+        if (algorithm.procreator === 'SC' && algorithm.mode === 'SIGN') {
+            var obj = gostCrypto.asn1.GostSignature.decode(signature);
+            signature = {r: obj.r, s: obj.s};
+        }
+        return execute(algorithm, 'verify',
+                [extractKey('verify', algorithm, key), signature, data]);
+    });
+}; // </editor-fold>
+
+/**
+ * The digest method returns a new Promise object that will digest data 
+ * using the specified algorithm identifier. 
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-digest}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.11-94</b> Old-Style GOST Hash</li>
+ *      <li><b>GOST R 34.11</b> GOST Streebog Hash</li>
+ *      <li><b>SHA</b> SHA Hash</li>
+ *  </ul>
+ *  For additional modes see {@link GostDigest}
+ * 
+ * @memberOf SubtleCrypto
+ * @method digest
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {CryptoOperationData} data Operation data
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.digest = function (algorithm, data) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.digest(algorithm, data);
+
+        algorithm = normalize(algorithm, 'digest');
+        return execute(algorithm, 'digest', [data]);
+    });
+}; // </editor-fold>
+
+/**
+ * The generateKey method returns a new Promise object that will key(s) using
+ * the specified algorithm identifier. Key can be used in according with
+ * KeyUsages sequence. The recognized key usage values are "encrypt", "decrypt", 
+ * "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-generateKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10</b> ECGOST Key Pairs</li>
+ *      <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
+ *      <li><b>GOST 28147-KW</b> Key for wrapping GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12</b> Key for encryption GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.12-KW</b> Key for wrapping GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
+ *  Note: Generation key for GOST R 34.10-94 not supported.
+ * 
+ * @memberOf SubtleCrypto
+ * @method generateKey
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Key algorithm identifier
+ * @param {boolean} extractable Whether or not the raw keying material may be exported by the application
+ * @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
+ * @returns {Promise} Promise that resolves with {@link Key} or {@link KeyPair} in according to key algorithm
+ */
+SubtleCrypto.prototype.generateKey = function (algorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.generateKey(algorithm, extractable, keyUsages);
+
+        var privateAlgorithm = algorithm.privateKey,
+                publicAlgorithm = algorithm.publicKey;
+        algorithm = normalize(algorithm, 'generateKey');
+        if (privateAlgorithm)
+            privateAlgorithm = normalize(privateAlgorithm, 'generateKey');
+        else
+            privateAlgorithm = algorithm;
+        if (publicAlgorithm)
+            publicAlgorithm = normalize(publicAlgorithm, 'generateKey');
+        else
+            publicAlgorithm = algorithm;
+        return execute(algorithm, 'generateKey', []).then(function (data) {
+            if (data.publicKey && data.privateKey)
+                return convertKeyPair(publicAlgorithm, privateAlgorithm, extractable, keyUsages, data.publicKey, data.privateKey);
+            else
+                return convertKey(algorithm, extractable, keyUsages, data);
+        });
+    });
+}; // </editor-fold>
+
+/**
+ * The deriveKey method returns a new Promise object that will key(s) using
+ * the specified algorithm identifier. Key can be used in according with
+ * KeyUsage sequence. The recognized key usage values are "encrypt", "decrypt", 
+ * "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-deriveKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-DH</b> ECDH Key Agreement mode</li>
+ *      <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PFXKDF</b> PFX Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-CPKDF</b> Password Based Key for CryptoPro Derivation Algorithm</li>
+ *      <li><b>SHA-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
+ *      <li><b>SHA-PFXKDF</b> PFX Key for Derivation Algorithm</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign} and {@link GostDigest}
+ * 
+ * @memberOf SubtleCrypto
+ * @method deriveKey
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} baseKey Derivation key object
+ * @param {AlgorithmIdentifier} derivedKeyType Derived key algorithm identifier
+ * @param {boolean} extractable Whether or not the raw keying material may be exported by the application
+ * @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key 
+ * @returns {Promise} Promise that resolves with {@link Key}
+ */
+SubtleCrypto.prototype.deriveKey = function (algorithm, baseKey,
+        derivedKeyType, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.deriveKey(algorithm, baseKey,
+                    derivedKeyType, extractable, keyUsages);
+
+        algorithm = normalize(algorithm, 'deriveKey');
+        derivedKeyType = normalize(derivedKeyType, 'generateKey');
+        algorithm.keySize = derivedKeyType.keySize;
+        if (algorithm['public']) {
+            algorithm['public'].algorithm = normalize(algorithm['public'].algorithm);
+            algorithm['public'] = extractKey('deriveKey', algorithm, algorithm['public']);
+        }
+        return execute(algorithm, 'deriveKey', [extractKey('deriveKey', algorithm, baseKey)]).then(function (data) {
+            return convertKey(derivedKeyType, extractable, keyUsages, data);
+        });
+    });
+}; // </editor-fold>
+
+/**
+ * The deriveBits method returns length bits on baseKey using the 
+ * specified algorithm identifier. 
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-deriveBits}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-DH</b> ECDH Key Agreement mode</li>
+ *      <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PFXKDF</b> PFX Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-CPKDF</b> Password Based Key for CryptoPro Derivation Algorithm</li>
+ *      <li><b>SHA-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
+ *      <li><b>SHA-PFXKDF</b> PFX Key for Derivation Algorithm</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign} and {@link GostDigest}
+ * 
+ * @memberOf SubtleCrypto
+ * @method deriveBits
+ * @instance
+ * @param {AlgorithmIdentifier} algorithm Algorithm identifier
+ * @param {Key} baseKey Derivation key object
+ * @param {number} length Length bits
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.deriveBits = function (algorithm, baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.deriveBits(algorithm, baseKey, length);
+
+        algorithm = normalize(algorithm, 'deriveBits');
+        if (algorithm['public'])
+            algorithm['public'] = extractKey('deriveBits', algorithm, algorithm['public']);
+        return execute(algorithm, 'deriveBits', [extractKey('deriveBits', algorithm, baseKey), length]);
+    });
+}; // </editor-fold>
+
+/**
+ * The importKey method returns a new Promise object that will key(s) using
+ * the specified algorithm identifier. Key can be used in according with
+ * KeyUsage sequence. The recognized key usage values are "encrypt", "decrypt", 
+ * "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".<br><br>
+ * Parameter keyData contains data in defined format.
+ * The suppored key format values are:
+ *  <ul>
+ *      <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
+ *      <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
+ *      <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
+ *  </ul>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-importKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-94</b> GOST Private and Public keys</li>
+ *      <li><b>GOST R 34.10</b> ECGOST Private and Public keys</li>
+ *      <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
+ *      <li><b>GOST 28147-KW</b> Key for key wrapping GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12</b> Key for encryption GOST 34.12 modes</li>
+ *      <li><b>GOST R 34.12-KW</b> Key for key wrapping GOST 34.12 modes</li>
+ *      <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
+ * 
+ * @memberOf SubtleCrypto
+ * @method importKey
+ * @instance
+ * @param {KeyFormat} format Key format Format specifies a serialization format for a key
+ * @param {CryptoOperationData} keyData
+ * @param {AlgorithmIdentifier} algorithm Key algorithm identifier
+ * @param {boolean} extractable Whether or not the raw keying material may be exported by the application
+ * @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
+ * @returns {Promise} Promise that resolves with {@link Key}
+ */
+SubtleCrypto.prototype.importKey = function (format, keyData, algorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
+{
+    var type;
+    return new Promise(call).then(function () {
+        if (checkNative(algorithm))
+            return rootCrypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages);
+
+        if (format === 'raw') {
+            algorithm = normalize(algorithm, 'importKey');
+            if (keyUsages && keyUsages.indexOf) {
+                var name = algorithm.name.toUpperCase().replace(/[\.\s]/g, '');
+                if (name.indexOf('3410') >= 0 && keyUsages.indexOf('sign') >= 0)
+                    type = 'private';
+                else if (name.indexOf('3410') >= 0 && keyUsages.indexOf('verify') >= 0)
+                    type = 'public';
+            }
+            return keyData;
+        } else {
+            var key;
+            if (format === 'pkcs8')
+                key = gostCrypto.asn1.GostPrivateKeyInfo.decode(keyData).object;
+            else if (format === 'spki')
+                key = gostCrypto.asn1.GostSubjectPublicKeyInfo.decode(keyData).object;
+            else
+                throw new NotSupportedError('Key format not supported');
+
+            algorithm = normalize(key.algorithm, 'importKey');
+            type = key.type;
+            if (extractable !== false)
+                extractable = extractable || key.extractable;
+            if (keyUsages) {
+                for (var i = 0; i < keyUsages.length; i++) {
+                    if (key.usages.indexOf(keyUsages[i]) < 0)
+                        throw DataError('Key usage not valid for this key');
+                }
+            } else
+                keyUsages = key.usages;
+            var data = key.buffer, keySize = algorithm.keySize, dataLen = data.byteLength;
+            if (type === 'public' || keySize === dataLen)
+                return data;
+            else {
+                // Remove private key masks
+                if (dataLen % keySize > 0)
+                    throw new DataError('Invalid key size');
+                algorithm.mode = 'MASK';
+                algorithm.procreator = 'VN';
+                var chain = [];
+                for (var i = keySize; i < dataLen; i += keySize) {
+                    chain.push((function (mask) {
+                        return function (data) {
+                            return execute(algorithm, 'unwrapKey', [mask, data]).then(function (data) {
+                                var next = chain.pop();
+                                if (next)
+                                    return next(data);
+                                else {
+                                    delete algorithm.mode;
+                                    return data;
+                                }
+                            });
+                        };
+                    })(new Uint8Array(data, i, keySize)));
+                }
+                return chain.pop()(new Uint8Array(data, 0, keySize));
+            }
+        }
+    }).then(function (data) {
+        return convertKey(algorithm, extractable, keyUsages, data, type);
+    });
+}; // </editor-fold>
+
+/**
+ * The exportKey method returns a new Promise object that will key data in
+ * defined format. <br><br>
+ * The suppored key format values are:
+ *  <ul>
+ *      <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
+ *      <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
+ *      <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
+ *  </ul>
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-exportKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST R 34.10-94</b> GOST Private and Public keys</li>
+ *      <li><b>GOST R 34.10</b> ECGOST Private and Public keys</li>
+ *      <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
+ *      <li><b>GOST 28147-KW</b> Key for key wrapping GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12</b> Key for encryption GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.12-KW</b> Key for key wrapping GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PBKDF2</b> Import Password for Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-PFXKDF</b> Import PFX Key for Derivation Algorithm</li>
+ *      <li><b>GOST R 34.11-CPKDF</b> Import Password Key for CryptoPro Derivation Algorithm</li>
+ *      <li><b>SHA-PBKDF2</b> Import Password for Key for Derivation Algorithm</li>
+ *      <li><b>SHA-PFXKDF</b> Import PFX Key for Derivation Algorithm</li>
+ *  </ul>
+ *  For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
+ * 
+ * @memberOf SubtleCrypto
+ * @method exportKey
+ * @instance
+ * @param {KeyFormat} format Format specifies a serialization format for a key
+ * @param {Key} key Key object
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.exportKey = function (format, key) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (key && checkNative(key.algorithm))
+            return rootCrypto.subtle.exportKey(format, key);
+
+        if (!key.extractable)
+            throw new InvalidAccessError('Key not extractable');
+
+        var raw = extractKey(null, null, key);
+        if (format === 'raw')
+            return raw;
+        else if (format === 'pkcs8' && key.algorithm && key.algorithm.id) {
+            if (key.algorithm.procreator === 'VN') {
+                // Add masks for ViPNet
+                var algorithm = key.algorithm, mask;
+                algorithm.mode = 'MASK';
+                return execute(algorithm, 'generateKey').then(function (data) {
+                    mask = data;
+                    return execute(algorithm, 'wrapKey', [mask, key.buffer]);
+                }).then(function (data) {
+                    delete algorithm.mode;
+                    var d = new Uint8Array(data.byteLength + mask.byteLength);
+                    d.set(new Uint8Array(data, 0, data.byteLength));
+                    d.set(new Uint8Array(mask, 0, mask.byteLength), data.byteLength);
+                    var buffer = d.buffer;
+                    buffer.enclosed = true;
+                    return gostCrypto.asn1.GostPrivateKeyInfo.encode({
+                        algorithm: algorithm,
+                        buffer: buffer
+                    });
+                });
+            } else
+                return gostCrypto.asn1.GostPrivateKeyInfo.encode(key);
+        } else if (format === 'spki' && key.algorithm && key.algorithm.id)
+            return gostCrypto.asn1.GostSubjectPublicKeyInfo.encode(key);
+        else
+            throw new NotSupportedError('Key format not supported');
+    });
+}; // </editor-fold>
+
+/**
+ * The wrapKey method returns a new Promise object that will wrapped key(s).
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-wrapKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST 28147-KW</b> Key Wrapping GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12-KW</b> Key Wrapping GOST R 34.12 modes</li>
+ *      <li><b>GOST 28147-MASK</b> Key Mask GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12-MASK</b> Key Mask GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.10-MASK</b> Key Mask GOST R 34.10 modes</li>
+ *  </ul>
+ *  For additional modes see {@link GostCipher}<br>
+ * 
+ * @memberOf SubtleCrypto
+ * @method wrapKey
+ * @instance
+ * @param {KeyFormat} format Format specifies a serialization format for a key. Now suppored only 'raw' key format.
+ * @param {Key} key Key object
+ * @param {Key} wrappingKey Wrapping key object
+ * @param {AlgorithmIdentifier} wrapAlgorithm Algorithm identifier
+ * @returns {Promise} Promise that resolves with {@link CryptoOperationData}
+ */
+SubtleCrypto.prototype.wrapKey = function (format, key, wrappingKey, wrapAlgorithm) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(wrapAlgorithm))
+            return rootCrypto.subtle.wrapKey(format, key, wrappingKey, wrapAlgorithm);
+
+        wrapAlgorithm = normalize(wrapAlgorithm, 'wrapKey');
+        var keyData = extractKey(null, null, key);
+        if (wrapAlgorithm.procreator === 'SC' && key.type === 'private')
+            keyData = swapBytes(keyData);
+        return execute(wrapAlgorithm, 'wrapKey',
+                [extractKey('wrapKey', wrapAlgorithm, wrappingKey), keyData]).then(function (data) {
+            if (format === 'raw')
+                return data;
+            else
+                throw new NotSupportedError('Key format not supported');
+        });
+    });
+}; // </editor-fold>
+
+/**
+ * The unwrapKey method returns a new Promise object that will unwrapped key(s).
+ * WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-unwrapKey}<br><br>
+ * 
+ * Supported algorithm names:
+ *  <ul>
+ *      <li><b>GOST 28147-KW</b> Key Wrapping GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12-KW</b> Key Wrapping GOST R 34.12 modes</li>
+ *      <li><b>GOST 28147-MASK</b> Key Mask GOST 28147 modes</li>
+ *      <li><b>GOST R 34.12-MASK</b> Key Mask GOST R 34.12 modes</li>
+ *      <li><b>GOST R 34.10-MASK</b> Key Mask GOST R 34.10 modes</li>
+ *  </ul>
+ *  For additional modes see {@link GostCipher}<br>
+ * 
+ * @memberOf SubtleCrypto
+ * @method unwrapKey
+ * @instance
+ * @param {KeyFormat} format Format specifies a serialization format for a key. Now suppored only 'raw' key format.
+ * @param {CryptoOperationData} wrappedKey Wrapped key data
+ * @param {Key} unwrappingKey Unwrapping key object
+ * @param {AlgorithmIdentifier} unwrapAlgorithm Algorithm identifier
+ * @param {AlgorithmIdentifier} unwrappedKeyAlgorithm Key algorithm identifier
+ * @param {boolean} extractable Whether or not the raw keying material may be exported by the application
+ * @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
+ * @returns {Promise} Promise that resolves with {@link Key}
+ */
+SubtleCrypto.prototype.unwrapKey = function (format, wrappedKey, unwrappingKey,
+        unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
+{
+    return new Promise(call).then(function () {
+        if (checkNative(unwrapAlgorithm))
+            return rootCrypto.subtle.unwrapKey(format, wrappedKey, unwrappingKey,
+                    unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages);
+
+        unwrapAlgorithm = normalize(unwrapAlgorithm, 'unwrapKey');
+        unwrappedKeyAlgorithm = normalize(unwrappedKeyAlgorithm, 'importKey');
+        if (format !== 'raw')
+            throw new NotSupportedError('Key format not supported');
+
+        return execute(unwrapAlgorithm, 'unwrapKey', [extractKey('unwrapKey', unwrapAlgorithm, unwrappingKey), wrappedKey]).then(function (data) {
+            var type;
+            if (unwrappedKeyAlgorithm && unwrappedKeyAlgorithm.name) {
+                var name = unwrappedKeyAlgorithm.name.toUpperCase().replace(/[\.\s]/g, '');
+                if (name.indexOf('3410') >= 0 && keyUsages.indexOf('sign') >= 0)
+                    type = 'private';
+                else if (name.indexOf('3410') >= 0 && keyUsages.indexOf('verify') >= 0)
+                    type = 'public';
+            }
+            if (unwrapAlgorithm.procreator === 'SC' && type === 'private')
+                data = swapBytes(data);
+            return convertKey(unwrappedKeyAlgorithm, extractable, keyUsages, data, type);
+        });
+    });
+}; // </editor-fold>
+
+/**
+ * The subtle attribute provides an instance of the SubtleCrypto 
+ * interface which provides low-level cryptographic primitives and 
+ * algorithms.
+ * 
+ * @memberOf gostCrypto
+ * @type SubtleCrypto
+ */
+gostCrypto.subtle = new SubtleCrypto();
+
+/**
+ * The getRandomValues method generates cryptographically random values. 
+ * 
+ * First try to use Web Crypto random genereator. Next make random
+ * bytes based on standart Math.random mixed with time and mouse pointer
+ * 
+ * @memberOf gostCrypto
+ * @param {(CryptoOperationData)} array Destination buffer for random data
+ */
+gostCrypto.getRandomValues = function (array) // <editor-fold defaultstate="collapsed">
+{
+    // Execute randomizer
+    GostRandom = GostRandom || root.GostRandom;
+    var randomSource = GostRandom ? new GostRandom() : rootCrypto;
+    if (randomSource.getRandomValues)
+        randomSource.getRandomValues(array);
+    else
+        throw new NotSupportedError('Random generator not found');
+}; // </editor-fold>
+// </editor-fold>
+
+export default gostCrypto;

+ 1260 - 0
src/core/vendor/gost/gostDigest.mjs

@@ -0,0 +1,1260 @@
+/**
+ * GOST R 34.11-94 / GOST R 34.11-12 implementation
+ * 1.76
+ * 2014-2016, Rudolf Nickolaev. All rights reserved.
+ * 
+ * Exported for CyberChef by mshwed [m@ttshwed.com]
+ */
+
+/*
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * Converted to JavaScript from source https://www.streebog.net/
+ * Copyright (c) 2013, Alexey Degtyarev.
+ * All rights reserved.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+ import GostRandom from './gostRandom';
+ import GostCipher from './gostCipher';
+ import crypto from 'crypto';
+
+/*
+    * GOST R 34.11
+    * Common methods 
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+var rootCrypto = crypto 
+
+var DataError = Error,
+        NotSupportedError = Error;
+
+// Copy len values from s[sOfs] to d[dOfs]
+function arraycopy(s, sOfs, d, dOfs, len) {
+    for (var i = 0; i < len; i++)
+        d[dOfs + i] = s[sOfs + i];
+}
+
+// Swap bytes in buffer
+function swap(s) {
+    var src = new Uint8Array(s),
+            dst = new Uint8Array(src.length);
+    for (var i = 0, n = src.length; i < n; i++)
+        dst[n - i - 1] = src[i];
+    return dst.buffer;
+}
+
+// Convert BASE64 string to Uint8Array
+// for decompression of constants and precalc values
+function b64decode(s) {
+    // s = s.replace(/[^A-Za-z0-9\+\/]/g, '');
+    var n = s.length,
+            k = n * 3 + 1 >> 2, r = new Uint8Array(k);
+
+    for (var m3, m4, u24 = 0, j = 0, i = 0; i < n; i++) {
+        m4 = i & 3;
+        var c = s.charCodeAt(i);
+
+        c = c > 64 && c < 91 ?
+                c - 65 : c > 96 && c < 123 ?
+                c - 71 : c > 47 && c < 58 ?
+                c + 4 : c === 43 ?
+                62 : c === 47 ?
+                63 : 0;
+
+        u24 |= c << 18 - 6 * m4;
+        if (m4 === 3 || n - i === 1) {
+            for (m3 = 0; m3 < 3 && j < k; m3++, j++) {
+                r[j] = u24 >>> (16 >>> m3 & 24) & 255;
+            }
+            u24 = 0;
+
+        }
+    }
+    return r.buffer;
+}
+
+// Random seed
+function getSeed(length) {
+    GostRandom = GostRandom || root.GostRandom;
+    var randomSource = GostRandom ? new (GostRandom || root.GostRandom) : rootCrypto;
+    if (randomSource.getRandomValues) {
+        var d = new Uint8Array(Math.ceil(length / 8));
+        randomSource.getRandomValues(d);
+        return d;
+    } else
+        throw new NotSupportedError('Random generator not found');
+}
+
+// Check buffer
+function buffer(d) {
+    if (d instanceof ArrayBuffer)
+        return d;
+    else if (d && d.buffer && d.buffer instanceof ArrayBuffer)
+        return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ?
+                d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;
+    else
+        throw new DataError('ArrayBuffer or ArrayBufferView required');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11 or GOST R 34.11-12<br><br>
+ * 
+ * http://tools.ietf.org/html/rfc6986
+ * 
+ * The digest method returns digest data in according to GOST R 4311-2012.<br>
+ * Size of digest also defines in algorithm name. 
+ *  <ul>
+ *      <li>GOST R 34.11-256-12 - 256 bits digest</li>
+ *      <li>GOST R 34.11-512-12 - 512 bits digest</li>
+ *  </ul>
+ *  
+ * @memberOf GostDigest
+ * @method digest
+ * @instance
+ * @param {(ArrayBuffer|TypedArray)} data Data
+ * @returns {ArrayBuffer} Digest of data
+ */
+var digest2012 = (function () // <editor-fold defaultstate="collapsed">
+{
+    // Constants 
+    var buffer0 = new Int32Array(16); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];  
+
+    var buffer512 = new Int32Array(16); // [512, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 
+    buffer512[0] = 512;
+
+    // Constant C 
+    var C = (function (s) {
+        var h = new Int32Array(b64decode(s)),
+                r = new Array(12);
+        for (var i = 0; i < 12; i++)
+            r[i] = new Int32Array(h.buffer, i * 64, 16);
+        return r;
+    })(
+            'B0Wm8lllgN0jTXTMNnR2BRXTYKQIKkKiAWlnkpHgfEv8xIV1jbhOcRbQRS5DdmovH3xlwIEvy+vp2soe2lsIsbebsSFwBHnmVs3L1xui3VXKpwrbwmG1XFiZ1hJrF7WaMQG1Fg9e1WGYKyMKcur+89e1cA9GneNPGi+dqYq1o2+yCroK9ZYemTHbeoZD9LbCCdtiYDc6ycGxnjWQ5A/i03t7KbEUderyix+cUl9e8QY1hD1qKPw5Cscvzius3HT1LtHjhLy+DCLxN+iToepTNL4DUpMzE7fYddYD7YIs16k/NV5orRxynX08XDN+hY5I3eRxXaDhSPnSZhXos98f71f+bHz9WBdg9WPqqX6iVnoWGicjtwD/36P1OiVHF82/vf8PgNc1njVKEIYWHxwVf2MjqWwMQT+amUdHraxr6ktufWRGekBo+jVPkDZyxXG/tsa+wmYf8gq0t5oct6b6z8aO8Jq0mn8YbKRCUfnEZi3AOTB6O8Okb9nTOh2urk+uk9QUOk1WhojzSjyiTEUXNQQFSiiDaUcGNyyCLcWrkgnJk3oZMz5H08mHv+bHxp45VAkkv/6GrFHsxaruFg7H9B7nAr/UDX+k' +
+            '2ahRWTXCrDYvxKXRK43RaZAGm5LLK4n0msTbTTtEtIke3jaccfi3TkFBbgwCqucDp8mTTUJbH5vbWiODUURhcmAqH8uS3DgOVJwHppqKK3uxzrLbC0QKgIQJDeC3Vdk8JEKJJRs6fTreXxbs2JpMlJsiMRZUWo837ZxFmPvHtHTDtjsV0fqYNvRSdjswbB56SzNprwJn558DYTMbiuH/H9t4iv8c50GJ8/PkskjlKjhSbwWApt6+qxst84HNpMprXdhvwEpZot6Ybkd9Hc2678q5SOrvcR2KeWaEFCGAASBhB6vru2v62JT+WmPNxgIw+4nI79CezXsg1xvxSpK8SJkbstnVF/T6UijhiKqkHeeGzJEYne+AXZufITDUEiD4dx3fvDI8pM16sUkEsIAT0roxFvFn5443');
+
+    // Precalc Ax 
+    var Ax = (function (s) {
+        return new Int32Array(b64decode(s));
+    })(
+            '5vh+XFtxH9Alg3eACST6FshJ4H6FLqSoW0aGoY8GwWoLMumi13tBbqvaN6RngVxm9heWqBpoZnb13AtwY5GVS0hi84235kvx/1ximmi9hcXLgn2m/NdXlWbTba9pufCJNWyfdEg9g7B8vOyxI4yZoTanAqwxxHCNnrao0C+839aLGfpR5bOuN5zPtUCKEn0LvAx4tQggj1rlM+OEIojs7c7Cx9N3wV/S7HgXtlBdD165TMLAgzaHHYwgXbTLCwStdjyFWyigiS9YjRt59v8yVz/s9p5DEZM+D8DTn4A6GMnuAQom9fOtgxDv6PRBGXmmXc2hDH3pOhBKG+4dEkjpLFO/8tshhHM5tPUMz6aiPQlftLyc2EeYzeiKLYsHHFb5f3dxaVp1apzF8C5xoLoevKZj+atCFeZyLrGeIt5fu3gNuc4PJZS6FIJSDmOXZk2ELwMeagII6phcfyFEob5r8Ho3yxzRY2Lbg+COK0sxHGTPcEebq5YOMoVrqYa53ucetUeMh3r1bOm4/kKIX2HW/RvdAVaWYjjIYiFXkj74qS78l/9CEUR2+J19NQhWRSzrTJDJsOCnElYjCFAt+8sBbC16A/qnpkhF' +
+            '9G6LOL/GxKu9vvj91HfeujqsTOvIB5t58JyxBeiHnQwn+moQrIpYy4lg58FAHQzqGm+BHko1aSiQxPsHc9GW/0NQGi9gnQqf96UW4MY/N5Yc5KazuNqSUhMkdSw44IqbpahkczvsFU8r8SRXVUmzP9dm2xVEDcXHp9F5455Ct5La3xUaYZl/04agNF7AJxQjONVRe22pOaRlGPB3EEADtAJ5HZClrqLdiNJniZxKXQqTD2bfCihlwk7p1CBFCbCLMlU4kWaFKSpBKQe/xTOoQrJ+K2JUTcZzbFMERWKV4Ada9AbpU1GQih8vO2vBI2Fvw3sJ3FJV5cY5Z9Ezsf5oRCmIOcfw5xHiQJuH9xlk+aLpOK3D20sHGQwLTkf5w+v0VTTVdtNriENGEKBa64sC2CDDzfWCMvJRbeGEDb7Cseeg6N4GsPodCHuFS1QNNDM7QuKaZ7zKW3/YpgiKxDfdDsY7s6nZQ+2BIXFNvV5lo7FnYe3nte6haSQx98jVc6v21R/GheGjZxpeBjzUBBDJLSg6uY8ssEACj+vAbLLy95AX1k8Rb6HTPOBzWfGpnuSqeE7WjHTNwAZuKhnVxztC2ocStBYccEXD' +
+            'NxWC5O2TIW2s45BBSTn2/H7F8SGGIjt8wLCUBCusFvv510U3mlJ+v3N8Py6jtoFoM+e42brSeMqpoyo0wi/+u+SBY8z+370NjllAJG6lpnBRxu9LhCrR5CK60GUnnFCM2RSIwhhgjO4xnqVJH3zaF9OU4SgTTJxgCUv0MnLV47Ob9hKlpKrXkcy72kPSb/0PNN4fPJRq0lBPW1RomV7ha9+fr2/qj3eUJkjqWHDdCSu/x+Vtcdl8Z93msv9PIdVJPCdrRjroYAORdntPr4bHH2ihPng11LmgtowRXwMMn9QUHdLJFlggAZg9j33dUySsZKpwP8wXUlTCyYmUjgK0Jj5edtafRsLeUHRvA1h9gARF2z2CknLx5WBYSgKbVgvz+65Ypz/83GKhWl5ObK1M6EupblXOH7jMCPl0eq6CslPBAhRM9/tHG58EKJjz6442BosnrfLv+3rtypf+jApevneOBRP099jPMCwlAcMri/eNkt38F1xVTfhlxX9GBS9f6vMwG6Ky9CSqaLfsu9YNhpmPDzUBBHVMAAAAAAAAAADxLjFNNNDM7HEFIr4GGCO1rygNmTDABcGX/VziXWk8ZRmkHMYzzJoV' +
+            'lYRBcvjHnrjcVDK3k3aEqZQ2wTokkM9YgCsT8zLI71nEQq45fO1PXPoc2O/jq42C8uWslU0pP9Fq2CPokHobfU0iSfg88EO2A8ud2Hn58z3eLS8nNtgmdCpDpB+JHuLfb5iZnRtsEzrUrUbNPfQ2+rs131AmmCXAlk/cqoE+bYXrQbBTfuWlxAVAunWLFghHpBrkO+e7RK/juMQp0GcXl4GZk7vun765rpqN0eyXVCHzVyzdkX5uMWOT19rir/jOR6IgEjfcUzijI0PeyQPuNXn8VsSompHmAbKASNxXUeASlvVk5Lfbe3X3GINRWXoS222VUr3OLjMenbsjHXQwj1INcpP90yLZ4gpEYQwwRnf+7uLStOrUJcow/e4ggAZ1YerKSkcBWhPnSv4UhyZOMCzIg7J78RmlFmTPWbP2gtyoEap8HnivWx1WJvtkjcOytz6RF99bzjTQX3zwarVvXf0lfwrNEycYV03I5nbFKp4HOaflLriqmlSGVT4PPNmjVv9IrqqSe36+dWUlrY4th30ObPn/28hBOx7MoxRQyplpE74w6YPoQK1REAmVbqccsbW2ui20NU5Eab3KTiWgBRWvUoHKD3Hh' +
+            'dEWYy40OK/JZP5sxKqhjt++zim4ppPxja2qjoEwtSp09lesO5r8x46KRw5YVVL/VGBacju+by/URXWi8nU4oRrqHXxj6z3Qg0e38uLbiPr2wBzby8eNkroTZKc5libb+cLei9tpPclUOclPXXG1JKQTyOj1XQVmnCoBp6gssEI5J0HPFa7EaEYqrehk55P/XzQlaCw44rO/J+2A2WXn1SJK95pfWfzQix4kz4QUUvGHhwdm5dcm1StImYWDPG82AmkSS7Xj9hnGzzKsqiBqXk3LOv2Z/4dCI1tRbXZhalCfIEagFjD9V3mX1tDGWtQYZ90+WsdZwbkOFnR6Ly0PTNlqrioXM+j2E+ce/mcKV/P2iH9Wh3ktjD82z73Y7i0VtgD9Z+Hz3w4WyfHO+XzGRPJjjrGYzsEghv2FnTCa4+BgP+8mVxMEwyKqghiAQdhqYYFfzQiEBFqr2PHYMBlTMNS3bRcxmfZBCvPRalkvUA4Jo6KDD7zxvPae9ktJp/3O8KQriAgHtIoe33jTN6IWBj9kB7qfdYQWb1vonMhmgNVPVbxrodMzOyeoxJFwug/VUcDRVXaB75JnOJtKsVue+9/0WGFelBU44' +
+            'ag59pFJ0NtFb2Go4HN6f8sr3dWIxdwwysJqu2eJ5yNBd7xCRxgZ02xEQRqJRXlBFI1Ns5HKYAvzFDLz39bY8+nOhaIfNFx8DfSlBr9nyjb0/Xj60Wk87nYTu/jYbZ3FAPbjj0+cHYnEaOij58g/SSH68fHW0nnYndOXyk8frVlwY3PWeT0eLpAxu9E+prctSxpmBLZjax2B4iwbcbkadDvxl+Op1IexOMKX3IZ6OC1Ur7D9lvKV7a93QSWm68bdemZBM2+OU6lcUsgHR5upA9ruwwIJBKErdUPIEY7+PHf/o1/k7k8usuE2Mto5HfIbowd0bOZImjj98WqESCdYvyy89mKvbNcmuZxNpViv9X/UVweFsNs7igB1+su3485sX2pTTfbAN/gGHe8PsdguK2suEld/hU65EBaJHc7e0ELMShXt4PDKr3463cNBoElE7U2c5udLj5mVYTVficbJkaNeJx4/JhJclqTW7+n0a4QKLFTej36ZBiNDNXZvDeN56Ssgsmk2Az7dCd38bg722IHLSiDodM711XnotS6tqj0H02qtruxyV2ZBc/+f9jTG2g6pkIhGbOB/ArvuEQgIsSaD5CMZjAzrj' +
+            'pCivCASTiCat5Bw0GopTx65xIe535qhdxH9cSiWSnoy1OOmqVc3YYwY3eqna2OspoYroe7MnmJVu39pqNeSEFGt9nRmCUJSn1Bz6VaTobL/lyu3J6kLFnKNsNRwOb8F5UYHk3m+rv4n/8MUwGE0X1J1B6xWEBFiSHA1SUCjXOWHxeOwYDKiFapoFcQGO+BHNQJGifD7178wZrxUjn2Mp0jR0UO/5HrmQ4RtKB43Sd1m5Vh3l/GATMZEvH1otqZPAFlTctluiGRo+Ld4JimuZ64pm1x4PguP+jFGtt9VaCNdFM+UPiUH/fwLm3We9SFns4Giqul321S/CSCbj/0p1pWw5Bw2IrN34ZIZUjEaRpG/Rvr0mE1x8DLMPkwOPFTNKgtmEn8G/mmmcMguoVCD65PpSgkOv+QdnntTWz+loowi4Jf1YLESxR5t2kbxe3LO7x+phkEj+ZRYQY6YfgXryM0fVOGg0CaaTY8LOmExt7TAqn9/YbIHZHXseOwYDKmaUZmCJ6/vZ/YMKWY7mc3UgewdEmhQK/ElfLKilcbZZMjQfmG+KRbvC+zgapKBQs3LCVCOjrdgfrzoXJzwLi4a7bP6DJY3IabWi' +
+            'KHkCv9HJgPH1qUvWazg3r4iACnmyyroSVVBDEAg7DUzfNpQOB7nusgTRp85nkLLFYSQT//EltNwm8SuXxSwST4YII1GmLyis75NjL5k35ec1B7BSKTob5ucsMK5XCpxw01hgQa4UJeDeRXSz151MxJK6IoBAxWha8AsMpdyMJxy+Eofx9pxabvOeMX+x4NyGSV0RQCDsNC1pm0B+PxjNS9yjqdRq1RUoDR0U8nmJaSQAAAAAAAAAAFk+t1+hlsYeLk54FgsRa9htSuewWIh/juZf0BOHLj4Gem3bu9MOxOKsl/yJyq7xsQnMszweGdvhifPqxGLuGGR3cM9JqoetxlbFfsplV/bWA5U92m1s+5o2ko2IRFbgfB7rjzeVn2CNMdYXnE6qqSNvrDrX5cAmYkMEn6ZTmRRWq9NmncBSuO6vAsFTp8IKKzzLA243I8AHk8nCPZDhyizDO8ZeL27X00z/VjOXWCSeselOZDJdaqY34W01lHJCCnn45mG+Yj94UhTZBALHRBNILvH98MiWWxP2m8XsFgmpDogpKBTlkr5OGYtUKhB9cszAD8vrr+cbG0nIRCIrcD4lZBZNqEDp1SDGUT4f9Plm' +
+            'usMgP5EM6Kvy7dHCYcR+8IFMuUWs02Hzlf64lEo5IQVcnPAsFiLWrZcYZfP3cXjpvYe6K5vwofREQAWyWWVdCe11vkgkf7wLdZYSLhfP9Cq0SwkXhel6FZZrhU4nVdqf7uCDkkkTR5EyQypGI8ZSuahGW0etPkN0+LRfJBKxXoskF/bweGRLo/shYv5/3aURS7vMJ52kbcEBc+C90CSidiIgjFmivKCKj8SQbbg2803kuQ10OmZn6nFHteBwX0bvJ4LLKhUIsDnsBl719FsefSG1sYPP0FsQ2+czwGApXHefpzZyOUwBfs9VMhGGwxyB2HIOGg1Fp+07j5l6Pd+JWDr8ecft+ysu6aQZhkPvDs5fCc32e04tN09qa+n6NN8Etq3UcDihI/mNIk0KBX6qocliSLhcG/eo4/2XYDCaLrULKm5bo1GCDetCxOH+p1cilI1YKZodg3N/z5zIZLrUUaVbT7XUtypQCL9Tgc49eZdGptjV5C0E5dIrgPx+MIeWV7aed7VzVKA5aUQdgJfQtDMwyvvz4vDP4o533eC+jMNisS4lnElPRqbOcm+529HKQeJCwe7RTbp2Ay/0eqMPsEWyaKk6zeTM' +
+            'r38L6IRUnQgEg1SzwUaCY5JUNcLIDv7S7k438n/f+6cWejOSDGDxTfsSO1LqA+WESgyrU/27kAed6vY4D3iKGctI7FWPDLMqtZ3Estb+9+Dc28oi9PPsthHfWBNUmpxA4z/e31aKztOgwcgSQyLpwwela4FY+m0NdyeVebHh893ZsYt0QirABLjsLZ//q8KU9Kz4qC11kU97v2mx7ytoeMT2L69Iesfhds6AnMZ+XQxnEdiPkuTBTGJ7mdkkPe3+I0qlw9+2i1GQmx8VJi2/bU9m6gVLYry1GuLPWlKqaui+oFP70M4BSO1oCMDmYxTJQ/4WzRWoJxDNBJIxoGlw9ue8imyXzEywM3zoNfyzucBl3vJYfMeA81IhTt5BMrtQlfFeQ5D0k9+HCDliXdLg8UExPBr7i2avkXIK8FGyEbxHfUJ+1O6lcy47TO72474lgmJ4NOsLzEOcA+PdeOckyCh3MorZhn35FLUZReJDsPJXSw+I9+uX4oi2+piapJQ6GcTwaMsWhYZQ7mQJrxH6733zF9XATqukelZ8VJi0xqm2u/uAT0IYjjzCK887xc0L0EM26qo5dxPwL6wb7DMTLCUG26fw00iN' +
+            '1+Zda/LDGh5eubIWH/gg9YQuBlDEbg+fcWvrHZ6EMAGpM3WMqzFe1D/kFP2ieSJlJ8nxcB7wCTJzpMHKcKdxvpQYS6bnaz0OQNgp/4wUyH4PvsP6x3Z0yzYWqWNKapVyjxORGcJe+Tf1Re1NWuo/nugCSZZQujh7ZDfnvQtYLiLmVZ+J4FPiYYCtUuMFKI38bcVaI+NLmTXeFOD1GtCtCcY5BXimWYZeltdhcQlIfLHi1ss6IRVgAgHpFeV3n67RrbAhP2p33LeYgLduuaGmq12fjSSGRM+b/V5FNsVmJljxxrn+m6y9/erNY0G+mXnE76ciFwhAVXZRB3Hs2I5UPsK6UctnHwQ9CtSCrHGvWHn+eHoEXNrJNrI4rzOOBJrtvYZsyUly7iZhXabrvYECkDKV/dCLLBcR+DQEYHO/CurzCZMpdY/8QhyusT59z6k0uiMHSBGIgysk785Ch0zmXA5X1h+w6doas9G61vmbNDzAdXsciTxFgitRDbhAOpKXXHaYwfHbYUo+DQEY1eaMtNYPSI6FXLTPrpYeDfPLM9k6jlWrFKAO10IXAyhiN4nBg4tt0ZyUYpKJX+997Ts668/LuOZOSjFJ' +
+            'Bkx+ZC9lw9w9Kz4qTFpj2lvT80CpIQxHtHTRV6FhWTGsWTTaHehyZm7jZRF693ZbyG7TZxawXESbpohcIB1JxbkFOHqINGxFExByxLq53f+/SUYep1GvmdUpd7wc4FuhsPeF5GAn21JUbTC6bld4jDBa1wdlD1auyYfGgmEv8pWlq4lE9fvFcX7VKOdZ8kTKjdy7zix9uIiqFUq+Mo2xuh5hm+mT7OiLCfK9nugTtxd0AapLKF0csyGFjxQxlcruSMOBhBOY0bj8t1DTsvmIiTmoapmNHOG5H4iODORzRlp4mVaDdpeHFgLPKtfuI0G/hccTtbPxoU7/kW/hK0Vn53waAjC30QV1DJj8yF7Km6Wj5/cg2p4GrWpgMaK7sfQ4lz50lH7X0mAs9GY5GMD/ml9Qp/NoZ44kNNmDtKRJ1M1orxt1VZK1h388PQIubeobq/xfW0USH2sNcektKVU1dN/99RBtTwPYCBuoe5+MGcbbfqGjrAmBu7vKEq1mFy36eXBDZgEIKccXkyZ3e/9fnAAAAAAAAAAA6yR2pMkG1xVyTdQvBzjfb7dS7mU43bZfN/+8hj31O6OO+oT8tcFX5unrXHMnJZaq' +
+            'GwvavyU1xDmG4SyHKk1OIJlpoovOPgh6+vsut52cS1UFakFWttksslo65qXevqKWIqOwJqgpJYBTyFs7Nq0VgbEekAEXuHWDxR86Sj/laTDgGeHtzzYhveyBHSWR/LoYRFt9TE1SSh2o2mBp3K7wBVj1zHIwneMp1MBiWWt/9XDOIq0DOdWfmFkc2ZdHAk34i5DFqgMYe1T2Y9J/w1bQ8NhYnpE1tW7VNTCWUdPWehwS+WchzSZzLtKMHD1EGjasSSqUYWQHf2ktHXPcb19RS28KcPQNaNiKYLSzDsoerEHTZQnYM4WYfQs9l0kGMPaonszJCpbEZXeiDuLFrQGofOSatV4OcKPepEKcoYJka6Dal7RG25Yvaszth9TX9t4nKrgYXTelPEafJdzv4VvLpsGcbvn+o+tTp2SjkxvYhM4v0lkLgXwQ9FaiGm2AdDkz5XOgu3nvDQ8VXAygldweI2wsT8aU1DfkEDZN9iMFMpHdMt/Hg2xCZwMmPzKZvO9uZvjNauV7b52MNa4rW+IWWTGzwuISkPh/k70gJ7+RUANpRg6QIg0bVimeJ2+uGdMoY5KMPFOiQy9wgv746Rue0LxveSw+7UD3' +
+            'TEDVN9LeU9t16L+uX8KyYk2pwNKlQf0KTo//4Dz9EmQmIOSVaW+n4+Hw9Ai4qY9s0aojD92m2cLH0BCd0cYoj4p50E90h9WFRpRXm6NxC6I4QX98+oNPaB1HpNsKUAflIGya8UYKZD+hKN33NL1HEoFERwZytyMt8uCGzAIQUpMYLeWNvIkrV8qh+bD4kx37a4kkR8wuWun53RGFBCCkO0vlvraKJD7WVYQlXxnI1l07Z0BOYz+gBqaNtnZsRyof94rHmrTJfiHDU0QuEICq7JpPnblXgucUBbp7yCybMiAxpUZl+LZeT7G2Ufd1R/TUi/oNhXukZoKFqWxaoWqYu5kPrvkI63nJoV43okf0pi12hX3NXSd0HvjFC4AKGCC8vmXcsgH3orRmbRuYb5Qm50zJIb9TxOZIlUEKD5PZykIgzcyqZHuk70KaQGCJChhxDE6k9psys4vM2jYt3jVM05bcI7x8Wy+pwwm7aKqFGrPSYTGnNkjgEwIdxSlB/E2yzVrat3BL5IqneWXZhO1x5jI4b9YXNLuk6C1t1TirckVcIUfqYXe0sV2hq3DPCRzorJB/znK4vf9XyF39lyJ4qKTkTGprb5QN' +
+            'OFGZW08f3+RiV4zK7XG8ntmIK7DAHSwKkXudXRE8UDuiwx4RqHZDxuRjySOjmcHO9xaGxX6odtyHtKlz4JbVCa8NVn2dOlgUtAwqP1ncxvQ2AviEldEh3dPh3T2YNkhK+UXnGqRmiOV1GFR+sqWR9ZNmWHRQwB2JnqgQGGWMBltPVAgMvEYDoy0DhMZRN7893DJQeOyGHirqMKj8eVc/9yFNIDDKBQy2ZfAyK4AWwwxpvpbdGyRwh9uV7pmB4WG40fwYFNnKBfiCDtK7zA3nKWPXYFBDDxTHO8yw6KCdOg+OQHZNVz9UojnRdcHhYXe9EvWjfHNPH0urN8EvH9/CbVZIsWc5XNDxbATtFTe/QqftlxYdFDBAZX1sZ9qrcrgH7Bf6h7pO6Dzfr3nLAwT7wXM/BgVxvEY+eNYcEofpiifQfPSOd7StobnCYlNskN0m4kSbWGCAFgWPwJrX+UH8+/rYzqlL5G0Oo0PyiwYI65+bEmvQSRc0e5qSh0rnaZwiGwF8QsTmnuA6TFxyDuOSVktun14+o5naa6NT9FrYPTXn/uCQTBskJSLQCYMlh+ldhCmAwA8UMOLGs8Cghh4okwh0M6QZ1yny' +
+            'NB89rdQtbG/uCj+u+7Kljkruc8SQ3TGDqrcttbGhajSpKgQGXiOP33tLNaFoa2/MaiO/bvSmlWwZHLlrhRrTUlXVmNTW3jUayWBN5fKufvMcpsKjqYHhct4vlVGtelOYMCWq/1bI9hYVUh2dHihg2VBv4xz6RQc6GJxV8StkewsBgOyarn6oWXzsi0AFDBBeI1DlGYv5QQTvitM0VcwN1wenvuFtZ3+S5eMluQ3naZdaBhWRom5jerYR7xYYIItGCfTfPrepgaseuweK6H2swLeRA4y2XiMfD9ONRXSwVmBn7fcCweqOvrpfS+CDEjjN48R3ws7+vlwNzkhsNUwb0oxds2QWwxkQJuqe0adicyQDnSmz74Ll658o/ILL8q4CqKronPBdJ4ZDGqz6J3SwKM9HH54xt6k4WBvQuOOSLsi8eBmbQAvvBpD7cce/QvhiHzvrEEYDBJloPnpHtVrY3piPQmOmldGQ2AjHKm5jhFMGJ1J7wxnXy+uwRGbXKZeu5n4MCuJljHwU0vEHsFbIgHEiwywwQAuMinrhH9Xaztug3ts46YoOdK0Qk1TcxhWmC+kaF/ZVzBmN3V/+uL2xSb/lMCiviQrt' +
+            '1lum9bStemp5VvCIKZcifhDoZlUys1L5DlNh39rO/jnOx/MEn8kBYf9itWFnf18ul1zPJtIlh/BR7w+GVDuvYy8eQe8Qy/KPUnImNbu5SoiujbrnM0TwTUEHadNmiP2as6uU3jS7uWaAExeSjfGqm6VkoPDFETxU8THUvr2xoRd/caLz6o71tUCHhUnI9lXDfvFOaUTwXezURmPc9VE32PKs/Q1SM0T8AAAAAAAAAABfvG5ZjvVRWhbPNC7xqoUysDa9bds5XI0TdU/m3TG3Ervfp3otbJCUiefIrDpYKzA8aw4JzfpFncSuBYnH4mUhSXNad39f1GjK/WRWHSybGNoVAgMvn8nhiGckNpQmg2k3ghQeO6+JhJy11TEkcEvp19tKbxrT0jOm+YlDKpPZv501OauKDuOwU/LKrxXH4tFuGSg8dkMPFT3r4pNjhO3EXjyCwyCL+QMzuINMuUoT/WRw3rEuaGtVNZ/RN3pTxDZhyqV5AvNZdQQ6l1KC5Zp5/X9wSCaDEpzFLukTaZzNeCi5/w59rI0dVFV0TnignUPLfYjMs1IzQUS9EhtKE8+6TUnNJf26ThE+dssgjAYILz/2J7oieKB2' +
+            'wolX8gT7supFPf6B5G1n45TB5pU9p2IbLINoXP9JF2TzLBGX/E3spSsk1r2SLmj2sit4RJrFET9I87bt0SF8MS6erXW+tVrWF0/YtF/ULWtO1OSWEjir+pLmtO7+vrXQRqDXMgvvgghHIDuopZEqUST3W/jmnj6W8LE4JBPPCU7+4ln7yQH3dydqcksJHNt9vfj1Ae51R19ZmzwiTeyGkW2EAY+Zwer+dJi45BzbOazgWV5xIXxbtyqkOic8UMCv9QtD7D9UO26Djj4hYnNPcMCUkttFB/9Ycr/qn9/C7mcRaIrPnM36oBqBkNhqmDa5esvZO8YVx5XHMyw6KGCAyoY0RelO6H1Q9pZqX9DW3oXprYFPltXaHHCiL7aePqPVCmn2jVgrZEC4Qo7Jwu51f2BKSeOsjfEsW4b5CwwQyyPh2bLrjwLz7ik5E5TT0iVEyOChf1zQ1qq1jMal96JurYGT+wgjjwLC1caPRlsvn4H8/5zSiP26xXcFkVfzWdxHHSYuOQf/SSv7WCIz5ZrFV92yvOJC+LZzJXe3Ykjgls9vmcSm2D2nTMEUfkHreVcB9IuvdpEqkzc+8p0kmywKGenhYyK2+GIv' +
+            'VTaZQEd1f3qfTVbVpHsLM4IlZ0ZqoRdMuPUFfesIL7LMSMEL9EdfUzcwiNQnXew6lo9DJRgK7RAXPSMs9wFhUa5O0J+Ub8wT/UtHQcRTmHMbWz8N2ZM3ZS/8sJZ7ZEBS4CN20gqJhAyjrjpwMpsY10GcvSM13oUm+v6/EVt8MZkDlwdPhaqbDcWK1PtINrlwvsYL4/xBBKge/zbcS3CHchMf3DPthFO2CETjPjQXZNMP8RtuqzjNOWQ1Hwp3YbhaO1aU9QnPug4whXCEuHJF0Eevs70il6488rpcL29rVUp0vcR2H09w4c/fxkRx7cRe5hB4TB3ArxZ6yinWPBE/KC3tQRd2qFmvrF8hHpmj1e7UhPlJqH7zOzzjbKWW4BPk0SDwmDqdQyxrxARk3Fl1Y2nV9eXRlWyemulfBDaYuyTJ7MjaZqTvRNaVCMilsurGxAwiNcBQO4A4wZO6jGUhAxzux11GvJ6P0zEBGTdRWtHY4uVohuylD7E3EI1XecmRcJ87aQXKQgZP61CDFoDK7+xFavMkG9I4WNZzr+GBq74kL1Tnytm/jAIR8YENzBn9kLxNuw9DxgqVGERqnaB2HaG/y/E/VwEq' +
+            'K95PiWHhcrUnuFOoT3MkgbCx5kPfH0thGMw4Qlw5rGjSt/fXvzfYITEDhkowFMcgFKokY3Kr+lxuYA21TrrFdDlHZXQEA6PzCcIV8Lxx5iMqWLlH6YfwRXtM3xi0d73Ylwm165Bsb+BzCDwmgGDZC/7cQA5B+QN+KElIxuRL6bhyjsroCAZb+wYzDp4XSSsaWVCFYWnnKU665PT85sQ2T8p7z5XjDnRJfX/RhqM+lsJSg2EQ2FrWkE36oQIbTNMSkTq7dYclRPrdRuy5FA8VGD1lmmsehpEUwj8sq9cZEJrXE/4GLdRoNtCmBlay+8HcIhxaed2QlJbv0m28obFJNQ537aAjXk/Jy/05W2to9rkN4OrvpvTUxAQi/x8ahTLn+Wm4Xt7WqpR/biAHrvKPPzrQYjuBqTj+ZiTui3qtoae2gujdyFZge6eMxW8oHiowx5slekX6oI1bQXTgZCsws19ji/9+rgJUS8mvnAwF+AjOWTCK+YtGro/FjanMVcOIgDSWx2dtDrHzPKrh5w3XurtiAjJuorS/1QIPhyAYccudXKdUqbcSzoQWadh96DxWimGEeF62c59CC7pssHQeK/EtW2Dqwc5H' +
+            'dqw19xKDaRwsa7fZ/s7bX/zNsY9MNRqDH3nAEsMWBYLwq62uYqdMt+GlgByC7wb8Z6IYRfLLI1dRFGZfXfBNnb9A/S10J4ZYoDk9P7cxg9oFpAnRkuOwF6n7KM8LQGX5JamiKUK/PXzbdeInA0Y+ArMm4QxatdBs55aOgpWmLea5c/OzY26tQt9XHTgZwwzl7lSbcinXy8USmSr9ZeLRRvjvTpBWsChktwQeE0Aw4ovALt0q2tUJZ5MrSvSK6V0Hb+b7e8bcR4Qjmqy3VfYWZkAaS+29uAfWSF6o04mvYwWkG8IgrbSxPXU7MriXKfIRmX5YS7MyICkdaDGTztocf/9atsDJn4GOFrvV4n9n46GlnTTuJdIzzZj4roU7VKLZbfcK+ssQXnl5XS6ZubukJY5De2dEM0F4AYb2zohmgvDr8JKjuzR70rzX+mLxjR1VrdnX0BHFVx4L0+Rxsb3/3qpsL4CO6v70XuV9MfbIgKT1D6R/8ET8oBrdycNR9bWV6nZkbTNS+SIAAAAAAAAAAIWQnxb1jr6mRilFc6rxLMwKVRK/Odt9Lnjb2Fcx3SbVKc++CGwta0ghi102WDoPmxUs0q36zXis' +
+            'g6ORiOLHlbzDudplX3+Sap7LoBssHYnDB7X4UJ8vqep+6NbJJpQNzza2fhqvO27KhgeYWXAkJav7eEnf0xqzaUx8V8yTKlHi2WQTpg6KJ/8mPqVmxxWmcWxx/DRDdtyJSk9ZUoRjevja8xTpiyC88lcnaMFKuWaHEIjbfGguyLuIcHX5U3pqYi56RljzAsKiYZEW2+WCCE2ofd4BgybnCdzAGnecaZfo7cOcPax9UMimCjOhoHiowMGoK+RSs4uXP3Rr6hNKiOmiKMy+uv2aJ6vq2U4GjHwE9IlSsXgiflBc9Iyw+wSZWWAX4BVt5Iq9RDi08qc9NTGMUormSf9YhbUV75JN/Pt2DGYcIS6SVjS0kxlcxZp5hpzaUZoh0ZA+MpSBBbW+XC0ZSs6M1F8umEONTKI4Epzbm2+pyr7+OdSBsmAJ7wuMQd7R6/aRpY4VTm2mTZ7mSB9UsG+OzxP9iknYXh0ByeH1r8gmURwJTuP2mKMwde5nrVrHgi7sTbJDjdR8KMGZ2nWJ9oM32xzoks3ON8V8Id2jUwWX3lA8VGBqQvKqVD/3k11yen5zYhup4jKHUwdFnfFWoZ4Pwt/kd8Yd07TNnCJ9' +
+            '5Yd/A5hqNBuUnrKkFcb07WIGEZRgKJNAY4DnWuhOEbCL53K21tDxb1CSkJHVls9t6GeV7D6e4N98+SdIK1gUMshqPhTuwm20cRnNp42swPbkAYnNEAy265KtvDoCj9/3sqAXwtLTUpwgDav40FyNazSnj5ui93c347RxnY8jHwFFvkI8L1u3wfceVf79iOVdaFMDK1nz7m5ls+nE/wc6qncqwzma5evsh4Ful/hCp1sRDi2y4EhKSzMSd8s92N7dvVEMrHnrn6U1IXlVKpH1x4qwqWhG4GptQ8foC0vwszoIybNUaxYe5TnxwjXrqZC+wb7yN2YGx7IsIJIzYUVpqusBUjtvwyialGlTq5Nazt0nKDj2PhM0DosEVeyhK6BSd6GyxJeP+KKlUSLKE+VAhiJ2E1hi0/HN243f3gi3bP5dHhLInkoXig5WgWsDlphn7l95lTMD7Vmv7XSLq3jXHW2Sny35PlPu9dio+Lp5jCr2GbFpjjnPa5Xdry90kQTi7CqcgOCIZCfOXI/YgluV6sTg2Zk6xgJxRpnDpRcwdvk9GxUfUKKfQp7VBeorx1lGNGZaz9x/S5hhsftTKSNC98chwAgOhkEw' +
+            'hpPNFpb9e3SHJzGScTaxS9NEbIpjoXIbZpo16KZoDkrKtljyOVCaFqTl3k70Loq5N6dDXug/CNkTTmI54mx/loJ5Gjwt9nSIP27wCoMpFjyOWn5C/etlkVyq7kx5gd21GfI0eFrx6A0lXd3j7Zi9cFCJijKpnMysKMpFGdpOZlauWYgPTLMdIg2XmPo31tsmMvlo8LT/zRqgDwlkTyWFRfo61RdeJN5y9GxUfF2yRhVxPoD7/w9+IHhDzytz0qr6vRfqNq7fYrT9ERus0W+Sz0q6p9vHLWfgs0FrXa1J+tO8oxaySRSoixXRUAaK7PkU4nwd6+Me/EBP5Ix1m+2iI37c/RQbUix4TlBw8XwmaBzmlsrBWBXzvDXSpks7tIGngAz/Kf59/fYe2frD1bqksGwmY6ke9ZnRA8EZkTRAQ0H3rU3tafIFVM2dlkm2G9aryMO95+rbE2jRMYmfsCr7ZR0Y41Lh+ufx2jkjWu98psGhu/XgqO5PepE3eAXPmgseMThxYYC/jlvZ+DrL2zzlgAJ15RXTi4l+Ry0/IfD7vMYtlG63ho6jlbo8JI0hlC4J5yI2Rb/eOYP/ZP65AuQbscl3QWMNENlX' +
+            'w8sXIrWNTsyieuxxnK4MO5n+y1GkjBX7FGWsgm0nMyvhvQR6116/AXn3M6+UGWDFZy7JbEGjxHXCf+umUkaE82Tv0P1144c07Z5gBAdDrhj7jimTue8UTThFPrEMYlqBaXhIB0I1XBJIz0LOFKbunhysH9YGMS3Oe4LWukeS6budFBx7H4caB1YWuA3BHEouuEnBmPIfp3d8qRgByNmlBrE0jkh+wnOtQbINHph7OkR0YKtVo8+744TmKANFdvIKG4fRbYl6YXMP4n3v5F1SWIPN5rjKPb63DCNkftAdERl6Nio+oFkjhLYfQPPxiT8QddRX0UQEcdxFWNo0I3A1uNymEWWH/CBDjZtn08mrJtArC1yI7g4lF2/nejgqtdqQJpzEctnY/jFjxB5G+qjLibervHcWQvUvfR3khS8SbzmoxrowJDOboGAFB9fO6IjIj+6Cxhogr65XokSJJteAEfyl5yg2pFjwByvOu49LTL1Je75K820koTyv6Zu3aVV9EvqevQWntanowEuqW4Nr20JzFI+sO3kFkIOEgShRwSHlV9NQbFWw/XL/mWrLTz1hPtoMjmTi3APwhoNW5rlJ6QTq1yq7Cw/8' +
+            'F6S1E1lncGrjyOFvBNU2f/hPMAKNr1cMGEbI/L06IjJbgSD39sqRCNRvojHs6j6mM02UdFM0ByVYQDlmworSSb7W86eanyH1aMy0g6X+li3QhXUbV+ExWv7QAj3lL9GOSw5bXyDmrd8aMy3pbrGrTKPOEPV7ZcYEEI97qNYsPNerB6OhEHPY4WsNrRKRvtVs8vNmQzUywJcuVXcmss7g1AAAAAAAAAAAywKkdt6bUCnk4y/Ui556wnNLZe4shPdeblOGvM1+EK8BtPyE58vKP8/oc1xlkF/VNhO/2g/0wuYRO4csMef26C/hi6JVBSrr6XS3LrxIoeQKvFZBuJ2Xm7RqpeYiArZuROwmsMS7/4emkDtbJ6UDx39oAZD8meZHl6hKOqcajZzdEu3hYDfqfMVUJR3dDchOiMVMfZVr4xNNkWlgSGYrXbCAcsyZCbmStd5ZYsXJfFGBuAOtGbY3ybL1l9lKgjDsCwiqxV9WXaTxMn/SAXKD1q2YkZ54815jarlRlnZ1H1Mk6SFnClN3T7n9PRwV1G1IkvZhlPvaSF9aNdxzEQFbN97T9HBUd6k9wAoOs4HNDY27iNgJxl/kNhYQSZe+rLpV' +
+            'IbcKyVaTsoxZ9MXiJUEYdtXbXrULIfSZVdehnPVcCW+pcka0w/hRn4VS1IeivTg1VGNdGBKXw1Ajwu/chRg78p9h+W7MDJN5U0iTo53cj+1e3wtZqgpUy6wsbRqfOJRc1667oNiqfecqv6AMCcXvKNhMxk889y+/IAP2TbFYeLOnJMffwG7J+AafMj9ogIaCzClqzVHQHJQFXiuuXMDFw2Jw4sIdYwG2O4QnIDgiGcDS8JAOhGq4JFL8byd6F0XSxpU8jOlNiw/gCfj+MJV1PmVbLHmSKE0LmEo31UNH38Tqta6/iAjipZo/0sCQzFa6nKDg//hM0DhMJZXkr63hYt9nCPSzvGMCv2IPI31U68qTQp0QHBGCYAl9T9CM3dTajC+bVy5g7O9winx/GMS0Hzow26Tf6dP/QAbxmn+w8Htfa/fdTcGe9B9tBkcycW6P+fvMhmpknTMwjI3lZ3REZIlxsPlyoCks1hpHJD9ht9jv64UR1MgnZpYctr5A0UejqrNfJfe4Et52FU5AcEQynVE9drZOVwaT80eax9L5Cqibiy5EdwechSl+uZ09haxpfjfmLfx9QMN3byWk7pOeW+BFyFDdj7Wt' +
+            'hu1bpxH/GVLpHQvZz2FrNTfgqyVuQI/7lgf2wDECWnoLAvXhFtI8nfPYSGv7UGUMYhz/J8QIdfV9QMtx+l/TSm2qZhbaopBin181SSPshOLshHw9xQfDswJaNmgEPOIFqL+ebE2sCxn6gIvi6b67lLW5nFJ3x0+jeNm8lfA5e8zjMuUM260mJMdPzhKTMnl+Fyns6y6nCavC1rn2mVTR+F2JjL+6uFUahZp2+xfditsb6FiGNi9/tfZBP4/xNs2K0xEPpbu341wKL+7VFMxNEegwEO3Nfxq5oedd5V9C1YHu3kpVwTshtvL1U1/5ThSADMG0bRiIdh684V/bZSmROy0l6JdacYHCcYF/HOLXpVQuUsXLXFMSS/n3pr7vnCgdnnIufSHy9W7OFw2bgdyn5g6bggUctJQbHnEvYjxJ1zMh5Fz6Qvn33MuOen+Lug9gjpiDGgEPtkZHTM8NjolbI6mShVhPsnqVjMK1cgUzVENC1bjphO/zpQEtGzQCHnGMV6Ziaq50GAv/GfwG49gTEjW6nU1qfG3+ydRMF4+G7WVQZSPmoC5SiAN3LVwGIpOJiwH0/gtpHsD42r2K7YJZkUxOOuyYW2e+' +
+            'sQ3wgn+/lqlqaSea1Pja4eeGidzT1f8ugS4aKx+lU9H7rZDW66DKGBrFQ7I0MQ45FgT33yy5eCemJBxpURifAnU1E8zqr3xeZPKln8hMTvokfSseSJ9fWttk1xirR0xIefSnofInCkAVc9qDKpvrrjSXhnloYhxyUUg40qIwIwTwr2U3/XL2hR0GAj46a0S6Z4WIw85u3XNmqJP3zHCs/9TSTim17anfOFYyFHDqamwHw0GMDlpKgyvLsi9WNbrNBLRs0Ah42QoG7lq4DEQ7DzshH0h2yPnlCVjDiRLu3pjRSznNv4sBWTl7KSBy9Bvgh8BAkxPhaN6tJumIR8qjn04UDIScZ4W71f9VHbfz2FOgykbRXVykDc1gIMeH/jRvhLdtzxXD+1fe/aD8oSHkzkuNe2CWAS09msZCrSmKLGQIddi9EPCvFLNXxup7g3SsTWMh2JpFFjLtqWcJxxmyP/dsJLvzKLwGxmLVJpEsCPI84l7EeJKzZrl4KD9vTzm9wIyPnp1oM/1PORewnnn0N1k94G+ywIwQ1oh4QbHRS9oZsm7uMhOdsLSUh2Z12T4vglk3dxmHwFiQ6ax4PUZhdfGCfgP/bIcJ' +
+            'lF3AqDU+uH9FFvllirW5Jj+Vc5h+sCDvuFUzC21RSDEq5qkbVCvLQWMx5BPGFgR5QI+OgYDTEaDv81FhwyVQOtBmIvm9lXDViHbZog1LjUmlUzE1VzoMi+Fo02TfkcQh9BsJ5/UKL48SsJsPJMGhLdpJzCypWT3EH1w0Vj5Xpr9U0U82qFaLgq983+BD9kGa6momhclD+Lzl3L+01+kdK7J63d55nQUga0Q8rtbmq217rpHJ9hvoRT64aKx8rlFjEce2UyLjMqTSPBSRuamS0I+1mC4DEcfKcKxkKODJ1NiJW8KWD1X8xXZCPpDsje/Xb/BQft6ecmc9z0XweozC6kqgYFSUH1yxWBD7W7De/Zxe/qHjvJrGk27dS0rcgAPrdBgI+OixDdIUXsG3KIWaIii8n3NQFylEJwoGQk69zNOXKu30Mxwr9gWZd+QKZqiGJVAwKkqBLtbdio2gpwN3R8UV+HqXDpt7MCPqqWAaxXi346o6c/utpg+2mTEequWXAAAAAAAAAAAxDvGdYgS09CKTcaZE22RVDeyvWRqWB5JcpJeLuKYklhwrGQo4dTU2QaKVtYLNYCwyedzBZCYnfcGhlKqfdkJx' +
+            'E52AOybf0KGuUcTUQegwFtgT+kStZd/BrAvyvEXU0hMjvmqSRsUV2UnXTQiSPc84nQUDISfQZucvf97/Xk1jx6R+KgFVJH0HmbFv8S+ov+1GYdQ5jJcqr9/Qu8ijP5VC3KeWlKUdBsuwIOu2faHnJboPBWNpbao05PGkgNX3bKfEOONOlRDq95OegSQ7ZPL8je+uRgctJc8sCPOjWG/wTtelY3WzzzpWIMlHzkDnhlBD+KPdhvGCKVaLeV6sammHgAMBHx27Il31NhLT9xReAxifddowDew8lXDbnDcgyfO7Ih5Xa3PbuHL2UkDk9TbdRDviUYiryKriH/442bNXqP1Dym7n5PEXyqNhS4mkfuz+NOcy4cZinoN0LEMbmbHUzzoWr4PC1mqq5agESZDpHCYnHXZMo71fkcS3TD9YEPl8bdBF+EGixn8a/Rn+YzFPyPlXI42YnOmnCQddUwbujlX8VAKqSPoOSPpWPJAjvrRl376rylI/dmyHfSLYvOHuzE0784XgReO+u2mzYRVzPhDqrWcg/UMots6xDnHl3Cq9zETvZzfgt1I/FY6kErCNmJx0xS22zmGb61mZK5Rd6Ios78oJd29M' +
+            'o71rjVt+N4TrRz2xy12JMMP7osKbSqB0nCgYFSXOF2toMxHy0MQ45F/Tute+hLcf/G7RWuX6gJs2zbARbF7+dymRhEdSCVjIopBwuVlgRghTEg66pgzBAToMBHx01ohpaR4KxtLaSWhz20l05utHUXqDiv30BZnJWkrNM7TiH5lgRslPwDSX8OarkujRy46iM1TH9WY4VvHZPuFwr3uuTWFr0nvCKuZ8krOaEDl6g3CryLMwS46YkL+WcodjCwKyW2fWB7b8bhXQMcOXzlU/5ha6WwGwBrUlqJut5ilucMhqH1Jdd9NDW24QNXBXPfoLZg77Khf8lat2Mnqel2NL9kutnWRiRYv18YMMrtvD90jFyPVCZpEx/5UEShzcSLDLiSli3zz4uGawueII6TDBNaFPs/BhGnZ8jSYF8hwWATbWtxki/sxUnjcIlDilkH2LC12jjlgD1JxaW8yc6m88vO2uJG07c//l0rh+D94i7c5eVKuxyoGF7B3n+I/oBWG5rV4ahwE1oIwvKtvWZc7MdleAtaeC9YNYPtyKLu3kez/J2Vw1Br7nD4O+ER1sTgXupgO5CVk2dBAQPIG0gJ/eXSxptgJ9DHdK' +
+            'OZCA19XIeVMJ1B4WSHQGtM3WOxgmUF5f+Z3C9JsCmOic0FQKlDy2f7yoS3+JHxfFcj0ds7eN8qZ4qm5x5ztPLhQz5pmgcWcNhPIb5FRiB4KY3zMntNIPL/BJ3OLTdp5c22xgGZZW63pkh0ayB4tHgzLNI1mNy63PHqSVW/DH2oXpoUNAG51Gtf2Spdm77CG4yBOMeQ4Ljhsu4AuabXulYvhXEriTt/H86yj+2AvqlJ1WSmXrikDqTGyZiOhHSigjRTWJixIdjy2r2MAyMazL9Loukcq5hny9eWC+Pe+OJjoMEal3YC/W8MtQ4a0WyTUn6uIulANf/YkoZtEvXeLOGv8bGEGrm/OQn5M53oz+DUOWRyfIxIoL91JFAsaqrlMcm5xe86wQtBNPovpJQqsypT8WWmLlURIrx0FI2nbm49eSSEDl5GSyp9NyrkPWl4TaIztyoQXhGoakigSRSUGmOLS2hSXJ3nhl3eq6rKbPgAIKl3PCULa9iMKE/7tevTOTi6DfRyyPak4q72y3TZUcMkJ5g3IqMY1Bc/fN/784m7IHTAr5OCwCbIpqDwskOgNab9rlPF+Ikx/Gi5iWflOKw0T/WccaqOY5' +
+            '4vzgzkOekimiDN4kedjNQBnon6LI69jp9Ea7z/OYJwxDs1M+IoTkVdgvDc2OlFBGUQZvErJs6CDnOVeva8VCbQgezlpAwW+gOxk9T8W/q3t/5mSI3xdNQg6YFO9wWATYgTeshXw518axczJE4YWoIWlcP4lvEfhn9s8GV+Pv9SQaq/J20Clj1S2jZk51uR5eAom9mBB30iiQwf199BNgjzxVN7b9k6kXqhIQfjkZouAGhtq1MJlreNqmsFWe44Juw04v91YIWodtU1ikT/9BN/xYdZWzWUisfKUJXMfV9n77FH9si3VKwL/rJquR3az5aJbvxWekkXPKmjHhHnxcM7vkQYaxMxWpDdt5O2iav+RwtKArp/ogjuR6OntzB/lRjOzVvhSjaCLu7Um5I7FE2Rdwi024s9wxYIghnydl/tOz+o/c8fJ6CZELLTH8pgmbD1LEo3jtbcxQzL9eutmBNGvVghF/ZipPlM6aUNT92d8rJbz7RSB1JmfEK2YfSfy/SSQg/HIyWd0DQ23UGMK7PB9uRRf4crORoIVjvGmvH2jUPqS67ruGtgHK0EwItWkUrJTKywmAyZhUw9hzmjc4ZCb+xcAtusrC' +
+            '3qnXeL4NOz4ED2ctIO65UOWw6jd7spBF8wqxNsu0JWBiAZwHNxIs++hrkwwTKC+hzBzrVC7lN0tTj9KKohs6CBthIjrYnArBNsJEdK0lFJ96I9Pp90ydBr4h9ueZaMXtz1+GgDYnjHf3BdYb61qcME0rR9FS3OCNX557/cI07Pgkd3hYPc0Y6oZ7pnxEFdWqTOGXnVppiZkAAAAAAAAAAOxk9CEzxpbxtXxVacFrEXHBx5JvRn+Ir2VNlv4PPi6XFfk21ajEDhm4pyxSqfGulalRfaoh2xncWNJxBPoY7pRZGKFI8q2HgFzdFina9lfEgnTBUWT7bPrR+xPbxuBW8n1v2RDPYJ9qtj84vdmpqk09n+f69SbAA3S7xwaHFJne32MHNLa4Uio60+0DzQrCb/reryCDwCPUwA1CI07K4buFOMuoXNdulsQCJQ5uJFjrR7w0EwJqXQWv16cfEUJypJeN94TMP2LjuW38HqFEx4Ehss85FZbIrjGOTo2VCRbzzpVWzD6S5WM4WlCb3X0QRzWBKaC156+j5vOH42NwK3ngdV1WU+lAAXvpA6X/+fQSErU8LJDoDHUzB/MVhX7E24+vuGoMYdMe' +
+            '2eXdgYYhOVJ3+KrSn9Yi4iW9qBQ1eHH+dXEXSo+h8MoTf+xgmF1lYTBEnsGdvH/npUDU3UH0zyzcIGrgrnrpFluRHNDi2lWosjBfkPlHEx00S/nsvVLGt10XxmXSQz7QGCJP7sBesf2eWemShEtkV5pWjr+kpd0Ho8YOaHFtpFR+LLTE16IkVoexdjBMoLy+QTrupjLzNn2ZFeNrvGdmO0DwPuo6Rl9pHC0ow+CwCK1OaCoFSh5bsQXFt2EoW9BE4b+NGltcKRXywGF6wwFMdLf16PHRHMNZY8tMSz+nRe+dGoRGnInfa+M2MIJLK/s91fR09uYO76L1jGuD+y1OGEZ25F8K3zQRIHgfdR0jobq9Ypszgap+0a4dd1MZ9xuw/tHIDaMumoRVCQg/koJRcCmsAWNVV6cOp8lpRVGDHQSOZWgmBNS6ChH2UfiIKrdJ133JbvZ5PYrvJ5n1KwQtzUju8LB6hzDJIvGi7Q1Uc5JhQvHTL9CXx0pnTShq8OLhgP18yXSMvtJxfnBnr09JmpOCkKns0duziOOykzRN0XInNBWMJQ+j1g'); //==
+
+    // Variables
+    var sigma, N, h;
+
+    // 64bit tools 
+    function get8(x, i) {
+        return (x[i >> 2] >> ((i & 3) << 3)) & 0xff;
+    }
+
+    // 512bit tools 
+    function add512(x, y) {
+        var CF = 0, w0, w1;
+        for (var i = 0; i < 16; i++) {
+            w0 = (x[i] & 0xffff) + (y[i] & 0xffff) + (CF || 0);
+            w1 = (x[i] >>> 16) + (y[i] >>> 16) + (w0 >>> 16);
+            x[i] = (w0 & 0xffff) | (w1 << 16);
+            CF = (w1 >>> 16);
+        }
+    }
+
+    function get512(d) {
+        return new Int32Array(d.buffer, d.byteOffset, 16);
+    }
+
+
+    function copy512(r, d) {
+        for (var i = 0; i < 16; i++)
+            r[i] = d[i];
+    }
+
+    function new512() {
+        return new Int32Array(16);
+    }
+
+    // Core private algorithms
+    function xor512(x, y) {
+        for (var i = 0; i < 16; i++)
+            x[i] = x[i] ^ y[i];
+    }
+
+
+    var r = new512();
+    function XLPS(x, y) {
+        copy512(r, x);
+        xor512(r, y);
+        for (var i = 0; i < 8; i++) {
+            var z0, z1, k = get8(r, i) << 1;
+            z0 = Ax[k];
+            z1 = Ax[k + 1];
+            for (var j = 1; j < 8; j++) {
+                k = (j << 9) + (get8(r, (j << 3) + i) << 1);
+                z0 = z0 ^ Ax[k];
+                z1 = z1 ^ Ax[k + 1];
+            }
+            x[i << 1] = z0;
+            x[(i << 1) + 1] = z1;
+        }
+    }
+
+    var data = new512(), Ki = new512();
+    function g(h, N, m)
+    {
+        var i;
+
+        copy512(data, h);
+        XLPS(data, N);
+
+        /* Starting E() */
+        copy512(Ki, data);
+        XLPS(data, m);
+
+        for (i = 0; i < 11; i++) {
+            XLPS(Ki, C[i]);
+            XLPS(data, Ki);
+        }
+
+        XLPS(Ki, C[11]);
+        xor512(data, Ki);
+        /* E() done */
+
+        xor512(h, data);
+        xor512(h, m);
+    }
+
+    // Stages
+    function stage2(d) {
+        var m = get512(d);
+        g(h, N, m);
+
+        add512(N, buffer512);
+        add512(sigma, m);
+    }
+
+    function stage3(d) {
+        var n = d.length;
+        if (n > 63)
+            return;
+
+        var b0 = new Int32Array(16);
+        b0[0] = n << 3;
+
+        var b = new Uint8Array(64);
+        for (var i = 0; i < n; i++)
+            b[i] = d[i];
+        b[n] = 0x01;
+
+        var m = get512(b), m0 = get512(b0);
+        g(h, N, m);
+
+        add512(N, m0);
+        add512(sigma, m);
+
+        g(h, buffer0, N);
+        g(h, buffer0, sigma);
+    }
+
+    return function (data) {
+
+        // Cleanup 
+        sigma = new512();
+        N = new512();
+
+        // Initial vector
+        h = new512();
+        for (var i = 0; i < 16; i++)
+            if (this.bitLength === 256)
+                h[i] = 0x01010101;
+
+        // Make data
+        var d = new Uint8Array(buffer(data));
+
+        var n = d.length;
+        var r = n % 64, q = (n - r) / 64;
+
+        for (var i = 0; i < q; i++)
+            stage2.call(this, new Uint8Array(d.buffer, i * 64, 64));
+
+        stage3.call(this, new Uint8Array(d.buffer, q * 64, r));
+
+        var digest;
+        if (this.bitLength === 256) {
+            digest = new Int32Array(8);
+            for (var i = 0; i < 8; i++)
+                digest[i] = h[8 + i];
+        } else {
+            digest = new Int32Array(16);
+            for (var i = 0; i < 16; i++)
+                digest[i] = h[i];
+        }
+        // Swap hash for SignalCom
+        if (this.procreator === 'SC' || this.procreator === 'VN')
+            return swap(digest.buffer);
+        else
+            return digest.buffer;
+    };
+} // </editor-fold>
+)();
+
+/**
+ * Algorithm name GOST R 34.11-94<br><br>
+ * 
+ * http://tools.ietf.org/html/rfc5831
+ * 
+ * The digest method returns digest data in according to GOST R 34.11-94.
+ * @memberOf GostDigest
+ * @method digest
+ * @instance
+ * @param {(ArrayBuffer|TypedArray)} data Data
+ * @returns {ArrayBuffer} Digest of data
+ */
+var digest94 = (function () // <editor-fold defaultstate="collapsed">
+{
+    var C, H, M, Sum;
+
+    // (i + 1 + 4(k - 1)) = 8i + k      i = 0-3, k = 1-8
+    function P(d) {
+        var K = new Uint8Array(32);
+
+        for (var k = 0; k < 8; k++) {
+            K[4 * k] = d[k];
+            K[1 + 4 * k] = d[ 8 + k];
+            K[2 + 4 * k] = d[16 + k];
+            K[3 + 4 * k] = d[24 + k];
+        }
+
+        return K;
+    }
+
+    //A (x) = (x0 ^ x1) || x3 || x2 || x1
+    function A(d)
+    {
+        var a = new Uint8Array(8);
+
+        for (var j = 0; j < 8; j++)
+        {
+            a[j] = (d[j] ^ d[j + 8]);
+        }
+
+        arraycopy(d, 8, d, 0, 24);
+        arraycopy(a, 0, d, 24, 8);
+
+        return d;
+    }
+
+    // (in:) n16||..||n1 ==> (out:) n1^n2^n3^n4^n13^n16||n16||..||n2
+    function fw(d) {
+        var wS = new Uint16Array(d.buffer, 0, 16);
+        var wS15 = wS[0] ^ wS[1] ^ wS[2] ^ wS[3] ^ wS[12] ^ wS[15];
+        arraycopy(wS, 1, wS, 0, 15);
+        wS[15] = wS15;
+    }
+
+    //Encrypt function, ECB mode
+    function encrypt(key, s, sOff, d, dOff) {
+        var t = new Uint8Array(8);
+        arraycopy(d, dOff, t, 0, 8);
+        var r = new Uint8Array(this.cipher.encrypt(key, t));
+        arraycopy(r, 0, s, sOff, 8);
+    }
+
+    // block processing
+    function process(d, dOff) {
+        var S = new Uint8Array(32), U = new Uint8Array(32),
+                V = new Uint8Array(32), W = new Uint8Array(32);
+
+        arraycopy(d, dOff, M, 0, 32);
+
+        //key step 1
+
+        // H = h3 || h2 || h1 || h0
+        // S = s3 || s2 || s1 || s0
+        arraycopy(H, 0, U, 0, 32);
+        arraycopy(M, 0, V, 0, 32);
+        for (var j = 0; j < 32; j++)
+        {
+            W[j] = (U[j] ^ V[j]);
+        }
+        // Encrypt GOST 28147-ECB
+        encrypt.call(this, P(W), S, 0, H, 0); // s0 = EK0 [h0]
+
+        //keys step 2,3,4
+        for (var i = 1; i < 4; i++) {
+            var tmpA = A(U);
+            for (var j = 0; j < 32; j++) {
+                U[j] = (tmpA[j] ^ C[i][j]);
+            }
+            V = A(A(V));
+            for (var j = 0; j < 32; j++) {
+                W[j] = (U[j] ^ V[j]);
+            }
+            // Encrypt GOST 28147-ECB
+            encrypt.call(this, P(W), S, i * 8, H, i * 8); // si = EKi [hi]
+        }
+
+        // x(M, H) = y61(H^y(M^y12(S)))
+        for (var n = 0; n < 12; n++) {
+            fw(S);
+        }
+        for (var n = 0; n < 32; n++) {
+            S[n] = (S[n] ^ M[n]);
+        }
+
+        fw(S);
+
+        for (var n = 0; n < 32; n++) {
+            S[n] = (H[n] ^ S[n]);
+        }
+        for (var n = 0; n < 61; n++) {
+            fw(S);
+        }
+        arraycopy(S, 0, H, 0, H.length);
+    }
+
+
+    //  256 bitsblock modul -> (Sum + a mod (2^256))
+    function summing(d)
+    {
+        var carry = 0;
+        for (var i = 0; i < Sum.length; i++)
+        {
+            var sum = (Sum[i] & 0xff) + (d[i] & 0xff) + carry;
+
+            Sum[i] = sum;
+
+            carry = sum >>> 8;
+        }
+    }
+
+    // reset the chaining variables to the IV values.
+    var C2 = new Uint8Array([
+        0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF,
+        0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
+        0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF,
+        0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF
+    ]);
+
+    return function (data) {
+
+        // Reset buffers
+        H = new Uint8Array(32);
+        M = new Uint8Array(32);
+        Sum = new Uint8Array(32);
+
+        // Reset IV value
+        C = new Array(4);
+        for (var i = 0; i < 4; i++)
+            C[i] = new Uint8Array(32);
+        arraycopy(C2, 0, C[2], 0, C2.length);
+
+        // Make data
+        var d = new Uint8Array(buffer(data));
+
+        var n = d.length;
+        var r = n % 32, q = (n - r) / 32;
+
+        // Proccess full blocks 
+        for (var i = 0; i < q; i++) {
+            var b = new Uint8Array(d.buffer, i * 32, 32);
+
+            summing.call(this, b); // calc sum M
+            process.call(this, b, 0);
+        }
+
+        // load d the remadder with padding zero;
+        if (r > 0) {
+            var b = new Uint8Array(d.buffer, q * 32),
+                    c = new Uint8Array(32);
+            arraycopy(b, 0, c, 0, r);
+            summing.call(this, c); // calc sum M
+            process.call(this, c, 0);
+
+        }
+
+        // get length into L (byteCount * 8 = bitCount) in little endian.
+        var L = new Uint8Array(32), n8 = n * 8, k = 0;
+        while (n8 > 0) {
+            L[k++] = n8 & 0xff;
+            n8 = Math.floor(n8 / 256);
+        }
+        process.call(this, L, 0);
+        process.call(this, Sum, 0);
+
+        var h = H.buffer;
+
+        // Swap hash for SignalCom
+        if (this.procreator === 'SC')
+            h = swap(h);
+
+        return h;
+    };
+
+} // </editor-fold>
+)();
+
+/**
+ * Algorithm name SHA-1<br><br>
+ * 
+ * https://tools.ietf.org/html/rfc3174
+ * 
+ * The digest method returns digest data in according to SHA-1.<br>
+ *  
+ * @memberOf GostDigest
+ * @method digest
+ * @instance
+ * @param {(ArrayBuffer|TypedArray)} data Data
+ * @returns {ArrayBuffer} Digest of data
+ */
+var digestSHA1 = (function () // <editor-fold defaultstate="collapsed">
+{
+
+    // Create a buffer for each 80 word block.
+    var state, block = new Uint32Array(80);
+
+    function common(a, e, w, k, f) {
+        return (f + e + w + k + ((a << 5) | (a >>> 27))) >>> 0;
+    }
+
+    function f1(a, b, c, d, e, w) {
+        return common(a, e, w, 0x5A827999, d ^ (b & (c ^ d)));
+    }
+
+    function f2(a, b, c, d, e, w) {
+        return common(a, e, w, 0x6ED9EBA1, b ^ c ^ d);
+    }
+
+    function f3(a, b, c, d, e, w) {
+        return common(a, e, w, 0x8F1BBCDC, (b & c) | (d & (b | c)));
+    }
+
+    function f4(a, b, c, d, e, w) {
+        return common(a, e, w, 0xCA62C1D6, b ^ c ^ d);
+    }
+
+    function cycle(state, block) {
+        var a = state[0],
+                b = state[1],
+                c = state[2],
+                d = state[3],
+                e = state[4];
+
+        // Partially unroll loops so we don't have to shift variables.
+        var fn = f1;
+        for (var i = 0; i < 80; i += 5) {
+            if (i === 20) {
+                fn = f2;
+            }
+            else if (i === 40) {
+                fn = f3;
+            }
+            else if (i === 60) {
+                fn = f4;
+            }
+            e = fn(a, b, c, d, e, block[i]);
+            b = ((b << 30) | (b >>> 2)) >>> 0;
+            d = fn(e, a, b, c, d, block[i + 1]);
+            a = ((a << 30) | (a >>> 2)) >>> 0;
+            c = fn(d, e, a, b, c, block[i + 2]);
+            e = ((e << 30) | (e >>> 2)) >>> 0;
+            b = fn(c, d, e, a, b, block[i + 3]);
+            d = ((d << 30) | (d >>> 2)) >>> 0;
+            a = fn(b, c, d, e, a, block[i + 4]);
+            c = ((c << 30) | (c >>> 2)) >>> 0;
+        }
+        state[0] += a;
+        state[1] += b;
+        state[2] += c;
+        state[3] += d;
+        state[4] += e;
+    }
+
+    // Swap bytes for 32bits word
+    function swap32(b) {
+        return ((b & 0xff) << 24)
+                | ((b & 0xff00) << 8)
+                | ((b >> 8) & 0xff00)
+                | ((b >> 24) & 0xff);
+    }
+
+    // input is a Uint8Array bitstream of the data
+    return function (data) {
+        var d = new Uint8Array(buffer(data)), dlen = d.length;
+
+        // Pad the input string length.
+        var len = dlen + 9;
+        if (len % 64) {
+            len += 64 - (len % 64);
+        }
+
+        state = new Uint32Array(5);
+        state[0] = 0x67452301;
+        state[1] = 0xefcdab89;
+        state[2] = 0x98badcfe;
+        state[3] = 0x10325476;
+        state[4] = 0xc3d2e1f0;
+
+        for (var ofs = 0; ofs < len; ofs += 64) {
+
+            // Copy input to block and write padding as needed
+            for (var i = 0; i < 64; i++) {
+                var b = 0,
+                        o = ofs + i;
+                if (o < dlen) {
+                    b = d[o];
+                }
+                else if (o === dlen) {
+                    b = 0x80;
+                }
+                else {
+                    // Write original bit length as a 64bit big-endian integer to the end.
+                    var x = len - o - 1;
+                    if (x >= 0 && x < 4) {
+                        b = (dlen << 3 >>> (x * 8)) & 0xff;
+                    }
+                }
+
+                // Interpret the input bytes as big-endian per the spec
+                if (i % 4 === 0) {
+                    block[i >> 2] = b << 24;
+                }
+                else {
+                    block[i >> 2] |= b << ((3 - (i % 4)) * 8);
+                }
+            }
+
+            // Extend the block
+            for (var i = 16; i < 80; i++) {
+                var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16];
+                block[i] = (w << 1) | (w >>> 31);
+            }
+
+            cycle(state, block);
+
+        }
+
+        // Swap the bytes around since they are big endian internally
+        for (var i = 0; i < 5; i++)
+            state[i] = swap32(state[i]);
+        return state.buffer;
+    };
+
+} // </editor-fold>
+)();
+
+/** 
+ * Algorithm name GOST R 34.11-HMAC<br><br>
+ * 
+ * HMAC with the specified hash function.
+ * @memberOf GostDigest
+ * @method sign
+ * @instance
+ * @param {ArrayBuffer} key The key for HMAC.
+ * @param {Hash} data Data
+ */
+function signHMAC(key, data) // <editor-fold defaultstate="collapsed">
+{
+    // GOST R 34.11-94 - B=32b, L=32b
+    // GOST R 34.11-256 - B=64b, L=32b
+    // GOST R 34.11-512 - B=64b, L=64b
+    var b = (this.digest === digest94) ? 32 : 64,
+            l = this.bitLength / 8,
+            k = buffer(key),
+            d = buffer(data), k0;
+    if (k.byteLength === b)
+        k0 = new Uint8Array(k);
+    else {
+        var k0 = new Uint8Array(b);
+        if (k.byteLength > b) {
+            k0.set(new Uint8Array(this.digest(k)));
+        } else {
+            k0.set(new Uint8Array(k));
+        }
+    }
+    var s0 = new Uint8Array(b + d.byteLength),
+            s1 = new Uint8Array(b + l);
+    for (var i = 0; i < b; i++) {
+        s0[i] = k0[i] ^ 0x36;
+        s1[i] = k0[i] ^ 0x5C;
+    }
+    s0.set(new Uint8Array(d), b);
+    s1.set(new Uint8Array(this.digest(s0)), b);
+    return this.digest(s1);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-HMAC<br><br>
+ * 
+ * Verify HMAC based on GOST R 34.11 hash
+ * 
+ * @memberOf GostDigest
+ * @method verify
+ * @instance
+ * @param {(ArrayBuffer|TypedArray)} key Key which used for HMAC generation
+ * @param {(ArrayBuffer|TypedArray)} signature generated HMAC
+ * @param {(ArrayBuffer|TypedArray)} data Data
+ * @returns {boolean} HMAC verified = true
+ */
+function verifyHMAC(key, signature, data) // <editor-fold defaultstate="collapsed">
+{
+    var hmac = new Uint8Array(this.sign(key, data)),
+            test = new Uint8Array(signature);
+    if (hmac.length !== test.length)
+        return false;
+    for (var i = 0, n = hmac.length; i < n; i++)
+        if (hmac[i] !== test[i])
+            return false;
+    return true;
+} // </editor-fold>
+
+
+/**
+ * Algorithm name GOST R 34.11-KDF<br><br>
+ * 
+ * Simple generate key 256/512 bit random seed for derivation algorithms
+ * 
+ * @memberOf GostDigest
+ * @method generateKey
+ * @instance
+ * @returns {ArrayBuffer} Generated key
+ */
+function generateKey() // <editor-fold defaultstate="collapsed">
+{
+    return getSeed(this.bitLength).buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-PFXKDF<br><br>
+ * 
+ * Derive bits from password (PKCS12 mode)
+ *  <ul>
+ *      <li>algorithm.salt - random value, salt</li>
+ *      <li>algorithm.iterations - number of iterations</li>
+ *  </ul>
+ * @memberOf GostDigest
+ * @method deriveBits
+ * @instance
+ * @param {ArrayBuffer} baseKey - password after UTF-8 decoding
+ * @param {number} length output bit-length
+ * @returns {ArrayBuffer} result
+ */
+function deriveBitsPFXKDF(baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    if (length % 8 > 0)
+        throw new DataError('Length must multiple of 8');
+    var u = this.bitLength / 8, v = (this.digest === digest94) ? 32 : 64,
+            n = length / 8, r = this.iterations;
+    //   1.  Construct a string, D (the "diversifier"), by concatenating v/8
+    //       copies of ID.
+    var ID = this.diversifier, D = new Uint8Array(v);
+    for (var i = 0; i < v; i++)
+        D[i] = ID;
+    //   2.  Concatenate copies of the salt together to create a string S of
+    //       length v(ceiling(s/v)) bits (the final copy of the salt may be
+    //       truncated to create S).  Note that if the salt is the empty
+    //       string, then so is S.
+    var S0 = new Uint8Array(buffer(this.salt)), s = S0.length,
+            slen = v * Math.ceil(s / v), S = new Uint8Array(slen);
+    for (var i = 0; i < slen; i++)
+        S[i] = S0[i % s];
+    //   3.  Concatenate copies of the password together to create a string P
+    //       of length v(ceiling(p/v)) bits (the final copy of the password
+    //       may be truncated to create P).  Note that if the password is the
+    //       empty string, then so is P.
+    var P0 = new Uint8Array(buffer(baseKey)), p = P0.length,
+            plen = v * Math.ceil(p / v), P = new Uint8Array(plen);
+    for (var i = 0; i < plen; i++)
+        P[i] = P0[i % p];
+    //   4.  Set I=S||P to be the concatenation of S and P.
+    var I = new Uint8Array(slen + plen);
+    arraycopy(S, 0, I, 0, slen);
+    arraycopy(P, 0, I, slen, plen);
+    //   5.  Set c=ceiling(n/u).
+    var c = Math.ceil(n / u);
+    //   6.  For i=1, 2, ..., c, do the following:
+    var A = new Uint8Array(c * u);
+    for (var i = 0; i < c; i++) {
+        //  A.  Set A2=H^r(D||I). (i.e., the r-th hash of D||1,
+        //      H(H(H(... H(D||I))))
+        var H = new Uint8Array(v + slen + plen);
+        arraycopy(D, 0, H, 0, v);
+        arraycopy(I, 0, H, v, slen + plen);
+        for (var j = 0; j < r; j++)
+            H = new Uint8Array(this.digest(H));
+        arraycopy(H, 0, A, i * u, u);
+        //  B.  Concatenate copies of Ai to create a string B of length v
+        //      bits (the final copy of Ai may be truncated to create B).
+        var B = new Uint8Array(v);
+        for (var j = 0; j < v; j++)
+            B[j] = H[j % u];
+        //  C.  Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit
+        //      blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by
+        //      setting I_j=(I_j+B+1) mod 2^v for each j.
+        var k = (slen + plen) / v;
+        for (j = 0; j < k; j++) {
+            var cf = 1, w;
+            for (var l = v - 1; l >= 0; --l) {
+                w = I[v * j + l] + B[l] + cf;
+                cf = w >>> 8;
+                I[v * j + l] = w & 0xff;
+            }
+        }
+    }
+    //   7.  Concatenate A_1, A_2, ..., A_c together to form a pseudorandom
+    //       bit string, A.
+    //   8.  Use the first n bits of A as the output of this entire process.
+    var R = new Uint8Array(n);
+    arraycopy(A, 0, R, 0, n);
+    return R.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-KDF<br><br>
+ * 
+ * Derive bits for KEK deversification in 34.10-2012 algorithm
+ * KDF(KEK, UKM, label) = HMAC256 (KEK,  0x01|label|0x00|UKM|0x01|0x00) 
+ * Default label = 0x26|0xBD|0xB8|0x78 
+ * 
+ * @memberOf GostDigest
+ * @method deriveBits
+ * @instance
+ * @param {(ArrayBuffer|TypedArray)} baseKey base key for deriviation
+ * @param {number} length output bit-length 
+ * @returns {ArrayBuffer} result
+ */
+function deriveBitsKDF(baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    if (length % 8 > 0)
+        throw new DataError('Length must be multiple of 8');
+    var rlen = length / 8, label, context = new Uint8Array(buffer(this.context)),
+            blen = this.bitLength / 8, n = Math.ceil(rlen / blen);
+    if (this.label)
+        label = new Uint8Array(buffer(this.label));
+    else
+        label = new Uint8Array([0x26, 0xBD, 0xB8, 0x78]);
+    var result = new Uint8Array(rlen);
+    for (var i = 0; i < n; i++) {
+        var data = new Uint8Array(label.length + context.length + 4);
+        data[0] = i + 1;
+        data.set(label, 1);
+        data[label.length + 1] = 0x00;
+        data.set(context, label.length + 2);
+        data[data.length - 2] = length >>> 8;
+        data[data.length - 1] = length & 0xff;
+        result.set(new Uint8Array(signHMAC.call(this, baseKey, data), 0,
+                i < n - 1 ? blen : rlen - i * blen), i * blen);
+    }
+    return result.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-PBKDF1<br><br>
+ * 
+ * Derive bits from password
+ *  <ul>
+ *      <li>algorithm.salt - random value, salt</li>
+ *      <li>algorithm.iterations - number of iterations</li>
+ *  </ul>
+ * @memberOf GostDigest
+ * @method deriveBits
+ * @instance
+ * @param {ArrayBuffer} baseKey - password after UTF-8 decoding
+ * @param {number} length output bit-length
+ * @returns {ArrayBuffer} result
+ */
+function deriveBitsPBKDF1(baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    if (length < this.bitLength / 2 || length % 8 > 0)
+        throw new DataError('Length must be more than ' + this.bitLength / 2 + ' bits and multiple of 8');
+    var hLen = this.bitLength / 8, dkLen = length / 8,
+            c = this.iterations,
+            P = new Uint8Array(buffer(baseKey)),
+            S = new Uint8Array(buffer(this.salt)),
+            slen = S.length, plen = P.length,
+            T = new Uint8Array(plen + slen),
+            DK = new Uint8Array(dkLen);
+    if (dkLen > hLen)
+        throw new DataError('Invalid parameters: Length value');
+    arraycopy(P, 0, T, 0, plen);
+    arraycopy(S, 0, T, plen, slen);
+    for (var i = 0; i < c; i++)
+        T = new Uint8Array(this.digest(T));
+    arraycopy(T, 0, DK, 0, dkLen);
+    return DK.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-PBKDF2<br><br>
+ * 
+ * Derive bits from password
+ *  <ul>
+ *      <li>algorithm.salt - random value, salt</li>
+ *      <li>algorithm.iterations - number of iterations</li>
+ *  </ul>
+ * @memberOf GostDigest
+ * @method deriveBits
+ * @instance
+ * @param {ArrayBuffer} baseKey - password after UTF-8 decoding
+ * @param {number} length output bit-length
+ * @returns {ArrayBuffer} result
+ */
+function deriveBitsPBKDF2(baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    var diversifier = this.diversifier || 1; // For PKCS12 MAC required 3*length
+    length = length * diversifier;
+    if (length < this.bitLength / 2 || length % 8 > 0)
+        throw new DataError('Length must be more than ' + this.bitLength / 2 + ' bits and multiple of 8');
+    var hLen = this.bitLength / 8, dkLen = length / 8,
+            c = this.iterations,
+            P = new Uint8Array(buffer(baseKey)),
+            S = new Uint8Array(buffer(this.salt));
+    var slen = S.byteLength,
+            data = new Uint8Array(slen + 4);
+    arraycopy(S, 0, data, 0, slen);
+
+    if (dkLen > (0xffffffff - 1) * 32)
+        throw new DataError('Invalid parameters: Length value');
+    var n = Math.ceil(dkLen / hLen),
+            DK = new Uint8Array(dkLen);
+    for (var i = 1; i <= n; i++) {
+        data[slen] = i >>> 24 & 0xff;
+        data[slen + 1] = i >>> 16 & 0xff;
+        data[slen + 2] = i >>> 8 & 0xff;
+        data[slen + 3] = i & 0xff;
+
+        var U = new Uint8Array(signHMAC.call(this, P, data)), Z = U;
+        for (var j = 1; j < c; j++) {
+            U = new Uint8Array(signHMAC.call(this, P, U));
+            for (var k = 0; k < hLen; k++)
+                Z[k] = U[k] ^ Z[k];
+        }
+        var ofs = (i - 1) * hLen;
+        arraycopy(Z, 0, DK, ofs, Math.min(hLen, dkLen - ofs));
+    }
+    if (diversifier > 1) {
+        var rLen = dkLen / diversifier, R = new Uint8Array(rLen);
+        arraycopy(DK, dkLen - rLen, R, 0, rLen);
+        return R.buffer;
+    } else
+        return DK.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.11-CPKDF<br><br>
+ * 
+ * Derive bits from password. CryptoPro algorithm
+ *  <ul>
+ *      <li>algorithm.salt - random value, salt</li>
+ *      <li>algorithm.iterations - number of iterations</li>
+ *  </ul>
+ * @memberOf GostDigest
+ * @method deriveBits
+ * @instance
+ * @param {ArrayBuffer} baseKey - password after UTF-8 decoding
+ * @param {number} length output bit-length
+ * @returns {ArrayBuffer} result
+ */
+function deriveBitsCP(baseKey, length) {
+    if (length > this.bitLength || length % 8 > 0)
+        throw new DataError('Length can\'t be more than ' + this.bitLength + ' bits and multiple of 8');
+    // GOST R 34.11-94 - B=32b, L=32b
+    // GOST R 34.11-256 - B=64b, L=32b
+    // GOST R 34.11-512 - B=64b, L=64b
+    var b = (this.digest === digest94) ? 32 : 64,
+            l = this.bitLength / 8,
+            p = baseKey && baseKey.byteLength > 0 ? new Uint8Array(buffer(baseKey)) : false,
+            plen = p ? p.length : 0,
+            iterations = this.iterations,
+            salt = new Uint8Array(buffer(this.salt)),
+            slen = salt.length,
+            d = new Uint8Array(slen + plen);
+    arraycopy(salt, 0, d, 0, slen);
+    if (p)
+        arraycopy(p, 0, d, slen, plen);
+
+    var h = new Uint8Array(this.digest(d)),
+            k = new Uint8Array(b),
+            s0 = new Uint8Array(b),
+            s1 = new Uint8Array(b);
+    var c = 'DENEFH028.760246785.IUEFHWUIO.EF';
+    for (var i = 0; i < c.length; i++)
+        k[i] = c.charCodeAt(i);
+
+    d = new Uint8Array(2 * (b + l));
+    for (var j = 0; j < iterations; j++) {
+        for (var i = 0; i < b; i++) {
+            s0[i] = k[i] ^ 0x36;
+            s1[i] = k[i] ^ 0x5C;
+            k[i] = 0;
+        }
+        arraycopy(s0, 0, d, 0, b);
+        arraycopy(h, 0, d, b, l);
+        arraycopy(s1, 0, d, b + l, b);
+        arraycopy(h, 0, d, b + l + b, l);
+        arraycopy(new Uint8Array(this.digest(d)), 0, k, 0, l);
+    }
+    for (var i = 0; i < l; i++) {
+        s0[i] = k[i] ^ 0x36;
+        s1[i] = k[i] ^ 0x5C;
+        k[i] = 0;
+    }
+    d = new Uint8Array(2 * l + slen + plen);
+    arraycopy(s0, 0, d, 0, l);
+    arraycopy(salt, 0, d, l, slen);
+    arraycopy(s1, 0, d, l + slen, l);
+    if (p)
+        arraycopy(p, 0, d, l + slen + l, plen);
+    h = this.digest(this.digest(d));
+    if (length === this.bitLength)
+        return h;
+    else {
+        var rlen = length / 8, r = new Uint8Array(rlen);
+        arraycopy(h, 0, r, 0, rlen);
+        return r.buffer;
+    }
+}
+
+/**
+ * Algorithm name GOST R 34.11-KDF or GOST R 34.11-PBKDF2 or other<br><br>
+ * 
+ * Derive key from derive bits subset
+ * 
+ * @memberOf GostDigest
+ * @method deriveKey
+ * @instance
+ * @param {ArrayBuffer} baseKey
+ * @returns {ArrayBuffer}
+ */
+function deriveKey(baseKey) // <editor-fold defaultstate="collapsed">
+{
+    return this.deriveBits(baseKey, this.keySize * 8);
+} // </editor-fold>
+
+/**
+ * GOST R 34.11 Algorithm<br><br>
+ * 
+ * References: {@link http://tools.ietf.org/html/rfc6986} and {@link http://tools.ietf.org/html/rfc5831}<br><br>
+ * 
+ * Normalized algorithm identifier common parameters:
+ * 
+ *  <ul>
+ *      <li><b>name</b> Algorithm name 'GOST R 34.11'</li>
+ *      <li><b>version</b> Algorithm version
+ *          <ul>
+ *              <li><b>1994</b> old-style 256 bits digest based on GOST 28147-89</li>
+ *              <li><b>2012</b> 256 ro 512 bits digest algorithm "Streebog" GOST R 34.11-2012 (default)</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>length</b> Digest length
+ *          <ul>
+ *              <li><b>256</b> 256 bits digest</li>
+ *              <li><b>512</b> 512 bits digest, valid only for algorithm "Streebog"</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>mode</b> Algorithm mode
+ *          <ul>
+ *              <li><b>HASH</b> simple digest mode (default)</li>
+ *              <li><b>HMAC</b> HMAC algorithm based on GOST R 34.11</li>
+ *              <li><b>KDF</b> Derive bits for KEK deversification</li>
+ *              <li><b>PBKDF2</b> Password based key dirivation algorithms PBKDF2 (based on HMAC)</li>
+ *              <li><b>PFXKDF</b> Password based PFX key dirivation algorithms</li>
+ *              <li><b>CPKDF</b> CpyptoPro Password based key dirivation algorithms</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>sBox</b> Paramset sBox for GOST 28147-89. Used only if version = 1994</li>
+ *  </ul>
+ * 
+ * Supported algorithms, modes and parameters:
+ * 
+ *  <ul>
+ *      <li>Digest HASH mode (default)</li>
+ *      <li>Sign/Verify HMAC modes parameters depends on version and length
+ *          <ul>
+ *              <li><b>version: 1994</b> HMAC parameters (B = 32, L = 32)</li>
+ *              <li><b>version: 2012, length: 256</b> HMAC parameters (B = 64, L = 32)</li>
+ *              <li><b>version: 2012, length: 512</b> HMAC parameters  (B = 64, L = 64)</li>
+ *          </ul>
+ *      </li>
+ *      <li>DeriveBits/DeriveKey KDF mode
+ *          <ul>
+ *              <li><b>context</b> {@link CryptoOperationData} Context of the key derivation</li>
+ *              <li><b>label</b> {@link CryptoOperationData} Label that identifies the purpose for the derived keying material</li>
+ *          </ul>
+ *      </li>
+ *      <li>DeriveBits/DeriveKey PBKDF2 mode
+ *          <ul>
+ *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+ *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+ *              <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption, ID=3 - integrity key for MACing</li>
+ *          </ul>
+ *      </li>
+ *      <li>DeriveBits/DeriveKey PFXKDF mode
+ *          <ul>
+ *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+ *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+ *              <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption, 
+ *              ID=2 - IV (Initial Value) for encryption or decryption, ID=3 - integrity key for MACing</li>
+ *          </ul>
+ *      </li>
+ *      <li>DeriveBits/DeriveKey CPKDF mode
+ *          <ul>
+ *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+ *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+ *          </ul>
+ *      </li>
+ *  </ul>
+ * 
+ * @class GostDigest
+ * @param {AlgorithmIdentifier} algorithm WebCryptoAPI algorithm identifier
+ */
+function GostDigest(algorithm) // <editor-fold defaultstate="collapsed">
+{
+
+    algorithm = algorithm || {};
+
+    this.name = (algorithm.name || 'GOST R 34.10') + '-' + ((algorithm.version || 2012) % 100) +
+            ((algorithm.version || 2012) > 1 ? '-' + (algorithm.length || 256) : '') +
+            (((algorithm.mode || 'HASH') !== 'HASH') ? '-' + algorithm.mode : '') +
+            (algorithm.procreator ? '/' + algorithm.procreator : '') +
+            (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : '');
+
+    // Algorithm procreator
+    this.procreator = algorithm.procreator;
+
+    // Bit length
+    this.bitLength = algorithm.length || 256;
+
+    switch (algorithm.version || 2012) {
+        case 1: // SHA-1
+            this.digest = digestSHA1;
+            this.bitLength = 160;
+            break;
+        case 1994:
+            this.digest = digest94;
+            // Define chiper algorithm
+            this.sBox = (algorithm.sBox || (algorithm.procreator === 'SC' ? 'D-SC' : 'D-A')).toUpperCase();
+
+            //if (!GostCipher)
+            //    GostCipher = root.GostCipher;
+            if (!GostCipher)
+                throw new NotSupportedError('Object GostCipher not found');
+
+            this.cipher = new GostCipher({
+                name: 'GOST 28147',
+                block: 'ECB',
+                sBox: this.sBox,
+                procreator: this.procreator
+            });
+
+            break;
+        case 2012:
+            this.digest = digest2012;
+            break;
+        default:
+            throw new NotSupportedError('Algorithm version ' + algorithm.version + ' not supported');
+    }
+
+    // Key size
+    this.keySize = algorithm.keySize || (algorithm.version <= 2 ? this.bitLength / 8 : 32);
+
+    switch (algorithm.mode || 'HASH') {
+        case 'HASH':
+            break;
+        case 'HMAC':
+            this.sign = signHMAC;
+            this.verify = verifyHMAC;
+            this.generateKey = generateKey;
+            break;
+        case 'KDF':
+            this.deriveKey = deriveKey;
+            this.deriveBits = deriveBitsKDF;
+            this.label = algorithm.label;
+            this.context = algorithm.context;
+            break;
+        case 'PBKDF2':
+            this.deriveKey = deriveKey;
+            this.deriveBits = deriveBitsPBKDF2;
+            this.generateKey = generateKey;
+            this.salt = algorithm.salt;
+            this.iterations = algorithm.iterations || 2000;
+            this.diversifier = algorithm.diversifier || 1;
+            break;
+        case 'PFXKDF':
+            this.deriveKey = deriveKey;
+            this.deriveBits = deriveBitsPFXKDF;
+            this.generateKey = generateKey;
+            this.salt = algorithm.salt;
+            this.iterations = algorithm.iterations || 2000;
+            this.diversifier = algorithm.diversifier || 1;
+            break;
+        case 'CPKDF':
+            this.deriveKey = deriveKey;
+            this.deriveBits = deriveBitsCP;
+            this.generateKey = generateKey;
+            this.salt = algorithm.salt;
+            this.iterations = algorithm.iterations || 2000;
+            break;
+        default:
+            throw new NotSupportedError('Algorithm mode ' + algorithm.mode + ' not supported');
+    }
+} // </editor-fold>
+
+export default GostDigest;

+ 451 - 0
src/core/vendor/gost/gostEngine.mjs

@@ -0,0 +1,451 @@
+/**
+ * @file GOST 34.10-2012 signature function with 1024/512 bits digest
+ * @version 1.76
+ * @copyright 2014-2016, Rudolf Nickolaev. 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+import GostRandom from './gostRandom';
+import GostCipher from './gostCipher';
+import GostDigest from './gostDigest';
+import GostSign from './gostSign';
+
+/*
+    * Engine definition base on normalized algorithm identifier
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+
+// Define engine
+function defineEngine(method, algorithm) {
+    if (!algorithm)
+        throw new (root.SyntaxError || Error)('Algorithm not defined');
+
+    if (!algorithm.name)
+        throw new (root.SyntaxError || Error)('Algorithm name not defined');
+
+    var name = algorithm.name, mode = algorithm.mode;
+    if ((name === 'GOST 28147' || name === 'GOST R 34.12' || name === 'RC2') && (method === 'generateKey' ||
+            (mode === 'MAC' && (method === 'sign' || method === 'verify')) ||
+            ((mode === 'KW' || mode === 'MASK') && (method === 'wrapKey' || method === 'unwrapKey')) ||
+            ((!mode || mode === 'ES') && (method === 'encrypt' || method === 'decrypt')))) {
+        return 'GostCipher';
+
+    } else if ((name === 'GOST R 34.11' || name === 'SHA') && (method === 'digest' ||
+            (mode === 'HMAC' && (method === 'sign' || method === 'verify' || method === 'generateKey')) ||
+            ((mode === 'KDF' || mode === 'PBKDF2' || mode === 'PFXKDF' || mode === 'CPKDF') &&
+                    (method === 'deriveKey' || method === 'deriveBits' || method === 'generateKey')))) {
+        return 'GostDigest';
+
+    } else if (name === 'GOST R 34.10' && (method === 'generateKey' ||
+            ((!mode || mode === 'SIGN') && (method === 'sign' || method === 'verify')) ||
+            (mode === 'MASK' && (method === 'wrapKey' || method === 'unwrapKey')) ||
+            (mode === 'DH' && (method === 'deriveKey' || method === 'deriveBits')))) {
+        return 'GostSign';
+    } else
+        throw new (root.NotSupportedError || Error)('Algorithm ' + name + '-' + mode + ' is not valid for ' + method);
+} // </editor-fold>
+
+/**
+ * Object implements dedicated Web Workers and provide a simple way to create 
+ * and run GOST cryptographic algorithms in background thread. 
+ * 
+ * Object provide interface to GOST low-level cryptogric classes:
+ *  <ul>
+ *      <li>GostCipher - implementation of GOST 28147, GOST R 34.12, GOST R 34.13 Encryption algorithms. Reference {@link http://tools.ietf.org/html/rfc5830}</li>
+ *      <li>GostDigest - implementation of GOST R 34.11 Hash Function algorithms. References {@link http://tools.ietf.org/html/rfc5831} and {@link http://tools.ietf.org/html/rfc6986}</li>
+ *      <li>GostSign - implementation of GOST R 34.10 Digital Signature algorithms. References {@link http://tools.ietf.org/html/rfc5832} and {@link http://tools.ietf.org/html/rfc7091}</li>
+ *  </ul>
+ * @namespace gostEngine
+ */
+var gostEngine = {
+    /**
+     * gostEngine.execute(algorithm, method, args) Entry point to execution 
+     * all low-level GOST cryptographic methods
+     * 
+     *  <ul>
+     *      <li>Determine the appropriate engine for a given execution method</li>
+     *      <li>Create cipher object for determineted engine</li>
+     *      <li>Execute method of cipher with given args</li>
+     *  </ul>
+     * 
+     * @memberOf gostEngine
+     * @param {AlgorithmIndentifier} algorithm Algorithm identifier
+     * @param {string} method Crypto method for execution
+     * @param {Array} args Method arguments (keys, data, additional parameters)
+     * @returns {(CryptoOperationData|Key|KeyPair|boolean)} Result of method execution
+     */
+    execute: function (algorithm, method, args) // <editor-fold defaultstate="collapsed">
+    {
+        // Define engine for GOST algorithms
+        var engine = defineEngine(method, algorithm);
+        // Create cipher 
+        var cipher = this['get' + engine](algorithm);
+        // Execute method
+        return cipher[method].apply(cipher, args);
+    }, // </editor-fold>
+    /**
+     * gostEngine.getGostCipher(algorithm) returns GOST 28147 / GOST R 34.12 cipher instance<br><br>
+     * 
+     * GOST 28147-89 / GOST R 34.12-15 Encryption Algorithm<br><br> 
+     * When keys and initialization vectors are converted to/from byte arrays, 
+     * little-endian byte order is assumed.<br><br>
+     * 
+     * Normalized algorithm identifier common parameters:
+     * 
+     *  <ul>
+     *      <li><b>name</b> Algorithm name 'GOST 28147' or 'GOST R 34.12'</li>
+     *      <li><b>version</b> Algorithm version, number
+     *          <ul>
+     *              <li><b>1989</b> Current version of standard</li>
+     *              <li><b>2015</b> New draft version of standard</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>length</b> Block length
+     *          <ul>
+     *              <li><b>64</b> 64 bits length (default)</li>
+     *              <li><b>128</b> 128 bits length (only for version 2015)</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>mode</b> Algorithm mode, string
+     *          <ul>
+     *              <li><b>ES</b> Encryption mode (default)</li>
+     *              <li><b>MAC</b> "imitovstavka" (MAC) mode</li>
+     *              <li><b>KW</b> Key wrapping mode</li>
+     *              <li><b>MASK</b> Key mask mode</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>sBox</b> Paramset sBox for GOST 28147-89, string. Used only if version = 1989</li>
+     *  </ul>
+     *  
+     * Supported algorithms, modes and parameters:
+     * 
+     *  <ul>
+     *      <li>Encript/Decrypt mode (ES)
+     *          <ul>
+     *              <li><b>block</b> Block mode, string. Default ECB</li>
+     *              <li><b>keyMeshing</b> Key meshing mode, string. Default NO</li>
+     *              <li><b>padding</b> Padding mode, string. Default NO for CFB and CTR modes, or ZERO for others</li>
+     *              <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
+     *          </ul>
+     *      </li>
+     *      <li>Sign/Verify mode (MAC)
+     *          <ul>
+     *              <li><b>macLength</b> Length of mac in bits (default - 32 bits)</li>
+     *              <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
+     *          </ul>
+     *      </li>
+     *      <li>Wrap/Unwrap key mode (KW)
+     *          <ul>
+     *              <li><b>keyWrapping</b> Mode of keywrapping, string. Default NO - standard GOST key wrapping</li>
+     *              <li><b>ukm</b> {@link CryptoOperationData} User key material. Default - random generated value</li>
+     *          </ul>
+     *      </li>
+     *      <li>Wrap/Unwrap key mode (MASK)</li>
+     *  </ul>
+     *      
+     * Supported paramters values:
+     *      
+     *  <ul>
+     *      <li>Block modes (parameter 'block')
+     *          <ul>
+     *              <li><b>ECB</b> "prostaya zamena" (ECB) mode (default)</li>
+     *              <li><b>CFB</b> "gammirovanie s obratnoj svyaziyu" (64-bit CFB) mode</li>
+     *              <li><b>CTR</b> "gammirovanie" (counter) mode</li>
+     *              <li><b>CBC</b> Cipher-Block-Chaining (CBC) mode</li>
+     *          </ul>
+     *      </li>
+     *      <li>Key meshing modes (parameter 'keyMeshing')
+     *          <ul>
+     *              <li><b>NO</b> No key wrapping (default)</li>
+     *              <li><b>CP</b> CryptoPor Key key meshing</li>
+     *          </ul>
+     *      </li>
+     *      <li>Padding modes (parameter 'padding')
+     *          <ul>
+     *              <li><b>NO</b> No padding only for CFB and CTR modes</li>
+     *              <li><b>PKCS5</b> PKCS#5 padding mode</li>
+     *              <li><b>ZERO</b> Zero bits padding mode</li>
+     *              <li><b>RANDOM</b> Random bits padding mode</li>
+     *          </ul>
+     *      </li>
+     *      <li>Wrapping key modes (parameter 'keyWrapping')
+     *          <ul>
+     *              <li><b>NO</b> Ref. rfc4357 6.1 GOST 28147-89 Key wrapping</li>
+     *              <li><b>CP</b> CryptoPro Key wrapping mode</li>
+     *              <li><b>SC</b> SignalCom Key wrapping mode</li>
+     *          </ul>
+     *      </li>
+     *  </ul>
+     * 
+     * @memberOf gostEngine
+     * @param {AlgorithmIndentifier} algorithm Algorithm identifier
+     * @returns {GostCipher} Instance of GostCipher
+     */
+    getGostCipher: function (algorithm) // <editor-fold defaultstate="collapsed">
+    {
+        return new (GostCipher || (GostCipher = root.GostCipher))(algorithm);
+    }, // </editor-fold>
+    /**
+     * gostEngine.getGostDigest(algorithm) returns GOST R 34.11 cipher instance<br><br>
+     * 
+     * Normalized algorithm identifier common parameters:
+     * 
+     *  <ul>
+     *      <li><b>name</b> Algorithm name 'GOST R 34.11'</li>
+     *      <li><b>version</b> Algorithm version
+     *          <ul>
+     *              <li><b>1994</b> old-style 256 bits digest based on GOST 28147-89</li>
+     *              <li><b>2012</b> 256 ro 512 bits digest algorithm "Streebog" GOST R 34.11-2012 (default)</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>length</b> Digest length
+     *          <ul>
+     *              <li><b>256</b> 256 bits digest</li>
+     *              <li><b>512</b> 512 bits digest, valid only for algorithm "Streebog"</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>mode</b> Algorithm mode
+     *          <ul>
+     *              <li><b>HASH</b> simple digest mode (default)</li>
+     *              <li><b>HMAC</b> HMAC algorithm based on GOST R 34.11</li>
+     *              <li><b>KDF</b> Derive bits for KEK deversification</li>
+     *              <li><b>PBKDF2</b> Password based key dirivation algorithms PBKDF2 (based on HMAC)</li>
+     *              <li><b>PFXKDF</b> PFX key dirivation algorithms PFXKDF</li>
+     *              <li><b>CPKDF</b> CryptoPro Password based key dirivation algorithms</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>sBox</b> Paramset sBox for GOST 28147-89. Used only if version = 1994</li>
+     *  </ul>
+     * 
+     * Supported algorithms, modes and parameters:
+     * 
+     *  <ul>
+     *      <li>Digest HASH mode (default)</li>
+     *      <li>Sign/Verify HMAC modes parameters depends on version and length
+     *          <ul>
+     *              <li><b>version: 1994</b> HMAC parameters (B = 32, L = 32)</li>
+     *              <li><b>version: 2012, length: 256</b> HMAC parameters (B = 64, L = 32)</li>
+     *              <li><b>version: 2012, length: 512</b> HMAC parameters  (B = 64, L = 64)</li>
+     *          </ul>
+     *      </li>
+     *      <li>DeriveBits/DeriveKey KDF mode
+     *          <ul>
+     *              <li><b>context</b> {@link CryptoOperationData} Context of the key derivation</li>
+     *              <li><b>label</b> {@link CryptoOperationData} Label that identifies the purpose for the derived keying material</li>
+     *          </ul>
+     *      </li>
+     *      <li>DeriveBits/DeriveKey PBKDF2 mode
+     *          <ul>
+     *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+     *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+     *          </ul>
+     *      </li>
+     *      <li>DeriveBits/DeriveKey PFXKDF mode
+     *          <ul>
+     *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+     *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+     *              <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption, 
+     *              ID=2 - IV (Initial Value) for encryption or decryption, ID=3 - integrity key for MACing</li>
+     *          </ul>
+     *      </li>
+     *      <li>DeriveBits/DeriveKey CPKDF mode
+     *          <ul>
+     *              <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
+     *              <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
+     *          </ul>
+     *      </li>
+     *  </ul>
+     * 
+     * @memberOf gostEngine
+     * @param {AlgorithmIndentifier} algorithm Algorithm identifier
+     * @returns {GostDigest} Instance of GostDigest
+     */
+    getGostDigest: function (algorithm) // <editor-fold defaultstate="collapsed">
+    {
+        return new (GostDigest || (GostDigest = root.GostDigest))(algorithm);
+    }, // </editor-fold>
+    /**
+     * gostEngine.getGostSign(algorithm) returns GOST R 34.10 cipher instance<br><br>
+     * 
+     * Normalized algorithm identifier common parameters:
+     * 
+     *  <ul>
+     *      <li><b>name</b> Algorithm name 'GOST R 34.10'</li>
+     *      <li><b>version</b> Algorithm version
+     *          <ul>
+     *              <li><b>1994</b> - Old-style GOST R 34.10-94 ExpMod algorithm with GOST R 34.11-94 hash</li>
+     *              <li><b>2001</b> - GOST R 34.10-2001 Eliptic curve algorithm with old GOST R 34.11-94 hash</li>
+     *              <li><b>2012</b> - GOST R 34.10-2012 Eliptic curve algorithm with GOST R 34.11-12 hash, default mode</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>length</b> Length of hash and signature. Key length == hash length for EC algorithms and 2 * hash length for ExpMod algorithm
+     *          <ul>
+     *              <li><b>GOST R 34.10-256</b> - 256 bits digest, default mode</li>
+     *              <li><b>GOST R 34.10-512</b> - 512 bits digest only for GOST R 34.11-2012 hash</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>mode</b> Algorithm mode
+     *          <ul>
+     *              <li><b>SIGN</b> Digital signature mode (default)</li>
+     *              <li><b>DH</b> Diffie-Hellman key generation and key agreement mode</li>
+     *              <li><b>MASK</b> Key mask mode</li>
+     *          </ul>
+     *      </li>
+     *      <li><b>sBox</b> Paramset sBox for GOST 34.11-94. Used only if version = 1994 or 2001</li>
+     *  </ul>
+     *  
+     * Supported algorithms, modes and parameters:
+     * 
+     *  <ul>
+     *      <li>Sign/Verify mode (SIGN)</li>
+     *      <li>Wrap/Unwrap mode (MASK)</li>
+     *      <li>DeriveKey/DeriveBits mode (DH)
+     *          <ul>
+     *              <li>{@link CryptoOperationData} <b>ukm</b> User key material. Default - random generated value</li>
+     *              <li>{@link CryptoOperationData} <b>public</b> The peer's EC public key data</li>
+     *          </ul>
+     *      </li>
+     *      <li>GenerateKey mode (SIGN and DH and MASK) version = 1994
+     *          <ul>
+     *              <li><b>namedParam</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
+     *          </ul>
+     *          Additional parameters, if namedParam not specified
+     *          <ul>
+     *              <li><b>modulusLength</b> Bit length of p (512 or 1024 bits). Default = 1024</li>
+     *              <li><b>p</b> {@link CryptoOperationData} Modulus, prime number, 2^(t-1)<p<2^t</li>
+     *              <li><b>q</b> {@link CryptoOperationData} Order of cyclic group, prime number, 2^254<q<2^256, q is a factor of p-1</li>
+     *              <li><b>a</b> {@link CryptoOperationData} Generator, integer, 1<a<p-1, at that aq (mod p) = 1</li>
+     *          </ul>
+     *      </li>
+     *      <li>GenerateKey mode (SIGN and DH and MASK) version = 2001 or 2012
+     *          <ul>
+     *              <li><b>namedCurve</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
+     *          </ul>
+     *          Additional EC parameters, if namedCurve not specified
+     *          <ul>
+     *              <li><b>p</b> {@link CryptoOperationData} Prime number - elliptic curve modulus</li>
+     *              <li><b>a</b> {@link CryptoOperationData} Coefficients a of the elliptic curve E</li>
+     *              <li><b>b</b> {@link CryptoOperationData} Coefficients b of the elliptic curve E</li>
+     *              <li><b>q</b> {@link CryptoOperationData} Prime number - order of cyclic group</li>
+     *              <li><b>x</b> {@link CryptoOperationData} Base point p x-coordinate</li>
+     *              <li><b>y</b> {@link CryptoOperationData} Base point p y-coordinate</li>
+     *          </ul>
+     *      </li>
+     *  </ul>
+     *  
+     * @memberOf gostEngine
+     * @param {AlgorithmIndentifier} algorithm Algorithm identifier
+     * @returns {GostSign} Instance of GostSign
+     */
+    getGostSign: function (algorithm) // <editor-fold defaultstate="collapsed">
+    {
+        return new (GostSign || (GostSign = root.GostSign))(algorithm);
+    } // </editor-fold>
+};
+
+/*
+    * Worker method execution
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+// Worker for gostCripto method execution
+if (root.importScripts) {
+
+    /**
+     * Method called when {@link SubtleCrypto} calls its own postMessage() 
+     * method with data parameter: algorithm, method and arg.<br>
+     * Call method execute and postMessage() results to onmessage event handler 
+     * in the main process.<br>
+     * If error occured onerror event handler executed in main process.
+     * 
+     * @memberOf gostEngine
+     * @name onmessage
+     * @param {MessageEvent} event Message event with data {algorithm, method, args}
+     */
+    root.onmessage = function (event) {
+        try {
+            postMessage({
+                id: event.data.id,
+                result: gostEngine.execute(event.data.algorithm,
+                        event.data.method, event.data.args)});
+        } catch (e) {
+            postMessage({
+                id: event.data.id,
+                error: e.message
+            });
+        }
+    };
+} else {
+
+    // Load dependens
+    var baseUrl = '', nameSuffix = '';
+    // Try to define from DOM model
+    if (typeof document !== 'undefined') {
+        (function () {
+            var regs = /^(.*)gostCrypto(.*)\.js$/i;
+            var list = document.querySelectorAll('script');
+            for (var i = 0, n = list.length; i < n; i++) {
+                var value = list[i].getAttribute('src');
+                var test = regs.exec(value);
+                if (test) {
+                    baseUrl = test[1];
+                    nameSuffix = test[2];
+                }
+            }
+        })();
+    }
+
+    // Local importScripts procedure for include dependens
+    var importScripts = function () {
+        for (var i = 0, n = arguments.length; i < n; i++) {
+            var name = arguments[i].split('.'),
+                    src = baseUrl + name[0] + nameSuffix + '.' + name[1];
+            var el = document.querySelector('script[src="' + src + '"]');
+            if (!el) {
+                el = document.createElement('script');
+                el.setAttribute('src', src);
+                document.head.appendChild(el);
+            }
+        }
+    };
+
+    // Import engines
+    if (!GostRandom)
+        importScripts('gostRandom.js');
+    if (!GostCipher)
+        importScripts('gostCipher.js');
+    if (!GostDigest)
+        importScripts('gostDigest.js');
+    if (!GostSign)
+        importScripts('gostSign.js');
+} // </editor-fold>
+
+export default gostEngine;
+

+ 128 - 0
src/core/vendor/gost/gostRandom.mjs

@@ -0,0 +1,128 @@
+/** 
+ * Implementation Web Crypto random generatore for GOST algorithms
+ * 1.76
+ * 2014-2016, Rudolf Nickolaev. All rights reserved.
+ * 
+ * Exported for CyberChef by mshwed [m@ttshwed.com]
+ */
+
+/*
+ * 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+import crypto from 'crypto';
+
+
+/**
+ * The gostCrypto provide general purpose cryptographic functionality for
+ * GOST standards including a cryptographically strong pseudo-random number 
+ * generator seeded with truly random values.
+ * 
+ * @Class GostRandom
+ * 
+ */ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+var rootCrypto = crypto;
+
+var TypeMismatchError = Error;
+var QuotaExceededError = Error;
+
+// Initialize mouse and time counters for random generator    
+var randomRing = {
+    seed: new Uint8Array(1024),
+    getIndex: 0,
+    setIndex: 0,
+    set: function (x) {
+        if (this.setIndex >= 1024)
+            this.setIndex = 0;
+        this.seed[this.setIndex++] = x;
+    },
+    get: function () {
+        if (this.getIndex >= 1024)
+            this.getIndex = 0;
+        return this.seed[this.getIndex++];
+    }
+};
+
+if (typeof document !== 'undefined') {
+    try {
+        // Mouse move event to fill random array
+        document.addEventListener('mousemove', function (e) {
+            randomRing.set((new Date().getTime() & 255) ^
+                    ((e.clientX || e.pageX) & 255) ^
+                    ((e.clientY || e.pageY) & 255));
+        }, false);
+    } catch (e) {
+    }
+
+    try {
+        // Keypress event to fill random array
+        document.addEventListener('keydown', function (e) {
+            randomRing.set((new Date().getTime() & 255) ^
+                    (e.keyCode & 255));
+        }, false);
+    } catch (e) {
+    }
+} // </editor-fold>
+
+function GostRandom() {
+}
+
+/**
+ * The getRandomValues method generates cryptographically random values. <br><br>
+ * 
+ * Random generator based on JavaScript Web Crypto random genereator 
+ * (if it is possible) or  Math.random mixed with time and parameters of 
+ * mouse and keyboard events
+ * 
+ * @memberOf GostRandom
+ * @param {(ArrayBuffer|ArrayBufferView)} array Destination buffer for random data
+ */
+GostRandom.prototype.getRandomValues = function (array) // <editor-fold defaultstate="collapsed">
+{
+
+    if (!array.byteLength)
+        throw new TypeMismatchError('Array is not of an integer type (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array)');
+
+    if (array.byteLength > 65536)
+        throw new QuotaExceededError('Byte length of array can\'t be greate then 65536');
+
+    var u8 = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
+    if (rootCrypto && rootCrypto.getRandomValues) {
+        // Native window cryptographic interface
+        rootCrypto.getRandomValues(u8);
+    } else {
+        // Standard Javascript method
+        for (var i = 0, n = u8.length; i < n; i++)
+            u8[i] = Math.floor(256 * Math.random()) & 255;
+    }
+
+    // Mix bio randomizator
+    for (var i = 0, n = u8.length; i < n; i++)
+        u8[i] = u8[i] ^ randomRing.get();
+    return array;
+}; // </editor-fold>
+
+export default GostRandom;

+ 2023 - 0
src/core/vendor/gost/gostSign.mjs

@@ -0,0 +1,2023 @@
+/**
+ * @file GOST 34.10-2012 signature function with 1024/512 bits digest
+ * @version 1.76
+ * @copyright 2014-2016, Rudolf Nickolaev. 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *    
+ * Used library JSBN http://www-cs-students.stanford.edu/~tjw/jsbn/
+ * Copyright (c) 2003-2005  Tom Wu (tjw@cs.Stanford.EDU)
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ */
+
+ import GostRandom from './gostRandom';
+ import GostDigest from './gostDigest';
+
+ import crypto from 'crypto';
+
+    /*
+     * Predefined curves and params collection
+     * 
+     * http://tools.ietf.org/html/rfc5832
+     * http://tools.ietf.org/html/rfc7091
+     * http://tools.ietf.org/html/rfc4357
+     * 
+     */ // <editor-fold defaultstate="collapsed">
+
+var root = {};
+var rootCrypto = crypto;
+var CryptoOperationData = ArrayBuffer;
+
+var OperationError = Error,
+        DataError = Error,
+        NotSupportedError = Error;
+
+// Predefined named curve collection
+var ECGostParams = {
+    'S-256-TEST': {
+        a: 7,
+        b: '0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E',
+        p: '0x8000000000000000000000000000000000000000000000000000000000000431',
+        q: '0x8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3',
+        x: 2,
+        y: '0x8E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8'
+    },
+    'S-256-A': {
+        a: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94',
+        b: 166,
+        p: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97',
+        q: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893',
+        x: 1,
+        y: '0x8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14'
+    },
+    'S-256-B': {
+        a: '0x8000000000000000000000000000000000000000000000000000000000000C96',
+        b: '0x3E1AF419A269A5F866A7D3C25C3DF80AE979259373FF2B182F49D4CE7E1BBC8B',
+        p: '0x8000000000000000000000000000000000000000000000000000000000000C99',
+        q: '0x800000000000000000000000000000015F700CFFF1A624E5E497161BCC8A198F',
+        x: 1,
+        y: '0x3FA8124359F96680B83D1C3EB2C070E5C545C9858D03ECFB744BF8D717717EFC'
+    },
+    'S-256-C': {
+        a: '0x9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598',
+        b: 32858,
+        p: '0x9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B',
+        q: '0x9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9',
+        x: 0,
+        y: '0x41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67'
+    },
+    'P-256': {
+        p: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF',
+        a: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC',
+        b: '0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B',
+        x: '0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296',
+        y: '0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5',
+        q: '0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551'
+    },
+    'T-512-TEST': {
+        a: 7,
+        b: '0x1CFF0806A31116DA29D8CFA54E57EB748BC5F377E49400FDD788B649ECA1AC4361834013B2AD7322480A89CA58E0CF74BC9E540C2ADD6897FAD0A3084F302ADC',
+        p: '0x4531ACD1FE0023C7550D267B6B2FEE80922B14B2FFB90F04D4EB7C09B5D2D15DF1D852741AF4704A0458047E80E4546D35B8336FAC224DD81664BBF528BE6373',
+        q: '0x4531ACD1FE0023C7550D267B6B2FEE80922B14B2FFB90F04D4EB7C09B5D2D15DA82F2D7ECB1DBAC719905C5EECC423F1D86E25EDBE23C595D644AAF187E6E6DF',
+        x: '0x24D19CC64572EE30F396BF6EBBFD7A6C5213B3B3D7057CC825F91093A68CD762FD60611262CD838DC6B60AA7EEE804E28BC849977FAC33B4B530F1B120248A9A',
+        y: '0x2BB312A43BD2CE6E0D020613C857ACDDCFBF061E91E5F2C3F32447C259F39B2C83AB156D77F1496BF7EB3351E1EE4E43DC1A18B91B24640B6DBB92CB1ADD371E'
+    },
+    'T-512-A': {
+        p: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7',
+        a: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4',
+        b: '0xE8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760',
+        q: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27E69532F48D89116FF22B8D4E0560609B4B38ABFAD2B85DCACDB1411F10B275',
+        x: 3,
+        y: '0x7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4'
+    },
+    'T-512-B': {
+        p: '0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006F',
+        a: '0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C',
+        b: '0x687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116',
+        q: '0x800000000000000000000000000000000000000000000000000000000000000149A1EC142565A545ACFDB77BD9D40CFA8B996712101BEA0EC6346C54374F25BD',
+        x: 2,
+        y: '0x1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD'
+    }
+};
+ECGostParams['X-256-A'] = ECGostParams['S-256-A'];
+ECGostParams['X-256-B'] = ECGostParams['S-256-C'];
+ECGostParams['T-256-TEST'] = ECGostParams['S-256-TEST'];
+ECGostParams['T-256-A'] = ECGostParams['S-256-A'];
+ECGostParams['T-256-B'] = ECGostParams['S-256-B'];
+ECGostParams['T-256-C'] = ECGostParams['S-256-C'];
+
+
+var GostParams = {
+    'S-TEST': {
+        modulusLength: 512, // bit length of p (512 or 1024 bits)
+        p: '0xEE8172AE8996608FB69359B89EB82A69854510E2977A4D63BC97322CE5DC3386EA0A12B343E9190F23177539845839786BB0C345D165976EF2195EC9B1C379E3',
+        q: '0x98915E7EC8265EDFCDA31E88F24809DDB064BDC7285DD50D7289F0AC6F49DD2D',
+        a: '0x9e96031500c8774a869582d4afde2127afad2538b4b6270a6f7c8837b50d50f206755984a49e509304d648be2ab5aab18ebe2cd46ac3d8495b142aa6ce23e21c'
+    },
+    'S-A': {
+        modulusLength: 1024,
+        p: '0xB4E25EFB018E3C8B87505E2A67553C5EDC56C2914B7E4F89D23F03F03377E70A2903489DD60E78418D3D851EDB5317C4871E40B04228C3B7902963C4B7D85D52B9AA88F2AFDBEB28DA8869D6DF846A1D98924E925561BD69300B9DDD05D247B5922D967CBB02671881C57D10E5EF72D3E6DAD4223DC82AA1F7D0294651A480DF',
+        q: '0x972432A437178B30BD96195B773789AB2FFF15594B176DD175B63256EE5AF2CF',
+        a: '0x8FD36731237654BBE41F5F1F8453E71CA414FFC22C25D915309E5D2E62A2A26C7111F3FC79568DAFA028042FE1A52A0489805C0DE9A1A469C844C7CABBEE625C3078888C1D85EEA883F1AD5BC4E6776E8E1A0750912DF64F79956499F1E182475B0B60E2632ADCD8CF94E9C54FD1F3B109D81F00BF2AB8CB862ADF7D40B9369A'
+    },
+    'S-B': {
+        modulusLength: 1024,
+        p: '0xC6971FC57524B30C9018C5E621DE15499736854F56A6F8AEE65A7A404632B1BCF0349FFCAFCB0A103177971FC1612ADCDB8C8CC938C70225C8FD12AFF01B1D064E0AD6FDE6AB9159166CB9F2FC171D92F0CC7B6A6B2CD7FA342ACBE2C9315A42D576B1ECCE77A963157F3D0BD96A8EB0B0F3502AD238101B05116334F1E5B7AB',
+        q: '0xB09D634C10899CD7D4C3A7657403E05810B07C61A688BAB2C37F475E308B0607',
+        a: '0x3D26B467D94A3FFC9D71BF8DB8934084137264F3C2E9EB16DCA214B8BC7C872485336744934FD2EF5943F9ED0B745B90AA3EC8D70CDC91682478B664A2E1F8FB56CEF2972FEE7EDB084AF746419B854FAD02CC3E3646FF2E1A18DD4BEB3C44F7F2745588029649674546CC9187C207FB8F2CECE8E2293F68395C4704AF04BAB5'
+    },
+    'S-C': {
+        modulusLength: 1024,
+        p: '0x9D88E6D7FE3313BD2E745C7CDD2AB9EE4AF3C8899E847DE74A33783EA68BC30588BA1F738C6AAF8AB350531F1854C3837CC3C860FFD7E2E106C3F63B3D8A4C034CE73942A6C3D585B599CF695ED7A3C4A93B2B947B7157BB1A1C043AB41EC8566C6145E938A611906DE0D32E562494569D7E999A0DDA5C879BDD91FE124DF1E9',
+        q: '0xFADD197ABD19A1B4653EECF7ECA4D6A22B1F7F893B641F901641FBB555354FAF',
+        a: '0x7447ED7156310599070B12609947A5C8C8A8625CF1CF252B407B331F93D639DDD1BA392656DECA992DD035354329A1E95A6E32D6F47882D960B8F10ACAFF796D13CD9611F853DAB6D2623483E46788708493937A1A29442598AEC2E0742022563440FE9C18740ECE6765AC05FAF024A64B026E7E408840819E962E7E5F401AE3'
+    },
+    'S-D': {
+        modulusLength: 1024,
+        p: '0x80F102D32B0FD167D069C27A307ADAD2C466091904DBAA55D5B8CC7026F2F7A1919B890CB652C40E054E1E9306735B43D7B279EDDF9102001CD9E1A831FE8A163EED89AB07CF2ABE8242AC9DEDDDBF98D62CDDD1EA4F5F15D3A42A6677BDD293B24260C0F27C0F1D15948614D567B66FA902BAA11A69AE3BCEADBB83E399C9B5',
+        q: '0xF0F544C418AAC234F683F033511B65C21651A6078BDA2D69BB9F732867502149',
+        a: '0x6BCC0B4FADB3889C1E06ADD23CC09B8AB6ECDEDF73F04632595EE4250005D6AF5F5ADE44CB1E26E6263C672347CFA26F9E9393681E6B759733784CDE5DBD9A14A39369DFD99FA85CC0D10241C4010343F34A91393A706CF12677CBFA1F578D6B6CFBE8A1242CFCC94B3B653A476E145E3862C18CC3FED8257CFEF74CDB205BF1'
+    },
+    'X-A': {
+        modulusLength: 1024,
+        p: '0xCA3B3F2EEE9FD46317D49595A9E7518E6C63D8F4EB4D22D10D28AF0B8839F079F8289E603B03530784B9BB5A1E76859E4850C670C7B71C0DF84CA3E0D6C177FE9F78A9D8433230A883CD82A2B2B5C7A3306980278570CDB79BF01074A69C9623348824B0C53791D53C6A78CAB69E1CFB28368611A397F50F541E16DB348DBE5F',
+        q: '0xCAE4D85F80C147704B0CA48E85FB00A9057AA4ACC44668E17F1996D7152690D9',
+        a: '0xBE27D652F2F1E339DA734211B85B06AE4DE236AA8FBEEB3F1ADCC52CD43853777E834A6A518138678A8ADBD3A55C70A7EAB1BA7A0719548677AAF4E609FFB47F6B9D7E45B0D06D83D7ADC53310ABD85783E7317F7EC73268B6A9C08D260B85D8485696CA39C17B17F044D1E050489036ABD381C5E6BF82BA352A1AFF136601AF'
+    },
+    'X-B': {
+        modulusLength: 1024,
+        p: '0x9286DBDA91ECCFC3060AA5598318E2A639F5BA90A4CA656157B2673FB191CD0589EE05F4CEF1BD13508408271458C30851CE7A4EF534742BFB11F4743C8F787B11193BA304C0E6BCA25701BF88AF1CB9B8FD4711D89F88E32B37D95316541BF1E5DBB4989B3DF13659B88C0F97A3C1087B9F2D5317D557DCD4AFC6D0A754E279',
+        q: '0xC966E9B3B8B7CDD82FF0F83AF87036C38F42238EC50A876CD390E43D67B6013F',
+        a: '0x7E9C3096676F51E3B2F9884CF0AC2156779496F410E049CED7E53D8B7B5B366B1A6008E5196605A55E89C3190DABF80B9F1163C979FCD18328DAE5E9048811B370107BB7715F82091BB9DE0E33EE2FED6255474F8769FCE5EAFAEEF1CB5A32E0D5C6C2F0FC0B3447072947F5B4C387666993A333FC06568E534AD56D2338D729'
+    },
+    'X-C': {
+        modulusLength: 1024,
+        p: '0xB194036ACE14139D36D64295AE6C50FC4B7D65D8B340711366CA93F383653908EE637BE428051D86612670AD7B402C09B820FA77D9DA29C8111A8496DA6C261A53ED252E4D8A69A20376E6ADDB3BDCD331749A491A184B8FDA6D84C31CF05F9119B5ED35246EA4562D85928BA1136A8D0E5A7E5C764BA8902029A1336C631A1D',
+        q: '0x96120477DF0F3896628E6F4A88D83C93204C210FF262BCCB7DAE450355125259',
+        a: '0x3F1817052BAA7598FE3E4F4FC5C5F616E122CFF9EBD89EF81DC7CE8BF56CC64B43586C80F1C4F56DD5718FDD76300BE336784259CA25AADE5A483F64C02A20CF4A10F9C189C433DEFE31D263E6C9764660A731ECCAECB74C8279303731E8CF69205BC73E5A70BDF93E5BB681DAB4EEB9C733CAAB2F673C475E0ECA921D29782E'
+    }
+}; // </editor-fold>
+
+/* 
+    * BigInteger arithmetic tools 
+    * optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js 
+    * 
+    */ // <editor-fold defaultstate="collapsed">
+
+// Bits per one element
+var DB = 28, DM = (1 << DB) - 1, DV = 1 << DB,
+        FV = Math.pow(2, 52), F1 = 52 - DB, F2 = 2 * DB - 52;
+
+function am(y, i, x, w, j, c, n) {
+    var xl = x & 0x3fff, xh = x >> 14;
+    while (--n >= 0) {
+        var l = y[i] & 0x3fff;
+        var h = y[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;
+}
+
+function nbi(words) {
+    var r = new Array(Math.ceil(words));
+    r.s = 0;
+    r.t = 0;
+    return r;
+}
+
+function copyTo(x, r) {
+    for (var i = x.t - 1; i >= 0; --i)
+        r[i] = x[i];
+    r.t = x.t;
+    r.s = x.s;
+    return r;
+}
+
+function copy(x) {
+    return copyTo(x, nbi(x.t));
+}
+
+function setInt(x, i) {
+    x.t = 1;
+    x.s = (i < 0) ? -1 : 0;
+    if (i > 0)
+        x[0] = i;
+    else if (i < -1)
+        x[0] = i + DV;
+    else
+        x.t = 0;
+    return x;
+}
+
+function nbv(i) {
+    var r = nbi(1);
+    setInt(r, i);
+    return r;
+}
+
+var ZERO = nbv(0), ONE = nbv(1), THREE = nbv(3);
+
+function clamp(x) {
+    var c = x.s & DM;
+    while (x.t > 0 && x[x.t - 1] === c)
+        --x.t;
+    return x;
+}
+
+function subTo(x, a, r) {
+    var i = 0, c = 0, m = Math.min(a.t, x.t);
+    while (i < m) {
+        c += x[i] - a[i];
+        r[i++] = c & DM;
+        c >>= DB;
+    }
+    if (a.t < x.t) {
+        c -= a.s;
+        while (i < x.t) {
+            c += x[i];
+            r[i++] = c & DM;
+            c >>= DB;
+        }
+        c += x.s;
+    }
+    else {
+        c += x.s;
+        while (i < a.t) {
+            c -= a[i];
+            r[i++] = c & DM;
+            c >>= DB;
+        }
+        c -= a.s;
+    }
+    r.s = (c < 0) ? -1 : 0;
+    if (c < -1)
+        r[i++] = DV + c;
+    else if (c > 0)
+        r[i++] = c;
+    r.t = i;
+    return clamp(r);
+}
+
+function sub(x, y) {
+    return subTo(x, y, nbi(x.t));
+}
+
+function addTo(x, a, r) {
+    var i = 0, c = 0, m = Math.min(a.t, x.t);
+    while (i < m) {
+        c += x[i] + a[i];
+        r[i++] = c & DM;
+        c >>= DB;
+    }
+    if (a.t < x.t) {
+        c += a.s;
+        while (i < x.t) {
+            c += x[i];
+            r[i++] = c & DM;
+            c >>= DB;
+        }
+        c += x.s;
+    }
+    else {
+        c += x.s;
+        while (i < a.t) {
+            c += a[i];
+            r[i++] = c & DM;
+            c = c >> DB;
+        }
+        c += a.s;
+    }
+    r.s = (c < 0) ? -1 : 0;
+    if (c > 0)
+        r[i++] = c;
+    else if (c < -1)
+        r[i++] = DV + c;
+    r.t = i;
+    return clamp(r);
+}
+
+function add(x, y) {
+    return addTo(x, y, nbi(x.t));
+}
+
+function negTo(x, r) {
+    return subTo(ZERO, x, r);
+}
+
+function neg(x) {
+    return negTo(x, nbi(x.t));
+}
+
+function absTo(x, r) {
+    return (x.s < 0) ? negTo(r) : copyTo(r);
+}
+
+function abs(x) {
+    return (x.s < 0) ? neg(x) : x;
+}
+
+function compare(x, a) {
+    var r = x.s - a.s;
+    if (r !== 0)
+        return r;
+    var i = x.t;
+    r = i - a.t;
+    if (r !== 0)
+        return (x.s < 0) ? -r : r;
+    while (--i >= 0)
+        if ((r = x[i] - a[i]) !== 0)
+            return r;
+    return 0;
+}
+
+function equals(x, y) {
+    return(compare(x, y) === 0);
+}
+
+function min(x, y) {
+    return(compare(x, y) < 0) ? x : y;
+}
+
+function max(x, y) {
+    return(compare(x, y) > 0) ? x : y;
+}
+
+function nbits(x) {
+    var r = 1, t;
+    if ((t = x >>> 16) !== 0) {
+        x = t;
+        r += 16;
+    }
+    if ((t = x >> 8) !== 0) {
+        x = t;
+        r += 8;
+    }
+    if ((t = x >> 4) !== 0) {
+        x = t;
+        r += 4;
+    }
+    if ((t = x >> 2) !== 0) {
+        x = t;
+        r += 2;
+    }
+    if ((t = x >> 1) !== 0) {
+        x = t;
+        r += 1;
+    }
+    return r;
+}
+
+function dshlTo(x, n, r) {
+    var i;
+    for (i = x.t - 1; i >= 0; --i)
+        r[i + n] = x[i];
+    for (i = n - 1; i >= 0; --i)
+        r[i] = 0;
+    r.t = x.t + n;
+    r.s = x.s;
+    return r;
+}
+function dshrTo(x, n, r) {
+    for (var i = n; i < x.t; ++i)
+        r[i - n] = x[i];
+    r.t = Math.max(x.t - n, 0);
+    r.s = x.s;
+    return r;
+}
+
+function shlTo(x, n, r) {
+    var bs = n % DB;
+    var cbs = DB - bs;
+    var bm = (1 << cbs) - 1;
+    var ds = Math.floor(n / DB), c = (x.s << bs) & DM, i;
+    for (i = x.t - 1; i >= 0; --i) {
+        r[i + ds + 1] = (x[i] >> cbs) | c;
+        c = (x[i] & bm) << bs;
+    }
+    for (i = ds - 1; i >= 0; --i)
+        r[i] = 0;
+    r[ds] = c;
+    r.t = x.t + ds + 1;
+    r.s = x.s;
+    return clamp(r);
+}
+
+function shrTo(x, n, r) {
+    r.s = x.s;
+    var ds = Math.floor(n / DB);
+    if (ds >= x.t) {
+        r.t = 0;
+        return;
+    }
+    var bs = n % DB;
+    var cbs = DB - bs;
+    var bm = (1 << bs) - 1;
+    r[0] = x[ds] >> bs;
+    for (var i = ds + 1; i < x.t; ++i) {
+        r[i - ds - 1] |= (x[i] & bm) << cbs;
+        r[i - ds] = x[i] >> bs;
+    }
+    if (bs > 0)
+        r[x.t - ds - 1] |= (x.s & bm) << cbs;
+    r.t = x.t - ds;
+    return clamp(r);
+}
+
+function shl(x, n) {
+    var r = nbi(x.t);
+    if (n < 0)
+        shrTo(x, -n, r);
+    else
+        shlTo(x, n, r);
+    return r;
+}
+
+function shr(x, n) {
+    var r = nbi(x.t);
+    if (n < 0)
+        shlTo(x, -n, r);
+    else
+        shrTo(x, n, r);
+    return r;
+}
+
+function bitLength(x) {
+    if (x.t <= 0)
+        return 0;
+    return DB * (x.t - 1) + nbits(x[x.t - 1] ^ (x.s & DM));
+}
+
+function mulTo(b, a, r) {
+    var x = abs(b), y = abs(a);
+    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] = am(x, 0, y[i], r, i, 0, x.t);
+    r.s = 0;
+    if (b.s !== a.s)
+        subTo(ZERO, r, r);
+    return clamp(r);
+}
+
+function mul(x, y) {
+    return mulTo(x, y, nbi(x.t + y.t));
+}
+
+function sqrTo(a, r) {
+    var x = abs(a);
+    var i = r.t = 2 * x.t;
+    while (--i >= 0)
+        r[i] = 0;
+    for (i = 0; i < x.t - 1; ++i) {
+        var c = am(x, i, x[i], r, 2 * i, 0, 1);
+        if ((r[i + x.t] += am(x, 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] += am(x, i, x[i], r, 2 * i, 0, 1);
+    r.s = 0;
+    return clamp(r);
+}
+
+function sqr(a) {
+    return sqrTo(a, nbi(a.t * 2));
+}
+
+function divRemTo(n, m, q, r) {
+    var pm = abs(m);
+    if (pm.t <= 0)
+        throw new OperationError('Division by zero');
+    var pt = abs(n);
+    if (pt.t < pm.t) {
+        if (q)
+            setInt(q, 0);
+        if (r)
+            copyTo(n, r);
+        return q;
+    }
+    if (!r)
+        r = nbi(m.t);
+    var y = nbi(m.t), ts = n.s, ms = m.s;
+    var nsh = DB - nbits(pm[pm.t - 1]);
+    if (nsh > 0) {
+        shlTo(pm, nsh, y);
+        shlTo(pt, nsh, r);
+    }
+    else {
+        copyTo(pm, y);
+        copyTo(pt, r);
+    }
+    var ys = y.t;
+    var y0 = y[ys - 1];
+    if (y0 === 0)
+        return q;
+    var yt = y0 * (1 << F1) + ((ys > 1) ? y[ys - 2] >> F2 : 0);
+    var d1 = FV / yt, d2 = (1 << F1) / yt, e = 1 << F2;
+    var i = r.t, j = i - ys, t = !q ? nbi(Math.max(n.t - m.t, 1)) : q;
+    dshlTo(y, j, t);
+    if (compare(r, t) >= 0) {
+        r[r.t++] = 1;
+        subTo(r, t, r);
+    }
+    dshlTo(ONE, ys, t);
+    subTo(t, y, y);
+    while (y.t < ys)
+        y[y.t++] = 0;
+    while (--j >= 0) {
+        var qd = (r[--i] === y0) ? DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
+        if ((r[i] += am(y, 0, qd, r, j, 0, ys)) < qd) {
+            dshlTo(y, j, t);
+            subTo(r, t, r);
+            while (r[i] < --qd)
+                subTo(r, t, r);
+        }
+    }
+    if (q) {
+        dshrTo(r, ys, q);
+        if (ts !== ms)
+            subTo(ZERO, q, q);
+    }
+    r.t = ys;
+    clamp(r);
+    if (nsh > 0)
+        shrTo(r, nsh, r);
+    if (ts < 0)
+        subTo(ZERO, r, r);
+    return q;
+}
+
+function modTo(b, a, r) {
+    divRemTo(abs(b), a, null, r);
+    if (b.s < 0 && compare(r, ZERO) > 0)
+        subTo(a, r, r);
+    return r;
+}
+
+function mod(b, a) {
+    return modTo(b, a, nbi(a.t));
+}
+
+function div(b, a) {
+    return divRemTo(b, a, nbi(Math.max(b.t - a.t, 1)), null);
+}
+
+function isEven(x) {
+
+    return ((x.t > 0) ? (x[0] & 1) : x.s) === 0;
+}
+
+function isZero(x) {
+    return equals(x, ZERO);
+}
+
+function sig(x) {
+    if (x.s < 0)
+        return -1;
+    else if (x.t <= 0 || (x.t === 1 && x[0] <= 0))
+        return 0;
+    else
+        return 1;
+}
+
+function invMod(x, m) {
+    var ac = isEven(m);
+    if ((isEven(x) && ac) || sig(m) === 0)
+        return ZERO;
+    var u = copy(m), v = copy(x);
+    var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
+    while (sig(u) !== 0) {
+        while (isEven(u)) {
+            shrTo(u, 1, u);
+            if (ac) {
+                if (!isEven(a) || !isEven(b)) {
+                    addTo(a, x, a);
+                    subTo(b, m, b);
+                }
+                shrTo(a, 1, a);
+            }
+            else if (!isEven(b))
+                subTo(b, m, b);
+            shrTo(b, 1, b);
+        }
+        while (isEven(v)) {
+            shrTo(v, 1, v);
+            if (ac) {
+                if (!isEven(c) || !isEven(d)) {
+                    addTo(c, x, c);
+                    subTo(d, m, d);
+                }
+                shrTo(c, 1, c);
+            }
+            else if (!isEven(d))
+                subTo(d, m, d);
+            shrTo(d, 1, d);
+        }
+        if (compare(u, v) >= 0) {
+            subTo(u, v, u);
+            if (ac)
+                subTo(a, c, a);
+            subTo(b, d, b);
+        }
+        else {
+            subTo(v, u, v);
+            if (ac)
+                subTo(c, a, c);
+            subTo(d, b, d);
+        }
+    }
+    if (compare(v, ONE) !== 0)
+        return ZERO;
+    if (compare(d, m) >= 0)
+        return subtract(d, m);
+    if (sig(d) < 0)
+        addTo(d, m, d);
+    else
+        return d;
+    if (sig(d) < 0)
+        return add(d, m);
+    else
+        return d;
+}
+
+function testBit(x, n) {
+    var j = Math.floor(n / DB);
+    if (j >= x.t)
+        return (x.s !== 0);
+    return ((x[j] & (1 << (n % DB))) !== 0);
+}
+
+function nothing(x) {
+    return x;
+}
+
+function extend(c, o) {
+    for (var i in o)
+        c.prototype[i] = o[i];
+} // </editor-fold>
+
+/*
+    * Classic, Barret, Mongomery reductions, optimized ExpMod algorithms
+    * optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn2.js
+    * 
+    */ // <editor-fold defaultstate="collapsed"> 
+
+// Classic reduction
+var Classic = function (m) {
+    this.m = m;
+};
+
+extend(Classic, {
+    convert: function (x) {
+        if (x.s < 0 || compare(x, this.m) >= 0)
+            return mod(x, this.m);
+        else
+            return x;
+    },
+    revert: nothing,
+    reduce: function (x) {
+        modTo(x, this.m, x);
+    },
+    sqrTo: function (x, r) {
+        sqrTo(x, r);
+        this.reduce(r);
+    },
+    mulTo: function (x, y, r) {
+        mulTo(x, y, r);
+        this.reduce(r);
+    }
+});
+
+function invDig(a) {
+    if (a.t < 1)
+        return 0;
+    var x = a[0];
+    if ((x & 1) === 0)
+        return 0;
+    var y = x & 3;
+    y = (y * (2 - (x & 0xf) * y)) & 0xf;
+    y = (y * (2 - (x & 0xff) * y)) & 0xff;
+    y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff;
+    y = (y * (2 - x * y % DV)) % DV;
+    return (y > 0) ? DV - y : -y;
+}
+
+// Montgomery reduction
+var Montgomery = function (m) {
+    this.m = m;
+    this.mp = invDig(m);
+    this.mpl = this.mp & 0x7fff;
+    this.mph = this.mp >> 15;
+    this.um = (1 << (DB - 15)) - 1;
+    this.mt2 = 2 * m.t;
+};
+
+extend(Montgomery, {
+    // xR mod m
+    convert: function (x) {
+        var r = nbi(x.t);
+        dshlTo(abs(x), this.m.t, r);
+        divRemTo(r, this.m, null, r);
+        if (x.s < 0 && compare(r, ZERO) > 0)
+            subTo(this.m, r, r);
+        return r;
+    },
+    // x/R mod m
+    revert: function (x) {
+        var r = nbi(x.t);
+        copyTo(x, r);
+        this.reduce(r);
+        return r;
+    },
+    // x = x/R mod m (HAC 14.32)
+    reduce: function (x) {
+        while (x.t <= this.mt2)
+            x[x.t++] = 0;
+        for (var i = 0; i < this.m.t; ++i) {
+            var j = x[i] & 0x7fff;
+            var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & DM;
+            j = i + this.m.t;
+            x[j] += am(this.m, 0, u0, x, i, 0, this.m.t);
+            while (x[j] >= DV) {
+                x[j] -= DV;
+                x[++j]++;
+            }
+        }
+        clamp(x);
+        dshrTo(x, this.m.t, x);
+        if (compare(x, this.m) >= 0)
+            subTo(x, this.m, x);
+    },
+    // r = "x^2/R mod m"; x != r
+    sqrTo: function (x, r) {
+        sqrTo(x, r);
+        this.reduce(r);
+    },
+    // r = "xy/R mod m"; x,y != r
+    mulTo: function (x, y, r) {
+        mulTo(x, y, r);
+        this.reduce(r);
+    }
+});
+
+function dAddOffset(x, n, w) {
+    if (n === 0)
+        return;
+    while (x.t <= w)
+        x[x.t++] = 0;
+    x[w] += n;
+    while (x[w] >= DV) {
+        x[w] -= DV;
+        if (++w >= x.t)
+            x[x.t++] = 0;
+        ++x[w];
+    }
+}
+
+function mulLowerTo(x, a, n, r) {
+    var i = Math.min(x.t + a.t, n);
+    r.s = 0; // assumes a,x >= 0
+    r.t = i;
+    while (i > 0)
+        r[--i] = 0;
+    var j;
+    for (j = r.t - x.t; i < j; ++i)
+        r[i + x.t] = am(x, 0, a[i], r, i, 0, x.t);
+    for (j = Math.min(a.t, n); i < j; ++i)
+        am(x, 0, a[i], r, i, 0, n - i);
+    return clamp(r);
+}
+
+function mulUpperTo(x, a, n, r) {
+    --n;
+    var i = r.t = x.t + a.t - n;
+    r.s = 0; // assumes a,x >= 0
+    while (--i >= 0)
+        r[i] = 0;
+    for (i = Math.max(n - x.t, 0); i < a.t; ++i)
+        r[x.t + i - n] = am(x, n - i, a[i], r, 0, 0, x.t + i - n);
+    clamp(r);
+    return dshrTo(r, 1, r);
+}
+
+// Barrett modular reduction
+function Barrett(m) {
+    // setup Barrett
+    this.r2 = nbi(2 * m.t);
+    this.q3 = nbi(2 * m.t);
+    dshlTo(ONE, 2 * m.t, this.r2);
+    this.mu = div(this.r2, m);
+    this.m = m;
+}
+
+extend(Barrett, {
+    convert: function (x) {
+        if (x.s < 0 || x.t > 2 * this.m.t)
+            return mod(x, this.m);
+        else if (compare(x, this.m) < 0)
+            return x;
+        else {
+            var r = nbi(x.t);
+            copyTo(x, r);
+            this.reduce(r);
+            return r;
+        }
+    },
+    revert: function (x) {
+        return x;
+    },
+    // x = x mod m (HAC 14.42)
+    reduce: function (x) {
+        dshrTo(x, this.m.t - 1, this.r2);
+        if (x.t > this.m.t + 1) {
+            x.t = this.m.t + 1;
+            clamp(x);
+        }
+        mulUpperTo(this.mu, this.r2, this.m.t + 1, this.q3);
+        mulLowerTo(this.m, this.q3, this.m.t + 1, this.r2);
+        while (compare(x, this.r2) < 0)
+            dAddOffset(x, 1, this.m.t + 1);
+        subTo(x, this.r2, x);
+        while (compare(x, this.m) >= 0)
+            subTo(x, this.m, x);
+    },
+    // r = x^2 mod m; x != r
+    sqrTo: function (x, r) {
+        sqrTo(x, r);
+        this.reduce(r);
+    },
+    // r = x*y mod m; x,y != r
+    mulTo: function (x, y, r) {
+        mulTo(x, y, r);
+        this.reduce(r);
+    }
+
+});
+
+// x^e % m (HAC 14.85)
+function expMod(x, e, m) {
+    var i = bitLength(e), k, r = nbv(1), z;
+    if (i <= 0)
+        return r;
+    else if (i < 18)
+        k = 1;
+    else if (i < 48)
+        k = 3;
+    else if (i < 144)
+        k = 4;
+    else if (i < 768)
+        k = 5;
+    else
+        k = 6;
+    if (i < 8)
+        z = new Classic(m);
+    else if (isEven(m))
+        z = new Barrett(m);
+    else
+        z = new Montgomery(m);
+
+    // precomputation
+    var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1;
+    g[1] = z.convert(x);
+    if (k > 1) {
+        var g2 = nbi(m.t * 2);
+        z.sqrTo(g[1], g2);
+        while (n <= km) {
+            g[n] = nbi(m.t * 2);
+            z.mulTo(g2, g[n - 2], g[n]);
+            n += 2;
+        }
+    }
+
+    var j = e.t - 1, w, is1 = true, r2 = nbi(m.t * 2), 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] >> (DB + i - k1);
+        }
+
+        n = k;
+        while ((w & 1) == 0) {
+            w >>= 1;
+            --n;
+        }
+        if ((i -= n) < 0) {
+            i += DB;
+            --j;
+        }
+        if (is1) {	// ret == 1, don't bother squaring or multiplying it
+            copyTo(g[w], 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 = DB - 1;
+                --j;
+            }
+        }
+    }
+    return z.revert(r);
+} // </editor-fold>
+
+/*
+    * EC Field Elements, Points, Curves
+    * optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/ec.js
+    * 
+    */ // <editor-fold defaultstate="collapsed"> 
+
+// EC Field Elemets
+function newFE(a, x) {
+    a.r.reduce(x);
+    x.q = a.q;
+    x.r = a.r;
+    return x;
+}
+
+function copyFE(a, x) {
+    x.q = a.q;
+    x.r = a.r;
+    return x;
+}
+
+function negFE(a) {
+    return copyFE(a, sub(a.q, a));
+}
+
+function addFE(a, b) {
+    var r = add(a, b);
+    if (compare(r, a.q) > 0)
+        subTo(r, a.q, r);
+    return copyFE(a, r);
+}
+
+function subFE(a, b) {
+    var r = sub(a, b);
+    if (r.s < 0)
+        addTo(a.q, r, r);
+    return copyFE(a, r);
+}
+
+function mulFE(a, b) {
+    return newFE(a, mul(a, b));
+}
+
+function sqrFE(a) {
+    return newFE(a, sqr(a));
+}
+
+function shlFE(a, i) {
+    return newFE(a, shl(a, i));
+}
+
+function invFE(a) {
+    return copyFE(a, invMod(a, a.q));
+}
+
+// EC Points
+function newEC(curve, x, y, z) {
+    return {
+        curve: curve,
+        x: x,
+        y: y,
+        z: z || newFE(curve, ONE)
+    };
+}
+
+function getX(point) {
+    if (!point.zinv)
+        point.zinv = invFE(point.z);
+    return mulFE(point.x, point.zinv);
+}
+
+function getY(point) {
+    if (!point.zinv)
+        point.zinv = invFE(point.z);
+    return mulFE(point.y, point.zinv);
+}
+
+function isInfinity(a) {
+    if ((!a.x) && (!a.y))
+        return true;
+    return isZero(a.z) && !isZero(a.y);
+}
+
+function getInfinity(a) {
+    return a.curve.infinity;
+}
+
+function equalsEC(a, b) {
+    if (a === b)
+        return true;
+    if (isInfinity(a))
+        return isInfinity(b);
+    if (isInfinity(b))
+        return isInfinity(a);
+    var u, v;
+    // u = Y2 * Z1 - Y1 * Z2
+    u = subFE(mulFE(b.y, a.z), mulFE(a.y, b.z));
+    if (!isZero(u))
+        return false;
+    // v = X2 * Z1 - X1 * Z2
+    v = subFE(mulFE(b.x, a.z), mulFE(a.x, b.z));
+    return isZero(v);
+}
+
+function negEC(a) {
+    return newEC(a.curve, a.x, negFE(a.y), a.z);
+}
+
+function addEC(a, b) {
+    if (isInfinity(a))
+        return b;
+    if (isInfinity(b))
+        return a;
+
+    // u = Y2 * Z1 - Y1 * Z2
+    var u = subFE(mulFE(b.y, a.z), mulFE(a.y, b.z));
+    // v = X2 * Z1 - X1 * Z2
+    var v = subFE(mulFE(b.x, a.z), mulFE(a.x, b.z));
+
+    if (isZero(v)) {
+        if (isZero(u)) {
+            return twiceEC(a); // a == b, so double
+        }
+        return getInfinity(a); // a = -b, so infinity
+    }
+
+    var x1 = a.x;
+    var y1 = a.y;
+
+    var v2 = sqrFE(v);
+    var v3 = mulFE(v2, v);
+    var x1v2 = mulFE(x1, v2);
+    var zu2 = mulFE(sqrFE(u), a.z);
+
+    // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
+    var x3 = mulFE(subFE(mulFE(subFE(zu2, shlFE(x1v2, 1)), b.z), v3), v);
+    // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
+    var y3 = addFE(mulFE(subFE(subFE(mulFE(mulFE(x1v2, THREE), u), mulFE(y1, v3)), mulFE(zu2, u)), b.z), mulFE(u, v3));
+    // z3 = v^3 * z1 * z2
+    var z3 = mulFE(mulFE(v3, a.z), b.z);
+
+    return newEC(a.curve, x3, y3, z3);
+}
+
+function twiceEC(b) {
+    if (isInfinity(b))
+        return b;
+    if (sig(b.y) === 0)
+        return getInfinity(b);
+
+    var x1 = b.x;
+    var y1 = b.y;
+
+    var y1z1 = mulFE(y1, b.z);
+    var y1sqz1 = mulFE(y1z1, y1);
+    var a = b.curve.a;
+
+    // w = 3 * x1^2 + a * z1^2
+    var w = mulFE(sqrFE(x1), THREE);
+    if (!isZero(a)) {
+        w = addFE(w, mulFE(sqrFE(b.z), a));
+    }
+
+    // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
+    var x3 = mulFE(shlFE(subFE(sqrFE(w), mulFE(shlFE(x1, 3), y1sqz1)), 1), y1z1);
+    // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
+    var y3 = subFE(mulFE(shlFE(subFE(mulFE(mulFE(w, THREE), x1), shlFE(y1sqz1, 1)), 2), y1sqz1), mulFE(sqrFE(w), w));
+    // z3 = 8 * (y1 * z1)^3
+    var z3 = shlFE(mulFE(sqrFE(y1z1), y1z1), 3);
+
+    return newEC(b.curve, x3, y3, z3);
+}
+
+// Simple NAF (Non-Adjacent Form) multiplication algorithm
+function mulEC(a, k) {
+    if (isInfinity(a))
+        return a;
+    if (sig(k) === 0)
+        return getInfinity(a);
+
+    var e = k;
+    var h = mul(e, THREE);
+
+    var neg = negEC(a);
+    var R = a;
+
+    var i;
+    for (i = bitLength(h) - 2; i > 0; --i) {
+        R = twiceEC(R);
+
+        var hBit = testBit(h, i);
+        var eBit = testBit(e, i);
+
+        if (hBit !== eBit) {
+            R = addEC(R, hBit ? a : neg);
+        }
+    }
+
+    return R;
+}
+
+function mul2AndAddEC(a, k) {
+    var nbits = bitLength(k);
+    var R = a,
+            Q = getInfinity(a);
+
+    for (var i = 0; i < nbits - 1; i++) {
+        if (testBit(k, i) === 1)
+            Q = addEC(Q, R);
+
+        R = twiceEC(R);
+    }
+
+    if (testBit(k, nbits - 1) === 1)
+        Q = addEC(Q, R);
+
+    return Q;
+}
+
+// Compute a*j + x*k (simultaneous multiplication)
+function mulTwoEC(a, j, x, k) {
+    var i;
+    if (bitLength(j) > bitLength(k))
+        i = bitLength(j) - 1;
+    else
+        i = bitLength(k) - 1;
+
+    var R = getInfinity(a);
+    var both = addEC(a, x);
+    while (i >= 0) {
+        R = twiceEC(R);
+        if (testBit(j, i)) {
+            if (testBit(k, i)) {
+                R = addEC(R, both);
+            }
+            else {
+                R = addEC(R, a);
+            }
+        }
+        else {
+            if (testBit(k, i)) {
+                R = addEC(R, x);
+            }
+        }
+        --i;
+    }
+
+    return R;
+}
+
+// EC Curve
+function newCurve(q, a, b) {
+    var curve = {};
+    curve.q = q;
+    curve.r = new Barrett(q);
+    curve.a = newFE(curve, a);
+    curve.b = newFE(curve, b);
+    curve.infinity = newEC(curve);
+    return curve;
+} // </editor-fold>
+
+/*
+    * Converion tools (hex, binary)
+    * 
+    */ // <editor-fold defaultstate="collapsed"> 
+
+function atobi(d) {
+    var k = 8;
+    var a = new Uint8Array(d);
+    var r = nbi(a.length * 8 / DB);
+    r.t = 0;
+    r.s = 0;
+    var sh = 0;
+    for (var i = 0, n = a.length; i < n; i++) {
+        var x = a[i];
+        if (sh === 0)
+            r[r.t++] = x;
+        else if (sh + k > DB) {
+            r[r.t - 1] |= (x & ((1 << (DB - sh)) - 1)) << sh;
+            r[r.t++] = (x >> (DB - sh));
+        }
+        else
+            r[r.t - 1] |= x << sh;
+        sh += k;
+        if (sh >= DB)
+            sh -= DB;
+    }
+    return clamp(r);
+}
+
+function bitoa(s, bitLength) {
+    var k = 8;
+    var km = (1 << k) - 1, d, m = false, r = [], i = s.t;
+    var p = DB - (i * DB) % k;
+    if (i-- > 0) {
+        if (p < DB && (d = s[i] >> p) > 0) {
+            m = true;
+            r.push(d);
+        }
+        while (i >= 0) {
+            if (p < k) {
+                d = (s[i] & ((1 << p) - 1)) << (k - p);
+                d |= s[--i] >> (p += DB - k);
+            }
+            else {
+                d = (s[i] >> (p -= k)) & km;
+                if (p <= 0) {
+                    p += DB;
+                    --i;
+                }
+            }
+            if (d > 0)
+                m = true;
+            if (m)
+                r.push(d);
+        }
+    }
+    var r8 = new Uint8Array(bitLength ? bitLength / 8 : r.length);
+    if (m)
+        r8.set(r.reverse());
+    return r8.buffer;
+}
+
+
+function htobi(s) {
+    if (typeof s === 'number' || s instanceof Number)
+        return nbv(s);
+    s = s.replace(/[^\-A-Fa-f0-9]/g, '');
+    if (!s)
+        s = '0';
+    var k = 4;
+    var r = nbi(s.length / 7);
+    var i = s.length, mi = false, sh = 0;
+    while (--i >= 0) {
+        var c = s.charAt(i);
+        if (c === '-') {
+            mi = true;
+            continue;
+        }
+        var x = parseInt(s.charAt(i), 16);
+        mi = false;
+        if (sh === 0)
+            r[r.t++] = x;
+        else if (sh + k > DB) {
+            r[r.t - 1] |= (x & ((1 << (DB - sh)) - 1)) << sh;
+            r[r.t++] = (x >> (DB - sh));
+        }
+        else
+            r[r.t - 1] |= x << sh;
+        sh += k;
+        if (sh >= DB)
+            sh -= DB;
+    }
+    if (mi)
+        subTo(ZERO, r, r);
+    return clamp(r);
+}
+
+function bitoh(x) {
+    if (x.s < 0)
+        return "-" + bitoh(negTo(x, nbi(x.t)));
+    var k = 4;
+    var km = (1 << k) - 1, d, m = false, r = "", i = x.t;
+    var p = DB - (i * DB) % k;
+    if (i-- > 0) {
+        if (p < DB && (d = x[i] >> p) > 0) {
+            m = true;
+            r = d.toString(16);
+        }
+        while (i >= 0) {
+            if (p < k) {
+                d = (x[i] & ((1 << p) - 1)) << (k - p);
+                d |= x[--i] >> (p += DB - k);
+            }
+            else {
+                d = (x[i] >> (p -= k)) & km;
+                if (p <= 0) {
+                    p += DB;
+                    --i;
+                }
+            }
+            if (d > 0)
+                m = true;
+            if (m)
+                r += d.toString(16);
+        }
+    }
+    return "0x" + (m ? r : "0");
+}
+
+// biginteger to big-endian integer bytearray
+function bitoi(s) {
+    var i = s.t, r = [];
+    r[0] = s.s;
+    var p = DB - (i * DB) % 8, d, k = 0;
+    if (i-- > 0) {
+        if (p < DB && (d = s[i] >> p) !== (s.s & DM) >> p)
+            r[k++] = d | (s.s << (DB - p));
+        while (i >= 0) {
+            if (p < 8) {
+                d = (s[i] & ((1 << p) - 1)) << (8 - p);
+                d |= s[--i] >> (p += DB - 8);
+            }
+            else {
+                d = (s[i] >> (p -= 8)) & 0xff;
+                if (p <= 0) {
+                    p += DB;
+                    --i;
+                }
+            }
+            if ((d & 0x80) !== 0)
+                d |= -256;
+            if (k === 0 && (s.s & 0x80) !== (d & 0x80))
+                ++k;
+            if (k > 0 || d !== s.s)
+                r[k++] = d;
+        }
+    }
+    return new Uint8Array(r).buffer;
+}
+
+// big-endian integer bytearray to biginteger
+function itobi(d) {
+    var k = 8, s = new Uint8Array(d),
+            r = nbi(s.length / 7);
+    r.t = 0;
+    r.s = 0;
+    var i = s.length, sh = 0;
+    while (--i >= 0) {
+        var x = s[i] & 0xff;
+        if (sh === 0)
+            r[r.t++] = x;
+        else if (sh + k > DB) {
+            r[r.t - 1] |= (x & ((1 << (DB - sh)) - 1)) << sh;
+            r[r.t++] = (x >> (DB - sh));
+        }
+        else
+            r[r.t - 1] |= x << sh;
+        sh += k;
+        if (sh >= DB)
+            sh -= DB;
+    }
+    if ((s[0] & 0x80) !== 0) {
+        r.s = -1;
+        if (sh > 0)
+            r[r.t - 1] |= ((1 << (DB - sh)) - 1) << sh;
+    }
+    return clamp(r);
+}
+
+
+// Swap bytes in buffer
+function swap(s) {
+    var src = new Uint8Array(s),
+            dst = new Uint8Array(src.length);
+    for (var i = 0, n = src.length; i < n; i++)
+        dst[n - i - 1] = src[i];
+    return dst.buffer;
+}
+
+// Calculate hash of data
+function hash(d) {
+    if (this.hash)
+        d = this.hash.digest(d);
+    // Swap hash for SignalCom
+    if (this.procreator === 'SC' ||
+            (this.procreator === 'VN' && this.hash.version === 2012))
+        d = swap(d);
+    return d;
+}
+
+// Check buffer
+function buffer(d) {
+    if (d instanceof CryptoOperationData)
+        return d;
+    else if (d && d.buffer && d.buffer instanceof CryptoOperationData)
+        return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ?
+                d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;
+    else
+        throw new DataError('CryptoOperationData or CryptoOperationDataView required');
+}
+
+// Check double buffer
+function to2(d) {
+    var b = buffer(d);
+    if (b.byteLength % 2 > 0)
+        throw new DataError('Buffer length must be even');
+    var n = b.byteLength / 2;
+    return [atobi(new Uint8Array(b, 0, n)), atobi(new Uint8Array(b, n, n))];
+}
+
+function from2(x, y, bitLength) {
+    var a = bitoa(x, bitLength),
+            b = bitoa(y, bitLength),
+            d = new Uint8Array(a.byteLength + b.byteLength);
+    d.set(new Uint8Array(a));
+    d.set(new Uint8Array(b), a.byteLength);
+    return d.buffer;
+}
+
+function getSeed(length) {
+    GostRandom = GostRandom || root.GostRandom;
+    var randomSource = GostRandom ? new (GostRandom || root.GostRandom) : rootCrypto;
+    if (randomSource.getRandomValues) {
+        var d = new Uint8Array(Math.ceil(length / 8));
+        randomSource.getRandomValues(d);
+        return d;
+    } else
+        throw new NotSupportedError('Random generator not found');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * The sign method returns sign data generated with the supplied privateKey.<br>
+ * 
+ * @memberOf GostSign
+ * @method sign
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} privateKey Private key
+ * @param {(CryptoOperationData|TypedArray)} data Data
+ * @returns {CryptoOperationData} Signature
+ */
+function sign(privateKey, data) // <editor-fold defaultstate="collapsed">
+{
+
+    // Stage 1
+    var b = buffer(data);
+    var alpha = atobi(hash.call(this, b));
+
+    var q = this.q;
+    var x = mod(atobi(buffer(privateKey)), q);
+
+    // Stage 2
+    var e = mod(alpha, q);
+    if (isZero(e))
+        e = ONE;
+
+    var s = ZERO;
+    while (isZero(s)) {
+        var r = ZERO;
+        while (isZero(r)) {
+
+            // Stage 3
+            var k = mod(atobi(this.ukm ||
+                    getSeed(this.bitLength)), q); // pseudo random 0 < k < q
+            // Stage 4
+            if (this.curve) {
+                // Gost R 34.10-2001 || Gost R 34.10-2012 
+                var P = this.P;
+                var C = mulEC(P, k);
+                r = mod(getX(C), q);
+            } else {
+                // Gost R 34.10-94
+                var p = this.p, a = this.a;
+                r = mod(expMod(a, k, p), q);
+            }
+        }
+        // Stage 5
+        s = mod(add(mul(r, x), mul(k, e)), q);
+    }
+    // Stage 6
+    // console.log('s', bitoh(s));
+    // console.log('r', bitoh(r));
+    var zetta;
+    // Integer structure for SignalCom algorithm
+    if (this.procreator === 'SC') {
+        zetta = {
+            r: bitoh(r),
+            s: bitoh(s)
+        };
+    } else {
+        zetta = from2(r, s, this.bitLength);
+        // Swap bytes for CryptoPro algorithm
+        if (this.procreator === 'CP' || this.procreator === 'VN')
+            zetta = swap(zetta);
+    }
+    return zetta;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * The verify method returns signature verification for the supplied publicKey.<br>
+ * 
+ * @memberOf GostSign
+ * @method sign
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} publicKey Public key
+ * @param {(CryptoOperationData|TypedArray)} signature Signature
+ * @param {(CryptoOperationData|TypedArray)} data Data
+ * @returns {boolean} Signature verified = true
+ */
+function verify(publicKey, signature, data) // <editor-fold defaultstate="collapsed">
+{
+
+    // Stage 1
+    var q = this.q;
+    var r, s;
+    // Ready int for SignalCom algorithm
+    if (this.procreator === 'SC') {
+        r = htobi(signature.r);
+        s = htobi(signature.s);
+    } else {
+        if (this.procreator === 'CP' || this.procreator === 'VN')
+            signature = swap(signature);
+        var zetta = to2(signature);
+        // Swap bytes for CryptoPro algorithm
+        s = zetta[1]; //  first 32 octets contain the big-endian representation of s 
+        r = zetta[0]; //  and second 32 octets contain the big-endian representation of r
+    }
+    if (compare(r, q) >= 0 || compare(s, q) >= 0)
+        return false;
+    // Stage 2
+    var b = buffer(data);
+    var alpha = atobi(hash.call(this, b));
+    // Stage 3
+    var e = mod(alpha, q);
+    if (isZero(e) === 0)
+        e = ONE;
+    // Stage 4
+    var v = invMod(e, q);
+    // Stage 5
+    var z1 = mod(mul(s, v), q);
+    var z2 = sub(q, mod(mul(r, v), q));
+    // Stage 6
+    if (this.curve) {
+        // Gost R 34.10-2001 || Gost R 34.10-2012 
+        var k2 = to2(publicKey),
+                curve = this.curve,
+                P = this.P,
+                x = newFE(curve, k2[0]), // first 32 octets contain the little-endian representation of x
+                y = newFE(curve, k2[1]), // and second 32 octets contain the little-endian representation of y.
+                Q = new newEC(curve, x, y); // This corresponds to the binary representation of (<y>256||<x>256) 
+        var C = mulTwoEC(P, z1, Q, z2);
+        var R = mod(getX(C), q);
+    } else {
+        // Gost R 34.10-94
+        var p = this.p, a = this.a;
+        var y = atobi(publicKey);
+        var R = mod(mod(mul(expMod(a, z1, p), expMod(y, z2, p)), p), q);
+    }
+    // Stage 7
+    return (compare(R, r) === 0);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * The generateKey method returns a new generated key pair using the specified 
+ * AlgorithmIdentifier.
+ * 
+ * @memberOf GostSign
+ * @method generateKey
+ * @instance
+ * @returns {Object} Object with two CryptoOperationData members: privateKey and publicKey
+ */
+function generateKey() // <editor-fold defaultstate="collapsed">
+{
+    var curve = this.curve;
+    if (curve) {
+
+        var Q = curve.infinity;
+        while (isInfinity(Q)) {
+
+            // Generate random private key
+            var d = ZERO;
+            if (this.ukm) {
+                d = atobi(this.ukm);
+            } else {
+                while (isZero(d))
+                    d = mod(atobi(getSeed(this.bitLength)), this.q); // 0 < d < q
+            }
+
+            // Calculate public key
+            Q = mulEC(this.P, d);
+            var x = getX(Q), y = getY(Q);
+            // console.log('d', bitoh(d));
+            // console.log('x', bitoh(x));
+            // console.log('y', bitoh(y));
+        }
+
+        // Return result
+        return {
+            privateKey: bitoa(d, this.bitLength),
+            publicKey: from2(x, y, this.bitLength) // This corresponds to the binary representation of (<y>256||<x>256)
+        };
+
+    } else
+        throw new NotSupportedError('Key generation for GOST R 34.10-94 not supported');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10 mode MASK<br><br>
+ * 
+ * The generateMaskKey method returns a new generated key mask using for wrapping.
+ * 
+ * @memberOf GostSign
+ * @method generateMaskKey
+ * @instance
+ * @returns {Object} Object with two CryptoOperationData members: privateKey and publicKey
+ */
+function generateMaskKey() // <editor-fold defaultstate="collapsed">
+{
+    var curve = this.curve;
+    if (curve) {
+        // Generate random private key
+        var d = ZERO;
+        while (isZero(d))
+            d = mod(atobi(getSeed(this.bitLength)), this.q); // 0 < d < q
+
+        // Return result
+        return bitoa(d, this.bitLength);
+    } else
+        throw new NotSupportedError('Key generation for GOST R 34.10-94 not supported');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * Unwrap private key from private key and ukm (mask)
+ * 
+ * @memberOf GostSign
+ * @method unwrap
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} baseKey Unwrapping key
+ * @param {(CryptoOperationData|TypedArray)} data Wrapped key
+ * @returns {Object} CryptoOperationData unwrapped privateKey
+ */
+function unwrapKey(baseKey, data) // <editor-fold defaultstate="collapsed">
+{
+    var curve = this.curve;
+    if (curve) {
+        var q = this.q;
+        var x = mod(atobi(buffer(data)), q);
+        var y = mod(atobi(buffer(baseKey)), q);
+        var z = this.procreator === 'VN' ? mod(mul(x, y), q) : mod(mul(x, invMod(y, q)), q);
+        return bitoa(z);
+    } else
+        throw new NotSupportedError('Key wrapping GOST R 34.10-94 not supported');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * Wrap private key with private key and ukm (mask)
+ * 
+ * @memberOf GostSign
+ * @method unwrap
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} baseKey Wrapping key
+ * @param {(CryptoOperationData|TypedArray)} data Key
+ * @returns {Object} CryptoOperationData unwrapped privateKey
+ */
+function wrapKey(baseKey, data) // <editor-fold defaultstate="collapsed">
+{
+    var curve = this.curve;
+    if (curve) {
+        var q = this.q;
+        var x = mod(atobi(buffer(data)), q);
+        var y = mod(atobi(buffer(baseKey)), q);
+        var z = this.procreator === 'VN' ? mod(mul(x, invMod(y, q)), q) : mod(mul(x, y), q);
+        return bitoa(z);
+    } else
+        throw new NotSupportedError('Key wrapping GOST R 34.10-94 not supported');
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * @memberOf GostSign
+ * @method derive
+ * @instance
+ * @private
+ * @param {CryptoOperationData} baseKey Key for deriviation
+ * @returns {CryptoOperationData}
+ */
+function derive(baseKey) // <editor-fold defaultstate="collapsed">
+{
+
+    var k, ukm = atobi(this.ukm);
+    var q = this.q;
+    var x = mod(atobi(buffer(baseKey)), q);
+
+    if (this.curve) {
+        // 1) Let K(x,y,UKM) = ((UKM*x)(mod q)) . (y.P) (512 bit), where      
+        // x - sender’s private key (256 bit)      
+        // x.P - sender’s public key (512 bit)      
+        // y - recipient’s private key (256 bit)      
+        // y.P - recipient’s public key (512 bit)      
+        // UKM - non-zero integer, produced as in step 2 p. 6.1 [GOSTR341001]      
+        // P - base point on the elliptic curve (two 256-bit coordinates)      
+        // UKM*x - x multiplied by UKM as integers      
+        // x.P - a multiple point   
+        var K = mulEC(this.peer_Q, mod(mul(ukm, x), q));
+        k = from2(getX(K), getY(K), // This corresponds to the binary representation of (<y>256||<x>256)
+                this.bitLength);
+    } else {
+        // 1) Let K(x,y) = a^(x*y) (mod p), where      
+        // x - sender’s private key, a^x - sender’s public key      
+        // y - recipient’s private key, a^y - recipient’s public key      
+        // a, p - parameters
+        var p = this.p, a = this.a;
+        k = bitoa(expMod(this.peer_y, x, p));
+    }
+    // 2) Calculate a 256-bit hash of K(x,y,UKM):      
+    // KEK(x,y,UKM) = gostSign (K(x,y,UKM)
+    return hash.call(this, k);
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * The deriveBits method returns length bits on baseKey.
+ * 
+ * @memberOf GostSign
+ * @method deriveBits
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} baseKey Key for deriviation
+ * @param {number} length output bit-length
+ * @returns {CryptoOperationData} result
+ */
+function deriveBits(baseKey, length) // <editor-fold defaultstate="collapsed">
+{
+    if (length < 8 || length > this.bitLength || length % 8 > 0)
+        throw new DataError('Length must be no more than ' + this.bitLength + ' bits and multiple of 8');
+    var n = length / 8,
+            b = derive.call(this, baseKey),
+            r = new Uint8Array(n);
+
+    r.set(new Uint8Array(b, 0, n));
+    return r.buffer;
+} // </editor-fold>
+
+/**
+ * Algorithm name GOST R 34.10<br><br>
+ * 
+ * The deriveKey method returns 256 bit Key encryption key on baseKey.
+ * 
+ * This algorithm creates a key encryption key (KEK) using 64 bit UKM,   
+ * the sender’s private key, and the recipient’s public key (or the   
+ * reverse of the latter pair
+ * 
+ * @memberOf GostSign
+ * @method deriveKey
+ * @instance
+ * @param {(CryptoOperationData|TypedArray)} baseKey Key for deriviation
+ * @returns {CryptoOperationData} result
+ */
+function deriveKey(baseKey) // <editor-fold defaultstate="collapsed">
+{
+    var b = derive.call(this, baseKey),
+            r = new Uint8Array(32);
+
+    r.set(new Uint8Array(b, 0, 32));
+    return r.buffer;
+} // </editor-fold>
+
+
+/**
+ * Gost R 34.10 universal object<br><br>
+ * 
+ * References: {@link http://tools.ietf.org/html/rfc6986} and {@link http://tools.ietf.org/html/rfc5831}<br><br>
+ * 
+ * Normalized algorithm identifier common parameters:
+ * 
+ *  <ul>
+ *      <li><b>name</b> Algorithm name 'GOST R 34.10'</li>
+ *      <li><b>version</b> Algorithm version
+ *          <ul>
+ *              <li><b>1994</b> - Old-style GOST R 34.10-94 ExpMod algorithm with GOST R 34.11-94 hash</li>
+ *              <li><b>2001</b> - GOST R 34.10-2001 Eliptic curve algorithm with old GOST R 34.11-94 hash</li>
+ *              <li><b>2012</b> - GOST R 34.10-2012 Eliptic curve algorithm with GOST R 34.11-12 hash, default mode</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>length</b> Length of hash and signature. Key length == hash length for EC algorithms and 2 * hash length for ExpMod algorithm
+ *          <ul>
+ *              <li><b>GOST R 34.10-256</b> - 256 bits digest, default mode</li>
+ *              <li><b>GOST R 34.10-512</b> - 512 bits digest only for GOST R 34.11-2012 hash</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>mode</b> Algorithm mode
+ *          <ul>
+ *              <li><b>SIGN</b> Digital signature mode (default)</li>
+ *              <li><b>DH</b> Diffie-Hellman key generation and key agreement mode</li>
+ *          </ul>
+ *      </li>
+ *      <li><b>sBox</b> Paramset sBox for GOST 34.11-94. Used only if version = 1994 or 2001</li>
+ *  </ul>
+ *  
+ * Supported algorithms, modes and parameters:
+ * 
+ *  <ul>
+ *      <li>Sign/Verify mode (SIGN)</li>
+ *      <li>DeriveKey/DeriveBits mode (DH)
+ *          <ul>
+ *              <li>{@link CryptoOperationData} <b>ukm</b> User key material. Default - random generated value</li>
+ *              <li>{@link CryptoOperationData} <b>public</b> The peer's EC public key data</li>
+ *          </ul>
+ *      </li>
+ *      <li>GenerateKey mode (SIGN and DH) version = 1994
+ *          <ul>
+ *              <li><b>namedParam</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
+ *          </ul>
+ *          Additional parameters, if namedParam not specified
+ *          <ul>
+ *              <li><b>modulusLength</b> Bit length of p (512 or 1024 bits). Default = 1024</li>
+ *              <li><b>p</b> {@link CryptoOperationData} Modulus, prime number, 2^(t-1)<p<2^t</li>
+ *              <li><b>q</b> {@link CryptoOperationData} Order of cyclic group, prime number, 2^254<q<2^256, q is a factor of p-1</li>
+ *              <li><b>a</b> {@link CryptoOperationData} Generator, integer, 1<a<p-1, at that aq (mod p) = 1</li>
+ *          </ul>
+ *      </li>
+ *      <li>GenerateKey mode (SIGN and DH) version = 2001 or 2012
+ *          <ul>
+ *              <li><b>namedCurve</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
+ *          </ul>
+ *          Additional EC parameters, if namedCurve not specified
+ *          <ul>
+ *              <li><b>p</b> {@link CryptoOperationData} Prime number - elliptic curve modulus</li>
+ *              <li><b>a</b> {@link CryptoOperationData} Coefficients a of the elliptic curve E</li>
+ *              <li><b>b</b> {@link CryptoOperationData} Coefficients b of the elliptic curve E</li>
+ *              <li><b>q</b> {@link CryptoOperationData} Prime number - order of cyclic group</li>
+ *              <li><b>x</b> {@link CryptoOperationData} Base point p x-coordinate</li>
+ *              <li><b>y</b> {@link CryptoOperationData} Base point p y-coordinate</li>
+ *          </ul>
+ *      </li>
+ *  </ul>
+ *  
+ * @class GostSign
+ * @param {AlgorithmIndentifier} algorithm
+ */
+function GostSign(algorithm) // <editor-fold defaultstate="collapsed">
+{
+    algorithm = algorithm || {};
+    this.name = (algorithm.name || 'GOST R 34.10') + '-' +
+            ((algorithm.version || 2012) % 100) + '-' + (algorithm.length || 256) +
+            (((algorithm.mode || 'SIGN') !== 'SIGN') ? '-' + algorithm.mode : '') +
+            (typeof algorithm.namedParam === 'string' ? '/' + algorithm.namedParam : '') +
+            (typeof algorithm.namedCurve === 'string' ? '/' + algorithm.namedCurve : '') +
+            (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : '');
+
+    var version = algorithm.version || 2012;
+
+    // Functions
+    switch (algorithm.mode || 'SIGN') {
+        case 'SIGN':
+            this.sign = sign;
+            this.verify = verify;
+            this.generateKey = generateKey;
+            break;
+        case 'DH':
+            this.deriveBits = deriveBits;
+            this.deriveKey = deriveKey;
+            this.generateKey = generateKey;
+            break;
+        case 'MASK':
+            this.wrapKey = wrapKey;
+            this.unwrapKey = unwrapKey;
+            this.generateKey = generateMaskKey;
+            break;
+    }
+
+    // Define parameters
+    if (version === 1994) {
+        // Named or parameters algorithm
+        var param = algorithm.param;
+        if (!param)
+            param = GostParams[this.namedParam = (algorithm.namedParam || 'S-A').toUpperCase()];
+        this.modulusLength = algorithm.modulusLength || param.modulusLength || 1024;
+        this.p = htobi(param.p);
+        this.q = htobi(param.q);
+        this.a = htobi(param.a);
+        // Public key for derive
+        if (algorithm['public'])
+            this.peer_y = atobi(algorithm['public']);
+    } else {
+        // Named or parameters algorithm
+        var param = algorithm.curve;
+        if (!param)
+            param = ECGostParams[this.namedCurve = (algorithm.namedCurve || 'S-256-A').toUpperCase()];
+        var curve = this.curve = newCurve(htobi(param.p), htobi(param.a), htobi(param.b));
+        this.P = newEC(curve,
+                newFE(curve, htobi(param.x)),
+                newFE(curve, htobi(param.y)));
+        this.q = htobi(param.q);
+        // Public key for derive
+        if (algorithm['public']) {
+            var k2 = to2(algorithm['public']);
+            this.peer_Q = new newEC(this.curve, // This corresponds to the binary representation of (<y>256||<x>256)
+                    newFE(this.curve, k2[0]), // first 32 octets contain the little-endian representation of x
+                    newFE(this.curve, k2[1])); // and second 32 octets contain the little-endian representation of y.
+        }
+    }
+
+    // Check bit length
+    var hashLen, keyLen;
+    if (this.curve) {
+        keyLen = algorithm.length || bitLength(this.q);
+        if (keyLen > 508 && keyLen <= 512)
+            keyLen = 512;
+        else if (keyLen > 254 && keyLen <= 256)
+            keyLen = 256;
+        else
+            throw new NotSupportedError('Support keys only 256 or 512 bits length');
+        hashLen = keyLen;
+    } else {
+        keyLen = algorithm.modulusLength || bitLength(this.p);
+        if (keyLen > 1016 && keyLen <= 1024)
+            keyLen = 1024;
+        else if (keyLen > 508 && keyLen <= 512)
+            keyLen = 512;
+        else
+            throw new NotSupportedError('Support keys only 512 or 1024 bits length');
+        hashLen = 256;
+    }
+    this.bitLength = hashLen;
+    this.keyLength = keyLen;
+
+    // Algorithm proceator for result conversion
+    this.procreator = algorithm.procreator;
+
+    // Hash function definition
+    var hash = algorithm.hash;
+    if (hash) {
+        if (typeof hash === 'string' || hash instanceof String)
+            hash = {name: hash};
+        if (algorithm.version === 1994 || algorithm.version === 2001) {
+            hash.version = 1994;
+            hash.length = 256;
+            hash.sBox = algorithm.sBox || hash.sBox;
+        } else {
+            hash.version = 2012;
+            hash.length = hashLen;
+        }
+        hash.procreator = hash.procreator || algorithm.procreator;
+
+        if (!GostDigest)
+            GostDigest = root.GostDigest;
+        if (!GostDigest)
+            throw new NotSupportedError('Object GostDigest not found');
+
+        this.hash = new GostDigest(hash);
+    }
+
+    // Pregenerated seed for key exchange algorithms
+    if (algorithm.ukm) // Now don't check size 
+        this.ukm = algorithm.ukm;
+
+} // </editor-fold>
+
+export default GostSign;

+ 120 - 29
src/web/App.mjs

@@ -41,6 +41,7 @@ class App {
         this.autoBakePause = false;
         this.progress      = 0;
         this.ingId         = 0;
+        this.timeouts      = {};
     }
 
 
@@ -87,7 +88,10 @@ class App {
         setTimeout(function() {
             document.getElementById("loader-wrapper").remove();
             document.body.classList.remove("loaded");
-        }, 1000);
+
+            // Bake initial input
+            this.manager.input.bakeAll();
+        }.bind(this), 1000);
 
         // Clear the loading message interval
         clearInterval(window.loadingMsgsInt);
@@ -96,6 +100,9 @@ class App {
         window.removeEventListener("error", window.loadingErrorHandler);
 
         document.dispatchEvent(this.manager.apploaded);
+
+        this.manager.input.calcMaxTabs();
+        this.manager.output.calcMaxTabs();
     }
 
 
@@ -108,7 +115,7 @@ class App {
     handleError(err, logToConsole) {
         if (logToConsole) log.error(err);
         const msg = err.displayStr || err.toString();
-        this.alert(msg, this.options.errorTimeout, !this.options.showErrors);
+        this.alert(Utils.escapeHtml(msg), this.options.errorTimeout, !this.options.showErrors);
     }
 
 
@@ -128,7 +135,6 @@ class App {
         this.manager.recipe.updateBreakpointIndicator(false);
 
         this.manager.worker.bake(
-            this.getInput(),        // The user's input
             this.getRecipeConfig(), // The configuration of the recipe
             this.options,           // Options set by the user
             this.progress,          // The current position in the recipe
@@ -148,13 +154,46 @@ class App {
 
         if (this.autoBake_ && !this.baking) {
             log.debug("Auto-baking");
-            this.bake();
+            this.manager.input.inputWorker.postMessage({
+                action: "autobake",
+                data: {
+                    activeTab: this.manager.tabs.getActiveInputTab()
+                }
+            });
         } else {
             this.manager.controls.showStaleIndicator();
         }
     }
 
 
+    /**
+     * Executes the next step of the recipe.
+     */
+    step() {
+        if (this.baking) return;
+
+        // Reset status using cancelBake
+        this.manager.worker.cancelBake(true, false);
+
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        if (activeTab === -1) return;
+
+        let progress = 0;
+        if (this.manager.output.outputs[activeTab].progress !== false) {
+            log.error(this.manager.output.outputs[activeTab]);
+            progress = this.manager.output.outputs[activeTab].progress;
+        }
+
+        this.manager.input.inputWorker.postMessage({
+            action: "step",
+            data: {
+                activeTab: activeTab,
+                progress: progress + 1
+            }
+        });
+    }
+
+
     /**
      * Runs a silent bake, forcing the browser to load and cache all the relevant JavaScript code needed
      * to do a real bake.
@@ -175,24 +214,25 @@ class App {
     }
 
 
-    /**
-     * Gets the user's input data.
-     *
-     * @returns {string}
-     */
-    getInput() {
-        return this.manager.input.get();
-    }
-
-
     /**
      * Sets the user's input data.
      *
      * @param {string} input - The string to set the input to
-     * @param {boolean} [silent=false] - Suppress statechange event
      */
-    setInput(input, silent=false) {
-        this.manager.input.set(input, silent);
+    setInput(input) {
+        // Get the currently active tab.
+        // If there isn't one, assume there are no inputs so use inputNum of 1
+        let inputNum = this.manager.tabs.getActiveInputTab();
+        if (inputNum === -1) inputNum = 1;
+        this.manager.input.updateInputValue(inputNum, input);
+
+        this.manager.input.inputWorker.postMessage({
+            action: "setInput",
+            data: {
+                inputNum: inputNum,
+                silent: true
+            }
+        });
     }
 
 
@@ -244,7 +284,7 @@ class App {
     /**
      * Sets up the adjustable splitter to allow the user to resize areas of the page.
      *
-     * @param {boolean} [minimise=false] - Set this flag if attempting to minimuse frames to 0 width
+     * @param {boolean} [minimise=false] - Set this flag if attempting to minimise frames to 0 width
      */
     initialiseSplitter(minimise=false) {
         if (this.columnSplitter) this.columnSplitter.destroy();
@@ -252,12 +292,14 @@ class App {
 
         this.columnSplitter = Split(["#operations", "#recipe", "#IO"], {
             sizes: [20, 30, 50],
-            minSize: minimise ? [0, 0, 0] : [240, 370, 450],
+            minSize: minimise ? [0, 0, 0] : [240, 310, 450],
             gutterSize: 4,
-            expandToMin: false,
-            onDrag: function() {
+            expandToMin: true,
+            onDrag: this.debounce(function() {
                 this.manager.recipe.adjustWidth();
-            }.bind(this)
+                this.manager.input.calcMaxTabs();
+                this.manager.output.calcMaxTabs();
+            }, 50, "dragSplitter", this, [])
         });
 
         this.ioSplitter = Split(["#input", "#output"], {
@@ -391,11 +433,12 @@ class App {
         this.manager.recipe.initialiseOperationDragNDrop();
     }
 
-
     /**
-     * Checks for input and recipe in the URI parameters and loads them if present.
+     * Gets the URI params from the window and parses them to extract the actual values.
+     *
+     * @returns {object}
      */
-    loadURIParams() {
+    getURIParams() {
         // Load query string or hash from URI (depending on which is populated)
         // We prefer getting the hash by splitting the href rather than referencing
         // location.hash as some browsers (Firefox) automatically URL decode it,
@@ -403,8 +446,20 @@ class App {
         const params = window.location.search ||
             window.location.href.split("#")[1] ||
             window.location.hash;
-        this.uriParams = Utils.parseURIParams(params);
+        const parsedParams = Utils.parseURIParams(params);
+        return parsedParams;
+    }
+
+    /**
+     * Searches the URI parameters for recipe and input parameters.
+     * If recipe is present, replaces the current recipe with the recipe provided in the URI.
+     * If input is present, decodes and sets the input to the one provided in the URI.
+     *
+     * @fires Manager#statechange
+     */
+    loadURIParams() {
         this.autoBakePause = true;
+        this.uriParams = this.getURIParams();
 
         // Read in recipe from URI params
         if (this.uriParams.recipe) {
@@ -433,7 +488,7 @@ class App {
         if (this.uriParams.input) {
             try {
                 const inputData = fromBase64(this.uriParams.input);
-                this.setInput(inputData, true);
+                this.setInput(inputData);
             } catch (err) {}
         }
 
@@ -522,6 +577,8 @@ class App {
         this.columnSplitter.setSizes([20, 30, 50]);
         this.ioSplitter.setSizes([50, 50]);
         this.manager.recipe.adjustWidth();
+        this.manager.input.calcMaxTabs();
+        this.manager.output.calcMaxTabs();
     }
 
 
@@ -656,6 +713,17 @@ class App {
         this.progress = 0;
         this.autoBake();
 
+        this.updateTitle(false, null, true);
+    }
+
+    /**
+     * Update the page title to contain the new recipe
+     *
+     * @param {boolean} includeInput
+     * @param {string} input
+     * @param {boolean} [changeUrl=true]
+     */
+    updateTitle(includeInput, input, changeUrl=true) {
         // Set title
         const recipeConfig = this.getRecipeConfig();
         let title = "CyberChef";
@@ -674,8 +742,8 @@ class App {
         document.title = title;
 
         // Update the current history state (not creating a new one)
-        if (this.options.updateUrl) {
-            this.lastStateUrl = this.manager.controls.generateStateUrl(true, true, recipeConfig);
+        if (this.options.updateUrl && changeUrl) {
+            this.lastStateUrl = this.manager.controls.generateStateUrl(true, includeInput, input, recipeConfig);
             window.history.replaceState({}, title, this.lastStateUrl);
         }
     }
@@ -691,6 +759,29 @@ class App {
         this.loadURIParams();
     }
 
+
+    /**
+     * Debouncer to stop functions from being executed multiple times in a
+     * short space of time
+     * https://davidwalsh.name/javascript-debounce-function
+     *
+     * @param {function} func - The function to be executed after the debounce time
+     * @param {number} wait - The time (ms) to wait before executing the function
+     * @param {string} id - Unique ID to reference the timeout for the function
+     * @param {object} scope - The object to bind to the debounced function
+     * @param {array} args - Array of arguments to be passed to func
+     * @returns {function}
+     */
+    debounce(func, wait, id, scope, args) {
+        return function() {
+            const later = function() {
+                func.apply(scope, args);
+            };
+            clearTimeout(this.timeouts[id]);
+            this.timeouts[id] = setTimeout(later, wait);
+        }.bind(this);
+    }
+
 }
 
 export default App;

+ 0 - 354
src/web/InputWaiter.mjs

@@ -1,354 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2016
- * @license Apache-2.0
- */
-
-import LoaderWorker from "worker-loader?inline&fallback=false!./LoaderWorker";
-import Utils from "../core/Utils";
-
-
-/**
- * Waiter to handle events related to the input.
- */
-class InputWaiter {
-
-    /**
-     * InputWaiter constructor.
-     *
-     * @param {App} app - The main view object for CyberChef.
-     * @param {Manager} manager - The CyberChef event manager.
-     */
-    constructor(app, manager) {
-        this.app = app;
-        this.manager = manager;
-
-        // Define keys that don't change the input so we don't have to autobake when they are pressed
-        this.badKeys = [
-            16, //Shift
-            17, //Ctrl
-            18, //Alt
-            19, //Pause
-            20, //Caps
-            27, //Esc
-            33, 34, 35, 36, //PgUp, PgDn, End, Home
-            37, 38, 39, 40, //Directional
-            44, //PrntScrn
-            91, 92, //Win
-            93, //Context
-            112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, //F1-12
-            144, //Num
-            145, //Scroll
-        ];
-
-        this.loaderWorker = null;
-        this.fileBuffer = null;
-    }
-
-
-    /**
-     * Gets the user's input from the input textarea.
-     *
-     * @returns {string}
-     */
-    get() {
-        return this.fileBuffer || document.getElementById("input-text").value;
-    }
-
-
-    /**
-     * Sets the input in the input area.
-     *
-     * @param {string|File} input
-     * @param {boolean} [silent=false] - Suppress statechange event
-     *
-     * @fires Manager#statechange
-     */
-    set(input, silent=false) {
-        const inputText = document.getElementById("input-text");
-        if (input instanceof File) {
-            this.setFile(input);
-            inputText.value = "";
-            this.setInputInfo(input.size, null);
-        } else {
-            inputText.value = input;
-            this.closeFile();
-            if (!silent) window.dispatchEvent(this.manager.statechange);
-            const lines = input.length < (this.app.options.ioDisplayThreshold * 1024) ?
-                input.count("\n") + 1 : null;
-            this.setInputInfo(input.length, lines);
-        }
-    }
-
-
-    /**
-     * Shows file details.
-     *
-     * @param {File} file
-     */
-    setFile(file) {
-        // Display file overlay in input area with details
-        const fileOverlay = document.getElementById("input-file"),
-            fileName = document.getElementById("input-file-name"),
-            fileSize = document.getElementById("input-file-size"),
-            fileType = document.getElementById("input-file-type"),
-            fileLoaded = document.getElementById("input-file-loaded");
-
-        this.fileBuffer = new ArrayBuffer();
-        fileOverlay.style.display = "block";
-        fileName.textContent = file.name;
-        fileSize.textContent = file.size.toLocaleString() + " bytes";
-        fileType.textContent = file.type || "unknown";
-        fileLoaded.textContent = "0%";
-    }
-
-
-    /**
-     * Displays information about the input.
-     *
-     * @param {number} length - The length of the current input string
-     * @param {number} lines - The number of the lines in the current input string
-     */
-    setInputInfo(length, lines) {
-        let width = length.toString().length;
-        width = width < 2 ? 2 : width;
-
-        const lengthStr = length.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
-        let msg = "length: " + lengthStr;
-
-        if (typeof lines === "number") {
-            const linesStr = lines.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
-            msg += "<br>lines: " + linesStr;
-        }
-
-        document.getElementById("input-info").innerHTML = msg;
-    }
-
-
-    /**
-     * Handler for input change events.
-     *
-     * @param {event} e
-     *
-     * @fires Manager#statechange
-     */
-    inputChange(e) {
-        // Ignore this function if the input is a File
-        if (this.fileBuffer) return;
-
-        // Remove highlighting from input and output panes as the offsets might be different now
-        this.manager.highlighter.removeHighlights();
-
-        // Reset recipe progress as any previous processing will be redundant now
-        this.app.progress = 0;
-
-        // Update the input metadata info
-        const inputText = this.get();
-        const lines = inputText.length < (this.app.options.ioDisplayThreshold * 1024) ?
-            inputText.count("\n") + 1 : null;
-
-        this.setInputInfo(inputText.length, lines);
-
-        if (e && this.badKeys.indexOf(e.keyCode) < 0) {
-            // Fire the statechange event as the input has been modified
-            window.dispatchEvent(this.manager.statechange);
-        }
-    }
-
-
-    /**
-     * Handler for input paste events.
-     * Checks that the size of the input is below the display limit, otherwise treats it as a file/blob.
-     *
-     * @param {event} e
-     */
-    inputPaste(e) {
-        const pastedData = e.clipboardData.getData("Text");
-
-        if (pastedData.length < (this.app.options.ioDisplayThreshold * 1024)) {
-            this.inputChange(e);
-        } else {
-            e.preventDefault();
-            e.stopPropagation();
-
-            const file = new File([pastedData], "PastedData", {
-                type: "text/plain",
-                lastModified: Date.now()
-            });
-
-            this.loaderWorker = new LoaderWorker();
-            this.loaderWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
-            this.loaderWorker.postMessage({"file": file});
-            this.set(file);
-            return false;
-        }
-    }
-
-
-    /**
-     * Handler for input dragover events.
-     * Gives the user a visual cue to show that items can be dropped here.
-     *
-     * @param {event} e
-     */
-    inputDragover(e) {
-        // This will be set if we're dragging an operation
-        if (e.dataTransfer.effectAllowed === "move")
-            return false;
-
-        e.stopPropagation();
-        e.preventDefault();
-        e.target.closest("#input-text,#input-file").classList.add("dropping-file");
-    }
-
-
-    /**
-     * Handler for input dragleave events.
-     * Removes the visual cue.
-     *
-     * @param {event} e
-     */
-    inputDragleave(e) {
-        e.stopPropagation();
-        e.preventDefault();
-        document.getElementById("input-text").classList.remove("dropping-file");
-        document.getElementById("input-file").classList.remove("dropping-file");
-    }
-
-
-    /**
-     * Handler for input drop events.
-     * Loads the dragged data into the input textarea.
-     *
-     * @param {event} e
-     */
-    inputDrop(e) {
-        // This will be set if we're dragging an operation
-        if (e.dataTransfer.effectAllowed === "move")
-            return false;
-
-        e.stopPropagation();
-        e.preventDefault();
-
-        const file = e.dataTransfer.files[0];
-        const text = e.dataTransfer.getData("Text");
-
-        document.getElementById("input-text").classList.remove("dropping-file");
-        document.getElementById("input-file").classList.remove("dropping-file");
-
-        if (text) {
-            this.closeFile();
-            this.set(text);
-            return;
-        }
-
-        if (file) {
-            this.loadFile(file);
-        }
-    }
-
-    /**
-     * Handler for open input button events
-     * Loads the opened data into the input textarea
-     *
-     * @param {event} e
-     */
-    inputOpen(e) {
-        e.preventDefault();
-        const file = e.srcElement.files[0];
-        this.loadFile(file);
-    }
-
-
-    /**
-     * Handler for messages sent back by the LoaderWorker.
-     *
-     * @param {MessageEvent} e
-     */
-    handleLoaderMessage(e) {
-        const r = e.data;
-        if (r.hasOwnProperty("progress")) {
-            const fileLoaded = document.getElementById("input-file-loaded");
-            fileLoaded.textContent = r.progress + "%";
-        }
-
-        if (r.hasOwnProperty("error")) {
-            this.app.alert(r.error, 10000);
-        }
-
-        if (r.hasOwnProperty("fileBuffer")) {
-            log.debug("Input file loaded");
-            this.fileBuffer = r.fileBuffer;
-            this.displayFilePreview();
-            window.dispatchEvent(this.manager.statechange);
-        }
-    }
-
-
-    /**
-     * Shows a chunk of the file in the input behind the file overlay.
-     */
-    displayFilePreview() {
-        const inputText = document.getElementById("input-text"),
-            fileSlice = this.fileBuffer.slice(0, 4096);
-
-        inputText.style.overflow = "hidden";
-        inputText.classList.add("blur");
-        inputText.value = Utils.printable(Utils.arrayBufferToStr(fileSlice));
-        if (this.fileBuffer.byteLength > 4096) {
-            inputText.value += "[truncated]...";
-        }
-    }
-
-
-    /**
-     * Handler for file close events.
-     */
-    closeFile() {
-        if (this.loaderWorker) this.loaderWorker.terminate();
-        this.fileBuffer = null;
-        document.getElementById("input-file").style.display = "none";
-        const inputText = document.getElementById("input-text");
-        inputText.style.overflow = "auto";
-        inputText.classList.remove("blur");
-    }
-
-
-    /**
-     * Loads a file into the input.
-     *
-     * @param {File} file
-     */
-    loadFile(file) {
-        if (file) {
-            this.closeFile();
-            this.loaderWorker = new LoaderWorker();
-            this.loaderWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
-            this.loaderWorker.postMessage({"file": file});
-            this.set(file);
-        }
-    }
-
-
-    /**
-     * Handler for clear IO events.
-     * Resets the input, output and info areas.
-     *
-     * @fires Manager#statechange
-     */
-    clearIoClick() {
-        this.closeFile();
-        this.manager.output.closeFile();
-        this.manager.highlighter.removeHighlights();
-        document.getElementById("input-text").value = "";
-        document.getElementById("output-text").value = "";
-        document.getElementById("input-info").innerHTML = "";
-        document.getElementById("output-info").innerHTML = "";
-        document.getElementById("input-selection-info").innerHTML = "";
-        document.getElementById("output-selection-info").innerHTML = "";
-        window.dispatchEvent(this.manager.statechange);
-    }
-
-}
-
-export default InputWaiter;

+ 62 - 17
src/web/Manager.mjs

@@ -4,18 +4,19 @@
  * @license Apache-2.0
  */
 
-import WorkerWaiter from "./WorkerWaiter";
-import WindowWaiter from "./WindowWaiter";
-import ControlsWaiter from "./ControlsWaiter";
-import RecipeWaiter from "./RecipeWaiter";
-import OperationsWaiter from "./OperationsWaiter";
-import InputWaiter from "./InputWaiter";
-import OutputWaiter from "./OutputWaiter";
-import OptionsWaiter from "./OptionsWaiter";
-import HighlighterWaiter from "./HighlighterWaiter";
-import SeasonalWaiter from "./SeasonalWaiter";
-import BindingsWaiter from "./BindingsWaiter";
-import BackgroundWorkerWaiter from "./BackgroundWorkerWaiter";
+import WorkerWaiter from "./waiters/WorkerWaiter";
+import WindowWaiter from "./waiters/WindowWaiter";
+import ControlsWaiter from "./waiters/ControlsWaiter";
+import RecipeWaiter from "./waiters/RecipeWaiter";
+import OperationsWaiter from "./waiters/OperationsWaiter";
+import InputWaiter from "./waiters/InputWaiter";
+import OutputWaiter from "./waiters/OutputWaiter";
+import OptionsWaiter from "./waiters/OptionsWaiter";
+import HighlighterWaiter from "./waiters/HighlighterWaiter";
+import SeasonalWaiter from "./waiters/SeasonalWaiter";
+import BindingsWaiter from "./waiters/BindingsWaiter";
+import BackgroundWorkerWaiter from "./waiters/BackgroundWorkerWaiter";
+import TabWaiter from "./waiters/TabWaiter";
 
 
 /**
@@ -63,6 +64,7 @@ class Manager {
         this.controls    = new ControlsWaiter(this.app, this);
         this.recipe      = new RecipeWaiter(this.app, this);
         this.ops         = new OperationsWaiter(this.app, this);
+        this.tabs        = new TabWaiter(this.app, this);
         this.input       = new InputWaiter(this.app, this);
         this.output      = new OutputWaiter(this.app, this);
         this.options     = new OptionsWaiter(this.app, this);
@@ -82,7 +84,9 @@ class Manager {
      * Sets up the various components and listeners.
      */
     setup() {
-        this.worker.registerChefWorker();
+        this.input.setupInputWorker();
+        this.input.addInput(true);
+        this.worker.setupChefWorker();
         this.recipe.initialiseOperationDragNDrop();
         this.controls.initComponents();
         this.controls.autoBakeChange();
@@ -142,11 +146,11 @@ class Manager {
         this.addDynamicListener("textarea.arg", "drop", this.recipe.textArgDrop, this.recipe);
 
         // Input
-        this.addMultiEventListener("#input-text", "keyup", this.input.inputChange, this.input);
+        this.addMultiEventListener("#input-text", "keyup", this.input.debounceInputChange, this.input);
         this.addMultiEventListener("#input-text", "paste", this.input.inputPaste, this.input);
         document.getElementById("reset-layout").addEventListener("click", this.app.resetLayout.bind(this.app));
-        document.getElementById("clr-io").addEventListener("click", this.input.clearIoClick.bind(this.input));
-        this.addListeners("#open-file", "change", this.input.inputOpen, this.input);
+        this.addListeners("#clr-io,#btn-close-all-tabs", "click", this.input.clearAllIoClick, this.input);
+        this.addListeners("#open-file,#open-folder", "change", this.input.inputOpen, this.input);
         this.addListeners("#input-text,#input-file", "dragover", this.input.inputDragover, this.input);
         this.addListeners("#input-text,#input-file", "dragleave", this.input.inputDragleave, this.input);
         this.addListeners("#input-text,#input-file", "drop", this.input.inputDrop, this.input);
@@ -155,9 +159,31 @@ class Manager {
         document.getElementById("input-text").addEventListener("mousemove", this.highlighter.inputMousemove.bind(this.highlighter));
         this.addMultiEventListener("#input-text", "mousedown dblclick select",  this.highlighter.inputMousedown, this.highlighter);
         document.querySelector("#input-file .close").addEventListener("click", this.input.clearIoClick.bind(this.input));
+        document.getElementById("btn-new-tab").addEventListener("click", this.input.addInputClick.bind(this.input));
+        document.getElementById("btn-previous-input-tab").addEventListener("mousedown", this.input.previousTabClick.bind(this.input));
+        document.getElementById("btn-next-input-tab").addEventListener("mousedown", this.input.nextTabClick.bind(this.input));
+        this.addListeners("#btn-next-input-tab,#btn-previous-input-tab", "mouseup", this.input.tabMouseUp, this.input);
+        this.addListeners("#btn-next-input-tab,#btn-previous-input-tab", "mouseout", this.input.tabMouseUp, this.input);
+        document.getElementById("btn-go-to-input-tab").addEventListener("click", this.input.goToTab.bind(this.input));
+        document.getElementById("btn-find-input-tab").addEventListener("click", this.input.findTab.bind(this.input));
+        this.addDynamicListener("#input-tabs li .input-tab-content", "click", this.input.changeTabClick, this.input);
+        document.getElementById("input-show-pending").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-show-loading").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-show-loaded").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+        this.addListeners("#input-filter-content,#input-filter-filename", "click", this.input.filterOptionClick, this.input);
+        document.getElementById("input-filter").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-filter").addEventListener("keyup", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-num-results").addEventListener("change", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-num-results").addEventListener("keyup", this.input.filterTabSearch.bind(this.input));
+        document.getElementById("input-filter-refresh").addEventListener("click", this.input.filterTabSearch.bind(this.input));
+        this.addDynamicListener(".input-filter-result", "click", this.input.filterItemClick, this.input);
+        document.getElementById("btn-open-file").addEventListener("click", this.input.inputOpenClick.bind(this.input));
+        document.getElementById("btn-open-folder").addEventListener("click", this.input.folderOpenClick.bind(this.input));
+
 
         // Output
         document.getElementById("save-to-file").addEventListener("click", this.output.saveClick.bind(this.output));
+        document.getElementById("save-all-to-file").addEventListener("click", this.output.saveAllClick.bind(this.output));
         document.getElementById("copy-output").addEventListener("click", this.output.copyClick.bind(this.output));
         document.getElementById("switch").addEventListener("click", this.output.switchClick.bind(this.output));
         document.getElementById("undo-switch").addEventListener("click", this.output.undoSwitchClick.bind(this.output));
@@ -174,6 +200,25 @@ class Manager {
         this.addDynamicListener("#output-file-slice i", "click", this.output.displayFileSlice, this.output);
         document.getElementById("show-file-overlay").addEventListener("click", this.output.showFileOverlayClick.bind(this.output));
         this.addDynamicListener(".extract-file,.extract-file i", "click", this.output.extractFileClick, this.output);
+        this.addDynamicListener("#output-tabs-wrapper #output-tabs li .output-tab-content", "click", this.output.changeTabClick, this.output);
+        document.getElementById("btn-previous-output-tab").addEventListener("mousedown", this.output.previousTabClick.bind(this.output));
+        document.getElementById("btn-next-output-tab").addEventListener("mousedown", this.output.nextTabClick.bind(this.output));
+        this.addListeners("#btn-next-output-tab,#btn-previous-output-tab", "mouseup", this.output.tabMouseUp, this.output);
+        this.addListeners("#btn-next-output-tab,#btn-previous-output-tab", "mouseout", this.output.tabMouseUp, this.output);
+        document.getElementById("btn-go-to-output-tab").addEventListener("click", this.output.goToTab.bind(this.output));
+        document.getElementById("btn-find-output-tab").addEventListener("click", this.output.findTab.bind(this.output));
+        document.getElementById("output-show-pending").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-show-baking").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-show-baked").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-show-stale").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-show-errored").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-content-filter").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-content-filter").addEventListener("keyup", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-num-results").addEventListener("change", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-num-results").addEventListener("keyup", this.output.filterTabSearch.bind(this.output));
+        document.getElementById("output-filter-refresh").addEventListener("click", this.output.filterTabSearch.bind(this.output));
+        this.addDynamicListener(".output-filter-result", "click", this.output.filterItemClick, this.output);
+
 
         // Options
         document.getElementById("options").addEventListener("click", this.options.optionsClick.bind(this.options));
@@ -186,6 +231,7 @@ class Manager {
         this.addDynamicListener(".option-item select", "change", this.options.selectChange, this.options);
         document.getElementById("theme").addEventListener("change", this.options.themeChange.bind(this.options));
         document.getElementById("logLevel").addEventListener("change", this.options.logLevelChange.bind(this.options));
+        document.getElementById("imagePreview").addEventListener("change", this.input.renderFileThumb.bind(this.input));
 
         // Misc
         window.addEventListener("keydown", this.bindings.parseInput.bind(this.bindings));
@@ -307,7 +353,6 @@ class Manager {
             }
         }
     }
-
 }
 
 export default Manager;

+ 0 - 547
src/web/OutputWaiter.mjs

@@ -1,547 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2016
- * @license Apache-2.0
- */
-
-import Utils from "../core/Utils";
-import FileSaver from "file-saver";
-
-
-/**
- * Waiter to handle events related to the output.
- */
-class OutputWaiter {
-
-    /**
-     * OutputWaiter constructor.
-     *
-     * @param {App} app - The main view object for CyberChef.
-     * @param {Manager} manager - The CyberChef event manager.
-     */
-    constructor(app, manager) {
-        this.app = app;
-        this.manager = manager;
-
-        this.dishBuffer = null;
-        this.dishStr = null;
-    }
-
-
-    /**
-     * Gets the output string from the output textarea.
-     *
-     * @returns {string}
-     */
-    get() {
-        return document.getElementById("output-text").value;
-    }
-
-
-    /**
-     * Sets the output in the output textarea.
-     *
-     * @param {string|ArrayBuffer} data - The output string/HTML/ArrayBuffer
-     * @param {string} type - The data type of the output
-     * @param {number} duration - The length of time (ms) it took to generate the output
-     * @param {boolean} [preserveBuffer=false] - Whether to preserve the dishBuffer
-     */
-    async set(data, type, duration, preserveBuffer) {
-        log.debug("Output type: " + type);
-        const outputText = document.getElementById("output-text");
-        const outputHtml = document.getElementById("output-html");
-        const outputFile = document.getElementById("output-file");
-        const outputHighlighter = document.getElementById("output-highlighter");
-        const inputHighlighter = document.getElementById("input-highlighter");
-        let scriptElements, lines, length;
-
-        if (!preserveBuffer) {
-            this.closeFile();
-            this.dishStr = null;
-            document.getElementById("show-file-overlay").style.display = "none";
-        }
-
-        switch (type) {
-            case "html":
-                outputText.style.display = "none";
-                outputHtml.style.display = "block";
-                outputFile.style.display = "none";
-                outputHighlighter.display = "none";
-                inputHighlighter.display = "none";
-
-                outputText.value = "";
-                outputHtml.innerHTML = data;
-
-                // Execute script sections
-                scriptElements = outputHtml.querySelectorAll("script");
-                for (let i = 0; i < scriptElements.length; i++) {
-                    try {
-                        eval(scriptElements[i].innerHTML); // eslint-disable-line no-eval
-                    } catch (err) {
-                        log.error(err);
-                    }
-                }
-
-                await this.getDishStr();
-                length = this.dishStr.length;
-                lines = this.dishStr.count("\n") + 1;
-                break;
-            case "ArrayBuffer":
-                outputText.style.display = "block";
-                outputHtml.style.display = "none";
-                outputHighlighter.display = "none";
-                inputHighlighter.display = "none";
-
-                outputText.value = "";
-                outputHtml.innerHTML = "";
-                length = data.byteLength;
-
-                this.setFile(data);
-                break;
-            case "string":
-            default:
-                outputText.style.display = "block";
-                outputHtml.style.display = "none";
-                outputFile.style.display = "none";
-                outputHighlighter.display = "block";
-                inputHighlighter.display = "block";
-
-                outputText.value = Utils.printable(data, true);
-                outputHtml.innerHTML = "";
-
-                lines = data.count("\n") + 1;
-                length = data.length;
-                this.dishStr = data;
-                break;
-        }
-
-        this.manager.highlighter.removeHighlights();
-        this.setOutputInfo(length, lines, duration);
-        this.backgroundMagic();
-    }
-
-
-    /**
-     * Shows file details.
-     *
-     * @param {ArrayBuffer} buf
-     */
-    setFile(buf) {
-        this.dishBuffer = buf;
-        const file = new File([buf], "output.dat");
-
-        // Display file overlay in output area with details
-        const fileOverlay = document.getElementById("output-file"),
-            fileSize = document.getElementById("output-file-size");
-
-        fileOverlay.style.display = "block";
-        fileSize.textContent = file.size.toLocaleString() + " bytes";
-
-        // Display preview slice in the background
-        const outputText = document.getElementById("output-text"),
-            fileSlice = this.dishBuffer.slice(0, 4096);
-
-        outputText.classList.add("blur");
-        outputText.value = Utils.printable(Utils.arrayBufferToStr(fileSlice));
-    }
-
-
-    /**
-     * Removes the output file and nulls its memory.
-     */
-    closeFile() {
-        this.dishBuffer = null;
-        document.getElementById("output-file").style.display = "none";
-        document.getElementById("output-text").classList.remove("blur");
-    }
-
-
-    /**
-     * Handler for file download events.
-     */
-    async downloadFile() {
-        this.filename = window.prompt("Please enter a filename:", this.filename || "download.dat");
-        await this.getDishBuffer();
-        const file = new File([this.dishBuffer], this.filename);
-        if (this.filename) FileSaver.saveAs(file, this.filename, false);
-    }
-
-
-    /**
-     * Handler for file slice display events.
-     */
-    displayFileSlice() {
-        const startTime = new Date().getTime(),
-            showFileOverlay = document.getElementById("show-file-overlay"),
-            sliceFromEl = document.getElementById("output-file-slice-from"),
-            sliceToEl = document.getElementById("output-file-slice-to"),
-            sliceFrom = parseInt(sliceFromEl.value, 10),
-            sliceTo = parseInt(sliceToEl.value, 10),
-            str = Utils.arrayBufferToStr(this.dishBuffer.slice(sliceFrom, sliceTo));
-
-        document.getElementById("output-text").classList.remove("blur");
-        showFileOverlay.style.display = "block";
-        this.set(str, "string", new Date().getTime() - startTime, true);
-    }
-
-
-    /**
-     * Handler for show file overlay events.
-     *
-     * @param {Event} e
-     */
-    showFileOverlayClick(e) {
-        const outputFile = document.getElementById("output-file"),
-            showFileOverlay = e.target;
-
-        document.getElementById("output-text").classList.add("blur");
-        outputFile.style.display = "block";
-        showFileOverlay.style.display = "none";
-        this.setOutputInfo(this.dishBuffer.byteLength, null, 0);
-    }
-
-
-    /**
-     * Displays information about the output.
-     *
-     * @param {number} length - The length of the current output string
-     * @param {number} lines - The number of the lines in the current output string
-     * @param {number} duration - The length of time (ms) it took to generate the output
-     */
-    setOutputInfo(length, lines, duration) {
-        let width = length.toString().length;
-        width = width < 4 ? 4 : width;
-
-        const lengthStr = length.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
-        const timeStr = (duration.toString() + "ms").padStart(width, " ").replace(/ /g, "&nbsp;");
-
-        let msg = "time: " + timeStr + "<br>length: " + lengthStr;
-
-        if (typeof lines === "number") {
-            const linesStr = lines.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
-            msg += "<br>lines: " + linesStr;
-        }
-
-        document.getElementById("output-info").innerHTML = msg;
-        document.getElementById("input-selection-info").innerHTML = "";
-        document.getElementById("output-selection-info").innerHTML = "";
-    }
-
-
-    /**
-     * Handler for save click events.
-     * Saves the current output to a file.
-     */
-    saveClick() {
-        this.downloadFile();
-    }
-
-
-    /**
-     * Handler for copy click events.
-     * Copies the output to the clipboard.
-     */
-    async copyClick() {
-        await this.getDishStr();
-
-        // Create invisible textarea to populate with the raw dish string (not the printable version that
-        // contains dots instead of the actual bytes)
-        const textarea = document.createElement("textarea");
-        textarea.style.position = "fixed";
-        textarea.style.top = 0;
-        textarea.style.left = 0;
-        textarea.style.width = 0;
-        textarea.style.height = 0;
-        textarea.style.border = "none";
-
-        textarea.value = this.dishStr;
-        document.body.appendChild(textarea);
-
-        // Select and copy the contents of this textarea
-        let success = false;
-        try {
-            textarea.select();
-            success = this.dishStr && document.execCommand("copy");
-        } catch (err) {
-            success = false;
-        }
-
-        if (success) {
-            this.app.alert("Copied raw output successfully.", 2000);
-        } else {
-            this.app.alert("Sorry, the output could not be copied.", 3000);
-        }
-
-        // Clean up
-        document.body.removeChild(textarea);
-    }
-
-
-    /**
-     * Handler for switch click events.
-     * Moves the current output into the input textarea.
-     */
-    async switchClick() {
-        this.switchOrigData = this.manager.input.get();
-        document.getElementById("undo-switch").disabled = false;
-        if (this.dishBuffer) {
-            this.manager.input.setFile(new File([this.dishBuffer], "output.dat"));
-            this.manager.input.handleLoaderMessage({
-                data: {
-                    progress: 100,
-                    fileBuffer: this.dishBuffer
-                }
-            });
-        } else {
-            await this.getDishStr();
-            this.app.setInput(this.dishStr);
-        }
-    }
-
-
-    /**
-     * Handler for undo switch click events.
-     * Removes the output from the input and replaces the input that was removed.
-     */
-    undoSwitchClick() {
-        this.app.setInput(this.switchOrigData);
-        const undoSwitch = document.getElementById("undo-switch");
-        undoSwitch.disabled = true;
-        $(undoSwitch).tooltip("hide");
-    }
-
-
-    /**
-     * Handler for maximise output click events.
-     * Resizes the output frame to be as large as possible, or restores it to its original size.
-     */
-    maximiseOutputClick(e) {
-        const el = e.target.id === "maximise-output" ? e.target : e.target.parentNode;
-
-        if (el.getAttribute("data-original-title").indexOf("Maximise") === 0) {
-            this.app.initialiseSplitter(true);
-            this.app.columnSplitter.collapse(0);
-            this.app.columnSplitter.collapse(1);
-            this.app.ioSplitter.collapse(0);
-
-            $(el).attr("data-original-title", "Restore output pane");
-            el.querySelector("i").innerHTML = "fullscreen_exit";
-        } else {
-            $(el).attr("data-original-title", "Maximise output pane");
-            el.querySelector("i").innerHTML = "fullscreen";
-            this.app.initialiseSplitter(false);
-            this.app.resetLayout();
-        }
-    }
-
-
-    /**
-     * Save bombe object then remove it from the DOM so that it does not cause performance issues.
-     */
-    saveBombe() {
-        this.bombeEl = document.getElementById("bombe");
-        this.bombeEl.parentNode.removeChild(this.bombeEl);
-    }
-
-
-    /**
-     * Shows or hides the output loading screen.
-     * The animated Bombe SVG, whilst quite aesthetically pleasing, is reasonably CPU
-     * intensive, so we remove it from the DOM when not in use. We only show it if the
-     * recipe is taking longer than 200ms. We add it to the DOM just before that so that
-     * it is ready to fade in without stuttering.
-     *
-     * @param {boolean} value - true == show loader
-     */
-    toggleLoader(value) {
-        clearTimeout(this.appendBombeTimeout);
-        clearTimeout(this.outputLoaderTimeout);
-
-        const outputLoader = document.getElementById("output-loader"),
-            outputElement = document.getElementById("output-text"),
-            animation = document.getElementById("output-loader-animation");
-
-        if (value) {
-            this.manager.controls.hideStaleIndicator();
-
-            // Start a timer to add the Bombe to the DOM just before we make it
-            // visible so that there is no stuttering
-            this.appendBombeTimeout = setTimeout(function() {
-                animation.appendChild(this.bombeEl);
-            }.bind(this), 150);
-
-            // Show the loading screen
-            this.outputLoaderTimeout = setTimeout(function() {
-                outputElement.disabled = true;
-                outputLoader.style.visibility = "visible";
-                outputLoader.style.opacity = 1;
-                this.manager.controls.toggleBakeButtonFunction(true);
-            }.bind(this), 200);
-        } else {
-            // Remove the Bombe from the DOM to save resources
-            this.outputLoaderTimeout = setTimeout(function () {
-                try {
-                    animation.removeChild(this.bombeEl);
-                } catch (err) {}
-            }.bind(this), 500);
-            outputElement.disabled = false;
-            outputLoader.style.opacity = 0;
-            outputLoader.style.visibility = "hidden";
-            this.manager.controls.toggleBakeButtonFunction(false);
-            this.setStatusMsg("");
-        }
-    }
-
-
-    /**
-     * Sets the baking status message value.
-     *
-     * @param {string} msg
-     */
-    setStatusMsg(msg) {
-        const el = document.querySelector("#output-loader .loading-msg");
-
-        el.textContent = msg;
-    }
-
-
-    /**
-     * Returns true if the output contains carriage returns
-     *
-     * @returns {boolean}
-     */
-    async containsCR() {
-        await this.getDishStr();
-        return this.dishStr.indexOf("\r") >= 0;
-    }
-
-
-    /**
-     * Retrieves the current dish as a string, returning the cached version if possible.
-     *
-     * @returns {string}
-     */
-    async getDishStr() {
-        if (this.dishStr) return this.dishStr;
-
-        this.dishStr = await new Promise(resolve => {
-            this.manager.worker.getDishAs(this.app.dish, "string", r => {
-                resolve(r.value);
-            });
-        });
-        return this.dishStr;
-    }
-
-
-    /**
-     * Retrieves the current dish as an ArrayBuffer, returning the cached version if possible.
-     *
-     * @returns {ArrayBuffer}
-     */
-    async getDishBuffer() {
-        if (this.dishBuffer) return this.dishBuffer;
-
-        this.dishBuffer = await new Promise(resolve => {
-            this.manager.worker.getDishAs(this.app.dish, "ArrayBuffer", r => {
-                resolve(r.value);
-            });
-        });
-        return this.dishBuffer;
-    }
-
-
-    /**
-     * Triggers the BackgroundWorker to attempt Magic on the current output.
-     */
-    backgroundMagic() {
-        this.hideMagicButton();
-        if (!this.app.options.autoMagic) return;
-
-        const sample = this.dishStr ? this.dishStr.slice(0, 1000) :
-            this.dishBuffer ? this.dishBuffer.slice(0, 1000) : "";
-
-        if (sample.length) {
-            this.manager.background.magic(sample);
-        }
-    }
-
-
-    /**
-     * Handles the results of a background Magic call.
-     *
-     * @param {Object[]} options
-     */
-    backgroundMagicResult(options) {
-        if (!options.length ||
-            !options[0].recipe.length)
-            return;
-
-        const currentRecipeConfig = this.app.getRecipeConfig();
-        const newRecipeConfig = currentRecipeConfig.concat(options[0].recipe);
-        const opSequence = options[0].recipe.map(o => o.op).join(", ");
-
-        this.showMagicButton(opSequence, options[0].data, newRecipeConfig);
-    }
-
-
-    /**
-     * Handler for Magic click events.
-     *
-     * Loads the Magic recipe.
-     *
-     * @fires Manager#statechange
-     */
-    magicClick() {
-        const magicButton = document.getElementById("magic");
-        this.app.setRecipeConfig(JSON.parse(magicButton.getAttribute("data-recipe")));
-        window.dispatchEvent(this.manager.statechange);
-        this.hideMagicButton();
-    }
-
-
-    /**
-     * Displays the Magic button with a title and adds a link to a complete recipe.
-     *
-     * @param {string} opSequence
-     * @param {string} result
-     * @param {Object[]} recipeConfig
-     */
-    showMagicButton(opSequence, result, recipeConfig) {
-        const magicButton = document.getElementById("magic");
-        magicButton.setAttribute("data-original-title", `<i>${opSequence}</i> will produce <span class="data-text">"${Utils.escapeHtml(Utils.truncate(result), 30)}"</span>`);
-        magicButton.setAttribute("data-recipe", JSON.stringify(recipeConfig), null, "");
-        magicButton.classList.remove("hidden");
-    }
-
-
-    /**
-     * Hides the Magic button and resets its values.
-     */
-    hideMagicButton() {
-        const magicButton = document.getElementById("magic");
-        magicButton.classList.add("hidden");
-        magicButton.setAttribute("data-recipe", "");
-        magicButton.setAttribute("data-original-title", "Magic!");
-    }
-
-
-    /**
-     * Handler for extract file events.
-     *
-     * @param {Event} e
-     */
-    async extractFileClick(e) {
-        e.preventDefault();
-        e.stopPropagation();
-
-        const el = e.target.nodeName === "I" ? e.target.parentNode : e.target;
-        const blobURL = el.getAttribute("blob-url");
-        const fileName = el.getAttribute("file-name");
-
-        const blob = await fetch(blobURL).then(r => r.blob());
-        this.manager.input.loadFile(new File([blob], fileName, {type: blob.type}));
-    }
-
-}
-
-export default OutputWaiter;

+ 0 - 239
src/web/WorkerWaiter.mjs

@@ -1,239 +0,0 @@
-/**
- * @author n1474335 [n1474335@gmail.com]
- * @copyright Crown Copyright 2017
- * @license Apache-2.0
- */
-
-import ChefWorker from "worker-loader?inline&fallback=false!../core/ChefWorker";
-
-/**
- * Waiter to handle conversations with the ChefWorker.
- */
-class WorkerWaiter {
-
-    /**
-     * WorkerWaiter constructor.
-     *
-     * @param {App} app - The main view object for CyberChef.
-     * @param {Manager} manager - The CyberChef event manager.
-     */
-    constructor(app, manager) {
-        this.app = app;
-        this.manager = manager;
-
-        this.callbacks = {};
-        this.callbackID = 0;
-    }
-
-
-    /**
-     * Sets up the ChefWorker and associated listeners.
-     */
-    registerChefWorker() {
-        log.debug("Registering new ChefWorker");
-        this.chefWorker = new ChefWorker();
-        this.chefWorker.addEventListener("message", this.handleChefMessage.bind(this));
-        this.setLogLevel();
-
-        let docURL = document.location.href.split(/[#?]/)[0];
-        const index = docURL.lastIndexOf("/");
-        if (index > 0) {
-            docURL = docURL.substring(0, index);
-        }
-        this.chefWorker.postMessage({"action": "docURL", "data": docURL});
-    }
-
-
-    /**
-     * Handler for messages sent back by the ChefWorker.
-     *
-     * @param {MessageEvent} e
-     */
-    handleChefMessage(e) {
-        const r = e.data;
-        log.debug("Receiving '" + r.action + "' from ChefWorker");
-
-        switch (r.action) {
-            case "bakeComplete":
-                this.bakingComplete(r.data);
-                break;
-            case "bakeError":
-                this.app.handleError(r.data);
-                this.setBakingStatus(false);
-                break;
-            case "dishReturned":
-                this.callbacks[r.data.id](r.data);
-                break;
-            case "silentBakeComplete":
-                break;
-            case "workerLoaded":
-                this.app.workerLoaded = true;
-                log.debug("ChefWorker loaded");
-                this.app.loaded();
-                break;
-            case "statusMessage":
-                this.manager.output.setStatusMsg(r.data);
-                break;
-            case "optionUpdate":
-                log.debug(`Setting ${r.data.option} to ${r.data.value}`);
-                this.app.options[r.data.option] = r.data.value;
-                break;
-            case "setRegisters":
-                this.manager.recipe.setRegisters(r.data.opIndex, r.data.numPrevRegisters, r.data.registers);
-                break;
-            case "highlightsCalculated":
-                this.manager.highlighter.displayHighlights(r.data.pos, r.data.direction);
-                break;
-            default:
-                log.error("Unrecognised message from ChefWorker", e);
-                break;
-        }
-    }
-
-
-    /**
-     * Updates the UI to show if baking is in process or not.
-     *
-     * @param {bakingStatus}
-     */
-    setBakingStatus(bakingStatus) {
-        this.app.baking = bakingStatus;
-
-        this.manager.output.toggleLoader(bakingStatus);
-    }
-
-
-    /**
-     * Cancels the current bake by terminating the ChefWorker and creating a new one.
-     */
-    cancelBake() {
-        this.chefWorker.terminate();
-        this.registerChefWorker();
-        this.setBakingStatus(false);
-        this.manager.controls.showStaleIndicator();
-    }
-
-
-    /**
-     * Handler for completed bakes.
-     *
-     * @param {Object} response
-     */
-    bakingComplete(response) {
-        this.setBakingStatus(false);
-
-        if (!response) return;
-
-        if (response.error) {
-            this.app.handleError(response.error);
-        }
-
-        this.app.progress = response.progress;
-        this.app.dish = response.dish;
-        this.manager.recipe.updateBreakpointIndicator(response.progress);
-        this.manager.output.set(response.result, response.type, response.duration);
-        log.debug("--- Bake complete ---");
-    }
-
-
-    /**
-     * Asks the ChefWorker to bake the current input using the current recipe.
-     *
-     * @param {string} input
-     * @param {Object[]} recipeConfig
-     * @param {Object} options
-     * @param {number} progress
-     * @param {boolean} step
-     */
-    bake(input, recipeConfig, options, progress, step) {
-        this.setBakingStatus(true);
-
-        this.chefWorker.postMessage({
-            action: "bake",
-            data: {
-                input: input,
-                recipeConfig: recipeConfig,
-                options: options,
-                progress: progress,
-                step: step
-            }
-        });
-    }
-
-
-    /**
-     * Asks the ChefWorker to run a silent bake, forcing the browser to load and cache all the relevant
-     * JavaScript code needed to do a real bake.
-     *
-     * @param {Object[]} [recipeConfig]
-     */
-    silentBake(recipeConfig) {
-        this.chefWorker.postMessage({
-            action: "silentBake",
-            data: {
-                recipeConfig: recipeConfig
-            }
-        });
-    }
-
-
-    /**
-     * Asks the ChefWorker to calculate highlight offsets if possible.
-     *
-     * @param {Object[]} recipeConfig
-     * @param {string} direction
-     * @param {Object} pos - The position object for the highlight.
-     * @param {number} pos.start - The start offset.
-     * @param {number} pos.end - The end offset.
-     */
-    highlight(recipeConfig, direction, pos) {
-        this.chefWorker.postMessage({
-            action: "highlight",
-            data: {
-                recipeConfig: recipeConfig,
-                direction: direction,
-                pos: pos
-            }
-        });
-    }
-
-
-    /**
-     * Asks the ChefWorker to return the dish as the specified type
-     *
-     * @param {Dish} dish
-     * @param {string} type
-     * @param {Function} callback
-     */
-    getDishAs(dish, type, callback) {
-        const id = this.callbackID++;
-        this.callbacks[id] = callback;
-        this.chefWorker.postMessage({
-            action: "getDishAs",
-            data: {
-                dish: dish,
-                type: type,
-                id: id
-            }
-        });
-    }
-
-
-    /**
-     * Sets the console log level in the worker.
-     *
-     * @param {string} level
-     */
-    setLogLevel(level) {
-        if (!this.chefWorker) return;
-
-        this.chefWorker.postMessage({
-            action: "setLogLevel",
-            data: log.getLevel()
-        });
-    }
-
-}
-
-
-export default WorkerWaiter;

+ 232 - 37
src/web/html/index.html

@@ -191,7 +191,7 @@
                     <ul id="rec-list" class="list-area no-select"></ul>
 
                     <div id="controls" class="no-select">
-                        <div class="d-flex align-items-center">
+                        <div id="controls-content" class="d-flex align-items-center">
                             <button type="button" class="mx-2 btn btn-lg btn-secondary" id="step" data-toggle="tooltip" title="Step through the recipe">
                                 Step
                             </button>
@@ -218,9 +218,16 @@
                         <div class="title no-select">
                             <label for="input-text">Input</label>
                             <span class="float-right">
-                                <button type="button" class="btn btn-primary bmd-btn-icon" id="btn-open-file" data-toggle="tooltip" title="Open file as input" onclick="document.getElementById('open-file').click();">
+                                <button type="button" class="btn btn-primary bmd-btn-icon" id="btn-new-tab" data-toggle="tooltip" title="Add a new input tab">
+                                    <i class="material-icons">add</i>
+                                </button>
+                                <button type="button" class="btn btn-primary bmd-btn-icon" id="btn-open-folder" data-toggle="tooltip" title="Open folder as input">
+                                    <i class="material-icons">folder_open</i>
+                                    <input type="file" id="open-folder" style="display: none" multiple directory webkitdirectory>
+                                </button>
+                                <button type="button" class="btn btn-primary bmd-btn-icon" id="btn-open-file" data-toggle="tooltip" title="Open file as input">
                                     <i class="material-icons">input</i>
-                                    <input type="file" id="open-file" style="display: none">
+                                    <input type="file" id="open-file" style="display: none" multiple>
                                 </button>
                                 <button type="button" class="btn btn-primary bmd-btn-icon" id="clr-io" data-toggle="tooltip" title="Clear input and output">
                                     <i class="material-icons">delete</i>
@@ -229,17 +236,42 @@
                                     <i class="material-icons">view_compact</i>
                                 </button>
                             </span>
+                            <div class="io-info" id="input-files-info"></div>
                             <div class="io-info" id="input-info"></div>
                             <div class="io-info" id="input-selection-info"></div>
                         </div>
-                        <div class="textarea-wrapper no-select">
+                        <div id="input-tabs-wrapper" style="display: none;" class="no-select">
+                            <span id="btn-previous-input-tab" class="input-tab-buttons">
+                                &lt;
+                            </span>
+                            <span id="btn-input-tab-dropdown" class="input-tab-buttons" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+                                ···
+                            </span>
+                            <div class="dropdown-menu" aria-labelledby="btn-input-tab-dropdown">
+                                <a id="btn-go-to-input-tab" class="dropdown-item">
+                                    Go to tab
+                                </a>
+                                <a id="btn-find-input-tab" class="dropdown-item">
+                                    Find tab
+                                </a>
+                                <a id="btn-close-all-tabs" class="dropdown-item">
+                                    Close all tabs
+                                </a>
+                            </div>
+                            <span id="btn-next-input-tab" class="input-tab-buttons">
+                                &gt;
+                            </span>
+                            <ul id="input-tabs">
+                            </ul>
+                        </div>
+                        <div class="textarea-wrapper no-select input-wrapper" id="input-wrapper">
                             <div id="input-highlighter" class="no-select"></div>
-                            <textarea id="input-text" spellcheck="false"></textarea>
-                            <div id="input-file">
-                                <div class="file-overlay"></div>
+                            <textarea id="input-text" class="input-text" spellcheck="false"></textarea>
+                            <div class="input-file" id="input-file">
+                                <div class="file-overlay" id="file-overlay"></div>
                                 <div style="position: relative; height: 100%;">
                                     <div class="io-card card">
-                                        <img aria-hidden="true" src="<%- require('../static/images/file-128x128.png') %>" alt="File icon"/>
+                                        <img aria-hidden="true" src="<%- require('../static/images/file-128x128.png') %>" alt="File icon" id="input-file-thumbnail"/>
                                         <div class="card-body">
                                             <button type="button" class="close" id="input-file-close">&times;</button>
                                             Name: <span id="input-file-name"></span><br>
@@ -257,13 +289,16 @@
                         <div class="title no-select">
                             <label for="output-text">Output</label>
                             <span class="float-right">
+                                <button type="button" class="btn btn-primary bmd-btn-icon" id="save-all-to-file" data-toggle="tooltip" title="Save all outputs to a zip file" style="display: none">
+                                        <i class="material-icons">archive</i>
+                                    </button>
                                 <button type="button" class="btn btn-primary bmd-btn-icon" id="save-to-file" data-toggle="tooltip" title="Save output to file">
                                     <i class="material-icons">save</i>
                                 </button>
                                 <button type="button" class="btn btn-primary bmd-btn-icon" id="copy-output" data-toggle="tooltip" title="Copy raw output to the clipboard">
                                     <i class="material-icons">content_copy</i>
                                 </button>
-                                <button type="button" class="btn btn-primary bmd-btn-icon" id="switch" data-toggle="tooltip" title="Move output to input">
+                                <button type="button" class="btn btn-primary bmd-btn-icon" id="switch" data-toggle="tooltip" title="Replace input with output">
                                     <i class="material-icons">open_in_browser</i>
                                 </button>
                                 <button type="button" class="btn btn-primary bmd-btn-icon" id="undo-switch" data-toggle="tooltip" title="Undo" disabled="disabled">
@@ -273,6 +308,7 @@
                                     <i class="material-icons">fullscreen</i>
                                 </button>
                             </span>
+                            <div class="io-info" id="bake-info"></div>
                             <div class="io-info" id="output-info"></div>
                             <div class="io-info" id="output-selection-info"></div>
                             <button type="button" class="btn btn-primary bmd-btn-icon hidden" id="magic" data-toggle="tooltip" title="Magic!" data-html="true">
@@ -284,38 +320,61 @@
                                 <i class="material-icons">access_time</i>
                             </span>
                         </div>
-                        <div class="textarea-wrapper">
-                            <div id="output-highlighter" class="no-select"></div>
-                            <div id="output-html"></div>
-                            <textarea id="output-text" readonly="readonly" spellcheck="false"></textarea>
-                            <img id="show-file-overlay" aria-hidden="true" src="<%- require('../static/images/file-32x32.png') %>" alt="Show file overlay" title="Show file overlay"/>
-                            <div id="output-file">
-                                <div class="file-overlay"></div>
-                                <div style="position: relative; height: 100%;">
-                                    <div class="io-card card">
-                                        <img aria-hidden="true" src="<%- require('../static/images/file-128x128.png') %>" alt="File icon"/>
-                                        <div class="card-body">
-                                            Size: <span id="output-file-size"></span><br>
-                                            <button id="output-file-download" type="button" class="btn btn-primary btn-outline">Download</button>
-                                            <div class="input-group">
-                                                <span class="input-group-btn">
-                                                    <button id="output-file-slice" type="button" class="btn btn-secondary bmd-btn-icon" title="View slice">
-                                                          <i class="material-icons">search</i>
-                                                    </button>
-                                                </span>
-                                                <input type="number" class="form-control" id="output-file-slice-from" placeholder="From" value="0" step="1024" min="0">
-                                                <div class="input-group-addon">to</div>
-                                                <input type="number" class="form-control" id="output-file-slice-to" placeholder="To" value="2048" step="1024" min="0">
+                        <div id="output-wrapper">
+                            <div id="output-tabs-wrapper" style="display: none" class="no-select">
+                                <span id="btn-previous-output-tab" class="output-tab-buttons">
+                                    &lt;
+                                </span>
+                                <span id="btn-output-tab-dropdown" class="output-tab-buttons" data-toggle="dropdown"  aria-haspopup="true" aria-expanded="false">
+                                    ···
+                                </span>
+                                <div class="dropdown-menu" aria-labelledby="btn-input-tab-dropdown">
+                                    <a id="btn-go-to-output-tab" class="dropdown-item">
+                                        Go to tab
+                                    </a>
+                                    <a id="btn-find-output-tab" class="dropdown-item">
+                                        Find tab
+                                    </a>
+                                </div>
+                                <span id="btn-next-output-tab" class="output-tab-buttons">
+                                    &gt;
+                                </span>
+                                <ul id="output-tabs">
+                                </ul>
+                            </div>
+                            <div class="textarea-wrapper">
+                                <div id="output-highlighter" class="no-select"></div>
+                                <div id="output-html"></div>
+                                <textarea id="output-text" readonly="readonly" spellcheck="false"></textarea>
+                                <img id="show-file-overlay" aria-hidden="true" src="<%- require('../static/images/file-32x32.png') %>" alt="Show file overlay" title="Show file overlay"/>
+                                <div id="output-file">
+                                    <div class="file-overlay"></div>
+                                    <div style="position: relative; height: 100%;">
+                                        <div class="io-card card">
+                                            <img aria-hidden="true" src="<%- require('../static/images/file-128x128.png') %>" alt="File icon"/>
+                                            <div class="card-body">
+                                                Size: <span id="output-file-size"></span><br>
+                                                <button id="output-file-download" type="button" class="btn btn-primary btn-outline">Download</button>
+                                                <div class="input-group">
+                                                    <span class="input-group-btn">
+                                                        <button id="output-file-slice" type="button" class="btn btn-secondary bmd-btn-icon" title="View slice">
+                                                            <i class="material-icons">search</i>
+                                                        </button>
+                                                    </span>
+                                                    <input type="number" class="form-control" id="output-file-slice-from" placeholder="From" value="0" step="1024" min="0">
+                                                    <div class="input-group-addon">to</div>
+                                                    <input type="number" class="form-control" id="output-file-slice-to" placeholder="To" value="2048" step="1024" min="0">
+                                                </div>
                                             </div>
                                         </div>
                                     </div>
                                 </div>
-                            </div>
-                            <div id="output-loader">
-                                <div id="output-loader-animation">
-                                    <object id="bombe" data="<%- require('../static/images/bombe.svg') %>" width="100%" height="100%"></object>
+                                <div id="output-loader">
+                                    <div id="output-loader-animation">
+                                        <object id="bombe" data="<%- require('../static/images/bombe.svg') %>" width="100%" height="100%"></object>
+                                    </div>
+                                    <div class="loading-msg"></div>
                                 </div>
-                                <div class="loading-msg"></div>
                             </div>
                         </div>
                     </div>
@@ -425,6 +484,8 @@
                                 <option value="classic">Classic</option>
                                 <option value="dark">Dark</option>
                                 <option value="geocities">GeoCities</option>
+                                <option value="solarizedDark">Solarized Dark</option>
+                                <option value="solarizedLight">Solarized Light</option>
                             </select>
                         </div>
 
@@ -498,6 +559,20 @@
                                 Attempt to detect encoded data automagically
                             </label>
                         </div>
+
+                        <div class="checkbox option-item">
+                            <label for="imagePreview">
+                                <input type="checkbox" option="imagePreview" id="imagePreview">
+                                Render a preview of the input if it's detected to be an image.
+                            </label>
+                        </div>
+
+                        <div class="checkbox option-item">
+                                <label for="syncTabs">
+                                    <input type="checkbox" option="syncTabs" id="syncTabs">
+                                    Keep the current tab in sync between the input and output.
+                                </label>
+                            </div>
                     </div>
                     <div class="modal-footer">
                         <button type="button" class="btn btn-secondary" id="reset-options">Reset options to default</button>
@@ -599,7 +674,7 @@
                                 </a>
                                 <div class="collapse" id="faq-load-files">
                                     <p>Yes! Just drag your file over the input box and drop it.</p>
-                                    <p>CyberChef can handle files up to around 500MB (depending on your browser), however some of the operations may take a very long time to run over this much data.</p>
+                                    <p>CyberChef can handle files up to around 2GB (depending on your browser), however some of the operations may take a very long time to run over this much data.</p>
                                     <p>If the output is larger than a certain threshold (default 1MiB), it will be presented to you as a file available for download. Slices of the file can be viewed in the output if you need to inspect them.</p>
                                 </div>
                                 <br>
@@ -688,5 +763,125 @@
             </div>
         </div>
 
+        <div class="modal" id="input-tab-modal" tabindex="-1" role="dialog">
+            <div class="modal-dialog modal-lg" role="document">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <h5 class="modal-title">Find Input Tab</h5>
+                    </div>
+                    <div class="modal-body" id="input-tab-body">
+                        <h6>Load Status</h6>
+                        <div id="input-find-options">
+                            <ul id="input-find-options-checkboxes">
+                                <li class="checkbox input-find-option">
+                                    <label for="input-show-pending">
+                                        <input type="checkbox" id="input-show-pending" checked="">
+                                        Pending
+                                    </label>
+                                </li>
+                                <li class="checkbox input-find-option">
+                                    <label for="input-show-loading">
+                                        <input type="checkbox" id="input-show-loading" checked="">
+                                        Loading
+                                    </label>
+                                </li>
+                                <li class="checkbox input-find-option">
+                                    <label for="input-show-loaded">
+                                        <input type="checkbox" id="input-show-loaded" checked="">
+                                        Loaded
+                                    </label>
+                                </li>
+                            </ul>
+                        </div>
+                        <div class="form-group input-group">
+                            <div class="toggle-string">
+                                <label for="input-filter" class="bmd-label-floating toggle-string">Filter (regex)</label>
+                                <input type="text" class="form-control toggle-string" id="input-filter">
+                            </div>
+                            <div class="input-group-append">
+                                <button class="btn btn-secondary dropdown-toggle" id="input-filter-button" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">CONTENT</button>
+                                <div class="dropdown-menu toggle-dropdown">
+                                    <a class="dropdown-item" id="input-filter-content">Content</a>
+                                    <a class="dropdown-item" id="input-filter-filename">Filename</a>
+                                </div>
+                            </div>
+                        </div>
+                        <div class="form-group input-find-option" id="input-num-results-container">
+                            <label for="input-num-results" class="bmd-label-floating">Number of results</label>
+                            <input type="number" class="form-control" id="input-num-results" value="20" min="1">
+                        </div>
+                        <div style="clear:both"></div>
+                        <h6>Results</h6>
+                        <ul id="input-search-results"></ul>
+                    </div>
+                    <div class="modal-footer">
+                            <button type="button" class="btn btn-primary" id="input-filter-refresh">Refresh</button>
+                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+        <div class="modal" id="output-tab-modal" tabindex="-1" role="dialog">
+            <div class="modal-dialog modal-lg" role="document">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <h5 class="modal-title">Find Output Tab</h5>
+                    </div>
+                    <div class="modal-body" id="output-tab-body">
+                        <h6>Bake Status</h6>
+                        <div id="output-find-options">
+                            <ul id="output-find-options-checkboxes">
+                                <li class="checkbox output-find-option">
+                                    <label for="output-show-pending">
+                                        <input type="checkbox" id="output-show-pending" checked="">
+                                        Pending
+                                    </label>
+                                </li>
+                                <li class="checkbox output-find-option">
+                                    <label for="output-show-baking">
+                                        <input type="checkbox" id="output-show-baking" checked="">
+                                        Baking
+                                    </label>
+                                </li>
+                                <li class="checkbox output-find-option">
+                                    <label for="output-show-baked">
+                                        <input type="checkbox" id="output-show-baked" checked="">
+                                        Baked
+                                    </label>
+                                </li>
+                                <li class="checkbox output-find-option">
+                                    <label for="output-show-stale">
+                                        <input type="checkbox" id="output-show-stale" checked="">
+                                        Stale
+                                    </label>
+                                </li>
+                                <li class="checkbox output-find-option">
+                                    <label for="output-show-errored">
+                                        <input type="checkbox" id="output-show-errored" checked="">
+                                        Errored
+                                    </label>
+                                </li>
+                            </ul>
+                            <div class="form-group output-find-option">
+                                <label for="output-content-filter" class="bmd-label-floating">Content filter (regex)</label>
+                                <input type="text" class="form-control" id="output-content-filter">
+                            </div>
+                            <div class="form-group output-find-option" id="output-num-results-container">
+                                <label for="output-num-results" class="bmd-label-floating">Number of results</label>
+                                <input type="number" class="form-control" id="output-num-results" value="20">
+                            </div>
+                        </div>
+                        <br>
+                        <h6>Results</h6>
+                        <ul id="output-search-results"></ul>
+                    </div>
+                    <div class="modal-footer">
+                            <button type="button" class="btn btn-primary" id="output-filter-refresh">Refresh</button>
+                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
+                    </div>
+                </div>
+            </div>
+        </div>
     </body>
 </html>

+ 3 - 1
src/web/index.js

@@ -10,7 +10,7 @@ import "./stylesheets/index.js";
 // Libs
 import "arrive";
 import "snackbarjs";
-import "bootstrap-material-design";
+import "bootstrap-material-design/js/index";
 import "bootstrap-colorpicker";
 import moment from "moment-timezone";
 import * as CanvasComponents from "../core/lib/CanvasComponents";
@@ -52,6 +52,8 @@ function main() {
         ioDisplayThreshold:  512,
         logLevel:            "info",
         autoMagic:           true,
+        imagePreview:        true,
+        syncTabs:            true
     };
 
     document.removeEventListener("DOMContentLoaded", main, false);

+ 485 - 0
src/web/static/fonts/bmfonts/Roboto72White.fnt

@@ -0,0 +1,485 @@
+info face="Roboto" size=72 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=-2,-2
+common lineHeight=85 base=67 scaleW=512 scaleH=512 pages=1 packed=0
+page id=0 file="Roboto72White.png"
+chars count=98
+char id=0       x=0    y=0    width=0    height=0    xoffset=-1   yoffset=66   xadvance=0    page=0    chnl=0 
+char id=10      x=0    y=0    width=70   height=99   xoffset=2    yoffset=-11  xadvance=74   page=0    chnl=0 
+char id=32      x=0    y=0    width=0    height=0    xoffset=-1   yoffset=66   xadvance=18   page=0    chnl=0 
+char id=33      x=493  y=99   width=10   height=55   xoffset=5    yoffset=14   xadvance=19   page=0    chnl=0 
+char id=34      x=446  y=319  width=16   height=19   xoffset=4    yoffset=12   xadvance=23   page=0    chnl=0 
+char id=35      x=204  y=265  width=41   height=54   xoffset=3    yoffset=14   xadvance=44   page=0    chnl=0 
+char id=36      x=269  y=0    width=35   height=69   xoffset=3    yoffset=6    xadvance=40   page=0    chnl=0 
+char id=37      x=31   y=155  width=48   height=56   xoffset=3    yoffset=13   xadvance=53   page=0    chnl=0 
+char id=38      x=79   y=155  width=43   height=56   xoffset=3    yoffset=13   xadvance=45   page=0    chnl=0 
+char id=39      x=503  y=99   width=7    height=19   xoffset=3    yoffset=12   xadvance=13   page=0    chnl=0 
+char id=40      x=70   y=0    width=21   height=78   xoffset=4    yoffset=7    xadvance=25   page=0    chnl=0 
+char id=41      x=91   y=0    width=22   height=78   xoffset=-1   yoffset=7    xadvance=25   page=0    chnl=0 
+char id=42      x=342  y=319  width=32   height=32   xoffset=-1   yoffset=14   xadvance=31   page=0    chnl=0 
+char id=43      x=242  y=319  width=37   height=40   xoffset=2    yoffset=23   xadvance=41   page=0    chnl=0 
+char id=44      x=433  y=319  width=13   height=21   xoffset=-1   yoffset=58   xadvance=14   page=0    chnl=0 
+char id=45      x=27   y=360  width=19   height=8    xoffset=0    yoffset=41   xadvance=19   page=0    chnl=0 
+char id=46      x=17   y=360  width=10   height=11   xoffset=4    yoffset=58   xadvance=19   page=0    chnl=0 
+char id=47      x=355  y=0    width=30   height=58   xoffset=-1   yoffset=14   xadvance=30   page=0    chnl=0 
+char id=48      x=449  y=99   width=34   height=56   xoffset=3    yoffset=13   xadvance=40   page=0    chnl=0 
+char id=49      x=474  y=211  width=22   height=54   xoffset=5    yoffset=14   xadvance=40   page=0    chnl=0 
+char id=50      x=195  y=155  width=37   height=55   xoffset=2    yoffset=13   xadvance=41   page=0    chnl=0 
+char id=51      x=379  y=99   width=35   height=56   xoffset=2    yoffset=13   xadvance=40   page=0    chnl=0 
+char id=52      x=128  y=265  width=39   height=54   xoffset=1    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=53      x=232  y=155  width=35   height=55   xoffset=4    yoffset=14   xadvance=40   page=0    chnl=0 
+char id=54      x=267  y=155  width=35   height=55   xoffset=4    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=55      x=167  y=265  width=37   height=54   xoffset=2    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=56      x=414  y=99   width=35   height=56   xoffset=3    yoffset=13   xadvance=40   page=0    chnl=0 
+char id=57      x=302  y=155  width=34   height=55   xoffset=3    yoffset=13   xadvance=41   page=0    chnl=0 
+char id=58      x=495  y=265  width=10   height=41   xoffset=4    yoffset=28   xadvance=18   page=0    chnl=0 
+char id=59      x=496  y=211  width=13   height=52   xoffset=0    yoffset=28   xadvance=15   page=0    chnl=0 
+char id=60      x=279  y=319  width=31   height=35   xoffset=2    yoffset=27   xadvance=37   page=0    chnl=0 
+char id=61      x=402  y=319  width=31   height=23   xoffset=4    yoffset=31   xadvance=39   page=0    chnl=0 
+char id=62      x=310  y=319  width=32   height=35   xoffset=4    yoffset=27   xadvance=38   page=0    chnl=0 
+char id=63      x=0    y=155  width=31   height=56   xoffset=2    yoffset=13   xadvance=34   page=0    chnl=0 
+char id=64      x=210  y=0    width=59   height=69   xoffset=3    yoffset=15   xadvance=65   page=0    chnl=0 
+char id=65      x=336  y=155  width=49   height=54   xoffset=-1   yoffset=14   xadvance=47   page=0    chnl=0 
+char id=66      x=385  y=155  width=37   height=54   xoffset=5    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=67      x=0    y=99   width=42   height=56   xoffset=3    yoffset=13   xadvance=46   page=0    chnl=0 
+char id=68      x=422  y=155  width=39   height=54   xoffset=5    yoffset=14   xadvance=47   page=0    chnl=0 
+char id=69      x=461  y=155  width=35   height=54   xoffset=5    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=70      x=0    y=211  width=34   height=54   xoffset=5    yoffset=14   xadvance=40   page=0    chnl=0 
+char id=71      x=42   y=99   width=42   height=56   xoffset=3    yoffset=13   xadvance=49   page=0    chnl=0 
+char id=72      x=34   y=211  width=41   height=54   xoffset=5    yoffset=14   xadvance=51   page=0    chnl=0 
+char id=73      x=496  y=155  width=9    height=54   xoffset=5    yoffset=14   xadvance=19   page=0    chnl=0 
+char id=74      x=122  y=155  width=34   height=55   xoffset=1    yoffset=14   xadvance=40   page=0    chnl=0 
+char id=75      x=75   y=211  width=41   height=54   xoffset=5    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=76      x=116  y=211  width=33   height=54   xoffset=5    yoffset=14   xadvance=39   page=0    chnl=0 
+char id=77      x=149  y=211  width=53   height=54   xoffset=5    yoffset=14   xadvance=63   page=0    chnl=0 
+char id=78      x=202  y=211  width=41   height=54   xoffset=5    yoffset=14   xadvance=51   page=0    chnl=0 
+char id=79      x=84   y=99   width=43   height=56   xoffset=3    yoffset=13   xadvance=49   page=0    chnl=0 
+char id=80      x=243  y=211  width=39   height=54   xoffset=5    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=81      x=304  y=0    width=44   height=64   xoffset=3    yoffset=13   xadvance=49   page=0    chnl=0 
+char id=82      x=282  y=211  width=40   height=54   xoffset=5    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=83      x=127  y=99   width=39   height=56   xoffset=2    yoffset=13   xadvance=43   page=0    chnl=0 
+char id=84      x=322  y=211  width=42   height=54   xoffset=1    yoffset=14   xadvance=44   page=0    chnl=0 
+char id=85      x=156  y=155  width=39   height=55   xoffset=4    yoffset=14   xadvance=47   page=0    chnl=0 
+char id=86      x=364  y=211  width=47   height=54   xoffset=-1   yoffset=14   xadvance=46   page=0    chnl=0 
+char id=87      x=411  y=211  width=63   height=54   xoffset=1    yoffset=14   xadvance=64   page=0    chnl=0 
+char id=88      x=0    y=265  width=44   height=54   xoffset=1    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=89      x=44   y=265  width=45   height=54   xoffset=-1   yoffset=14   xadvance=43   page=0    chnl=0 
+char id=90      x=89   y=265  width=39   height=54   xoffset=2    yoffset=14   xadvance=43   page=0    chnl=0 
+char id=91      x=161  y=0    width=16   height=72   xoffset=4    yoffset=7    xadvance=19   page=0    chnl=0 
+char id=92      x=385  y=0    width=30   height=58   xoffset=0    yoffset=14   xadvance=30   page=0    chnl=0 
+char id=93      x=177  y=0    width=16   height=72   xoffset=0    yoffset=7    xadvance=20   page=0    chnl=0 
+char id=94      x=374  y=319  width=28   height=28   xoffset=1    yoffset=14   xadvance=30   page=0    chnl=0 
+char id=95      x=46   y=360  width=34   height=8    xoffset=0    yoffset=65   xadvance=34   page=0    chnl=0 
+char id=96      x=0    y=360  width=17   height=13   xoffset=1    yoffset=11   xadvance=22   page=0    chnl=0 
+char id=97      x=268  y=265  width=34   height=42   xoffset=3    yoffset=27   xadvance=39   page=0    chnl=0 
+char id=98      x=415  y=0    width=34   height=57   xoffset=4    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=99      x=302  y=265  width=34   height=42   xoffset=2    yoffset=27   xadvance=38   page=0    chnl=0 
+char id=100     x=449  y=0    width=34   height=57   xoffset=2    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=101     x=336  y=265  width=34   height=42   xoffset=2    yoffset=27   xadvance=38   page=0    chnl=0 
+char id=102     x=483  y=0    width=25   height=57   xoffset=1    yoffset=11   xadvance=26   page=0    chnl=0 
+char id=103     x=166  y=99   width=34   height=56   xoffset=2    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=104     x=200  y=99   width=32   height=56   xoffset=4    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=105     x=483  y=99   width=10   height=55   xoffset=4    yoffset=13   xadvance=18   page=0    chnl=0 
+char id=106     x=193  y=0    width=17   height=71   xoffset=-4   yoffset=13   xadvance=17   page=0    chnl=0 
+char id=107     x=232  y=99   width=34   height=56   xoffset=4    yoffset=12   xadvance=37   page=0    chnl=0 
+char id=108     x=266  y=99   width=9    height=56   xoffset=4    yoffset=12   xadvance=17   page=0    chnl=0 
+char id=109     x=439  y=265  width=56   height=41   xoffset=4    yoffset=27   xadvance=64   page=0    chnl=0 
+char id=110     x=0    y=319  width=32   height=41   xoffset=4    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=111     x=370  y=265  width=37   height=42   xoffset=2    yoffset=27   xadvance=41   page=0    chnl=0 
+char id=112     x=275  y=99   width=34   height=56   xoffset=4    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=113     x=309  y=99   width=34   height=56   xoffset=2    yoffset=27   xadvance=41   page=0    chnl=0 
+char id=114     x=32   y=319  width=21   height=41   xoffset=4    yoffset=27   xadvance=25   page=0    chnl=0 
+char id=115     x=407  y=265  width=32   height=42   xoffset=2    yoffset=27   xadvance=37   page=0    chnl=0 
+char id=116     x=245  y=265  width=23   height=51   xoffset=0    yoffset=18   xadvance=25   page=0    chnl=0 
+char id=117     x=53   y=319  width=32   height=41   xoffset=4    yoffset=28   xadvance=40   page=0    chnl=0 
+char id=118     x=85   y=319  width=35   height=40   xoffset=0    yoffset=28   xadvance=35   page=0    chnl=0 
+char id=119     x=120  y=319  width=54   height=40   xoffset=0    yoffset=28   xadvance=54   page=0    chnl=0 
+char id=120     x=174  y=319  width=36   height=40   xoffset=0    yoffset=28   xadvance=36   page=0    chnl=0 
+char id=121     x=343  y=99   width=36   height=56   xoffset=-1   yoffset=28   xadvance=34   page=0    chnl=0 
+char id=122     x=210  y=319  width=32   height=40   xoffset=2    yoffset=28   xadvance=35   page=0    chnl=0 
+char id=123     x=113  y=0    width=24   height=73   xoffset=1    yoffset=9    xadvance=25   page=0    chnl=0 
+char id=124     x=348  y=0    width=7    height=63   xoffset=5    yoffset=14   xadvance=17   page=0    chnl=0 
+char id=125     x=137  y=0    width=24   height=73   xoffset=-1   yoffset=9    xadvance=24   page=0    chnl=0 
+char id=126     x=462  y=319  width=42   height=16   xoffset=4    yoffset=38   xadvance=50   page=0    chnl=0 
+char id=127     x=0    y=0    width=70   height=99   xoffset=2    yoffset=-11  xadvance=74   page=0    chnl=0 
+kernings count=382
+kerning first=70 second=74 amount=-9
+kerning first=34 second=97 amount=-2
+kerning first=34 second=101 amount=-2
+kerning first=34 second=113 amount=-2
+kerning first=34 second=99 amount=-2
+kerning first=70 second=99 amount=-1
+kerning first=88 second=113 amount=-1
+kerning first=84 second=46 amount=-8
+kerning first=84 second=119 amount=-2
+kerning first=87 second=97 amount=-1
+kerning first=90 second=117 amount=-1
+kerning first=39 second=97 amount=-2
+kerning first=69 second=111 amount=-1
+kerning first=87 second=41 amount=1
+kerning first=76 second=86 amount=-6
+kerning first=121 second=34 amount=1
+kerning first=40 second=86 amount=1
+kerning first=85 second=65 amount=-1
+kerning first=89 second=89 amount=1
+kerning first=72 second=65 amount=1
+kerning first=104 second=39 amount=-4
+kerning first=114 second=102 amount=1
+kerning first=89 second=42 amount=-2
+kerning first=114 second=34 amount=1
+kerning first=84 second=115 amount=-4
+kerning first=84 second=71 amount=-1
+kerning first=89 second=101 amount=-2
+kerning first=89 second=45 amount=-2
+kerning first=122 second=99 amount=-1
+kerning first=78 second=88 amount=1
+kerning first=68 second=89 amount=-2
+kerning first=122 second=103 amount=-1
+kerning first=78 second=84 amount=-1
+kerning first=86 second=103 amount=-2
+kerning first=89 second=67 amount=-1
+kerning first=89 second=79 amount=-1
+kerning first=75 second=111 amount=-1
+kerning first=111 second=120 amount=-1
+kerning first=87 second=44 amount=-4
+kerning first=91 second=74 amount=-1
+kerning first=120 second=111 amount=-1
+kerning first=84 second=111 amount=-3
+kerning first=102 second=113 amount=-1
+kerning first=80 second=88 amount=-1
+kerning first=66 second=84 amount=-1
+kerning first=65 second=87 amount=-2
+kerning first=86 second=100 amount=-2
+kerning first=122 second=100 amount=-1
+kerning first=75 second=118 amount=-1
+kerning first=70 second=118 amount=-1
+kerning first=73 second=88 amount=1
+kerning first=70 second=121 amount=-1
+kerning first=65 second=34 amount=-4
+kerning first=39 second=101 amount=-2
+kerning first=75 second=101 amount=-1
+kerning first=84 second=99 amount=-3
+kerning first=84 second=65 amount=-3
+kerning first=112 second=39 amount=-1
+kerning first=76 second=39 amount=-12
+kerning first=78 second=65 amount=1
+kerning first=88 second=45 amount=-2
+kerning first=65 second=121 amount=-2
+kerning first=34 second=111 amount=-2
+kerning first=89 second=85 amount=-3
+kerning first=114 second=99 amount=-1
+kerning first=86 second=125 amount=1
+kerning first=70 second=111 amount=-1
+kerning first=89 second=120 amount=-1
+kerning first=90 second=119 amount=-1
+kerning first=120 second=99 amount=-1
+kerning first=89 second=117 amount=-1
+kerning first=82 second=89 amount=-2
+kerning first=75 second=117 amount=-1
+kerning first=34 second=34 amount=-4
+kerning first=89 second=110 amount=-1
+kerning first=88 second=101 amount=-1
+kerning first=107 second=103 amount=-1
+kerning first=34 second=115 amount=-3
+kerning first=98 second=39 amount=-1
+kerning first=70 second=65 amount=-6
+kerning first=70 second=46 amount=-8
+kerning first=98 second=34 amount=-1
+kerning first=70 second=84 amount=1
+kerning first=114 second=100 amount=-1
+kerning first=88 second=79 amount=-1
+kerning first=39 second=113 amount=-2
+kerning first=114 second=103 amount=-1
+kerning first=77 second=65 amount=1
+kerning first=120 second=103 amount=-1
+kerning first=114 second=121 amount=1
+kerning first=89 second=100 amount=-2
+kerning first=80 second=65 amount=-5
+kerning first=121 second=111 amount=-1
+kerning first=84 second=74 amount=-8
+kerning first=122 second=111 amount=-1
+kerning first=114 second=118 amount=1
+kerning first=102 second=41 amount=1
+kerning first=122 second=113 amount=-1
+kerning first=89 second=122 amount=-1
+kerning first=89 second=38 amount=-1
+kerning first=81 second=89 amount=-1
+kerning first=114 second=111 amount=-1
+kerning first=46 second=34 amount=-6
+kerning first=84 second=112 amount=-4
+kerning first=112 second=34 amount=-1
+kerning first=76 second=34 amount=-12
+kerning first=102 second=125 amount=1
+kerning first=39 second=115 amount=-3
+kerning first=76 second=118 amount=-5
+kerning first=86 second=99 amount=-2
+kerning first=84 second=84 amount=1
+kerning first=86 second=65 amount=-3
+kerning first=87 second=101 amount=-1
+kerning first=67 second=125 amount=-1
+kerning first=120 second=113 amount=-1
+kerning first=118 second=46 amount=-4
+kerning first=88 second=103 amount=-1
+kerning first=111 second=122 amount=-1
+kerning first=77 second=84 amount=-1
+kerning first=114 second=46 amount=-4
+kerning first=34 second=39 amount=-4
+kerning first=114 second=44 amount=-4
+kerning first=69 second=84 amount=1
+kerning first=89 second=46 amount=-7
+kerning first=97 second=39 amount=-2
+kerning first=34 second=100 amount=-2
+kerning first=70 second=100 amount=-1
+kerning first=84 second=120 amount=-3
+kerning first=90 second=118 amount=-1
+kerning first=70 second=114 amount=-1
+kerning first=34 second=112 amount=-1
+kerning first=109 second=34 amount=-4
+kerning first=86 second=113 amount=-2
+kerning first=88 second=71 amount=-1
+kerning first=66 second=89 amount=-2
+kerning first=102 second=103 amount=-1
+kerning first=88 second=67 amount=-1
+kerning first=39 second=110 amount=-1
+kerning first=75 second=110 amount=-1
+kerning first=88 second=117 amount=-1
+kerning first=89 second=118 amount=-1
+kerning first=97 second=118 amount=-1
+kerning first=87 second=65 amount=-2
+kerning first=73 second=89 amount=-1
+kerning first=89 second=74 amount=-3
+kerning first=102 second=101 amount=-1
+kerning first=86 second=111 amount=-2
+kerning first=65 second=119 amount=-1
+kerning first=84 second=100 amount=-3
+kerning first=104 second=34 amount=-4
+kerning first=86 second=41 amount=1
+kerning first=111 second=34 amount=-5
+kerning first=40 second=89 amount=1
+kerning first=121 second=39 amount=1
+kerning first=68 second=90 amount=-1
+kerning first=114 second=113 amount=-1
+kerning first=68 second=88 amount=-1
+kerning first=98 second=120 amount=-1
+kerning first=110 second=34 amount=-4
+kerning first=119 second=44 amount=-4
+kerning first=119 second=46 amount=-4
+kerning first=118 second=44 amount=-4
+kerning first=84 second=114 amount=-3
+kerning first=86 second=97 amount=-2
+kerning first=68 second=86 amount=-1
+kerning first=86 second=93 amount=1
+kerning first=97 second=34 amount=-2
+kerning first=34 second=65 amount=-4
+kerning first=84 second=118 amount=-3
+kerning first=76 second=84 amount=-10
+kerning first=107 second=99 amount=-1
+kerning first=121 second=46 amount=-4
+kerning first=123 second=85 amount=-1
+kerning first=65 second=63 amount=-2
+kerning first=89 second=44 amount=-7
+kerning first=80 second=118 amount=1
+kerning first=112 second=122 amount=-1
+kerning first=79 second=65 amount=-1
+kerning first=80 second=121 amount=1
+kerning first=118 second=34 amount=1
+kerning first=87 second=45 amount=-2
+kerning first=69 second=100 amount=-1
+kerning first=87 second=103 amount=-1
+kerning first=112 second=120 amount=-1
+kerning first=68 second=44 amount=-4
+kerning first=86 second=45 amount=-1
+kerning first=39 second=34 amount=-4
+kerning first=68 second=46 amount=-4
+kerning first=65 second=89 amount=-3
+kerning first=69 second=118 amount=-1
+kerning first=88 second=99 amount=-1
+kerning first=87 second=46 amount=-4
+kerning first=47 second=47 amount=-8
+kerning first=73 second=65 amount=1
+kerning first=123 second=74 amount=-1
+kerning first=69 second=102 amount=-1
+kerning first=87 second=111 amount=-1
+kerning first=39 second=112 amount=-1
+kerning first=89 second=116 amount=-1
+kerning first=70 second=113 amount=-1
+kerning first=77 second=88 amount=1
+kerning first=84 second=32 amount=-1
+kerning first=90 second=103 amount=-1
+kerning first=65 second=86 amount=-3
+kerning first=75 second=112 amount=-1
+kerning first=39 second=109 amount=-1
+kerning first=75 second=81 amount=-1
+kerning first=89 second=115 amount=-2
+kerning first=84 second=83 amount=-1
+kerning first=89 second=87 amount=1
+kerning first=114 second=101 amount=-1
+kerning first=116 second=111 amount=-1
+kerning first=90 second=100 amount=-1
+kerning first=84 second=122 amount=-2
+kerning first=68 second=84 amount=-1
+kerning first=32 second=84 amount=-1
+kerning first=84 second=117 amount=-3
+kerning first=74 second=65 amount=-1
+kerning first=107 second=101 amount=-1
+kerning first=75 second=109 amount=-1
+kerning first=80 second=46 amount=-11
+kerning first=89 second=93 amount=1
+kerning first=89 second=65 amount=-3
+kerning first=87 second=117 amount=-1
+kerning first=89 second=81 amount=-1
+kerning first=39 second=103 amount=-2
+kerning first=86 second=101 amount=-2
+kerning first=86 second=117 amount=-1
+kerning first=84 second=113 amount=-3
+kerning first=34 second=110 amount=-1
+kerning first=89 second=84 amount=1
+kerning first=84 second=110 amount=-4
+kerning first=39 second=99 amount=-2
+kerning first=88 second=121 amount=-1
+kerning first=65 second=39 amount=-4
+kerning first=110 second=39 amount=-4
+kerning first=75 second=67 amount=-1
+kerning first=88 second=118 amount=-1
+kerning first=86 second=114 amount=-1
+kerning first=80 second=74 amount=-7
+kerning first=84 second=97 amount=-4
+kerning first=82 second=84 amount=-3
+kerning first=91 second=85 amount=-1
+kerning first=102 second=99 amount=-1
+kerning first=66 second=86 amount=-1
+kerning first=120 second=101 amount=-1
+kerning first=102 second=93 amount=1
+kerning first=75 second=100 amount=-1
+kerning first=84 second=79 amount=-1
+kerning first=111 second=121 amount=-1
+kerning first=75 second=121 amount=-1
+kerning first=81 second=87 amount=-1
+kerning first=107 second=113 amount=-1
+kerning first=120 second=100 amount=-1
+kerning first=90 second=79 amount=-1
+kerning first=89 second=114 amount=-1
+kerning first=122 second=101 amount=-1
+kerning first=111 second=118 amount=-1
+kerning first=82 second=86 amount=-1
+kerning first=67 second=84 amount=-1
+kerning first=70 second=101 amount=-1
+kerning first=89 second=83 amount=-1
+kerning first=114 second=97 amount=-1
+kerning first=70 second=97 amount=-1
+kerning first=89 second=102 amount=-1
+kerning first=78 second=89 amount=-1
+kerning first=70 second=44 amount=-8
+kerning first=44 second=39 amount=-6
+kerning first=84 second=45 amount=-8
+kerning first=89 second=121 amount=-1
+kerning first=84 second=86 amount=1
+kerning first=87 second=99 amount=-1
+kerning first=98 second=122 amount=-1
+kerning first=89 second=112 amount=-1
+kerning first=89 second=103 amount=-2
+kerning first=88 second=81 amount=-1
+kerning first=102 second=34 amount=1
+kerning first=109 second=39 amount=-4
+kerning first=81 second=84 amount=-2
+kerning first=121 second=97 amount=-1
+kerning first=89 second=99 amount=-2
+kerning first=89 second=125 amount=1
+kerning first=81 second=86 amount=-1
+kerning first=114 second=116 amount=2
+kerning first=114 second=119 amount=1
+kerning first=84 second=44 amount=-8
+kerning first=102 second=39 amount=1
+kerning first=44 second=34 amount=-6
+kerning first=34 second=109 amount=-1
+kerning first=75 second=119 amount=-2
+kerning first=76 second=65 amount=1
+kerning first=84 second=81 amount=-1
+kerning first=76 second=121 amount=-5
+kerning first=69 second=101 amount=-1
+kerning first=89 second=111 amount=-2
+kerning first=80 second=90 amount=-1
+kerning first=89 second=97 amount=-3
+kerning first=89 second=109 amount=-1
+kerning first=90 second=99 amount=-1
+kerning first=89 second=86 amount=1
+kerning first=79 second=88 amount=-1
+kerning first=70 second=103 amount=-1
+kerning first=34 second=103 amount=-2
+kerning first=84 second=67 amount=-1
+kerning first=76 second=79 amount=-2
+kerning first=89 second=41 amount=1
+kerning first=65 second=118 amount=-2
+kerning first=75 second=71 amount=-1
+kerning first=76 second=87 amount=-5
+kerning first=77 second=89 amount=-1
+kerning first=90 second=113 amount=-1
+kerning first=79 second=89 amount=-2
+kerning first=118 second=111 amount=-1
+kerning first=118 second=97 amount=-1
+kerning first=88 second=100 amount=-1
+kerning first=90 second=121 amount=-1
+kerning first=89 second=113 amount=-2
+kerning first=84 second=87 amount=1
+kerning first=39 second=111 amount=-2
+kerning first=80 second=44 amount=-11
+kerning first=39 second=100 amount=-2
+kerning first=75 second=113 amount=-1
+kerning first=88 second=111 amount=-1
+kerning first=84 second=89 amount=1
+kerning first=84 second=103 amount=-3
+kerning first=70 second=117 amount=-1
+kerning first=67 second=41 amount=-1
+kerning first=89 second=71 amount=-1
+kerning first=121 second=44 amount=-4
+kerning first=97 second=121 amount=-1
+kerning first=87 second=113 amount=-1
+kerning first=73 second=84 amount=-1
+kerning first=84 second=101 amount=-3
+kerning first=75 second=99 amount=-1
+kerning first=65 second=85 amount=-1
+kerning first=76 second=67 amount=-2
+kerning first=76 second=81 amount=-2
+kerning first=75 second=79 amount=-1
+kerning first=39 second=65 amount=-4
+kerning first=76 second=117 amount=-2
+kerning first=65 second=84 amount=-5
+kerning first=90 second=101 amount=-1
+kerning first=84 second=121 amount=-3
+kerning first=69 second=99 amount=-1
+kerning first=114 second=39 amount=1
+kerning first=84 second=109 amount=-4
+kerning first=76 second=119 amount=-3
+kerning first=76 second=85 amount=-2
+kerning first=65 second=116 amount=-1
+kerning first=76 second=71 amount=-2
+kerning first=79 second=90 amount=-1
+kerning first=107 second=100 amount=-1
+kerning first=90 second=111 amount=-1
+kerning first=79 second=44 amount=-4
+kerning first=75 second=45 amount=-2
+kerning first=40 second=87 amount=1
+kerning first=79 second=86 amount=-1
+kerning first=102 second=100 amount=-1
+kerning first=72 second=89 amount=-1
+kerning first=72 second=88 amount=1
+kerning first=79 second=46 amount=-4
+kerning first=76 second=89 amount=-8
+kerning first=68 second=65 amount=-1
+kerning first=79 second=84 amount=-1
+kerning first=87 second=100 amount=-1
+kerning first=75 second=103 amount=-1
+kerning first=90 second=67 amount=-1
+kerning first=69 second=103 amount=-1
+kerning first=90 second=71 amount=-1
+kerning first=86 second=44 amount=-8
+kerning first=69 second=121 amount=-1
+kerning first=87 second=114 amount=-1
+kerning first=118 second=39 amount=1
+kerning first=46 second=39 amount=-6
+kerning first=72 second=84 amount=-1
+kerning first=86 second=46 amount=-8
+kerning first=69 second=113 amount=-1
+kerning first=69 second=119 amount=-1
+kerning first=39 second=39 amount=-4
+kerning first=69 second=117 amount=-1
+kerning first=111 second=39 amount=-5
+kerning first=90 second=81 amount=-1

BIN
src/web/static/fonts/bmfonts/Roboto72White.png


+ 488 - 0
src/web/static/fonts/bmfonts/RobotoBlack72White.fnt

@@ -0,0 +1,488 @@
+info face="Roboto Black" size=72 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=-2,-2
+common lineHeight=85 base=67 scaleW=512 scaleH=512 pages=1 packed=0
+page id=0 file="RobotoBlack72White.png"
+chars count=98
+char id=0       x=0    y=0    width=0    height=0    xoffset=-1   yoffset=66   xadvance=0    page=0    chnl=0 
+char id=10      x=0    y=0    width=70   height=99   xoffset=2    yoffset=-11  xadvance=74   page=0    chnl=0 
+char id=32      x=0    y=0    width=0    height=0    xoffset=-1   yoffset=66   xadvance=18   page=0    chnl=0 
+char id=33      x=460  y=156  width=15   height=55   xoffset=3    yoffset=14   xadvance=20   page=0    chnl=0 
+char id=34      x=207  y=362  width=22   height=22   xoffset=0    yoffset=12   xadvance=23   page=0    chnl=0 
+char id=35      x=404  y=266  width=41   height=54   xoffset=0    yoffset=14   xadvance=42   page=0    chnl=0 
+char id=36      x=220  y=0    width=38   height=69   xoffset=2    yoffset=7    xadvance=42   page=0    chnl=0 
+char id=37      x=167  y=156  width=49   height=56   xoffset=2    yoffset=13   xadvance=53   page=0    chnl=0 
+char id=38      x=216  y=156  width=48   height=56   xoffset=1    yoffset=13   xadvance=48   page=0    chnl=0 
+char id=39      x=499  y=320  width=10   height=22   xoffset=1    yoffset=12   xadvance=11   page=0    chnl=0 
+char id=40      x=70   y=0    width=22   height=75   xoffset=3    yoffset=9    xadvance=25   page=0    chnl=0 
+char id=41      x=92   y=0    width=23   height=75   xoffset=0    yoffset=9    xadvance=25   page=0    chnl=0 
+char id=42      x=103  y=362  width=36   height=34   xoffset=-1   yoffset=14   xadvance=33   page=0    chnl=0 
+char id=43      x=0    y=362  width=37   height=40   xoffset=1    yoffset=23   xadvance=39   page=0    chnl=0 
+char id=44      x=483  y=320  width=16   height=25   xoffset=0    yoffset=57   xadvance=20   page=0    chnl=0 
+char id=45      x=308  y=362  width=23   height=12   xoffset=4    yoffset=38   xadvance=32   page=0    chnl=0 
+char id=46      x=270  y=362  width=15   height=15   xoffset=3    yoffset=54   xadvance=22   page=0    chnl=0 
+char id=47      x=374  y=0    width=29   height=58   xoffset=-3   yoffset=14   xadvance=25   page=0    chnl=0 
+char id=48      x=77   y=156  width=38   height=56   xoffset=2    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=49      x=299  y=266  width=26   height=54   xoffset=4    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=50      x=383  y=156  width=39   height=55   xoffset=1    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=51      x=434  y=99   width=39   height=56   xoffset=1    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=52      x=325  y=266  width=40   height=54   xoffset=1    yoffset=14   xadvance=42   page=0    chnl=0 
+char id=53      x=422  y=156  width=38   height=55   xoffset=2    yoffset=14   xadvance=42   page=0    chnl=0 
+char id=54      x=0    y=156  width=39   height=56   xoffset=2    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=55      x=365  y=266  width=39   height=54   xoffset=1    yoffset=14   xadvance=42   page=0    chnl=0 
+char id=56      x=473  y=99   width=38   height=56   xoffset=2    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=57      x=39   y=156  width=38   height=56   xoffset=2    yoffset=13   xadvance=42   page=0    chnl=0 
+char id=58      x=471  y=266  width=15   height=43   xoffset=3    yoffset=26   xadvance=21   page=0    chnl=0 
+char id=59      x=150  y=156  width=17   height=56   xoffset=1    yoffset=26   xadvance=21   page=0    chnl=0 
+char id=60      x=37   y=362  width=33   height=38   xoffset=1    yoffset=26   xadvance=37   page=0    chnl=0 
+char id=61      x=172  y=362  width=35   height=27   xoffset=3    yoffset=31   xadvance=42   page=0    chnl=0 
+char id=62      x=70   y=362  width=33   height=38   xoffset=3    yoffset=26   xadvance=37   page=0    chnl=0 
+char id=63      x=115  y=156  width=35   height=56   xoffset=0    yoffset=13   xadvance=36   page=0    chnl=0 
+char id=64      x=258  y=0    width=61   height=68   xoffset=1    yoffset=16   xadvance=64   page=0    chnl=0 
+char id=65      x=0    y=212  width=53   height=54   xoffset=-2   yoffset=14   xadvance=49   page=0    chnl=0 
+char id=66      x=53   y=212  width=42   height=54   xoffset=3    yoffset=14   xadvance=47   page=0    chnl=0 
+char id=67      x=37   y=99   width=46   height=56   xoffset=1    yoffset=13   xadvance=47   page=0    chnl=0 
+char id=68      x=95   y=212  width=42   height=54   xoffset=3    yoffset=14   xadvance=47   page=0    chnl=0 
+char id=69      x=137  y=212  width=38   height=54   xoffset=3    yoffset=14   xadvance=41   page=0    chnl=0 
+char id=70      x=475  y=156  width=36   height=54   xoffset=3    yoffset=14   xadvance=39   page=0    chnl=0 
+char id=71      x=83   y=99   width=45   height=56   xoffset=2    yoffset=13   xadvance=49   page=0    chnl=0 
+char id=72      x=175  y=212  width=45   height=54   xoffset=3    yoffset=14   xadvance=51   page=0    chnl=0 
+char id=73      x=220  y=212  width=14   height=54   xoffset=4    yoffset=14   xadvance=22   page=0    chnl=0 
+char id=74      x=264  y=156  width=37   height=55   xoffset=0    yoffset=14   xadvance=40   page=0    chnl=0 
+char id=75      x=234  y=212  width=45   height=54   xoffset=3    yoffset=14   xadvance=46   page=0    chnl=0 
+char id=76      x=279  y=212  width=36   height=54   xoffset=3    yoffset=14   xadvance=39   page=0    chnl=0 
+char id=77      x=315  y=212  width=58   height=54   xoffset=3    yoffset=14   xadvance=63   page=0    chnl=0 
+char id=78      x=373  y=212  width=45   height=54   xoffset=3    yoffset=14   xadvance=51   page=0    chnl=0 
+char id=79      x=128  y=99   width=47   height=56   xoffset=1    yoffset=13   xadvance=50   page=0    chnl=0 
+char id=80      x=418  y=212  width=43   height=54   xoffset=3    yoffset=14   xadvance=48   page=0    chnl=0 
+char id=81      x=319  y=0    width=47   height=65   xoffset=2    yoffset=13   xadvance=50   page=0    chnl=0 
+char id=82      x=461  y=212  width=43   height=54   xoffset=3    yoffset=14   xadvance=46   page=0    chnl=0 
+char id=83      x=175  y=99   width=42   height=56   xoffset=1    yoffset=13   xadvance=44   page=0    chnl=0 
+char id=84      x=0    y=266  width=45   height=54   xoffset=0    yoffset=14   xadvance=45   page=0    chnl=0 
+char id=85      x=301  y=156  width=42   height=55   xoffset=3    yoffset=14   xadvance=48   page=0    chnl=0 
+char id=86      x=45   y=266  width=51   height=54   xoffset=-2   yoffset=14   xadvance=48   page=0    chnl=0 
+char id=87      x=96   y=266  width=64   height=54   xoffset=-1   yoffset=14   xadvance=63   page=0    chnl=0 
+char id=88      x=160  y=266  width=48   height=54   xoffset=-1   yoffset=14   xadvance=46   page=0    chnl=0 
+char id=89      x=208  y=266  width=49   height=54   xoffset=-2   yoffset=14   xadvance=45   page=0    chnl=0 
+char id=90      x=257  y=266  width=42   height=54   xoffset=1    yoffset=14   xadvance=44   page=0    chnl=0 
+char id=91      x=115  y=0    width=18   height=75   xoffset=3    yoffset=5    xadvance=21   page=0    chnl=0 
+char id=92      x=403  y=0    width=37   height=58   xoffset=-2   yoffset=14   xadvance=31   page=0    chnl=0 
+char id=93      x=133  y=0    width=18   height=75   xoffset=0    yoffset=5    xadvance=21   page=0    chnl=0 
+char id=94      x=139  y=362  width=33   height=28   xoffset=0    yoffset=14   xadvance=32   page=0    chnl=0 
+char id=95      x=331  y=362  width=34   height=12   xoffset=-1   yoffset=65   xadvance=33   page=0    chnl=0 
+char id=96      x=285  y=362  width=23   height=13   xoffset=0    yoffset=12   xadvance=24   page=0    chnl=0 
+char id=97      x=0    y=320  width=37   height=42   xoffset=1    yoffset=27   xadvance=38   page=0    chnl=0 
+char id=98      x=440  y=0    width=37   height=57   xoffset=2    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=99      x=37   y=320  width=36   height=42   xoffset=1    yoffset=27   xadvance=38   page=0    chnl=0 
+char id=100     x=0    y=99   width=37   height=57   xoffset=1    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=101     x=73   y=320  width=38   height=42   xoffset=1    yoffset=27   xadvance=39   page=0    chnl=0 
+char id=102     x=477  y=0    width=28   height=57   xoffset=0    yoffset=11   xadvance=27   page=0    chnl=0 
+char id=103     x=217  y=99   width=38   height=56   xoffset=1    yoffset=27   xadvance=41   page=0    chnl=0 
+char id=104     x=255  y=99   width=36   height=56   xoffset=2    yoffset=12   xadvance=40   page=0    chnl=0 
+char id=105     x=291  y=99   width=15   height=56   xoffset=2    yoffset=12   xadvance=19   page=0    chnl=0 
+char id=106     x=197  y=0    width=23   height=71   xoffset=-5   yoffset=12   xadvance=20   page=0    chnl=0 
+char id=107     x=306  y=99   width=40   height=56   xoffset=2    yoffset=12   xadvance=39   page=0    chnl=0 
+char id=108     x=346  y=99   width=14   height=56   xoffset=3    yoffset=12   xadvance=20   page=0    chnl=0 
+char id=109     x=186  y=320  width=58   height=41   xoffset=2    yoffset=27   xadvance=63   page=0    chnl=0 
+char id=110     x=244  y=320  width=36   height=41   xoffset=2    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=111     x=111  y=320  width=39   height=42   xoffset=1    yoffset=27   xadvance=41   page=0    chnl=0 
+char id=112     x=360  y=99   width=37   height=56   xoffset=2    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=113     x=397  y=99   width=37   height=56   xoffset=1    yoffset=27   xadvance=40   page=0    chnl=0 
+char id=114     x=486  y=266  width=25   height=41   xoffset=2    yoffset=27   xadvance=27   page=0    chnl=0 
+char id=115     x=150  y=320  width=36   height=42   xoffset=0    yoffset=27   xadvance=37   page=0    chnl=0 
+char id=116     x=445  y=266  width=26   height=51   xoffset=0    yoffset=18   xadvance=25   page=0    chnl=0 
+char id=117     x=280  y=320  width=36   height=41   xoffset=2    yoffset=28   xadvance=40   page=0    chnl=0 
+char id=118     x=316  y=320  width=39   height=40   xoffset=-1   yoffset=28   xadvance=37   page=0    chnl=0 
+char id=119     x=355  y=320  width=54   height=40   xoffset=-1   yoffset=28   xadvance=52   page=0    chnl=0 
+char id=120     x=409  y=320  width=40   height=40   xoffset=-1   yoffset=28   xadvance=37   page=0    chnl=0 
+char id=121     x=343  y=156  width=40   height=55   xoffset=-1   yoffset=28   xadvance=37   page=0    chnl=0 
+char id=122     x=449  y=320  width=34   height=40   xoffset=1    yoffset=28   xadvance=36   page=0    chnl=0 
+char id=123     x=151  y=0    width=23   height=72   xoffset=0    yoffset=9    xadvance=23   page=0    chnl=0 
+char id=124     x=366  y=0    width=8    height=63   xoffset=5    yoffset=14   xadvance=18   page=0    chnl=0 
+char id=125     x=174  y=0    width=23   height=72   xoffset=0    yoffset=9    xadvance=23   page=0    chnl=0 
+char id=126     x=229  y=362  width=41   height=19   xoffset=2    yoffset=36   xadvance=45   page=0    chnl=0 
+char id=127     x=0    y=0    width=70   height=99   xoffset=2    yoffset=-11  xadvance=74   page=0    chnl=0 
+kernings count=385
+kerning first=84 second=74 amount=-8
+kerning first=86 second=100 amount=-2
+kerning first=114 second=113 amount=-1
+kerning first=70 second=121 amount=-1
+kerning first=34 second=99 amount=-2
+kerning first=70 second=99 amount=-1
+kerning first=69 second=99 amount=-1
+kerning first=88 second=113 amount=-1
+kerning first=84 second=46 amount=-9
+kerning first=87 second=97 amount=-1
+kerning first=90 second=117 amount=-1
+kerning first=39 second=97 amount=-2
+kerning first=69 second=111 amount=-1
+kerning first=87 second=41 amount=1
+kerning first=121 second=34 amount=1
+kerning first=40 second=86 amount=1
+kerning first=85 second=65 amount=-1
+kerning first=72 second=65 amount=1
+kerning first=114 second=102 amount=1
+kerning first=89 second=42 amount=-2
+kerning first=114 second=34 amount=1
+kerning first=75 second=67 amount=-1
+kerning first=89 second=85 amount=-3
+kerning first=77 second=88 amount=1
+kerning first=84 second=115 amount=-3
+kerning first=84 second=71 amount=-1
+kerning first=89 second=101 amount=-2
+kerning first=89 second=45 amount=-5
+kerning first=78 second=88 amount=1
+kerning first=68 second=89 amount=-2
+kerning first=122 second=103 amount=-1
+kerning first=78 second=84 amount=-1
+kerning first=86 second=103 amount=-2
+kerning first=89 second=79 amount=-1
+kerning first=75 second=111 amount=-1
+kerning first=111 second=120 amount=-1
+kerning first=87 second=44 amount=-5
+kerning first=67 second=84 amount=-1
+kerning first=84 second=111 amount=-7
+kerning first=84 second=83 amount=-1
+kerning first=102 second=113 amount=-1
+kerning first=39 second=101 amount=-2
+kerning first=80 second=88 amount=-2
+kerning first=66 second=84 amount=-1
+kerning first=65 second=87 amount=-1
+kerning first=122 second=100 amount=-1
+kerning first=75 second=118 amount=-1
+kerning first=73 second=65 amount=1
+kerning first=70 second=118 amount=-1
+kerning first=73 second=88 amount=1
+kerning first=82 second=89 amount=-2
+kerning first=65 second=34 amount=-4
+kerning first=120 second=99 amount=-1
+kerning first=84 second=99 amount=-3
+kerning first=84 second=65 amount=-4
+kerning first=112 second=39 amount=-1
+kerning first=76 second=39 amount=-10
+kerning first=78 second=65 amount=1
+kerning first=88 second=45 amount=-5
+kerning first=34 second=111 amount=-3
+kerning first=114 second=99 amount=-1
+kerning first=86 second=125 amount=1
+kerning first=70 second=111 amount=-1
+kerning first=89 second=120 amount=-1
+kerning first=90 second=119 amount=-1
+kerning first=89 second=89 amount=1
+kerning first=89 second=117 amount=-1
+kerning first=75 second=117 amount=-1
+kerning first=76 second=65 amount=1
+kerning first=34 second=34 amount=-1
+kerning first=89 second=110 amount=-1
+kerning first=88 second=101 amount=-1
+kerning first=107 second=103 amount=-1
+kerning first=34 second=115 amount=-3
+kerning first=80 second=44 amount=-14
+kerning first=98 second=39 amount=-1
+kerning first=70 second=65 amount=-7
+kerning first=89 second=116 amount=-1
+kerning first=70 second=46 amount=-10
+kerning first=98 second=34 amount=-1
+kerning first=70 second=84 amount=1
+kerning first=114 second=100 amount=-1
+kerning first=88 second=79 amount=-1
+kerning first=39 second=113 amount=-2
+kerning first=65 second=118 amount=-2
+kerning first=114 second=103 amount=-1
+kerning first=77 second=65 amount=1
+kerning first=120 second=103 amount=-1
+kerning first=65 second=110 amount=-2
+kerning first=114 second=121 amount=1
+kerning first=89 second=100 amount=-2
+kerning first=80 second=65 amount=-6
+kerning first=121 second=111 amount=-1
+kerning first=34 second=101 amount=-2
+kerning first=122 second=111 amount=-1
+kerning first=114 second=118 amount=1
+kerning first=102 second=41 amount=1
+kerning first=122 second=113 amount=-1
+kerning first=89 second=122 amount=-1
+kerning first=68 second=88 amount=-1
+kerning first=81 second=89 amount=-1
+kerning first=114 second=111 amount=-1
+kerning first=46 second=34 amount=-10
+kerning first=84 second=112 amount=-3
+kerning first=76 second=34 amount=-10
+kerning first=39 second=115 amount=-3
+kerning first=76 second=118 amount=-4
+kerning first=86 second=99 amount=-2
+kerning first=84 second=84 amount=1
+kerning first=120 second=111 amount=-1
+kerning first=65 second=79 amount=-1
+kerning first=87 second=101 amount=-1
+kerning first=67 second=125 amount=-1
+kerning first=120 second=113 amount=-1
+kerning first=118 second=46 amount=-6
+kerning first=88 second=103 amount=-1
+kerning first=111 second=122 amount=-1
+kerning first=77 second=84 amount=-1
+kerning first=114 second=46 amount=-6
+kerning first=34 second=39 amount=-1
+kerning first=65 second=121 amount=-2
+kerning first=114 second=44 amount=-6
+kerning first=69 second=84 amount=1
+kerning first=89 second=46 amount=-8
+kerning first=97 second=39 amount=-1
+kerning first=34 second=100 amount=-2
+kerning first=70 second=100 amount=-1
+kerning first=84 second=120 amount=-3
+kerning first=90 second=118 amount=-1
+kerning first=70 second=114 amount=-1
+kerning first=34 second=112 amount=-1
+kerning first=89 second=86 amount=1
+kerning first=86 second=113 amount=-2
+kerning first=88 second=71 amount=-1
+kerning first=122 second=99 amount=-1
+kerning first=66 second=89 amount=-2
+kerning first=102 second=103 amount=-1
+kerning first=88 second=67 amount=-1
+kerning first=39 second=110 amount=-1
+kerning first=88 second=117 amount=-1
+kerning first=89 second=118 amount=-1
+kerning first=97 second=118 amount=-1
+kerning first=87 second=65 amount=-2
+kerning first=89 second=67 amount=-1
+kerning first=89 second=74 amount=-3
+kerning first=102 second=101 amount=-1
+kerning first=86 second=111 amount=-2
+kerning first=65 second=119 amount=-1
+kerning first=84 second=100 amount=-3
+kerning first=120 second=100 amount=-1
+kerning first=104 second=34 amount=-3
+kerning first=86 second=41 amount=1
+kerning first=111 second=34 amount=-3
+kerning first=40 second=89 amount=1
+kerning first=121 second=39 amount=1
+kerning first=70 second=74 amount=-7
+kerning first=68 second=90 amount=-1
+kerning first=98 second=120 amount=-1
+kerning first=110 second=34 amount=-3
+kerning first=119 second=46 amount=-4
+kerning first=69 second=102 amount=-1
+kerning first=118 second=44 amount=-6
+kerning first=84 second=114 amount=-2
+kerning first=86 second=97 amount=-2
+kerning first=40 second=87 amount=1
+kerning first=65 second=109 amount=-2
+kerning first=68 second=86 amount=-1
+kerning first=86 second=93 amount=1
+kerning first=65 second=67 amount=-1
+kerning first=97 second=34 amount=-1
+kerning first=34 second=65 amount=-4
+kerning first=84 second=118 amount=-3
+kerning first=112 second=34 amount=-1
+kerning first=76 second=84 amount=-7
+kerning first=107 second=99 amount=-1
+kerning first=123 second=85 amount=-1
+kerning first=102 second=125 amount=1
+kerning first=65 second=63 amount=-3
+kerning first=89 second=44 amount=-8
+kerning first=80 second=118 amount=1
+kerning first=112 second=122 amount=-1
+kerning first=79 second=65 amount=-1
+kerning first=80 second=121 amount=1
+kerning first=118 second=34 amount=1
+kerning first=87 second=45 amount=-2
+kerning first=69 second=100 amount=-1
+kerning first=87 second=103 amount=-1
+kerning first=112 second=120 amount=-1
+kerning first=86 second=65 amount=-3
+kerning first=65 second=81 amount=-1
+kerning first=68 second=44 amount=-4
+kerning first=86 second=45 amount=-6
+kerning first=39 second=34 amount=-1
+kerning first=72 second=88 amount=1
+kerning first=68 second=46 amount=-4
+kerning first=65 second=89 amount=-5
+kerning first=69 second=118 amount=-1
+kerning first=89 second=38 amount=-1
+kerning first=88 second=99 amount=-1
+kerning first=65 second=71 amount=-1
+kerning first=91 second=74 amount=-1
+kerning first=75 second=101 amount=-1
+kerning first=39 second=112 amount=-1
+kerning first=70 second=113 amount=-1
+kerning first=119 second=44 amount=-4
+kerning first=72 second=89 amount=-1
+kerning first=90 second=103 amount=-1
+kerning first=65 second=86 amount=-3
+kerning first=84 second=119 amount=-2
+kerning first=34 second=110 amount=-1
+kerning first=39 second=109 amount=-1
+kerning first=75 second=81 amount=-1
+kerning first=89 second=115 amount=-2
+kerning first=89 second=87 amount=1
+kerning first=114 second=101 amount=-1
+kerning first=116 second=111 amount=-1
+kerning first=90 second=100 amount=-1
+kerning first=79 second=89 amount=-2
+kerning first=84 second=122 amount=-2
+kerning first=68 second=84 amount=-3
+kerning first=76 second=86 amount=-7
+kerning first=74 second=65 amount=-1
+kerning first=107 second=101 amount=-1
+kerning first=80 second=46 amount=-14
+kerning first=89 second=93 amount=1
+kerning first=89 second=65 amount=-5
+kerning first=87 second=117 amount=-1
+kerning first=89 second=81 amount=-1
+kerning first=39 second=103 amount=-2
+kerning first=86 second=101 amount=-2
+kerning first=86 second=117 amount=-1
+kerning first=84 second=113 amount=-3
+kerning first=87 second=46 amount=-5
+kerning first=47 second=47 amount=-9
+kerning first=75 second=103 amount=-1
+kerning first=89 second=84 amount=1
+kerning first=84 second=110 amount=-3
+kerning first=39 second=99 amount=-2
+kerning first=88 second=121 amount=-1
+kerning first=65 second=39 amount=-4
+kerning first=110 second=39 amount=-3
+kerning first=88 second=118 amount=-1
+kerning first=86 second=114 amount=-1
+kerning first=80 second=74 amount=-6
+kerning first=84 second=97 amount=-6
+kerning first=82 second=84 amount=-2
+kerning first=91 second=85 amount=-1
+kerning first=102 second=99 amount=-1
+kerning first=66 second=86 amount=-1
+kerning first=120 second=101 amount=-1
+kerning first=102 second=93 amount=1
+kerning first=75 second=100 amount=-1
+kerning first=84 second=79 amount=-1
+kerning first=44 second=39 amount=-10
+kerning first=111 second=121 amount=-1
+kerning first=75 second=121 amount=-1
+kerning first=81 second=87 amount=-1
+kerning first=107 second=113 amount=-1
+kerning first=90 second=79 amount=-1
+kerning first=89 second=114 amount=-1
+kerning first=122 second=101 amount=-1
+kerning first=111 second=118 amount=-1
+kerning first=82 second=86 amount=-1
+kerning first=70 second=101 amount=-1
+kerning first=114 second=97 amount=-1
+kerning first=70 second=97 amount=-1
+kerning first=34 second=97 amount=-2
+kerning first=89 second=102 amount=-1
+kerning first=78 second=89 amount=-1
+kerning first=70 second=44 amount=-10
+kerning first=104 second=39 amount=-3
+kerning first=84 second=45 amount=-10
+kerning first=89 second=121 amount=-1
+kerning first=109 second=34 amount=-3
+kerning first=84 second=86 amount=1
+kerning first=87 second=99 amount=-1
+kerning first=32 second=84 amount=-2
+kerning first=98 second=122 amount=-1
+kerning first=89 second=112 amount=-1
+kerning first=89 second=103 amount=-2
+kerning first=65 second=116 amount=-1
+kerning first=88 second=81 amount=-1
+kerning first=102 second=34 amount=1
+kerning first=109 second=39 amount=-3
+kerning first=81 second=84 amount=-1
+kerning first=121 second=97 amount=-1
+kerning first=89 second=99 amount=-2
+kerning first=89 second=125 amount=1
+kerning first=81 second=86 amount=-1
+kerning first=114 second=116 amount=2
+kerning first=114 second=119 amount=1
+kerning first=84 second=44 amount=-9
+kerning first=102 second=39 amount=1
+kerning first=44 second=34 amount=-10
+kerning first=34 second=109 amount=-1
+kerning first=84 second=101 amount=-3
+kerning first=75 second=119 amount=-2
+kerning first=84 second=81 amount=-1
+kerning first=76 second=121 amount=-4
+kerning first=69 second=101 amount=-1
+kerning first=80 second=90 amount=-1
+kerning first=89 second=97 amount=-2
+kerning first=89 second=109 amount=-1
+kerning first=90 second=99 amount=-1
+kerning first=79 second=88 amount=-1
+kerning first=70 second=103 amount=-1
+kerning first=34 second=103 amount=-2
+kerning first=84 second=67 amount=-1
+kerning first=76 second=79 amount=-2
+kerning first=34 second=113 amount=-2
+kerning first=89 second=41 amount=1
+kerning first=75 second=71 amount=-1
+kerning first=76 second=87 amount=-3
+kerning first=77 second=89 amount=-1
+kerning first=90 second=113 amount=-1
+kerning first=118 second=111 amount=-1
+kerning first=118 second=97 amount=-1
+kerning first=88 second=100 amount=-1
+kerning first=89 second=111 amount=-2
+kerning first=90 second=121 amount=-1
+kerning first=89 second=113 amount=-2
+kerning first=84 second=87 amount=1
+kerning first=39 second=111 amount=-3
+kerning first=39 second=100 amount=-2
+kerning first=75 second=113 amount=-1
+kerning first=88 second=111 amount=-1
+kerning first=87 second=111 amount=-1
+kerning first=89 second=83 amount=-1
+kerning first=84 second=89 amount=1
+kerning first=84 second=103 amount=-3
+kerning first=70 second=117 amount=-1
+kerning first=67 second=41 amount=-1
+kerning first=89 second=71 amount=-1
+kerning first=121 second=44 amount=-6
+kerning first=97 second=121 amount=-1
+kerning first=87 second=113 amount=-1
+kerning first=73 second=84 amount=-1
+kerning first=121 second=46 amount=-6
+kerning first=75 second=99 amount=-1
+kerning first=65 second=112 amount=-2
+kerning first=65 second=85 amount=-1
+kerning first=76 second=67 amount=-2
+kerning first=76 second=81 amount=-2
+kerning first=102 second=100 amount=-1
+kerning first=75 second=79 amount=-1
+kerning first=39 second=65 amount=-4
+kerning first=65 second=84 amount=-4
+kerning first=90 second=101 amount=-1
+kerning first=84 second=121 amount=-3
+kerning first=114 second=39 amount=1
+kerning first=84 second=109 amount=-3
+kerning first=123 second=74 amount=-1
+kerning first=76 second=119 amount=-2
+kerning first=84 second=117 amount=-2
+kerning first=76 second=85 amount=-1
+kerning first=76 second=71 amount=-2
+kerning first=79 second=90 amount=-1
+kerning first=107 second=100 amount=-1
+kerning first=90 second=111 amount=-1
+kerning first=79 second=44 amount=-4
+kerning first=75 second=45 amount=-6
+kerning first=79 second=86 amount=-1
+kerning first=79 second=46 amount=-4
+kerning first=76 second=89 amount=-10
+kerning first=68 second=65 amount=-1
+kerning first=79 second=84 amount=-3
+kerning first=87 second=100 amount=-1
+kerning first=84 second=32 amount=-2
+kerning first=90 second=67 amount=-1
+kerning first=69 second=103 amount=-1
+kerning first=90 second=71 amount=-1
+kerning first=86 second=44 amount=-8
+kerning first=69 second=121 amount=-1
+kerning first=87 second=114 amount=-1
+kerning first=118 second=39 amount=1
+kerning first=46 second=39 amount=-10
+kerning first=72 second=84 amount=-1
+kerning first=86 second=46 amount=-8
+kerning first=69 second=113 amount=-1
+kerning first=69 second=119 amount=-1
+kerning first=73 second=89 amount=-1
+kerning first=39 second=39 amount=-1
+kerning first=69 second=117 amount=-1
+kerning first=111 second=39 amount=-3
+kerning first=90 second=81 amount=-1

BIN
src/web/static/fonts/bmfonts/RobotoBlack72White.png


+ 103 - 0
src/web/static/fonts/bmfonts/RobotoMono72White.fnt

@@ -0,0 +1,103 @@
+info face="Roboto Mono" size=72 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=-2,-2
+common lineHeight=96 base=76 scaleW=512 scaleH=512 pages=1 packed=0
+page id=0 file="RobotoMono72White.png"
+chars count=98
+char id=0       x=0    y=0    width=0    height=0    xoffset=-1   yoffset=75   xadvance=0    page=0    chnl=0 
+char id=10      x=0    y=0    width=45   height=99   xoffset=-1   yoffset=-2   xadvance=43   page=0    chnl=0 
+char id=32      x=0    y=0    width=0    height=0    xoffset=-1   yoffset=75   xadvance=43   page=0    chnl=0 
+char id=33      x=498  y=99   width=10   height=55   xoffset=16   yoffset=23   xadvance=43   page=0    chnl=0 
+char id=34      x=434  y=319  width=20   height=19   xoffset=11   yoffset=21   xadvance=43   page=0    chnl=0 
+char id=35      x=175  y=265  width=41   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=36      x=200  y=0    width=35   height=69   xoffset=5    yoffset=15   xadvance=43   page=0    chnl=0 
+char id=37      x=0    y=155  width=42   height=56   xoffset=1    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=38      x=42   y=155  width=41   height=56   xoffset=3    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=39      x=502  y=211  width=7    height=19   xoffset=16   yoffset=21   xadvance=43   page=0    chnl=0 
+char id=40      x=45   y=0    width=21   height=78   xoffset=12   yoffset=16   xadvance=44   page=0    chnl=0 
+char id=41      x=66   y=0    width=22   height=78   xoffset=9    yoffset=16   xadvance=43   page=0    chnl=0 
+char id=42      x=256  y=319  width=37   height=37   xoffset=4    yoffset=32   xadvance=43   page=0    chnl=0 
+char id=43      x=219  y=319  width=37   height=40   xoffset=3    yoffset=32   xadvance=43   page=0    chnl=0 
+char id=44      x=421  y=319  width=13   height=22   xoffset=11   yoffset=67   xadvance=43   page=0    chnl=0 
+char id=45      x=17   y=360  width=29   height=8    xoffset=7    yoffset=49   xadvance=44   page=0    chnl=0 
+char id=46      x=496  y=319  width=12   height=13   xoffset=16   yoffset=65   xadvance=43   page=0    chnl=0 
+char id=47      x=319  y=0    width=31   height=58   xoffset=7    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=48      x=431  y=99   width=35   height=56   xoffset=4    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=49      x=36   y=265  width=23   height=54   xoffset=6    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=50      x=189  y=155  width=37   height=55   xoffset=2    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=51      x=361  y=99   width=35   height=56   xoffset=2    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=52      x=59   y=265  width=39   height=54   xoffset=2    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=53      x=226  y=155  width=35   height=55   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=54      x=261  y=155  width=35   height=55   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=55      x=98   y=265  width=37   height=54   xoffset=3    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=56      x=396  y=99   width=35   height=56   xoffset=5    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=57      x=296  y=155  width=34   height=55   xoffset=4    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=58      x=490  y=211  width=12   height=43   xoffset=18   yoffset=35   xadvance=43   page=0    chnl=0 
+char id=59      x=486  y=0    width=14   height=55   xoffset=16   yoffset=35   xadvance=43   page=0    chnl=0 
+char id=60      x=293  y=319  width=32   height=35   xoffset=5    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=61      x=388  y=319  width=33   height=23   xoffset=5    yoffset=41   xadvance=43   page=0    chnl=0 
+char id=62      x=325  y=319  width=33   height=35   xoffset=5    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=63      x=466  y=99   width=32   height=56   xoffset=6    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=64      x=135  y=265  width=40   height=54   xoffset=1    yoffset=23   xadvance=42   page=0    chnl=0 
+char id=65      x=330  y=155  width=42   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=66      x=372  y=155  width=35   height=54   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=67      x=448  y=0    width=38   height=56   xoffset=3    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=68      x=407  y=155  width=37   height=54   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=69      x=444  y=155  width=34   height=54   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=70      x=0    y=211  width=34   height=54   xoffset=6    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=71      x=0    y=99   width=38   height=56   xoffset=3    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=72      x=34   y=211  width=36   height=54   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=73      x=478  y=155  width=33   height=54   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=74      x=83   y=155  width=36   height=55   xoffset=2    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=75      x=70   y=211  width=38   height=54   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=76      x=108  y=211  width=34   height=54   xoffset=6    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=77      x=142  y=211  width=36   height=54   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=78      x=178  y=211  width=35   height=54   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=79      x=38   y=99   width=38   height=56   xoffset=3    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=80      x=213  y=211  width=36   height=54   xoffset=6    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=81      x=242  y=0    width=40   height=64   xoffset=2    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=82      x=249  y=211  width=36   height=54   xoffset=5    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=83      x=76   y=99   width=38   height=56   xoffset=3    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=84      x=285  y=211  width=40   height=54   xoffset=2    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=85      x=119  y=155  width=36   height=55   xoffset=4    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=86      x=325  y=211  width=41   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=87      x=366  y=211  width=42   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=88      x=408  y=211  width=41   height=54   xoffset=2    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=89      x=449  y=211  width=41   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=90      x=0    y=265  width=36   height=54   xoffset=3    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=91      x=88   y=0    width=16   height=72   xoffset=14   yoffset=16   xadvance=43   page=0    chnl=0 
+char id=92      x=350  y=0    width=30   height=58   xoffset=7    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=93      x=104  y=0    width=17   height=72   xoffset=13   yoffset=16   xadvance=44   page=0    chnl=0 
+char id=94      x=358  y=319  width=30   height=30   xoffset=7    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=95      x=46   y=360  width=34   height=8    xoffset=4    yoffset=74   xadvance=43   page=0    chnl=0 
+char id=96      x=0    y=360  width=17   height=12   xoffset=13   yoffset=22   xadvance=43   page=0    chnl=0 
+char id=97      x=251  y=265  width=35   height=42   xoffset=4    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=98      x=380  y=0    width=34   height=57   xoffset=5    yoffset=21   xadvance=43   page=0    chnl=0 
+char id=99      x=286  y=265  width=35   height=42   xoffset=4    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=100     x=414  y=0    width=34   height=57   xoffset=4    yoffset=21   xadvance=43   page=0    chnl=0 
+char id=101     x=321  y=265  width=36   height=42   xoffset=4    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=102     x=282  y=0    width=37   height=58   xoffset=4    yoffset=19   xadvance=43   page=0    chnl=0 
+char id=103     x=114  y=99   width=34   height=56   xoffset=4    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=104     x=148  y=99   width=34   height=56   xoffset=5    yoffset=21   xadvance=43   page=0    chnl=0 
+char id=105     x=155  y=155  width=34   height=55   xoffset=6    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=106     x=121  y=0    width=26   height=71   xoffset=6    yoffset=22   xadvance=44   page=0    chnl=0 
+char id=107     x=182  y=99   width=36   height=56   xoffset=5    yoffset=21   xadvance=43   page=0    chnl=0 
+char id=108     x=218  y=99   width=34   height=56   xoffset=6    yoffset=21   xadvance=43   page=0    chnl=0 
+char id=109     x=428  y=265  width=39   height=41   xoffset=2    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=110     x=467  y=265  width=34   height=41   xoffset=5    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=111     x=357  y=265  width=37   height=42   xoffset=3    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=112     x=252  y=99   width=34   height=56   xoffset=5    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=113     x=286  y=99   width=34   height=56   xoffset=4    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=114     x=0    y=319  width=29   height=41   xoffset=11   yoffset=36   xadvance=44   page=0    chnl=0 
+char id=115     x=394  y=265  width=34   height=42   xoffset=5    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=116     x=216  y=265  width=35   height=51   xoffset=4    yoffset=27   xadvance=43   page=0    chnl=0 
+char id=117     x=29   y=319  width=33   height=41   xoffset=5    yoffset=37   xadvance=43   page=0    chnl=0 
+char id=118     x=62   y=319  width=39   height=40   xoffset=2    yoffset=37   xadvance=43   page=0    chnl=0 
+char id=119     x=101  y=319  width=43   height=40   xoffset=0    yoffset=37   xadvance=43   page=0    chnl=0 
+char id=120     x=144  y=319  width=40   height=40   xoffset=2    yoffset=37   xadvance=43   page=0    chnl=0 
+char id=121     x=320  y=99   width=41   height=56   xoffset=1    yoffset=37   xadvance=43   page=0    chnl=0 
+char id=122     x=184  y=319  width=35   height=40   xoffset=5    yoffset=37   xadvance=44   page=0    chnl=0 
+char id=123     x=147  y=0    width=26   height=71   xoffset=10   yoffset=19   xadvance=43   page=0    chnl=0 
+char id=124     x=235  y=0    width=7    height=68   xoffset=18   yoffset=23   xadvance=43   page=0    chnl=0 
+char id=125     x=173  y=0    width=27   height=71   xoffset=10   yoffset=19   xadvance=44   page=0    chnl=0 
+char id=126     x=454  y=319  width=42   height=16   xoffset=1    yoffset=47   xadvance=44   page=0    chnl=0 
+char id=127     x=0    y=0    width=45   height=99   xoffset=-1   yoffset=-2   xadvance=43   page=0    chnl=0 
+kernings count=0

BIN
src/web/static/fonts/bmfonts/RobotoMono72White.png


+ 492 - 0
src/web/static/fonts/bmfonts/RobotoSlab72White.fnt

@@ -0,0 +1,492 @@
+info face="Roboto Slab Regular" size=72 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=-2,-2
+common lineHeight=96 base=76 scaleW=512 scaleH=512 pages=1 packed=0
+page id=0 file="RobotoSlab72White.png"
+chars count=98
+char id=0       x=0    y=0    width=0    height=0    xoffset=-1   yoffset=75   xadvance=0    page=0    chnl=0 
+char id=10      x=0    y=0    width=70   height=98   xoffset=0    yoffset=-1   xadvance=70   page=0    chnl=0 
+char id=32      x=0    y=0    width=0    height=0    xoffset=-1   yoffset=75   xadvance=18   page=0    chnl=0 
+char id=33      x=497  y=156  width=9    height=54   xoffset=4    yoffset=23   xadvance=17   page=0    chnl=0 
+char id=34      x=191  y=362  width=19   height=20   xoffset=5    yoffset=20   xadvance=28   page=0    chnl=0 
+char id=35      x=406  y=266  width=41   height=54   xoffset=1    yoffset=23   xadvance=43   page=0    chnl=0 
+char id=36      x=212  y=0    width=35   height=69   xoffset=2    yoffset=15   xadvance=39   page=0    chnl=0 
+char id=37      x=174  y=156  width=48   height=56   xoffset=2    yoffset=22   xadvance=52   page=0    chnl=0 
+char id=38      x=222  y=156  width=44   height=56   xoffset=2    yoffset=22   xadvance=46   page=0    chnl=0 
+char id=39      x=210  y=362  width=8    height=20   xoffset=5    yoffset=20   xadvance=17   page=0    chnl=0 
+char id=40      x=70   y=0    width=21   height=77   xoffset=3    yoffset=17   xadvance=23   page=0    chnl=0 
+char id=41      x=91   y=0    width=21   height=77   xoffset=-1   yoffset=17   xadvance=23   page=0    chnl=0 
+char id=42      x=100  y=362  width=31   height=33   xoffset=1    yoffset=23   xadvance=33   page=0    chnl=0 
+char id=43      x=0    y=362  width=37   height=40   xoffset=2    yoffset=32   xadvance=41   page=0    chnl=0 
+char id=44      x=492  y=320  width=13   height=21   xoffset=-1   yoffset=67   xadvance=14   page=0    chnl=0 
+char id=45      x=287  y=362  width=19   height=8    xoffset=4    yoffset=50   xadvance=27   page=0    chnl=0 
+char id=46      x=278  y=362  width=9    height=9    xoffset=4    yoffset=68   xadvance=17   page=0    chnl=0 
+char id=47      x=470  y=0    width=30   height=58   xoffset=-1   yoffset=23   xadvance=29   page=0    chnl=0 
+char id=48      x=139  y=156  width=35   height=56   xoffset=3    yoffset=22   xadvance=41   page=0    chnl=0 
+char id=49      x=305  y=266  width=25   height=54   xoffset=3    yoffset=23   xadvance=30   page=0    chnl=0 
+char id=50      x=357  y=156  width=36   height=55   xoffset=2    yoffset=22   xadvance=40   page=0    chnl=0 
+char id=51      x=0    y=156  width=34   height=56   xoffset=2    yoffset=22   xadvance=39   page=0    chnl=0 
+char id=52      x=330  y=266  width=39   height=54   xoffset=1    yoffset=23   xadvance=42   page=0    chnl=0 
+char id=53      x=393  y=156  width=33   height=55   xoffset=2    yoffset=23   xadvance=37   page=0    chnl=0 
+char id=54      x=34   y=156  width=35   height=56   xoffset=3    yoffset=22   xadvance=40   page=0    chnl=0 
+char id=55      x=369  y=266  width=37   height=54   xoffset=2    yoffset=23   xadvance=40   page=0    chnl=0 
+char id=56      x=69   y=156  width=35   height=56   xoffset=2    yoffset=22   xadvance=39   page=0    chnl=0 
+char id=57      x=104  y=156  width=35   height=56   xoffset=2    yoffset=22   xadvance=41   page=0    chnl=0 
+char id=58      x=500  y=0    width=9    height=40   xoffset=4    yoffset=37   xadvance=15   page=0    chnl=0 
+char id=59      x=447  y=266  width=13   height=52   xoffset=0    yoffset=37   xadvance=15   page=0    chnl=0 
+char id=60      x=37   y=362  width=31   height=35   xoffset=2    yoffset=39   xadvance=36   page=0    chnl=0 
+char id=61      x=160  y=362  width=31   height=23   xoffset=4    yoffset=40   xadvance=39   page=0    chnl=0 
+char id=62      x=68   y=362  width=32   height=35   xoffset=3    yoffset=39   xadvance=37   page=0    chnl=0 
+char id=63      x=480  y=98   width=31   height=55   xoffset=1    yoffset=22   xadvance=33   page=0    chnl=0 
+char id=64      x=247  y=0    width=60   height=68   xoffset=1    yoffset=25   xadvance=64   page=0    chnl=0 
+char id=65      x=426  y=156  width=51   height=54   xoffset=1    yoffset=23   xadvance=53   page=0    chnl=0 
+char id=66      x=0    y=212  width=44   height=54   xoffset=1    yoffset=23   xadvance=47   page=0    chnl=0 
+char id=67      x=191  y=98   width=42   height=56   xoffset=1    yoffset=22   xadvance=46   page=0    chnl=0 
+char id=68      x=44   y=212  width=46   height=54   xoffset=1    yoffset=23   xadvance=50   page=0    chnl=0 
+char id=69      x=90   y=212  width=42   height=54   xoffset=1    yoffset=23   xadvance=46   page=0    chnl=0 
+char id=70      x=132  y=212  width=42   height=54   xoffset=1    yoffset=23   xadvance=44   page=0    chnl=0 
+char id=71      x=233  y=98   width=43   height=56   xoffset=1    yoffset=22   xadvance=49   page=0    chnl=0 
+char id=72      x=174  y=212  width=52   height=54   xoffset=1    yoffset=23   xadvance=55   page=0    chnl=0 
+char id=73      x=477  y=156  width=20   height=54   xoffset=1    yoffset=23   xadvance=22   page=0    chnl=0 
+char id=74      x=266  y=156  width=39   height=55   xoffset=1    yoffset=23   xadvance=41   page=0    chnl=0 
+char id=75      x=226  y=212  width=48   height=54   xoffset=1    yoffset=23   xadvance=50   page=0    chnl=0 
+char id=76      x=274  y=212  width=39   height=54   xoffset=1    yoffset=23   xadvance=42   page=0    chnl=0 
+char id=77      x=313  y=212  width=64   height=54   xoffset=1    yoffset=23   xadvance=66   page=0    chnl=0 
+char id=78      x=377  y=212  width=52   height=54   xoffset=1    yoffset=23   xadvance=54   page=0    chnl=0 
+char id=79      x=276  y=98   width=47   height=56   xoffset=2    yoffset=22   xadvance=51   page=0    chnl=0 
+char id=80      x=429  y=212  width=43   height=54   xoffset=1    yoffset=23   xadvance=45   page=0    chnl=0 
+char id=81      x=307  y=0    width=48   height=64   xoffset=2    yoffset=22   xadvance=51   page=0    chnl=0 
+char id=82      x=0    y=266  width=46   height=54   xoffset=1    yoffset=23   xadvance=48   page=0    chnl=0 
+char id=83      x=323  y=98   width=38   height=56   xoffset=3    yoffset=22   xadvance=43   page=0    chnl=0 
+char id=84      x=46   y=266  width=45   height=54   xoffset=0    yoffset=23   xadvance=45   page=0    chnl=0 
+char id=85      x=305  y=156  width=52   height=55   xoffset=1    yoffset=23   xadvance=54   page=0    chnl=0 
+char id=86      x=91   y=266  width=50   height=54   xoffset=1    yoffset=23   xadvance=52   page=0    chnl=0 
+char id=87      x=141  y=266  width=67   height=54   xoffset=0    yoffset=23   xadvance=67   page=0    chnl=0 
+char id=88      x=208  y=266  width=49   height=54   xoffset=1    yoffset=23   xadvance=51   page=0    chnl=0 
+char id=89      x=257  y=266  width=48   height=54   xoffset=1    yoffset=23   xadvance=50   page=0    chnl=0 
+char id=90      x=472  y=212  width=38   height=54   xoffset=2    yoffset=23   xadvance=42   page=0    chnl=0 
+char id=91      x=180  y=0    width=16   height=72   xoffset=5    yoffset=16   xadvance=21   page=0    chnl=0 
+char id=92      x=0    y=98   width=31   height=58   xoffset=0    yoffset=23   xadvance=30   page=0    chnl=0 
+char id=93      x=196  y=0    width=16   height=72   xoffset=-1   yoffset=16   xadvance=19   page=0    chnl=0 
+char id=94      x=131  y=362  width=29   height=28   xoffset=1    yoffset=23   xadvance=30   page=0    chnl=0 
+char id=95      x=306  y=362  width=34   height=8    xoffset=3    yoffset=74   xadvance=40   page=0    chnl=0 
+char id=96      x=260  y=362  width=18   height=12   xoffset=1    yoffset=22   xadvance=20   page=0    chnl=0 
+char id=97      x=0    y=320  width=36   height=42   xoffset=3    yoffset=36   xadvance=41   page=0    chnl=0 
+char id=98      x=363  y=0    width=41   height=58   xoffset=-2   yoffset=20   xadvance=42   page=0    chnl=0 
+char id=99      x=36   y=320  width=34   height=42   xoffset=2    yoffset=36   xadvance=39   page=0    chnl=0 
+char id=100     x=404  y=0    width=40   height=58   xoffset=2    yoffset=20   xadvance=43   page=0    chnl=0 
+char id=101     x=70   y=320  width=34   height=42   xoffset=2    yoffset=36   xadvance=39   page=0    chnl=0 
+char id=102     x=444  y=0    width=26   height=58   xoffset=1    yoffset=19   xadvance=25   page=0    chnl=0 
+char id=103     x=31   y=98   width=34   height=57   xoffset=2    yoffset=36   xadvance=40   page=0    chnl=0 
+char id=104     x=65   y=98   width=44   height=57   xoffset=1    yoffset=20   xadvance=46   page=0    chnl=0 
+char id=105     x=109  y=98   width=20   height=57   xoffset=2    yoffset=20   xadvance=23   page=0    chnl=0 
+char id=106     x=112  y=0    width=18   height=73   xoffset=-2   yoffset=20   xadvance=20   page=0    chnl=0 
+char id=107     x=129  y=98   width=42   height=57   xoffset=1    yoffset=20   xadvance=44   page=0    chnl=0 
+char id=108     x=171  y=98   width=20   height=57   xoffset=1    yoffset=20   xadvance=22   page=0    chnl=0 
+char id=109     x=171  y=320  width=66   height=41   xoffset=1    yoffset=36   xadvance=68   page=0    chnl=0 
+char id=110     x=237  y=320  width=44   height=41   xoffset=1    yoffset=36   xadvance=46   page=0    chnl=0 
+char id=111     x=104  y=320  width=36   height=42   xoffset=2    yoffset=36   xadvance=40   page=0    chnl=0 
+char id=112     x=361  y=98   width=40   height=56   xoffset=1    yoffset=36   xadvance=43   page=0    chnl=0 
+char id=113     x=401  y=98   width=39   height=56   xoffset=2    yoffset=36   xadvance=40   page=0    chnl=0 
+char id=114     x=484  y=266  width=27   height=41   xoffset=2    yoffset=36   xadvance=30   page=0    chnl=0 
+char id=115     x=140  y=320  width=31   height=42   xoffset=3    yoffset=36   xadvance=36   page=0    chnl=0 
+char id=116     x=460  y=266  width=24   height=51   xoffset=1    yoffset=27   xadvance=26   page=0    chnl=0 
+char id=117     x=281  y=320  width=43   height=41   xoffset=0    yoffset=37   xadvance=44   page=0    chnl=0 
+char id=118     x=324  y=320  width=39   height=40   xoffset=0    yoffset=37   xadvance=40   page=0    chnl=0 
+char id=119     x=363  y=320  width=57   height=40   xoffset=1    yoffset=37   xadvance=59   page=0    chnl=0 
+char id=120     x=420  y=320  width=40   height=40   xoffset=1    yoffset=37   xadvance=42   page=0    chnl=0 
+char id=121     x=440  y=98   width=40   height=56   xoffset=0    yoffset=37   xadvance=41   page=0    chnl=0 
+char id=122     x=460  y=320  width=32   height=40   xoffset=3    yoffset=37   xadvance=38   page=0    chnl=0 
+char id=123     x=130  y=0    width=25   height=73   xoffset=1    yoffset=18   xadvance=25   page=0    chnl=0 
+char id=124     x=355  y=0    width=8    height=63   xoffset=4    yoffset=23   xadvance=16   page=0    chnl=0 
+char id=125     x=155  y=0    width=25   height=73   xoffset=-1   yoffset=18   xadvance=25   page=0    chnl=0 
+char id=126     x=218  y=362  width=42   height=16   xoffset=3    yoffset=47   xadvance=49   page=0    chnl=0 
+char id=127     x=0    y=0    width=70   height=98   xoffset=0    yoffset=-1   xadvance=70   page=0    chnl=0 
+kernings count=389
+kerning first=86 second=45 amount=-1
+kerning first=114 second=46 amount=-4
+kerning first=40 second=87 amount=1
+kerning first=70 second=99 amount=-1
+kerning first=84 second=110 amount=-3
+kerning first=114 second=116 amount=1
+kerning first=39 second=65 amount=-4
+kerning first=104 second=34 amount=-1
+kerning first=89 second=71 amount=-1
+kerning first=107 second=113 amount=-1
+kerning first=78 second=88 amount=1
+kerning first=109 second=39 amount=-1
+kerning first=120 second=100 amount=-1
+kerning first=84 second=100 amount=-3
+kerning first=68 second=90 amount=-1
+kerning first=68 second=44 amount=-4
+kerning first=84 second=103 amount=-3
+kerning first=34 second=97 amount=-2
+kerning first=70 second=97 amount=-1
+kerning first=76 second=81 amount=-2
+kerning first=73 second=89 amount=-1
+kerning first=84 second=44 amount=-8
+kerning first=68 second=65 amount=-3
+kerning first=97 second=34 amount=-2
+kerning first=111 second=121 amount=-1
+kerning first=79 second=90 amount=-1
+kerning first=75 second=121 amount=-1
+kerning first=75 second=118 amount=-1
+kerning first=111 second=118 amount=-1
+kerning first=89 second=65 amount=-9
+kerning first=75 second=71 amount=-4
+kerning first=39 second=99 amount=-2
+kerning first=75 second=99 amount=-1
+kerning first=90 second=121 amount=-1
+kerning first=44 second=39 amount=-6
+kerning first=89 second=46 amount=-7
+kerning first=89 second=74 amount=-7
+kerning first=34 second=103 amount=-2
+kerning first=70 second=103 amount=-1
+kerning first=112 second=39 amount=-1
+kerning first=122 second=113 amount=-1
+kerning first=86 second=113 amount=-2
+kerning first=68 second=84 amount=-1
+kerning first=89 second=110 amount=-1
+kerning first=34 second=100 amount=-2
+kerning first=68 second=86 amount=-1
+kerning first=87 second=45 amount=-2
+kerning first=39 second=34 amount=-4
+kerning first=114 second=100 amount=-1
+kerning first=84 second=81 amount=-1
+kerning first=70 second=101 amount=-1
+kerning first=68 second=89 amount=-2
+kerning first=88 second=117 amount=-1
+kerning first=112 second=34 amount=-1
+kerning first=76 second=67 amount=-2
+kerning first=76 second=34 amount=-5
+kerning first=88 second=111 amount=-1
+kerning first=66 second=86 amount=-1
+kerning first=66 second=89 amount=-2
+kerning first=122 second=101 amount=-1
+kerning first=86 second=101 amount=-2
+kerning first=76 second=121 amount=-5
+kerning first=84 second=119 amount=-2
+kerning first=84 second=112 amount=-3
+kerning first=87 second=111 amount=-1
+kerning first=69 second=118 amount=-1
+kerning first=65 second=117 amount=-2
+kerning first=65 second=89 amount=-9
+kerning first=72 second=89 amount=-1
+kerning first=119 second=44 amount=-4
+kerning first=69 second=121 amount=-1
+kerning first=84 second=109 amount=-3
+kerning first=84 second=122 amount=-2
+kerning first=89 second=99 amount=-2
+kerning first=76 second=118 amount=-5
+kerning first=90 second=99 amount=-1
+kerning first=90 second=103 amount=-1
+kerning first=79 second=89 amount=-2
+kerning first=90 second=79 amount=-1
+kerning first=84 second=115 amount=-4
+kerning first=76 second=65 amount=1
+kerning first=90 second=100 amount=-1
+kerning first=118 second=46 amount=-4
+kerning first=87 second=117 amount=-1
+kerning first=118 second=34 amount=1
+kerning first=69 second=103 amount=-1
+kerning first=97 second=121 amount=-1
+kerning first=39 second=111 amount=-2
+kerning first=72 second=88 amount=1
+kerning first=76 second=87 amount=-5
+kerning first=69 second=119 amount=-1
+kerning first=121 second=97 amount=-1
+kerning first=75 second=45 amount=-8
+kerning first=65 second=86 amount=-9
+kerning first=46 second=34 amount=-6
+kerning first=76 second=84 amount=-10
+kerning first=116 second=111 amount=-1
+kerning first=87 second=113 amount=-1
+kerning first=69 second=100 amount=-1
+kerning first=97 second=118 amount=-1
+kerning first=65 second=85 amount=-2
+kerning first=90 second=71 amount=-1
+kerning first=68 second=46 amount=-4
+kerning first=65 second=79 amount=-3
+kerning first=98 second=122 amount=-1
+kerning first=86 second=41 amount=1
+kerning first=84 second=118 amount=-3
+kerning first=70 second=118 amount=-1
+kerning first=121 second=111 amount=-1
+kerning first=81 second=87 amount=-1
+kerning first=70 second=100 amount=-1
+kerning first=102 second=93 amount=1
+kerning first=114 second=101 amount=-1
+kerning first=88 second=45 amount=-2
+kerning first=39 second=103 amount=-2
+kerning first=75 second=103 amount=-1
+kerning first=88 second=101 amount=-1
+kerning first=89 second=103 amount=-2
+kerning first=110 second=39 amount=-1
+kerning first=89 second=89 amount=1
+kerning first=87 second=65 amount=-2
+kerning first=119 second=46 amount=-4
+kerning first=34 second=34 amount=-4
+kerning first=88 second=79 amount=-2
+kerning first=79 second=86 amount=-1
+kerning first=76 second=119 amount=-3
+kerning first=75 second=111 amount=-1
+kerning first=65 second=116 amount=-4
+kerning first=86 second=65 amount=-9
+kerning first=70 second=84 amount=1
+kerning first=75 second=117 amount=-1
+kerning first=80 second=65 amount=-9
+kerning first=34 second=112 amount=-1
+kerning first=102 second=99 amount=-1
+kerning first=118 second=97 amount=-1
+kerning first=89 second=81 amount=-1
+kerning first=118 second=111 amount=-1
+kerning first=102 second=101 amount=-1
+kerning first=114 second=44 amount=-4
+kerning first=90 second=119 amount=-1
+kerning first=75 second=81 amount=-4
+kerning first=88 second=121 amount=-1
+kerning first=34 second=110 amount=-1
+kerning first=86 second=100 amount=-2
+kerning first=122 second=100 amount=-1
+kerning first=89 second=67 amount=-1
+kerning first=90 second=118 amount=-1
+kerning first=84 second=84 amount=1
+kerning first=121 second=34 amount=1
+kerning first=91 second=74 amount=-1
+kerning first=88 second=113 amount=-1
+kerning first=77 second=88 amount=1
+kerning first=75 second=119 amount=-2
+kerning first=114 second=104 amount=-1
+kerning first=68 second=88 amount=-2
+kerning first=121 second=44 amount=-4
+kerning first=81 second=89 amount=-1
+kerning first=102 second=39 amount=1
+kerning first=74 second=65 amount=-2
+kerning first=114 second=118 amount=1
+kerning first=84 second=46 amount=-8
+kerning first=111 second=34 amount=-1
+kerning first=88 second=71 amount=-2
+kerning first=88 second=99 amount=-1
+kerning first=84 second=74 amount=-8
+kerning first=39 second=109 amount=-1
+kerning first=98 second=34 amount=-1
+kerning first=86 second=114 amount=-1
+kerning first=88 second=81 amount=-2
+kerning first=70 second=74 amount=-11
+kerning first=89 second=83 amount=-1
+kerning first=87 second=41 amount=1
+kerning first=89 second=97 amount=-3
+kerning first=89 second=87 amount=1
+kerning first=67 second=125 amount=-1
+kerning first=89 second=93 amount=1
+kerning first=80 second=118 amount=1
+kerning first=107 second=100 amount=-1
+kerning first=114 second=34 amount=1
+kerning first=89 second=109 amount=-1
+kerning first=89 second=45 amount=-2
+kerning first=70 second=44 amount=-8
+kerning first=34 second=39 amount=-4
+kerning first=88 second=67 amount=-2
+kerning first=70 second=46 amount=-8
+kerning first=102 second=41 amount=1
+kerning first=89 second=117 amount=-1
+kerning first=89 second=111 amount=-4
+kerning first=89 second=115 amount=-4
+kerning first=114 second=102 amount=1
+kerning first=89 second=125 amount=1
+kerning first=89 second=121 amount=-1
+kerning first=114 second=108 amount=-1
+kerning first=47 second=47 amount=-8
+kerning first=65 second=63 amount=-2
+kerning first=75 second=67 amount=-4
+kerning first=87 second=100 amount=-1
+kerning first=111 second=104 amount=-1
+kerning first=111 second=107 amount=-1
+kerning first=75 second=109 amount=-1
+kerning first=87 second=114 amount=-1
+kerning first=111 second=120 amount=-1
+kerning first=69 second=99 amount=-1
+kerning first=65 second=84 amount=-6
+kerning first=39 second=97 amount=-2
+kerning first=121 second=46 amount=-4
+kerning first=89 second=85 amount=-3
+kerning first=75 second=79 amount=-4
+kerning first=107 second=99 amount=-1
+kerning first=102 second=100 amount=-1
+kerning first=102 second=103 amount=-1
+kerning first=75 second=110 amount=-1
+kerning first=39 second=110 amount=-1
+kerning first=69 second=84 amount=1
+kerning first=84 second=111 amount=-3
+kerning first=120 second=111 amount=-1
+kerning first=84 second=114 amount=-3
+kerning first=112 second=120 amount=-1
+kerning first=79 second=84 amount=-1
+kerning first=84 second=117 amount=-3
+kerning first=89 second=79 amount=-1
+kerning first=75 second=113 amount=-1
+kerning first=39 second=113 amount=-2
+kerning first=80 second=44 amount=-11
+kerning first=79 second=88 amount=-2
+kerning first=98 second=39 amount=-1
+kerning first=65 second=118 amount=-4
+kerning first=65 second=34 amount=-4
+kerning first=88 second=103 amount=-1
+kerning first=77 second=89 amount=-1
+kerning first=39 second=101 amount=-2
+kerning first=75 second=101 amount=-1
+kerning first=88 second=100 amount=-1
+kerning first=78 second=65 amount=-3
+kerning first=87 second=44 amount=-4
+kerning first=67 second=41 amount=-1
+kerning first=86 second=93 amount=1
+kerning first=84 second=83 amount=-1
+kerning first=102 second=113 amount=-1
+kerning first=34 second=111 amount=-2
+kerning first=70 second=111 amount=-1
+kerning first=86 second=99 amount=-2
+kerning first=84 second=86 amount=1
+kerning first=122 second=99 amount=-1
+kerning first=84 second=89 amount=1
+kerning first=70 second=114 amount=-1
+kerning first=86 second=74 amount=-8
+kerning first=89 second=38 amount=-1
+kerning first=87 second=97 amount=-1
+kerning first=76 second=86 amount=-9
+kerning first=40 second=86 amount=1
+kerning first=90 second=113 amount=-1
+kerning first=39 second=39 amount=-4
+kerning first=111 second=39 amount=-1
+kerning first=90 second=117 amount=-1
+kerning first=89 second=41 amount=1
+kerning first=65 second=121 amount=-4
+kerning first=89 second=100 amount=-2
+kerning first=89 second=42 amount=-2
+kerning first=76 second=117 amount=-2
+kerning first=69 second=111 amount=-1
+kerning first=46 second=39 amount=-6
+kerning first=118 second=39 amount=1
+kerning first=91 second=85 amount=-1
+kerning first=80 second=90 amount=-1
+kerning first=90 second=81 amount=-1
+kerning first=69 second=117 amount=-1
+kerning first=76 second=39 amount=-5
+kerning first=90 second=67 amount=-1
+kerning first=87 second=103 amount=-1
+kerning first=84 second=120 amount=-3
+kerning first=89 second=101 amount=-2
+kerning first=102 second=125 amount=1
+kerning first=76 second=85 amount=-2
+kerning first=79 second=65 amount=-3
+kerning first=65 second=71 amount=-3
+kerning first=79 second=44 amount=-4
+kerning first=97 second=39 amount=-2
+kerning first=90 second=101 amount=-1
+kerning first=65 second=87 amount=-5
+kerning first=79 second=46 amount=-4
+kerning first=87 second=99 amount=-1
+kerning first=34 second=101 amount=-2
+kerning first=40 second=89 amount=1
+kerning first=76 second=89 amount=-8
+kerning first=69 second=113 amount=-1
+kerning first=120 second=103 amount=-1
+kerning first=69 second=101 amount=-1
+kerning first=69 second=102 amount=-1
+kerning first=104 second=39 amount=-1
+kerning first=80 second=121 amount=1
+kerning first=86 second=46 amount=-8
+kerning first=65 second=81 amount=-3
+kerning first=86 second=44 amount=-8
+kerning first=120 second=99 amount=-1
+kerning first=98 second=120 amount=-1
+kerning first=39 second=115 amount=-3
+kerning first=121 second=39 amount=1
+kerning first=88 second=118 amount=-1
+kerning first=84 second=65 amount=-6
+kerning first=65 second=39 amount=-4
+kerning first=84 second=79 amount=-1
+kerning first=65 second=119 amount=-4
+kerning first=70 second=117 amount=-1
+kerning first=75 second=100 amount=-1
+kerning first=86 second=111 amount=-2
+kerning first=122 second=111 amount=-1
+kerning first=81 second=84 amount=-2
+kerning first=107 second=103 amount=-1
+kerning first=118 second=44 amount=-4
+kerning first=87 second=46 amount=-4
+kerning first=87 second=101 amount=-1
+kerning first=70 second=79 amount=-2
+kerning first=87 second=74 amount=-2
+kerning first=123 second=74 amount=-1
+kerning first=76 second=71 amount=-2
+kerning first=39 second=100 amount=-2
+kerning first=80 second=88 amount=-1
+kerning first=84 second=121 amount=-3
+kerning first=112 second=122 amount=-1
+kerning first=84 second=71 amount=-1
+kerning first=89 second=86 amount=1
+kerning first=84 second=113 amount=-3
+kerning first=120 second=113 amount=-1
+kerning first=89 second=44 amount=-7
+kerning first=84 second=99 amount=-3
+kerning first=34 second=113 amount=-2
+kerning first=80 second=46 amount=-11
+kerning first=86 second=117 amount=-1
+kerning first=110 second=34 amount=-1
+kerning first=80 second=74 amount=-7
+kerning first=120 second=101 amount=-1
+kerning first=73 second=88 amount=1
+kerning first=108 second=111 amount=-1
+kerning first=34 second=115 amount=-3
+kerning first=89 second=113 amount=-2
+kerning first=82 second=86 amount=-3
+kerning first=114 second=39 amount=1
+kerning first=34 second=109 amount=-1
+kerning first=84 second=101 amount=-3
+kerning first=70 second=121 amount=-1
+kerning first=123 second=85 amount=-1
+kerning first=122 second=103 amount=-1
+kerning first=86 second=97 amount=-2
+kerning first=82 second=89 amount=-4
+kerning first=66 second=84 amount=-1
+kerning first=84 second=97 amount=-4
+kerning first=86 second=103 amount=-2
+kerning first=70 second=113 amount=-1
+kerning first=84 second=87 amount=1
+kerning first=75 second=112 amount=-1
+kerning first=114 second=111 amount=-1
+kerning first=39 second=112 amount=-1
+kerning first=107 second=101 amount=-1
+kerning first=82 second=84 amount=-3
+kerning first=114 second=121 amount=1
+kerning first=34 second=99 amount=-2
+kerning first=70 second=81 amount=-2
+kerning first=111 second=122 amount=-1
+kerning first=84 second=67 amount=-1
+kerning first=111 second=108 amount=-1
+kerning first=89 second=84 amount=1
+kerning first=76 second=79 amount=-2
+kerning first=85 second=65 amount=-2
+kerning first=44 second=34 amount=-6
+kerning first=65 second=67 amount=-3
+kerning first=109 second=34 amount=-1
+kerning first=114 second=103 amount=-1
+kerning first=78 second=89 amount=-1
+kerning first=89 second=114 amount=-1
+kerning first=89 second=112 amount=-1
+kerning first=34 second=65 amount=-4
+kerning first=70 second=65 amount=-11
+kerning first=81 second=86 amount=-1
+kerning first=114 second=119 amount=1
+kerning first=89 second=102 amount=-1
+kerning first=84 second=45 amount=-8
+kerning first=86 second=125 amount=1
+kerning first=70 second=67 amount=-2
+kerning first=89 second=116 amount=-1
+kerning first=102 second=34 amount=1
+kerning first=114 second=99 amount=-1
+kerning first=67 second=84 amount=-1
+kerning first=114 second=113 amount=-1
+kerning first=89 second=122 amount=-1
+kerning first=89 second=118 amount=-1
+kerning first=70 second=71 amount=-2
+kerning first=114 second=107 amount=-1
+kerning first=89 second=120 amount=-1

BIN
src/web/static/fonts/bmfonts/RobotoSlab72White.png


+ 44 - 8
src/web/stylesheets/components/_operation.css

@@ -82,11 +82,47 @@ div.toggle-string {
 .operation .is-focused [class*=' bmd-label'],
 .operation .is-focused label,
 .operation .checkbox label:hover {
-    color: #1976d2;
+    color: var(--input-highlight-colour);
+}
+
+.ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check,
+.ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check::before {
+    border-color: var(--input-border-colour);
+    color: var(--input-highlight-colour);
+}
+
+.ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check,
+.ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check::before {
+    border-color: var(--input-highlight-colour);
+    color: var(--input-highlight-colour);
+}
+
+.disabled .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check,
+.disabled .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check::before,
+.disabled .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check,
+.disabled .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check::before {
+    border-color: var(--disabled-font-colour);
+    color: var(--disabled-font-colour);
+}
+
+.break .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check,
+.break .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check::before,
+.break .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check,
+.break .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check::before {
+    border-color: var(--breakpoint-font-colour);
+    color: var(--breakpoint-font-colour);
+}
+
+.flow-control-op.break .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check,
+.flow-control-op.break .ingredients .checkbox label input[type=checkbox]+.checkbox-decorator .check::before,
+.flow-control-op.break .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check,
+.flow-control-op.break .ingredients .checkbox label input[type=checkbox]:checked+.checkbox-decorator .check::before {
+    border-color: var(--fc-breakpoint-operation-font-colour);
+    color: var(--fc-breakpoint-operation-font-colour);
 }
 
 .operation .form-control {
-    padding: 20px 12px 6px 12px;
+    padding: 20px 12px 6px 12px !important;
     border-top-left-radius: 4px;
     border-top-right-radius: 4px;
     background-image: none;
@@ -97,7 +133,7 @@ div.toggle-string {
 
 .operation .form-control:hover {
     background-image:
-        linear-gradient(to top, #1976d2 2px, rgba(25, 118, 210, 0) 2px),
+        linear-gradient(to top, var(--input-highlight-colour) 2px, rgba(25, 118, 210, 0) 2px),
         linear-gradient(to top, rgba(0, 0, 0, 0.26) 1px, rgba(0, 0, 0, 0) 1px);
     filter: brightness(97%);
 }
@@ -105,7 +141,7 @@ div.toggle-string {
 .operation .form-control:focus {
     background-color: var(--arg-background);
     background-image:
-        linear-gradient(to top, #1976d2 2px, rgba(25, 118, 210, 0) 2px),
+        linear-gradient(to top, var(--input-highlight-colour) 2px, rgba(25, 118, 210, 0) 2px),
         linear-gradient(to top, rgba(0, 0, 0, 0.26) 1px, rgba(0, 0, 0, 0) 1px);
     filter: brightness(100%);
 }
@@ -205,19 +241,19 @@ div.toggle-string {
 }
 
 .disable-icon {
-    color: #9e9e9e;
+    color: var(--disable-icon-colour);
 }
 
 .disable-icon-selected {
-    color: #f44336;
+    color: var(--disable-icon-selected-colour);
 }
 
 .breakpoint {
-    color: #9e9e9e;
+    color: var(--breakpoint-icon-colour);
 }
 
 .breakpoint-selected {
-    color: #f44336;
+    color: var(--breakpoint-icon-selected-colour);
 }
 
 .break {

+ 12 - 4
src/web/stylesheets/components/_pane.css

@@ -8,6 +8,7 @@
 
 :root {
     --title-height: 48px;
+    --tab-height: 40px;
 }
 
 .title {
@@ -52,6 +53,7 @@
     line-height: 30px;
     background-color: var(--primary-background-colour);
     flex-direction: row;
+    padding-left: 10px;
 }
 
 .io-card.card:hover {
@@ -60,10 +62,16 @@
 
 .io-card.card>img {
     float: left;
-    width: 128px;
-    height: 128px;
-    margin-left: 10px;
-    margin-top: 11px;
+    width: auto;
+    height: auto;
+    max-width: 128px;
+    max-height: 128px;
+    margin-left: auto;
+    margin-top: auto;
+    margin-right: auto;
+    margin-bottom: auto;
+    padding: 0px;
+
 }
 
 .io-card.card .card-body .close {

+ 2 - 0
src/web/stylesheets/index.css

@@ -10,6 +10,8 @@
 @import "./themes/_classic.css";
 @import "./themes/_dark.css";
 @import "./themes/_geocities.css";
+@import "./themes/_solarizedDark.css";
+@import "./themes/_solarizedLight.css";
 
 /* Utilities */
 @import "./utils/_overrides.css";

+ 4 - 0
src/web/stylesheets/layout/_banner.css

@@ -22,6 +22,10 @@
     padding-right: 10px;
 }
 
+#banner a {
+    color: var(--banner-url-colour);
+}
+
 #notice-wrapper {
     text-align: center;
     overflow: hidden;

+ 26 - 0
src/web/stylesheets/layout/_controls.css

@@ -21,6 +21,14 @@
     background-color: var(--secondary-background-colour);
 }
 
+#controls-content {
+    position: relative;
+    left: 50%;
+    top: 50%;
+    transform: translate(-50%, -50%);
+    transform-origin: center left;
+}
+
 #auto-bake-label {
     display: inline-block;
     width: 100px;
@@ -32,6 +40,12 @@
     cursor: pointer;
 }
 
+#auto-bake-label .check,
+#auto-bake-label .check::before {
+    border-color: var(--input-highlight-colour);
+    color: var(--input-highlight-colour);
+}
+
 #auto-bake-label .checkbox-decorator {
     position: relative;
 }
@@ -43,3 +57,15 @@
 #controls .btn {
     border-radius: 30px;
 }
+
+.spin {
+    animation-name: spin;
+    animation-duration: 3s;
+    animation-iteration-count: infinite;
+    animation-timing-function: linear;
+}
+
+@keyframes spin {
+    0%      {transform: rotate(0deg);}
+    100%    {transform: rotate(360deg);}
+}

+ 263 - 12
src/web/stylesheets/layout/_io.css

@@ -24,18 +24,172 @@
     word-wrap: break-word;
 }
 
+#output-wrapper{
+    margin: 0;
+    padding: 0;
+}
+
+#output-wrapper .textarea-wrapper {
+    width: 100%;
+    height: 100%;
+    box-sizing: border-box;
+    overflow: hidden;
+    pointer-events: auto;
+}
+
+
 #output-html {
     display: none;
     overflow-y: auto;
     -moz-padding-start: 1px; /* Fixes bug in Firefox */
 }
 
-.textarea-wrapper {
-    position: absolute;
-    top: var(--title-height);
-    bottom: 0;
+#input-tabs-wrapper #input-tabs,
+#output-tabs-wrapper #output-tabs {
+    list-style: none;
+    background-color: var(--title-background-colour);
+    padding: 0;
+    margin: 0;
+    overflow-x: auto;
+    overflow-y: hidden;
+    display: flex;
+    flex-direction: row;
+    border-bottom: 1px solid var(--primary-border-colour);
+    border-left: 1px solid var(--primary-border-colour);
+    height: var(--tab-height);
+    clear: none;
+}
+
+#input-tabs li,
+#output-tabs li {
+    display: flex;
+    flex-direction: row;
+    width: 100%;
+    min-width: 120px;
+    float: left;
+    padding: 0px;
+    text-align: center;
+    border-right: 1px solid var(--primary-border-colour);
+    height: var(--tab-height);
+    vertical-align: middle;
+}
+
+#input-tabs li:hover,
+#output-tabs li:hover {
+    cursor: pointer;
+    background-color: var(--primary-background-colour);
+}
+
+.active-input-tab,
+.active-output-tab {
+    font-weight: bold;
+    background-color: var(--primary-background-colour);
+}
+
+.input-tab-content+.btn-close-tab {
+    display: block;
+    margin-top: auto;
+    margin-bottom: auto;
+    margin-right: 2px;
+}
+
+.input-tab-content+.btn-close-tab i {
+    font-size: 0.8em;
+}
+
+.input-tab-buttons,
+.output-tab-buttons {
+    width: 25px;
+    text-align: center;
+    margin: 0;
+    height: var(--tab-height);
+    line-height: var(--tab-height);
+    font-weight: bold;
+    background-color: var(--title-background-colour);
+    border-bottom: 1px solid var(--primary-border-colour);
+}
+
+.input-tab-buttons:hover,
+.output-tab-buttons:hover {
+    cursor: pointer;
+    background-color: var(--primary-background-colour);
+}
+
+
+#btn-next-input-tab,
+#btn-input-tab-dropdown,
+#btn-next-output-tab,
+#btn-output-tab-dropdown {
+    float: right;
+}
+
+#btn-previous-input-tab,
+#btn-previous-output-tab {
+    float: left;
+}
+
+#btn-close-all-tabs {
+    color: var(--breakpoint-font-colour) !important;
+}
+
+.input-tab-content,
+.output-tab-content {
+    width: 100%;
+    max-width: 100%;
+    padding-left: 5px;
+    padding-right: 5px;
+    padding-top: 10px;
+    padding-bottom: 10px;
+    height: var(--tab-height);
+    vertical-align: middle;
+    overflow: hidden;
+    white-space: nowrap;
+    text-overflow: ellipsis;
+}
+
+.btn-close-tab {
+    height: var(--tab-height);
+    vertical-align: middle;
+    width: fit-content;
+}
+
+.tabs-left > li:first-child {
+    box-shadow: 15px 0px 15px -15px var(--primary-border-colour) inset;
+}
+
+.tabs-right > li:last-child {
+    box-shadow: -15px 0px 15px -15px var(--primary-border-colour) inset;
+}
+
+#input-wrapper,
+#output-wrapper,
+#input-wrapper > * ,
+#output-wrapper > .textarea-wrapper > div,
+#output-wrapper > .textarea-wrapper > textarea {
+    height: calc(100% - var(--title-height));
+}
+
+#input-wrapper.show-tabs,
+#input-wrapper.show-tabs > *,
+#output-wrapper.show-tabs,
+#output-wrapper.show-tabs > .textarea-wrapper > div,
+#output-wrapper.show-tabs > .textarea-wrapper > textarea {
+    height: calc(100% - var(--tab-height) - var(--title-height));
+}
+
+#output-wrapper > .textarea-wrapper > #output-html {
+    height: 100%;
+}
+
+#show-file-overlay {
+    height: 32px;
+}
+
+.input-wrapper.textarea-wrapper {
     width: 100%;
+    box-sizing: border-box;
     overflow: hidden;
+    pointer-events: auto;
 }
 
 .textarea-wrapper textarea,
@@ -49,9 +203,8 @@
 #output-highlighter {
     position: absolute;
     left: 0;
-    top: 0;
+    bottom: 0;
     width: 100%;
-    height: 100%;
     padding: 3px;
     margin: 0;
     overflow: hidden;
@@ -61,14 +214,14 @@
     color: #fff;
     background-color: transparent;
     border: none;
+    pointer-events: none;
 }
 
 #output-loader {
     position: absolute;
-    top: 0;
+    bottom: 0;
     left: 0;
     width: 100%;
-    height: 100%;
     margin: 0;
     background-color: var(--primary-background-colour);
     visibility: hidden;
@@ -105,9 +258,8 @@
 #output-file {
     position: absolute;
     left: 0;
-    top: 0;
+    bottom: 0;
     width: 100%;
-    height: 100%;
     display: none;
 }
 
@@ -122,7 +274,7 @@
 #show-file-overlay {
     position: absolute;
     right: 15px;
-    top: 15px;
+    top: calc(var(--title-height) + 10px);
     cursor: pointer;
     display: none;
 }
@@ -147,7 +299,6 @@
 
 .dropping-file {
     border: 5px dashed var(--drop-file-border-colour) !important;
-    margin: -5px;
 }
 
 #stale-indicator {
@@ -185,3 +336,103 @@
 #magic svg path {
     fill: var(--primary-font-colour);
 }
+
+#input-find-options,
+#output-find-options {
+    display: flex;
+    flex-direction: row;
+    flex-wrap: wrap;
+    width: 100%;
+}
+
+#input-tab-body .form-group.input-group,
+#output-tab-body .form-group.input-group {
+    width: 70%;
+    float: left;
+    margin-bottom: 2rem;
+}
+
+.input-find-option .toggle-string {
+    width: 70%;
+    display: inline-block;
+}
+
+.input-find-option-append button {
+    border-top-right-radius: 4px;
+    background-color: var(--arg-background) !important;
+    margin: unset;
+}
+
+.input-find-option-append button:hover {
+    filter: brightness(97%);
+}
+
+.form-group.output-find-option {
+    width: 70%;
+    float: left;
+}
+
+#input-num-results-container,
+#output-num-results-container {
+    width: 20%;
+    float: right;
+    margin: 0;
+    margin-left: 10%;
+}
+
+#input-find-options-checkboxes,
+#output-find-options-checkboxes {
+    list-style: none;
+    padding: 0;
+    margin: auto;
+    overflow-x: auto;
+    overflow-y: hidden;
+    text-align: center;
+    width: fit-content;
+}
+
+#input-find-options-checkboxes li,
+#output-find-options-checkboxes li {
+    display: flex;
+    flex-direction: row;
+    float: left;
+    padding: 10px;
+    text-align: center;
+}
+
+
+#input-search-results,
+#output-search-results {
+    list-style: none;
+    width: 75%;
+    min-width: 200px;
+    margin-left: auto;
+    margin-right: auto;
+}
+
+#input-search-results li,
+#output-search-results li {
+    padding-left: 5px;
+    padding-right: 5px;
+    padding-top: 10px;
+    padding-bottom: 10px;
+    text-align: center;
+    width: 100%;
+    color: var(--op-list-operation-font-colour);
+    background-color: var(--op-list-operation-bg-colour);
+    border-bottom: 2px solid var(--op-list-operation-border-colour);
+    overflow: hidden;
+    white-space: nowrap;
+    text-overflow: ellipsis;
+}
+
+#input-search-results li:first-of-type,
+#output-search-results li:first-of-type {
+    border-top: 2px solid var(--op-list-operation-border-colour);
+}
+
+#input-search-results li:hover,
+#output-search-results li:hover {
+    cursor: pointer;
+    filter: brightness(98%);
+}

+ 31 - 0
src/web/stylesheets/layout/_modals.css

@@ -77,3 +77,34 @@
     padding: 20px;
     border-left: 2px solid var(--primary-border-colour);
 }
+
+.checkbox label input[type=checkbox]+.checkbox-decorator .check,
+.checkbox label input[type=checkbox]+.checkbox-decorator .check::before {
+    border-color: var(--input-border-colour);
+    color: var(--input-highlight-colour);
+}
+
+.checkbox label input[type=checkbox]:checked+.checkbox-decorator .check,
+.checkbox label input[type=checkbox]:checked+.checkbox-decorator .check::before {
+    border-color: var(--input-highlight-colour);
+    color: var(--input-highlight-colour);
+}
+
+.bmd-form-group.is-focused .option-item label {
+    color: var(--input-highlight-colour);
+}
+
+.bmd-form-group.is-focused [class^='bmd-label'],
+.bmd-form-group.is-focused [class*=' bmd-label'],
+.bmd-form-group.is-focused [class^='bmd-label'],
+.bmd-form-group.is-focused [class*=' bmd-label'],
+.bmd-form-group.is-focused label,
+.checkbox label:hover {
+    color: var(--input-highlight-colour);
+}
+
+.bmd-form-group.option-item label+.form-control{
+    background-image:
+        linear-gradient(to top, var(--input-highlight-colour) 2px, rgba(0, 0, 0, 0) 2px),
+        linear-gradient(to top, var(--primary-border-colour) 1px, rgba(0, 0, 0, 0) 1px);
+}

+ 2 - 2
src/web/stylesheets/layout/_operations.css

@@ -16,7 +16,7 @@
     padding-left: 10px;
     padding-right: 10px;
     background-image:
-        linear-gradient(to top, #1976d2 2px, rgba(25, 118, 210, 0) 2px),
+        linear-gradient(to top, var(--input-highlight-colour) 2px, rgba(0, 0, 0, 0) 2px),
         linear-gradient(to top, var(--primary-border-colour) 1px, rgba(0, 0, 0, 0) 1px);
 }
 
@@ -33,7 +33,7 @@
 }
 
 #categories a {
-    color: #1976d2;
+    color: var(--category-list-font-colour);
     cursor: pointer;
 }
 

+ 5 - 5
src/web/stylesheets/preloader.css

@@ -6,14 +6,14 @@
  * @license Apache-2.0
  */
 
-#loader-wrapper {
+ #loader-wrapper {
     position: fixed;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     z-index: 1000;
-    background-color: var(--secondary-border-colour);
+    background-color: var(--loader-background-colour);
 }
 
 .loader {
@@ -26,7 +26,7 @@
     margin: -75px 0 0 -75px;
 
     border: 3px solid transparent;
-    border-top-color: #3498db;
+    border-top-color: var(--loader-outer-colour);
     border-radius: 50%;
 
     animation: spin 2s linear infinite;
@@ -45,7 +45,7 @@
     left: 5px;
     right: 5px;
     bottom: 5px;
-    border-top-color: #e74c3c;
+    border-top-color: var(--loader-middle-colour);
     animation: spin 3s linear infinite;
 }
 
@@ -54,7 +54,7 @@
     left: 13px;
     right: 13px;
     bottom: 13px;
-    border-top-color: #f9c922;
+    border-top-color: var(--loader-inner-colour);
     animation: spin 1.5s linear infinite;
 }
 

+ 17 - 0
src/web/stylesheets/themes/_classic.css

@@ -35,6 +35,14 @@
 
     --banner-font-colour: #468847;
     --banner-bg-colour: #dff0d8;
+    --banner-url-colour: #1976d2;
+
+    --category-list-font-colour: #1976d2;
+
+    --loader-background-colour: var(--secondary-border-colour);
+    --loader-outer-colour: #3498db;
+    --loader-middle-colour: #e74c3c;
+    --loader-inner-colour: #f9c922;
 
 
     /* Operation colours */
@@ -76,6 +84,13 @@
     --arg-label-colour: #388e3c;
 
 
+    /* Operation buttons */
+    --disable-icon-colour: #9e9e9e;
+    --disable-icon-selected-colour: #f44336;
+    --breakpoint-icon-colour: #9e9e9e;
+    --breakpoint-icon-selected-colour: #f44336;
+
+
     /* Buttons */
     --btn-default-font-colour: #333;
     --btn-default-bg-colour: #fff;
@@ -114,4 +129,6 @@
     --popover-border-colour: #ccc;
     --code-background: #f9f2f4;
     --code-font-colour: #c7254e;
+    --input-highlight-colour: #1976d2;
+    --input-border-colour: #424242;
 }

+ 17 - 0
src/web/stylesheets/themes/_dark.css

@@ -31,6 +31,14 @@
 
     --banner-font-colour: #c5c5c5;
     --banner-bg-colour: #252525;
+    --banner-url-colour: #1976d2;
+
+    --category-list-font-colour: #1976d2;
+
+    --loader-background-colour: var(--secondary-border-colour);
+    --loader-outer-colour: #3498db;
+    --loader-middle-colour: #e74c3c;
+    --loader-inner-colour: #f9c922;
 
 
     /* Operation colours */
@@ -72,6 +80,13 @@
     --arg-label-colour: rgb(25, 118, 210);
 
 
+    /* Operation buttons */
+    --disable-icon-colour: #9e9e9e;
+    --disable-icon-selected-colour: #f44336;
+    --breakpoint-icon-colour: #9e9e9e;
+    --breakpoint-icon-selected-colour: #f44336;
+
+
     /* Buttons */
     --btn-default-font-colour: #c5c5c5;
     --btn-default-bg-colour: #2d2d2d;
@@ -110,4 +125,6 @@
     --popover-border-colour: #555;
     --code-background: #0e639c;
     --code-font-colour: #fff;
+    --input-highlight-colour: #1976d2;
+    --input-border-colour: #424242;
 }

+ 17 - 0
src/web/stylesheets/themes/_geocities.css

@@ -31,6 +31,14 @@
 
     --banner-font-colour: white;
     --banner-bg-colour: maroon;
+    --banner-url-colour: yellow;
+
+    --category-list-font-colour: yellow;
+
+    --loader-background-colour: #00f;
+    --loader-outer-colour: #0f0;
+    --loader-middle-colour: red;
+    --loader-inner-colour: yellow;
 
 
     /* Operation colours */
@@ -72,6 +80,13 @@
     --arg-label-colour: red;
 
 
+    /* Operation buttons */
+    --disable-icon-colour: #0f0;
+    --disable-icon-selected-colour: yellow;
+    --breakpoint-icon-colour: #0f0;
+    --breakpoint-icon-selected-colour: yellow;
+
+
     /* Buttons */
     --btn-default-font-colour: black;
     --btn-default-bg-colour: white;
@@ -110,4 +125,6 @@
     --popover-border-colour: violet;
     --code-background: black;
     --code-font-colour: limegreen;
+    --input-highlight-colour: limegreen;
+    --input-border-colour: limegreen;
 }

+ 147 - 0
src/web/stylesheets/themes/_solarizedDark.css

@@ -0,0 +1,147 @@
+/**
+ * Solarized dark theme definitions
+ *
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+:root.solarizedDark {
+    --base03: #002b36;
+    --base02: #073642;
+    --base01: #586e75;
+    --base00: #657b83;
+    --base0: #839496;
+    --base1: #93a1a1;
+    --base2: #eee8d5;
+    --base3: #fdf6e3;
+    --sol-yellow: #b58900;
+    --sol-orange: #cb4b16;
+    --sol-red: #dc322f;
+    --sol-magenta: #d33682;
+    --sol-violet: #6c71c4;
+    --sol-blue: #268bd2;
+    --sol-cyan: #2aa198;
+    --sol-green: #859900;
+
+    --primary-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
+        Roboto, "Helvetica Neue", Arial, sans-serif;
+    --primary-font-colour: var(--base0);
+    --primary-font-size: 14px;
+    --primary-line-height: 20px;
+
+    --fixed-width-font-family: SFMono-Regular, Menlo, Monaco, Consolas,
+        "Liberation Mono", "Courier New", monospace;
+    --fixed-width-font-colour: inherit;
+    --fixed-width-font-size: inherit;
+
+    --subtext-font-colour: var(--base01);
+    --subtext-font-size: 13px;
+
+    --primary-background-colour: var(--base03);
+    --secondary-background-colour: var(--base02);
+
+    --primary-border-colour: var(--base00);
+    --secondary-border-colour: var(--base01);
+
+    --title-colour: var(--base1);
+    --title-weight: bold;
+    --title-background-colour: var(--base02);
+
+    --banner-font-colour: var(--base0);
+    --banner-bg-colour: var(--base03);
+    --banner-url-colour: var(--base1);
+
+    --category-list-font-colour: var(--base1);
+
+    --loader-background-colour: var(--base03);
+    --loader-outer-colour: var(--base1);
+    --loader-middle-colour: var(--base0);
+    --loader-inner-colour: var(--base00);
+
+
+    /* Operation colours */
+    --op-list-operation-font-colour: var(--base0);
+    --op-list-operation-bg-colour: var(--base03);
+    --op-list-operation-border-colour: var(--base02);
+
+    --rec-list-operation-font-colour: var(--base0);
+    --rec-list-operation-bg-colour: var(--base02);
+    --rec-list-operation-border-colour: var(--base01);
+
+    --selected-operation-font-color: var(--base1);
+    --selected-operation-bg-colour: var(--base02);
+    --selected-operation-border-colour: var(--base01);
+
+    --breakpoint-font-colour: var(--sol-red);
+    --breakpoint-bg-colour: var(--base02);
+    --breakpoint-border-colour: var(--base00);
+
+    --disabled-font-colour: var(--base01);
+    --disabled-bg-colour: var(--base03);
+    --disabled-border-colour: var(--base02);
+
+    --fc-operation-font-colour: var(--base1);
+    --fc-operation-bg-colour: var(--base02);
+    --fc-operation-border-colour: var(--base01);
+
+    --fc-breakpoint-operation-font-colour: var(--sol-orange);
+    --fc-breakpoint-operation-bg-colour: var(--base02);
+    --fc-breakpoint-operation-border-colour: var(--base00);
+
+
+    /* Operation arguments */
+    --op-title-font-weight: bold;
+    --arg-font-colour: var(--base0);
+    --arg-background: var(--base03);
+    --arg-border-colour: var(--base00);
+    --arg-disabled-background: var(--base03);
+    --arg-label-colour: var(--base1);
+
+
+    /* Operation buttons */
+    --disable-icon-colour: var(--base00);
+    --disable-icon-selected-colour: var(--sol-red);
+    --breakpoint-icon-colour: var(--base00);
+    --breakpoint-icon-selected-colour: var(--sol-red);
+
+    /* Buttons */
+    --btn-default-font-colour: var(--base0);
+    --btn-default-bg-colour: var(--base02);
+    --btn-default-border-colour: var(--base01);
+
+    --btn-default-hover-font-colour: var(--base1);
+    --btn-default-hover-bg-colour: var(--base01);
+    --btn-default-hover-border-colour: var(--base00);
+
+    --btn-success-font-colour: var(--base0);
+    --btn-success-bg-colour: var(--base03);
+    --btn-success-border-colour: var(--base00);
+
+    --btn-success-hover-font-colour: var(--base1);
+    --btn-success-hover-bg-colour: var(--base01);
+    --btn-success-hover-border-colour: var(--base00);
+
+    /* Highlighter colours */
+    --hl1: var(--base01);
+    --hl2: var(--sol-blue);
+    --hl3: var(--sol-magenta);
+    --hl4: var(--sol-yellow);
+    --hl5: var(--sol-green);
+
+
+    /* Scrollbar */
+    --scrollbar-track: var(--base03);
+    --scrollbar-thumb: var(--base00);
+    --scrollbar-hover: var(--base01);
+
+
+    /* Misc. */
+    --drop-file-border-colour: var(--base01);
+    --popover-background: var(--base02);
+    --popover-border-colour: var(--base01);
+    --code-background: var(--base03);
+    --code-font-colour: var(--base1);
+    --input-highlight-colour: var(--base1);
+    --input-border-colour: var(--base0);
+}

+ 149 - 0
src/web/stylesheets/themes/_solarizedLight.css

@@ -0,0 +1,149 @@
+/**
+ * Solarized light theme definitions
+ *
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2019
+ * @license Apache-2.0
+ */
+
+:root.solarizedLight {
+    --base03: #002b36;
+    --base02: #073642;
+    --base01: #586e75;
+    --base00: #657b83;
+    --base0: #839496;
+    --base1: #93a1a1;
+    --base2: #eee8d5;
+    --base3: #fdf6e3;
+    --sol-yellow: #b58900;
+    --sol-orange: #cb4b16;
+    --sol-red: #dc322f;
+    --sol-magenta: #d33682;
+    --sol-violet: #6c71c4;
+    --sol-blue: #268bd2;
+    --sol-cyan: #2aa198;
+    --sol-green: #859900;
+
+    --primary-font-family: -apple-system, BlinkMacSystemFont, "Segoe UI",
+        Roboto, "Helvetica Neue", Arial, sans-serif;
+    --primary-font-colour: var(--base00);
+    --primary-font-size: 14px;
+    --primary-line-height: 20px;
+
+    --fixed-width-font-family: SFMono-Regular, Menlo, Monaco, Consolas,
+        "Liberation Mono", "Courier New", monospace;
+    --fixed-width-font-colour: inherit;
+    --fixed-width-font-size: inherit;
+
+    --subtext-font-colour: var(--base1);
+    --subtext-font-size: 13px;
+
+    --primary-background-colour: var(--base3);
+    --secondary-background-colour: var(--base2);
+
+    --primary-border-colour: var(--base0);
+    --secondary-border-colour: var(--base1);
+
+    --title-colour: var(--base01);
+    --title-weight: bold;
+    --title-background-colour: var(--base2);
+
+    --banner-font-colour: var(--base00);
+    --banner-bg-colour: var(--base3);
+    --banner-url-colour: var(--base01);
+
+    --category-list-font-colour: var(--base01);
+
+    --loader-background-colour: var(--base3);
+    --loader-outer-colour: var(--base01);
+    --loader-middle-colour: var(--base00);
+    --loader-inner-colour: var(--base0);
+
+
+    /* Operation colours */
+    --op-list-operation-font-colour: var(--base00);
+    --op-list-operation-bg-colour: var(--base3);
+    --op-list-operation-border-colour: var(--base2);
+
+    --rec-list-operation-font-colour: var(--base00);
+    --rec-list-operation-bg-colour: var(--base2);
+    --rec-list-operation-border-colour: var(--base1);
+
+    --selected-operation-font-color: var(--base01);
+    --selected-operation-bg-colour: var(--base2);
+    --selected-operation-border-colour: var(--base1);
+
+    --breakpoint-font-colour: var(--sol-red);
+    --breakpoint-bg-colour: var(--base2);
+    --breakpoint-border-colour: var(--base0);
+
+    --disabled-font-colour: var(--base1);
+    --disabled-bg-colour: var(--base3);
+    --disabled-border-colour: var(--base2);
+
+    --fc-operation-font-colour: var(--base01);
+    --fc-operation-bg-colour: var(--base2);
+    --fc-operation-border-colour: var(--base1);
+
+    --fc-breakpoint-operation-font-colour: var(--base02);
+    --fc-breakpoint-operation-bg-colour: var(--base1);
+    --fc-breakpoint-operation-border-colour: var(--base0);
+
+
+    /* Operation arguments */
+    --op-title-font-weight: bold;
+    --arg-font-colour: var(--base00);
+    --arg-background: var(--base3);
+    --arg-border-colour: var(--base0);
+    --arg-disabled-background: var(--base3);
+    --arg-label-colour: var(--base01);
+
+
+    /* Operation buttons */
+    --disable-icon-colour: #9e9e9e;
+    --disable-icon-selected-colour: #f44336;
+    --breakpoint-icon-colour: #9e9e9e;
+    --breakpoint-icon-selected-colour: #f44336;
+
+
+    /* Buttons */
+    --btn-default-font-colour: var(--base00);
+    --btn-default-bg-colour: var(--base2);
+    --btn-default-border-colour: var(--base1);
+
+    --btn-default-hover-font-colour: var(--base01);
+    --btn-default-hover-bg-colour: var(--base1);
+    --btn-default-hover-border-colour: var(--base0);
+
+    --btn-success-font-colour: var(--base00);
+    --btn-success-bg-colour: var(--base3);
+    --btn-success-border-colour: var(--base0);
+
+    --btn-success-hover-font-colour: var(--base01);
+    --btn-success-hover-bg-colour: var(--base1);
+    --btn-success-hover-border-colour: var(--base0);
+
+
+    /* Highlighter colours */
+    --hl1: var(--base1);
+    --hl2: var(--sol-blue);
+    --hl3: var(--sol-magenta);
+    --hl4: var(--sol-yellow);
+    --hl5: var(--sol-green);
+
+
+    /* Scrollbar */
+    --scrollbar-track: var(--base3);
+    --scrollbar-thumb: var(--base1);
+    --scrollbar-hover: var(--base0);
+
+
+    /* Misc. */
+    --drop-file-border-colour: var(--base1);
+    --popover-background: var(--base2);
+    --popover-border-colour: var(--base1);
+    --code-background: var(--base3);
+    --code-font-colour: var(--base01);
+    --input-highlight-colour: var(--base01);
+    --input-border-colour: var(--base00);
+}

+ 5 - 2
src/web/stylesheets/utils/_overrides.css

@@ -104,8 +104,11 @@ select.form-control:not([size]):not([multiple]), select.custom-file-control:not(
     color: var(--primary-font-colour);
 }
 
-.form-control {
-    background-image: linear-gradient(to top, rgb(25, 118, 210) 2px, rgba(25, 118, 210, 0) 2px), linear-gradient(to top, var(--primary-border-colour) 1px, rgba(0, 0, 0, 0) 1px);
+.form-control,
+.is-focused .form-control {
+    background-image:
+        linear-gradient(to top, var(--input-highlight-colour) 2px, rgba(0, 0, 0, 0) 2px),
+        linear-gradient(to top, var(--primary-border-colour) 1px, rgba(0, 0, 0, 0) 1px);
 }
 
 code {

+ 2 - 1
src/web/BackgroundWorkerWaiter.mjs → src/web/waiters/BackgroundWorkerWaiter.mjs

@@ -4,7 +4,7 @@
  * @license Apache-2.0
  */
 
-import ChefWorker from "worker-loader?inline&fallback=false!../core/ChefWorker";
+import ChefWorker from "worker-loader?inline&fallback=false!../../core/ChefWorker";
 
 /**
  * Waiter to handle conversations with a ChefWorker in the background.
@@ -68,6 +68,7 @@ class BackgroundWorkerWaiter {
                 break;
             case "optionUpdate":
             case "statusMessage":
+            case "progressMessage":
                 // Ignore these messages
                 break;
             default:

+ 38 - 2
src/web/BindingsWaiter.mjs → src/web/waiters/BindingsWaiter.mjs

@@ -98,11 +98,11 @@ class BindingsWaiter {
                     break;
                 case "Space": // Bake
                     e.preventDefault();
-                    this.app.bake();
+                    this.manager.controls.bakeClick();
                     break;
                 case "Quote": // Step through
                     e.preventDefault();
-                    this.app.bake(true);
+                    this.manager.controls.stepClick();
                     break;
                 case "KeyC": // Clear recipe
                     e.preventDefault();
@@ -120,6 +120,22 @@ class BindingsWaiter {
                     e.preventDefault();
                     this.manager.output.switchClick();
                     break;
+                case "KeyT": // New tab
+                    e.preventDefault();
+                    this.manager.input.addInputClick();
+                    break;
+                case "KeyW": // Close tab
+                    e.preventDefault();
+                    this.manager.input.removeInput(this.manager.tabs.getActiveInputTab());
+                    break;
+                case "ArrowLeft": // Go to previous tab
+                    e.preventDefault();
+                    this.manager.input.changeTabLeft();
+                    break;
+                case "ArrowRight": // Go to next tab
+                    e.preventDefault();
+                    this.manager.input.changeTabRight();
+                    break;
                 default:
                     if (e.code.match(/Digit[0-9]/g)) { // Select nth operation
                         e.preventDefault();
@@ -216,6 +232,26 @@ class BindingsWaiter {
             <td>Ctrl+${modWinLin}+m</td>
             <td>Ctrl+${modMac}+m</td>
         </tr>
+        <tr>
+            <td>Create a new tab</td>
+            <td>Ctrl+${modWinLin}+t</td>
+            <td>Ctrl+${modMac}+t</td>
+        </tr>
+        <tr>
+            <td>Close the current tab</td>
+            <td>Ctrl+${modWinLin}+w</td>
+            <td>Ctrl+${modMac}+w</td>
+        </tr>
+        <tr>
+            <td>Go to next tab</td>
+            <td>Ctrl+${modWinLin}+RightArrow</td>
+            <td>Ctrl+${modMac}+RightArrow</td>
+        </tr>
+        <tr>
+            <td>Go to previous tab</td>
+            <td>Ctrl+${modWinLin}+LeftArrow</td>
+            <td>Ctrl+${modMac}+LeftArrow</td>
+        </tr>
         `;
     }
 

+ 44 - 25
src/web/ControlsWaiter.mjs → src/web/waiters/ControlsWaiter.mjs

@@ -4,8 +4,7 @@
  * @license Apache-2.0
  */
 
-import Utils from "../core/Utils";
-import {toBase64} from "../core/lib/Base64";
+import Utils from "../../core/Utils";
 
 
 /**
@@ -57,10 +56,11 @@ class ControlsWaiter {
      * Handler to trigger baking.
      */
     bakeClick() {
-        if (document.getElementById("bake").textContent.indexOf("Bake") > 0) {
-            this.app.bake();
-        } else {
-            this.manager.worker.cancelBake();
+        const btnBake = document.getElementById("bake");
+        if (btnBake.textContent.indexOf("Bake") > 0) {
+            this.app.manager.input.bakeAll();
+        } else if (btnBake.textContent.indexOf("Cancel") > 0) {
+            this.manager.worker.cancelBake(false, true);
         }
     }
 
@@ -69,7 +69,7 @@ class ControlsWaiter {
      * Handler for the 'Step through' command. Executes the next step of the recipe.
      */
     stepClick() {
-        this.app.bake(true);
+        this.app.step();
     }
 
 
@@ -90,7 +90,7 @@ class ControlsWaiter {
 
 
     /**
-     * Populates the save disalog box with a URL incorporating the recipe and input.
+     * Populates the save dialog box with a URL incorporating the recipe and input.
      *
      * @param {Object[]} [recipeConfig] - The recipe configuration object array.
      */
@@ -112,26 +112,33 @@ class ControlsWaiter {
      *
      * @param {boolean} includeRecipe - Whether to include the recipe in the URL.
      * @param {boolean} includeInput - Whether to include the input in the URL.
+     * @param {string} input
      * @param {Object[]} [recipeConfig] - The recipe configuration object array.
      * @param {string} [baseURL] - The CyberChef URL, set to the current URL if not included
      * @returns {string}
      */
-    generateStateUrl(includeRecipe, includeInput, recipeConfig, baseURL) {
+    generateStateUrl(includeRecipe, includeInput, input, recipeConfig, baseURL) {
         recipeConfig = recipeConfig || this.app.getRecipeConfig();
 
         const link = baseURL || window.location.protocol + "//" +
             window.location.host +
             window.location.pathname;
         const recipeStr = Utils.generatePrettyRecipe(recipeConfig);
-        const inputStr = toBase64(this.app.getInput(), "A-Za-z0-9+/"); // B64 alphabet with no padding
 
         includeRecipe = includeRecipe && (recipeConfig.length > 0);
-        // Only inlcude input if it is less than 50KB (51200 * 4/3 as it is Base64 encoded)
-        includeInput = includeInput && (inputStr.length > 0) && (inputStr.length <= 68267);
+
+        // If we don't get passed an input, get it from the current URI
+        if (input === null) {
+            const params = this.app.getURIParams();
+            if (params.input) {
+                includeInput = true;
+                input = params.input;
+            }
+        }
 
         const params = [
             includeRecipe ? ["recipe", recipeStr] : undefined,
-            includeInput ? ["input", inputStr] : undefined,
+            includeInput ? ["input", input] : undefined,
         ];
 
         const hash = params
@@ -335,7 +342,7 @@ class ControlsWaiter {
         e.preventDefault();
 
         const reportBugInfo = document.getElementById("report-bug-info");
-        const saveLink = this.generateStateUrl(true, true, null, "https://gchq.github.io/CyberChef/");
+        const saveLink = this.generateStateUrl(true, true, null, null, "https://gchq.github.io/CyberChef/");
 
         if (reportBugInfo) {
             reportBugInfo.innerHTML = `* Version: ${PKG_VERSION}
@@ -370,22 +377,34 @@ ${navigator.userAgent}
 
 
     /**
-     * Switches the Bake button between 'Bake' and 'Cancel' functions.
+     * Switches the Bake button between 'Bake', 'Cancel' and 'Loading' functions.
      *
-     * @param {boolean} cancel - Whether to change to cancel or not
+     * @param {string} func - The function to change to. Either "cancel", "loading" or "bake"
      */
-    toggleBakeButtonFunction(cancel) {
+    toggleBakeButtonFunction(func) {
         const bakeButton = document.getElementById("bake"),
             btnText = bakeButton.querySelector("span");
 
-        if (cancel) {
-            btnText.innerText = "Cancel";
-            bakeButton.classList.remove("btn-success");
-            bakeButton.classList.add("btn-danger");
-        } else {
-            btnText.innerText = "Bake!";
-            bakeButton.classList.remove("btn-danger");
-            bakeButton.classList.add("btn-success");
+        switch (func) {
+            case "cancel":
+                btnText.innerText = "Cancel";
+                bakeButton.classList.remove("btn-success");
+                bakeButton.classList.remove("btn-warning");
+                bakeButton.classList.add("btn-danger");
+                break;
+            case "loading":
+                bakeButton.style.background = "";
+                btnText.innerText = "Loading...";
+                bakeButton.classList.remove("btn-success");
+                bakeButton.classList.remove("btn-danger");
+                bakeButton.classList.add("btn-warning");
+                break;
+            default:
+                bakeButton.style.background = "";
+                btnText.innerText = "Bake!";
+                bakeButton.classList.remove("btn-danger");
+                bakeButton.classList.remove("btn-warning");
+                bakeButton.classList.add("btn-success");
         }
     }
 

+ 2 - 0
src/web/HighlighterWaiter.mjs → src/web/waiters/HighlighterWaiter.mjs

@@ -378,6 +378,8 @@ class HighlighterWaiter {
     displayHighlights(pos, direction) {
         if (!pos) return;
 
+        if (this.manager.tabs.getActiveInputTab() !== this.manager.tabs.getActiveOutputTab()) return;
+
         const io = direction === "forward" ? "output" : "input";
 
         document.getElementById(io + "-selection-info").innerHTML = this.selectionInfo(pos[0].start, pos[0].end);

+ 1371 - 0
src/web/waiters/InputWaiter.mjs

@@ -0,0 +1,1371 @@
+/**
+ * @author n1474335 [n1474335@gmail.com]
+ * @author j433866 [j433866@gmail.com]
+ * @copyright Crown Copyright 2016
+ * @license Apache-2.0
+ */
+
+import LoaderWorker from "worker-loader?inline&fallback=false!../workers/LoaderWorker";
+import InputWorker from "worker-loader?inline&fallback=false!../workers/InputWorker";
+import Utils from "../../core/Utils";
+import { toBase64 } from "../../core/lib/Base64";
+import { isImage } from "../../core/lib/FileType";
+
+
+/**
+ * Waiter to handle events related to the input.
+ */
+class InputWaiter {
+
+    /**
+     * InputWaiter constructor.
+     *
+     * @param {App} app - The main view object for CyberChef.
+     * @param {Manager} manager - The CyberChef event manager.
+     */
+    constructor(app, manager) {
+        this.app = app;
+        this.manager = manager;
+
+        // Define keys that don't change the input so we don't have to autobake when they are pressed
+        this.badKeys = [
+            16, //Shift
+            17, //Ctrl
+            18, //Alt
+            19, //Pause
+            20, //Caps
+            27, //Esc
+            33, 34, 35, 36, //PgUp, PgDn, End, Home
+            37, 38, 39, 40, //Directional
+            44, //PrntScrn
+            91, 92, //Win
+            93, //Context
+            112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, //F1-12
+            144, //Num
+            145, //Scroll
+        ];
+
+        this.inputWorker = null;
+        this.loaderWorkers = [];
+        this.workerId = 0;
+        this.maxTabs = this.manager.tabs.calcMaxTabs();
+        this.callbacks = {};
+        this.callbackID = 0;
+
+        this.maxWorkers = 1;
+        if (navigator.hardwareConcurrency !== undefined &&
+            navigator.hardwareConcurrency > 1) {
+            // Subtract 1 from hardwareConcurrency value to avoid using
+            // the entire available resources
+            this.maxWorkers = navigator.hardwareConcurrency - 1;
+        }
+    }
+
+    /**
+     * Calculates the maximum number of tabs to display
+     */
+    calcMaxTabs() {
+        const numTabs = this.manager.tabs.calcMaxTabs();
+        if (this.inputWorker && this.maxTabs !== numTabs) {
+            this.maxTabs = numTabs;
+            this.inputWorker.postMessage({
+                action: "updateMaxTabs",
+                data: {
+                    maxTabs: numTabs,
+                    activeTab: this.manager.tabs.getActiveInputTab()
+                }
+            });
+        }
+    }
+
+    /**
+     * Terminates any existing workers and sets up a new InputWorker and LoaderWorker
+     */
+    setupInputWorker() {
+        if (this.inputWorker !== null) {
+            this.inputWorker.terminate();
+            this.inputWorker = null;
+        }
+
+        for (let i = this.loaderWorkers.length - 1; i >= 0; i--) {
+            this.removeLoaderWorker(this.loaderWorkers[i]);
+        }
+
+        log.debug("Adding new InputWorker");
+        this.inputWorker = new InputWorker();
+        this.inputWorker.postMessage({
+            action: "updateMaxWorkers",
+            data: this.maxWorkers
+        });
+        this.inputWorker.postMessage({
+            action: "updateMaxTabs",
+            data: {
+                maxTabs: this.maxTabs,
+                activeTab: this.manager.tabs.getActiveInputTab()
+            }
+        });
+        this.inputWorker.postMessage({
+            action: "setLogLevel",
+            data: log.getLevel()
+        });
+        this.inputWorker.addEventListener("message", this.handleInputWorkerMessage.bind(this));
+    }
+
+    /**
+     * Activates a loaderWorker and sends it to the InputWorker
+     */
+    activateLoaderWorker() {
+        const workerIdx = this.addLoaderWorker();
+        if (workerIdx === -1) return;
+
+        const workerObj = this.loaderWorkers[workerIdx];
+        this.inputWorker.postMessage({
+            action: "loaderWorkerReady",
+            data: {
+                id: workerObj.id
+            }
+        });
+    }
+
+    /**
+     * Adds a new loaderWorker
+     *
+     * @returns {number} - The index of the created worker
+     */
+    addLoaderWorker() {
+        if (this.loaderWorkers.length === this.maxWorkers) {
+            return -1;
+        }
+        log.debug("Adding new LoaderWorker.");
+        const newWorker = new LoaderWorker();
+        const workerId = this.workerId++;
+        newWorker.addEventListener("message", this.handleLoaderMessage.bind(this));
+        newWorker.postMessage({id: workerId});
+        const newWorkerObj = {
+            worker: newWorker,
+            id: workerId
+        };
+        this.loaderWorkers.push(newWorkerObj);
+        return this.loaderWorkers.indexOf(newWorkerObj);
+    }
+
+    /**
+     * Removes a loaderworker
+     *
+     * @param {Object} workerObj - Object containing the loaderWorker and its id
+     * @param {LoaderWorker} workerObj.worker - The actual loaderWorker
+     * @param {number} workerObj.id - The ID of the loaderWorker
+     */
+    removeLoaderWorker(workerObj) {
+        const idx = this.loaderWorkers.indexOf(workerObj);
+        if (idx === -1) {
+            return;
+        }
+        log.debug(`Terminating worker ${this.loaderWorkers[idx].id}`);
+        this.loaderWorkers[idx].worker.terminate();
+        this.loaderWorkers.splice(idx, 1);
+    }
+
+    /**
+     * Finds and returns the object for the loaderWorker of a given id
+     *
+     * @param {number} id - The ID of the loaderWorker to find
+     * @returns {object}
+     */
+    getLoaderWorker(id) {
+        const idx = this.getLoaderWorkerIndex(id);
+        if (idx === -1) return;
+        return this.loaderWorkers[idx];
+    }
+
+    /**
+     * Gets the index for the loaderWorker of a given id
+     *
+     * @param {number} id - The ID of hte loaderWorker to find
+     * @returns {number} The current index of the loaderWorker in the array
+     */
+    getLoaderWorkerIndex(id) {
+        for (let i = 0; i < this.loaderWorkers.length; i++) {
+            if (this.loaderWorkers[i].id === id) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Sends an input to be loaded to the loaderWorker
+     *
+     * @param {object} inputData - Object containing the input to be loaded
+     * @param {File} inputData.file - The actual file object to load
+     * @param {number} inputData.inputNum - The inputNum for the file object
+     * @param {number} inputData.workerId - The ID of the loaderWorker that will load it
+     */
+    loadInput(inputData) {
+        const idx = this.getLoaderWorkerIndex(inputData.workerId);
+        if (idx === -1) return;
+        this.loaderWorkers[idx].worker.postMessage({
+            file: inputData.file,
+            inputNum: inputData.inputNum
+        });
+    }
+
+    /**
+     * Handler for messages sent back by the loaderWorker
+     * Sends the message straight to the inputWorker to be handled there.
+     *
+     * @param {MessageEvent} e
+     */
+    handleLoaderMessage(e) {
+        const r = e.data;
+
+        if (r.hasOwnProperty("progress") && r.hasOwnProperty("inputNum")) {
+            this.manager.tabs.updateInputTabProgress(r.inputNum, r.progress, 100);
+        } else if (r.hasOwnProperty("fileBuffer")) {
+            this.manager.tabs.updateInputTabProgress(r.inputNum, 100, 100);
+        }
+
+        const transferable = r.hasOwnProperty("fileBuffer") ? [r.fileBuffer] : undefined;
+        this.inputWorker.postMessage({
+            action: "loaderWorkerMessage",
+            data: r
+        }, transferable);
+    }
+
+
+    /**
+     * Handler for messages sent back by the inputWorker
+     *
+     * @param {MessageEvent} e
+     */
+    handleInputWorkerMessage(e) {
+        const r = e.data;
+
+        if (!r.hasOwnProperty("action")) {
+            log.error("A message was received from the InputWorker with no action property. Ignoring message.");
+            return;
+        }
+
+        log.debug(`Receiving ${r.action} from InputWorker.`);
+
+        switch (r.action) {
+            case "activateLoaderWorker":
+                this.activateLoaderWorker();
+                break;
+            case "loadInput":
+                this.loadInput(r.data);
+                break;
+            case "terminateLoaderWorker":
+                this.removeLoaderWorker(this.getLoaderWorker(r.data));
+                break;
+            case "refreshTabs":
+                this.refreshTabs(r.data.nums, r.data.activeTab, r.data.tabsLeft, r.data.tabsRight);
+                break;
+            case "changeTab":
+                this.changeTab(r.data, this.app.options.syncTabs);
+                break;
+            case "updateTabHeader":
+                this.manager.tabs.updateInputTabHeader(r.data.inputNum, r.data.input);
+                break;
+            case "loadingInfo":
+                this.showLoadingInfo(r.data, true);
+                break;
+            case "setInput":
+                this.app.debounce(this.set, 50, "setInput", this, [r.data.inputObj, r.data.silent])();
+                break;
+            case "inputAdded":
+                this.inputAdded(r.data.changeTab, r.data.inputNum);
+                break;
+            case "queueInput":
+                this.manager.worker.queueInput(r.data);
+                break;
+            case "queueInputError":
+                this.manager.worker.queueInputError(r.data);
+                break;
+            case "bakeAllInputs":
+                this.manager.worker.bakeAllInputs(r.data);
+                break;
+            case "displayTabSearchResults":
+                this.displayTabSearchResults(r.data);
+                break;
+            case "filterTabError":
+                this.app.handleError(r.data);
+                break;
+            case "setUrl":
+                this.setUrl(r.data);
+                break;
+            case "inputSwitch":
+                this.manager.output.inputSwitch(r.data);
+                break;
+            case "getInput":
+            case "getInputNums":
+                this.callbacks[r.data.id](r.data);
+                break;
+            case "removeChefWorker":
+                this.removeChefWorker();
+                break;
+            default:
+                log.error(`Unknown action ${r.action}.`);
+        }
+    }
+
+    /**
+     * Sends a message to the inputWorker to bake all inputs
+     */
+    bakeAll() {
+        this.app.progress = 0;
+        this.app.debounce(this.manager.controls.toggleBakeButtonFunction, 20, "toggleBakeButton", this, ["loading"]);
+        this.inputWorker.postMessage({
+            action: "bakeAll"
+        });
+    }
+
+    /**
+     * Sets the input in the input area
+     *
+     * @param {object} inputData - Object containing the input and its metadata
+     * @param {number} inputData.inputNum - The unique inputNum for the selected input
+     * @param {string | object} inputData.input - The actual input data
+     * @param {string} inputData.name - The name of the input file
+     * @param {number} inputData.size - The size in bytes of the input file
+     * @param {string} inputData.type - The MIME type of the input file
+     * @param {number} inputData.progress - The load progress of the input file
+     * @param {boolean} [silent=false] - If true, fires the manager statechange event
+     */
+    async set(inputData, silent=false) {
+        return new Promise(function(resolve, reject) {
+            const activeTab = this.manager.tabs.getActiveInputTab();
+            if (inputData.inputNum !== activeTab) return;
+
+            const inputText = document.getElementById("input-text");
+
+            if (typeof inputData.input === "string") {
+                inputText.value = inputData.input;
+                const fileOverlay = document.getElementById("input-file"),
+                    fileName = document.getElementById("input-file-name"),
+                    fileSize = document.getElementById("input-file-size"),
+                    fileType = document.getElementById("input-file-type"),
+                    fileLoaded = document.getElementById("input-file-loaded");
+
+                fileOverlay.style.display = "none";
+                fileName.textContent = "";
+                fileSize.textContent = "";
+                fileType.textContent = "";
+                fileLoaded.textContent = "";
+
+                inputText.style.overflow = "auto";
+                inputText.classList.remove("blur");
+                inputText.scroll(0, 0);
+
+                const lines = inputData.input.length < (this.app.options.ioDisplayThreshold * 1024) ?
+                    inputData.input.count("\n") + 1 : null;
+                this.setInputInfo(inputData.input.length, lines);
+
+                // Set URL to current input
+                const inputStr = toBase64(inputData.input, "A-Za-z0-9+/");
+                if (inputStr.length > 0 && inputStr.length <= 68267) {
+                    this.setUrl({
+                        includeInput: true,
+                        input: inputStr
+                    });
+                }
+
+                if (!silent) window.dispatchEvent(this.manager.statechange);
+            } else {
+                this.setFile(inputData);
+            }
+
+        }.bind(this));
+    }
+
+    /**
+     * Displays file details
+     *
+     * @param {object} inputData - Object containing the input and its metadata
+     * @param {number} inputData.inputNum - The unique inputNum for the selected input
+     * @param {string | object} inputData.input - The actual input data
+     * @param {string} inputData.name - The name of the input file
+     * @param {number} inputData.size - The size in bytes of the input file
+     * @param {string} inputData.type - The MIME type of the input file
+     * @param {number} inputData.progress - The load progress of the input file
+     */
+    setFile(inputData) {
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        if (inputData.inputNum !== activeTab) return;
+
+        const fileOverlay = document.getElementById("input-file"),
+            fileName = document.getElementById("input-file-name"),
+            fileSize = document.getElementById("input-file-size"),
+            fileType = document.getElementById("input-file-type"),
+            fileLoaded = document.getElementById("input-file-loaded");
+
+        fileOverlay.style.display = "block";
+        fileName.textContent = inputData.name;
+        fileSize.textContent = inputData.size + " bytes";
+        fileType.textContent = inputData.type;
+        if (inputData.status === "error") {
+            fileLoaded.textContent = "Error";
+            fileLoaded.style.color = "#FF0000";
+        } else {
+            fileLoaded.style.color = "";
+            fileLoaded.textContent = inputData.progress + "%";
+        }
+
+        this.setInputInfo(inputData.size, null);
+        this.displayFilePreview(inputData);
+    }
+
+    /**
+     * Render the input thumbnail
+     */
+    async renderFileThumb() {
+        const activeTab = this.manager.tabs.getActiveInputTab(),
+            input = await this.getInputValue(activeTab),
+            fileThumb = document.getElementById("input-file-thumbnail");
+
+        if (typeof input === "string" ||
+            !this.app.options.imagePreview) {
+            this.resetFileThumb();
+            return;
+        }
+
+        const inputArr = new Uint8Array(input),
+            type = isImage(inputArr);
+
+        if (type && type !== "image/tiff" && inputArr.byteLength <= 512000) {
+            // Most browsers don't support displaying TIFFs, so ignore them
+            // Don't render images over 512000 bytes
+            const blob = new Blob([inputArr], {type: type}),
+                url = URL.createObjectURL(blob);
+            fileThumb.src = url;
+        } else {
+            this.resetFileThumb();
+        }
+
+    }
+
+    /**
+     * Reset the input thumbnail to the default icon
+     */
+    resetFileThumb() {
+        const fileThumb = document.getElementById("input-file-thumbnail");
+        fileThumb.src = require("../static/images/file-128x128.png");
+    }
+
+    /**
+     * Shows a chunk of the file in the input behind the file overlay
+     *
+     * @param {Object} inputData - Object containing the input data
+     * @param {number} inputData.inputNum - The inputNum of the file being displayed
+     * @param {ArrayBuffer} inputData.input - The actual input to display
+     */
+    displayFilePreview(inputData) {
+        const activeTab = this.manager.tabs.getActiveInputTab(),
+            input = inputData.input,
+            inputText = document.getElementById("input-text");
+        if (inputData.inputNum !== activeTab) return;
+        inputText.style.overflow = "hidden";
+        inputText.classList.add("blur");
+        inputText.value = Utils.printable(Utils.arrayBufferToStr(input.slice(0, 4096)));
+
+        this.renderFileThumb();
+
+    }
+
+    /**
+     * Updates the displayed load progress for a file
+     *
+     * @param {number} inputNum
+     * @param {number | string} progress - Either a number or "error"
+     */
+    updateFileProgress(inputNum, progress) {
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        if (inputNum !== activeTab) return;
+
+        const fileLoaded = document.getElementById("input-file-loaded");
+        let oldProgress = fileLoaded.textContent;
+        if (oldProgress !== "Error") {
+            oldProgress = parseInt(oldProgress.replace("%", ""), 10);
+        }
+        if (progress === "error") {
+            fileLoaded.textContent = "Error";
+            fileLoaded.style.color = "#FF0000";
+        } else {
+            fileLoaded.textContent = progress + "%";
+            fileLoaded.style.color = "";
+        }
+
+        if (progress === 100 && progress !== oldProgress) {
+            // Don't set the input if the progress hasn't changed
+            this.inputWorker.postMessage({
+                action: "setInput",
+                data: {
+                    inputNum: inputNum,
+                    silent: false
+                }
+            });
+            window.dispatchEvent(this.manager.statechange);
+
+        }
+    }
+
+    /**
+     * Updates the stored value for the specified inputNum
+     *
+     * @param {number} inputNum
+     * @param {string | ArrayBuffer} value
+     */
+    updateInputValue(inputNum, value) {
+        let includeInput = false;
+        const recipeStr = toBase64(value, "A-Za-z0-9+/"); // B64 alphabet with no padding
+        if (recipeStr.length > 0 && recipeStr.length <= 68267) {
+            includeInput = true;
+        }
+        this.setUrl({
+            includeInput: includeInput,
+            input: recipeStr
+        });
+
+        // Value is either a string set by the input or an ArrayBuffer from a LoaderWorker,
+        // so is safe to use typeof === "string"
+        const transferable = (typeof value !== "string") ? [value] : undefined;
+        this.inputWorker.postMessage({
+            action: "updateInputValue",
+            data: {
+                inputNum: inputNum,
+                value: value
+            }
+        }, transferable);
+    }
+
+    /**
+     * Updates the .data property for the input of the specified inputNum.
+     * Used for switching the output into the input
+     *
+     * @param {number} inputNum - The inputNum of the input we're changing
+     * @param {object} inputData - The new data object
+     */
+    updateInputObj(inputNum, inputData) {
+        const transferable = (typeof inputData !== "string") ? [inputData.fileBuffer] : undefined;
+        this.inputWorker.postMessage({
+            action: "updateInputObj",
+            data: {
+                inputNum: inputNum,
+                data: inputData
+            }
+        }, transferable);
+    }
+
+    /**
+     * Get the input value for the specified input
+     *
+     * @param {number} inputNum - The inputNum of the input to retrieve from the inputWorker
+     * @returns {ArrayBuffer | string}
+     */
+    async getInputValue(inputNum) {
+        return await new Promise(resolve => {
+            this.getInput(inputNum, false, r => {
+                resolve(r.data);
+            });
+        });
+    }
+
+    /**
+     * Get the input object for the specified input
+     *
+     * @param {number} inputNum - The inputNum of the input to retrieve from the inputWorker
+     * @returns {object}
+     */
+    async getInputObj(inputNum) {
+        return await new Promise(resolve => {
+            this.getInput(inputNum, true, r => {
+                resolve(r.data);
+            });
+        });
+    }
+
+    /**
+     * Gets the specified input from the inputWorker
+     *
+     * @param {number} inputNum - The inputNum of the data to get
+     * @param {boolean} getObj - If true, get the actual data object of the input instead of just the value
+     * @param {Function} callback - The callback to execute when the input is returned
+     * @returns {ArrayBuffer | string | object}
+     */
+    getInput(inputNum, getObj, callback) {
+        const id = this.callbackID++;
+
+        this.callbacks[id] = callback;
+
+        this.inputWorker.postMessage({
+            action: "getInput",
+            data: {
+                inputNum: inputNum,
+                getObj: getObj,
+                id: id
+            }
+        });
+    }
+
+    /**
+     * Gets the number of inputs from the inputWorker
+     *
+     * @returns {object}
+     */
+    async getInputNums() {
+        return await new Promise(resolve => {
+            this.getNums(r => {
+                resolve(r);
+            });
+        });
+    }
+
+    /**
+     * Gets a list of inputNums from the inputWorker, and sends
+     * them back to the specified callback
+     */
+    getNums(callback) {
+        const id = this.callbackID++;
+
+        this.callbacks[id] = callback;
+
+        this.inputWorker.postMessage({
+            action: "getInputNums",
+            data: id
+        });
+    }
+
+
+    /**
+     * Displays information about the input.
+     *
+     * @param {number} length - The length of the current input string
+     * @param {number} lines - The number of the lines in the current input string
+     */
+    setInputInfo(length, lines) {
+        let width = length.toString().length.toLocaleString();
+        width = width < 2 ? 2 : width;
+
+        const lengthStr = length.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
+        let msg = "length: " + lengthStr;
+
+        if (typeof lines === "number") {
+            const linesStr = lines.toString().padStart(width, " ").replace(/ /g, "&nbsp;");
+            msg += "<br>lines: " + linesStr;
+        }
+
+        document.getElementById("input-info").innerHTML = msg;
+
+    }
+
+    /**
+     * Handler for input change events.
+     * Debounces the input so we don't call autobake too often.
+     *
+     * @param {event} e
+     */
+    debounceInputChange(e) {
+        this.app.debounce(this.inputChange, 50, "inputChange", this, [e])();
+    }
+
+    /**
+     * Handler for input change events.
+     * Updates the value stored in the inputWorker
+     *
+     * @param {event} e
+     *
+     * @fires Manager#statechange
+     */
+    inputChange(e) {
+        // Ignore this function if the input is a file
+        const fileOverlay = document.getElementById("input-file");
+        if (fileOverlay.style.display === "block") return;
+
+        // Remove highlighting from input and output panes as the offsets might be different now
+        this.manager.highlighter.removeHighlights();
+
+        const textArea = document.getElementById("input-text");
+        const value = (textArea.value !== undefined) ? textArea.value : "";
+        const activeTab = this.manager.tabs.getActiveInputTab();
+
+        this.app.progress = 0;
+
+        const lines = value.length < (this.app.options.ioDisplayThreshold * 1024) ?
+            (value.count("\n") + 1) : null;
+        this.setInputInfo(value.length, lines);
+        this.updateInputValue(activeTab, value);
+        this.manager.tabs.updateInputTabHeader(activeTab, value.replace(/[\n\r]/g, "").slice(0, 100));
+
+        if (e && this.badKeys.indexOf(e.keyCode) < 0) {
+            // Fire the statechange event as the input has been modified
+            window.dispatchEvent(this.manager.statechange);
+        }
+    }
+
+    /**
+     * Handler for input paste events
+     * Checks that the size of the input is below the display limit, otherwise treats it as a file/blob
+     *
+     * @param {event} e
+     */
+    inputPaste(e) {
+        const pastedData = e.clipboardData.getData("Text");
+        if (pastedData.length < (this.app.options.ioDisplayThreshold * 1024)) {
+            // Pasting normally fires the inputChange() event before
+            // changing the value, so instead change it here ourselves
+            // and manually fire inputChange()
+            e.preventDefault();
+            const inputText = document.getElementById("input-text");
+            const selStart = inputText.selectionStart;
+            const selEnd = inputText.selectionEnd;
+            const startVal = inputText.value.slice(0, selStart);
+            const endVal = inputText.value.slice(selEnd);
+
+            inputText.value = startVal + pastedData + endVal;
+            inputText.setSelectionRange(selStart + pastedData.length, selStart + pastedData.length);
+            this.debounceInputChange(e);
+        } else {
+            e.preventDefault();
+            e.stopPropagation();
+
+            const file = new File([pastedData], "PastedData", {
+                type: "text/plain",
+                lastModified: Date.now()
+            });
+
+            this.loadUIFiles([file]);
+            return false;
+        }
+    }
+
+
+    /**
+     * Handler for input dragover events.
+     * Gives the user a visual cue to show that items can be dropped here.
+     *
+     * @param {event} e
+     */
+    inputDragover(e) {
+        // This will be set if we're dragging an operation
+        if (e.dataTransfer.effectAllowed === "move")
+            return false;
+
+        e.stopPropagation();
+        e.preventDefault();
+        e.target.closest("#input-text,#input-file").classList.add("dropping-file");
+    }
+
+    /**
+     * Handler for input dragleave events.
+     * Removes the visual cue.
+     *
+     * @param {event} e
+     */
+    inputDragleave(e) {
+        e.stopPropagation();
+        e.preventDefault();
+        e.target.closest("#input-text,#input-file").classList.remove("dropping-file");
+    }
+
+    /**
+     * Handler for input drop events.
+     * Loads the dragged data.
+     *
+     * @param {event} e
+     */
+    inputDrop(e) {
+        // This will be set if we're dragging an operation
+        if (e.dataTransfer.effectAllowed === "move")
+            return false;
+
+        e.stopPropagation();
+        e.preventDefault();
+
+        const text = e.dataTransfer.getData("Text");
+
+        e.target.closest("#input-text,#input-file").classList.remove("dropping-file");
+
+        if (text) {
+            // Append the text to the current input and fire inputChange()
+            document.getElementById("input-text").value += text;
+            this.inputChange(e);
+            return;
+        }
+
+        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
+            this.loadUIFiles(e.dataTransfer.files);
+        }
+    }
+
+    /**
+     * Handler for open input button events
+     * Loads the opened data into the input textarea
+     *
+     * @param {event} e
+     */
+    inputOpen(e) {
+        e.preventDefault();
+
+        if (e.target.files.length > 0) {
+            this.loadUIFiles(e.target.files);
+            e.target.value = "";
+        }
+    }
+
+    /**
+     * Load files from the UI into the inputWorker
+     *
+     * @param {FileList} files - The list of files to be loaded
+     */
+    loadUIFiles(files) {
+        const numFiles = files.length;
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        log.debug(`Loading ${numFiles} files.`);
+
+        // Display the number of files as pending so the user
+        // knows that we've received the files.
+        this.showLoadingInfo({
+            pending: numFiles,
+            loading: 0,
+            loaded: 0,
+            total: numFiles,
+            activeProgress: {
+                inputNum: activeTab,
+                progress: 0
+            }
+        }, false);
+
+        this.inputWorker.postMessage({
+            action: "loadUIFiles",
+            data: {
+                files: files,
+                activeTab: activeTab
+            }
+        });
+    }
+
+    /**
+     * Handler for open input button click.
+     * Opens the open file dialog.
+     */
+    inputOpenClick() {
+        document.getElementById("open-file").click();
+    }
+
+    /**
+     * Handler for open folder button click
+     * Opens the open folder dialog.
+     */
+    folderOpenClick() {
+        document.getElementById("open-folder").click();
+    }
+
+    /**
+     * Display the loaded files information in the input header.
+     * Also, sets the background of the Input header to be a progress bar
+     * @param {object} loadedData - Object containing the loading information
+     * @param {number} loadedData.pending - How many files are pending (not loading / loaded)
+     * @param {number} loadedData.loading - How many files are being loaded
+     * @param {number} loadedData.loaded - How many files have been loaded
+     * @param {number} loadedData.total - The total number of files
+     * @param {object} loadedData.activeProgress - Object containing data about the active tab
+     * @param {number} loadedData.activeProgress.inputNum - The inputNum of the input the progress is for
+     * @param {number} loadedData.activeProgress.progress - The loading progress of the active input
+     * @param {boolean} autoRefresh - If true, automatically refreshes the loading info by sending a message to the inputWorker after 100ms
+     */
+    showLoadingInfo(loadedData, autoRefresh) {
+        const pending = loadedData.pending;
+        const loading = loadedData.loading;
+        const loaded = loadedData.loaded;
+        const total = loadedData.total;
+
+        let width = total.toLocaleString().length;
+        width = width < 2 ? 2 : width;
+
+        const totalStr = total.toLocaleString().padStart(width, " ").replace(/ /g, "&nbsp;");
+        let msg = "total: " + totalStr;
+
+        const loadedStr = loaded.toLocaleString().padStart(width, " ").replace(/ /g, "&nbsp;");
+        msg += "<br>loaded: " + loadedStr;
+
+        if (pending > 0) {
+            const pendingStr = pending.toLocaleString().padStart(width, " ").replace(/ /g, "&nbsp;");
+            msg += "<br>pending: " + pendingStr;
+        } else if (loading > 0) {
+            const loadingStr = loading.toLocaleString().padStart(width, " ").replace(/ /g, "&nbsp;");
+            msg += "<br>loading: " + loadingStr;
+        }
+
+        const inFiles = document.getElementById("input-files-info");
+        if (total > 1) {
+            inFiles.innerHTML = msg;
+            inFiles.style.display = "";
+        } else {
+            inFiles.style.display = "none";
+        }
+
+        this.updateFileProgress(loadedData.activeProgress.inputNum, loadedData.activeProgress.progress);
+
+        const inputTitle = document.getElementById("input").firstElementChild;
+        if (loaded < total) {
+            const percentComplete = loaded / total * 100;
+            inputTitle.style.background = `linear-gradient(to right, var(--title-background-colour) ${percentComplete}%, var(--primary-background-colour) ${percentComplete}%)`;
+        } else {
+            inputTitle.style.background = "";
+        }
+
+        if (loaded < total && autoRefresh) {
+            setTimeout(function() {
+                this.inputWorker.postMessage({
+                    action: "getLoadProgress",
+                    data: this.manager.tabs.getActiveInputTab()
+                });
+            }.bind(this), 100);
+        }
+    }
+
+    /**
+     * Change to a different tab.
+     *
+     * @param {number} inputNum - The inputNum of the tab to change to
+     * @param {boolean} [changeOutput=false] - If true, also changes the output
+     */
+    changeTab(inputNum, changeOutput) {
+        if (this.manager.tabs.getInputTabItem(inputNum) !== null) {
+            this.manager.tabs.changeInputTab(inputNum);
+            this.inputWorker.postMessage({
+                action: "setInput",
+                data: {
+                    inputNum: inputNum,
+                    silent: true
+                }
+            });
+        } else {
+            const minNum = Math.min(...this.manager.tabs.getInputTabList());
+            let direction = "right";
+            if (inputNum < minNum) {
+                direction = "left";
+            }
+            this.inputWorker.postMessage({
+                action: "refreshTabs",
+                data: {
+                    inputNum: inputNum,
+                    direction: direction
+                }
+            });
+        }
+
+        if (changeOutput) {
+            this.manager.output.changeTab(inputNum, false);
+        }
+    }
+
+    /**
+     * Handler for clicking on a tab
+     *
+     * @param {event} mouseEvent
+     */
+    changeTabClick(mouseEvent) {
+        if (!mouseEvent.target) return;
+
+        const tabNum = mouseEvent.target.parentElement.getAttribute("inputNum");
+        if (tabNum >= 0) {
+            this.changeTab(parseInt(tabNum, 10), this.app.options.syncTabs);
+        }
+    }
+
+    /**
+     * Handler for clear all IO events.
+     * Resets the input, output and info areas, and creates a new inputWorker
+     */
+    clearAllIoClick() {
+        this.manager.worker.cancelBake(true, true);
+        this.manager.worker.loaded = false;
+        this.manager.output.removeAllOutputs();
+        this.manager.output.terminateZipWorker();
+
+        this.manager.highlighter.removeHighlights();
+        getSelection().removeAllRanges();
+
+        const tabsList = document.getElementById("input-tabs").children;
+        for (let i = tabsList.length - 1; i >= 0; i--) {
+            tabsList.item(i).remove();
+        }
+
+        this.showLoadingInfo({
+            pending: 0,
+            loading: 0,
+            loaded: 1,
+            total: 1,
+            activeProgress: {
+                inputNum: 1,
+                progress: 100
+            }
+        });
+
+        this.setupInputWorker();
+        this.manager.worker.setupChefWorker();
+        this.addInput(true);
+        this.bakeAll();
+    }
+
+    /**
+     * Handler for clear IO click event.
+     * Resets the input for the current tab
+     */
+    clearIoClick() {
+        const inputNum = this.manager.tabs.getActiveInputTab();
+        if (inputNum === -1) return;
+
+        this.manager.highlighter.removeHighlights();
+        getSelection().removeAllRanges();
+
+        this.updateInputValue(inputNum, "");
+
+        this.set({
+            inputNum: inputNum,
+            input: ""
+        });
+
+        this.manager.tabs.updateInputTabHeader(inputNum, "");
+    }
+
+    /**
+     * Sets the console log level in the worker.
+     *
+     * @param {string} level
+     */
+    setLogLevel(level) {
+        if (!this.inputWorker) return;
+        this.inputWorker.postMessage({
+            action: "setLogLevel",
+            data: log.getLevel()
+        });
+    }
+
+    /**
+     * Sends a message to the inputWorker to add a new input.
+     * @param {boolean} [changeTab=false] - If true, changes the tab to the new input
+     */
+    addInput(changeTab=false) {
+        if (!this.inputWorker) return;
+        this.inputWorker.postMessage({
+            action: "addInput",
+            data: changeTab
+        });
+    }
+
+    /**
+     * Handler for add input button clicked.
+     */
+    addInputClick() {
+        this.addInput(true);
+    }
+
+    /**
+     * Handler for when the inputWorker adds a new input
+     *
+     * @param {boolean} changeTab - Whether or not to change to the new input tab
+     * @param {number} inputNum - The new inputNum
+     */
+    inputAdded(changeTab, inputNum) {
+        this.addTab(inputNum, changeTab);
+
+        this.manager.output.addOutput(inputNum, changeTab);
+        this.manager.worker.addChefWorker();
+    }
+
+    /**
+     * Remove a chefWorker from the workerWaiter if we remove an input
+     */
+    removeChefWorker() {
+        const workerIdx = this.manager.worker.getInactiveChefWorker(true);
+        const worker = this.manager.worker.chefWorkers[workerIdx];
+        this.manager.worker.removeChefWorker(worker);
+    }
+
+    /**
+     * Adds a new input tab.
+     *
+     * @param {number} inputNum - The inputNum of the new tab
+     * @param {boolean} [changeTab=true] - If true, changes to the new tab once it's been added
+     */
+    addTab(inputNum, changeTab = true) {
+        const tabsWrapper = document.getElementById("input-tabs"),
+            numTabs = tabsWrapper.children.length;
+
+        if (!this.manager.tabs.getInputTabItem(inputNum) && numTabs < this.maxTabs) {
+            const newTab = this.manager.tabs.createInputTabElement(inputNum, changeTab);
+            tabsWrapper.appendChild(newTab);
+
+            if (numTabs > 0) {
+                this.manager.tabs.showTabBar();
+            } else {
+                this.manager.tabs.hideTabBar();
+            }
+
+            this.inputWorker.postMessage({
+                action: "updateTabHeader",
+                data: inputNum
+            });
+        } else if (numTabs === this.maxTabs) {
+            // Can't create a new tab
+            document.getElementById("input-tabs").lastElementChild.style.boxShadow = "-15px 0px 15px -15px var(--primary-border-colour) inset";
+        }
+
+        if (changeTab) this.changeTab(inputNum, false);
+    }
+
+    /**
+     * Refreshes the input tabs, and changes to activeTab
+     *
+     * @param {number[]} nums - The inputNums to be displayed as tabs
+     * @param {number} activeTab - The tab to change to
+     * @param {boolean} tabsLeft - True if there are input tabs to the left of the displayed tabs
+     * @param {boolean} tabsRight - True if there are input tabs to the right of the displayed tabs
+     */
+    refreshTabs(nums, activeTab, tabsLeft, tabsRight) {
+        this.manager.tabs.refreshInputTabs(nums, activeTab, tabsLeft, tabsRight);
+
+        this.inputWorker.postMessage({
+            action: "setInput",
+            data: {
+                inputNum: activeTab,
+                silent: true
+            }
+        });
+    }
+
+    /**
+     * Sends a message to the inputWorker to remove an input.
+     * If the input tab is on the screen, refreshes the tabs
+     *
+     * @param {number} inputNum - The inputNum of the tab to be removed
+     */
+    removeInput(inputNum) {
+        let refresh = false;
+        if (this.manager.tabs.getInputTabItem(inputNum) !== null) {
+            refresh = true;
+        }
+        this.inputWorker.postMessage({
+            action: "removeInput",
+            data: {
+                inputNum: inputNum,
+                refreshTabs: refresh,
+                removeChefWorker: true
+            }
+        });
+
+        this.manager.output.removeTab(inputNum);
+    }
+
+    /**
+     * Handler for clicking on a remove tab button
+     *
+     * @param {event} mouseEvent
+     */
+    removeTabClick(mouseEvent) {
+        if (!mouseEvent.target) {
+            return;
+        }
+        const tabNum = mouseEvent.target.closest("button").parentElement.getAttribute("inputNum");
+        if (tabNum) {
+            this.removeInput(parseInt(tabNum, 10));
+        }
+    }
+
+    /**
+     * Handler for scrolling on the input tabs area
+     *
+     * @param {event} wheelEvent
+     */
+    scrollTab(wheelEvent) {
+        wheelEvent.preventDefault();
+
+        if (wheelEvent.deltaY > 0) {
+            this.changeTabLeft();
+        } else if (wheelEvent.deltaY < 0) {
+            this.changeTabRight();
+        }
+    }
+
+    /**
+     * Handler for mouse down on the next tab button
+     */
+    nextTabClick() {
+        this.mousedown = true;
+        this.changeTabRight();
+        const time = 200;
+        const func = function(time) {
+            if (this.mousedown) {
+                this.changeTabRight();
+                const newTime = (time > 50) ? time = time - 10 : 50;
+                setTimeout(func.bind(this, [newTime]), newTime);
+            }
+        };
+        this.tabTimeout = setTimeout(func.bind(this, [time]), time);
+    }
+
+    /**
+     * Handler for mouse down on the previous tab button
+     */
+    previousTabClick() {
+        this.mousedown = true;
+        this.changeTabLeft();
+        const time = 200;
+        const func = function(time) {
+            if (this.mousedown) {
+                this.changeTabLeft();
+                const newTime = (time > 50) ? time = time - 10 : 50;
+                setTimeout(func.bind(this, [newTime]), newTime);
+            }
+        };
+        this.tabTimeout = setTimeout(func.bind(this, [time]), time);
+    }
+
+    /**
+     * Handler for mouse up event on the tab buttons
+     */
+    tabMouseUp() {
+        this.mousedown = false;
+
+        clearTimeout(this.tabTimeout);
+        this.tabTimeout = null;
+    }
+
+    /**
+     * Changes to the next (right) tab
+     */
+    changeTabRight() {
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        if (activeTab === -1) return;
+        this.inputWorker.postMessage({
+            action: "changeTabRight",
+            data: {
+                activeTab: activeTab
+            }
+        });
+    }
+
+    /**
+     * Changes to the previous (left) tab
+     */
+    changeTabLeft() {
+        const activeTab = this.manager.tabs.getActiveInputTab();
+        if (activeTab === -1) return;
+        this.inputWorker.postMessage({
+            action: "changeTabLeft",
+            data: {
+                activeTab: activeTab
+            }
+        });
+    }
+
+    /**
+     * Handler for go to tab button clicked
+     */
+    async goToTab() {
+        const inputNums = await this.getInputNums();
+        let tabNum = window.prompt(`Enter tab number (${inputNums.min} - ${inputNums.max}):`, this.manager.tabs.getActiveInputTab().toString());
+
+        if (tabNum === null) return;
+        tabNum = parseInt(tabNum, 10);
+
+        this.changeTab(tabNum, this.app.options.syncTabs);
+    }
+
+    /**
+     * Handler for find tab button clicked
+     */
+    findTab() {
+        this.filterTabSearch();
+        $("#input-tab-modal").modal();
+    }
+
+    /**
+     * Sends a message to the inputWorker to search the inputs
+     */
+    filterTabSearch() {
+        const showPending = document.getElementById("input-show-pending").checked;
+        const showLoading = document.getElementById("input-show-loading").checked;
+        const showLoaded = document.getElementById("input-show-loaded").checked;
+
+        const filter = document.getElementById("input-filter").value;
+        const filterType = document.getElementById("input-filter-button").innerText;
+        const numResults = parseInt(document.getElementById("input-num-results").value, 10);
+
+        this.inputWorker.postMessage({
+            action: "filterTabs",
+            data: {
+                showPending: showPending,
+                showLoading: showLoading,
+                showLoaded: showLoaded,
+                filter: filter,
+                filterType: filterType,
+                numResults: numResults
+            }
+        });
+    }
+
+    /**
+     * Handle when an option in the filter drop down box is clicked
+     *
+     * @param {event} mouseEvent
+     */
+    filterOptionClick(mouseEvent) {
+        document.getElementById("input-filter-button").innerText = mouseEvent.target.innerText;
+        this.filterTabSearch();
+    }
+
+    /**
+     * Displays the results of a tab search in the find tab box
+     *
+     * @param {object[]} results - List of results objects
+     *
+     */
+    displayTabSearchResults(results) {
+        const resultsList = document.getElementById("input-search-results");
+
+        for (let i = resultsList.children.length - 1; i >= 0; i--) {
+            resultsList.children.item(i).remove();
+        }
+
+        for (let i = 0; i < results.length; i++) {
+            const newListItem = document.createElement("li");
+            newListItem.classList.add("input-filter-result");
+            newListItem.setAttribute("inputNum", results[i].inputNum);
+            newListItem.innerText = `${results[i].inputNum}: ${results[i].textDisplay}`;
+
+            resultsList.appendChild(newListItem);
+        }
+    }
+
+    /**
+     * Handler for clicking on a filter result
+     *
+     * @param {event} e
+     */
+    filterItemClick(e) {
+        if (!e.target) return;
+        const inputNum = parseInt(e.target.getAttribute("inputNum"), 10);
+        if (inputNum <= 0) return;
+
+        $("#input-tab-modal").modal("hide");
+        this.changeTab(inputNum, this.app.options.syncTabs);
+    }
+
+    /**
+     * Update the input URL to the new value
+     *
+     * @param {object} urlData - Object containing the URL data
+     * @param {boolean} urlData.includeInput - If true, the input is included in the title
+     * @param {string} urlData.input - The input data to be included
+     */
+    setUrl(urlData) {
+        this.app.updateTitle(urlData.includeInput, urlData.input, true);
+    }
+
+
+}
+
+export default InputWaiter;

Деякі файли не було показано, через те що забагато файлів було змінено