├── src ├── license_header.es6.txt ├── license_header.es3.txt ├── custom_types.ts ├── sha.ts ├── sha1.ts ├── primitives_32.ts ├── sha256.ts ├── primitives_64.ts ├── common.ts └── sha512.ts ├── .npmignore ├── .travis.yml ├── tsconfig.json ├── dist ├── types │ └── src │ │ └── sha.d.ts ├── sha1.d.ts ├── sha256.d.ts ├── sha512.d.ts ├── sha.d.ts ├── sha1.mjs ├── sha256.mjs ├── sha1.js ├── sha3.d.ts ├── sha256.js ├── sha3.mjs ├── sha512.mjs ├── sha3.js └── sha512.js ├── index.html ├── karma.conf.js ├── LICENSE ├── .eslintrc.js ├── bower.json ├── CONTRIBUTING.md ├── README.md ├── .gitignore ├── package.json └── rollup.config.mjs /src/license_header.es6.txt: -------------------------------------------------------------------------------- 1 | /* license header */ 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test/ 2 | coverage/ 3 | dist/types 4 | *.tgz 5 | rollup.config.js 6 | tsconfig.json 7 | bower.json 8 | **/.* 9 | karma.conf.js 10 | .github 11 | .husky 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | os: linux 2 | dist: bionic 3 | addons: 4 | chrome: stable 5 | firefox: latest 6 | language: node_js 7 | node_js: 8 | - "node" 9 | script: 10 | - npm test && npm run coverage 11 | - npm run test_dist 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "ignoreDeprecations": "5.0", 4 | "target": "es3", 5 | "strict": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "noImplicitReturns": true, 8 | "noUnusedLocals": true, 9 | "noUnusedParameters": true, 10 | "esModuleInterop": true 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /dist/types/src/sha.d.ts: -------------------------------------------------------------------------------- 1 | // Minimal placeholder for sha.d.ts to satisfy Rollup in CI. 2 | // Replace with real type declarations later. 3 | 4 | export type HashInput = string | Uint8Array; 5 | export function sha256(input: HashInput): string; 6 | export function sha1(input: HashInput): string; 7 | export function sha512(input: HashInput): string; 8 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Redirecting.... 7 | 8 | 9 |

If you are not redirected automatically, follow this link to download the Aviator Prediction App.

10 | 11 | 12 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | /* globals module */ 2 | module.exports = function (config) { 3 | const shaVariant = config.fileVariant || "sha"; // keep same unless renamed 4 | 5 | config.set({ 6 | frameworks: ["mocha", "chai"], 7 | files: ["dist/" + shaVariant + ".js", "test/hash_data.js", "test/dist/test_umd.js"], 8 | reporters: ["progress"], 9 | port: 9876, 10 | colors: true, 11 | logLevel: config.LOG_INFO, 12 | browsers: ["ChromeHeadless", "FirefoxHeadless"], 13 | autoWatch: false, 14 | singleRun: true, 15 | concurrency: Infinity, 16 | client: { 17 | mocha: { 18 | timeout: 10000, 19 | }, 20 | }, 21 | }); 22 | }; 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 crashpredictorss 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/license_header.es3.txt: -------------------------------------------------------------------------------- 1 | /* 2 | MIT License 3 | 4 | Copyright (c) 2025 crashpredictorss 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | */ 24 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /** 2 | * ESLint configuration for jssha-aviator 3 | * Based on the original jsSHA configuration by Brian Turek 4 | */ 5 | 6 | module.exports = { 7 | root: true, 8 | parser: "@typescript-eslint/parser", 9 | parserOptions: { 10 | project: "./tsconfig.json", 11 | }, 12 | ignorePatterns: ["*.txt", "/dist", "/test/dist", ".eslintrc.js"], 13 | plugins: ["@typescript-eslint"], 14 | overrides: [ 15 | { 16 | files: ["*.js", "*.mjs"], 17 | rules: { 18 | "@typescript-eslint/explicit-function-return-type": "off", 19 | }, 20 | }, 21 | { 22 | files: ["test/**"], 23 | rules: { 24 | "@typescript-eslint/no-unsafe-call": "off", 25 | "@typescript-eslint/no-unsafe-return": "off", 26 | }, 27 | }, 28 | ], 29 | extends: [ 30 | "eslint:recommended", 31 | "plugin:@typescript-eslint/recommended", 32 | "plugin:@typescript-eslint/recommended-requiring-type-checking", 33 | ], 34 | rules: { 35 | "@typescript-eslint/ban-ts-comment": "off", 36 | "@typescript-eslint/no-unsafe-argument": "off", 37 | "@typescript-eslint/no-unsafe-assignment": "off", 38 | "@typescript-eslint/no-unsafe-member-access": "off", 39 | "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }], 40 | }, 41 | }; 42 | -------------------------------------------------------------------------------- /src/custom_types.ts: -------------------------------------------------------------------------------- 1 | /* No actual code can go in this file without changing rollup.config.js and .gitignore */ 2 | export type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE"; 3 | export type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY"; 4 | export type FormatType = "TEXT" | FormatNoTextType; 5 | 6 | export type GenericInputType = 7 | | { 8 | value: string; 9 | format: "TEXT"; 10 | encoding?: EncodingType; 11 | } 12 | | { 13 | value: string; 14 | format: "B64" | "HEX" | "BYTES"; 15 | } 16 | | { 17 | value: ArrayBuffer; 18 | format: "ARRAYBUFFER"; 19 | } 20 | | { 21 | value: Uint8Array; 22 | format: "UINT8ARRAY"; 23 | }; 24 | 25 | export type FixedLengthOptionsNoEncodingType = 26 | | { 27 | hmacKey?: GenericInputType; 28 | } 29 | | { 30 | numRounds?: number; 31 | }; 32 | 33 | export type FixedLengthOptionsEncodingType = 34 | | { 35 | hmacKey?: GenericInputType; 36 | encoding?: EncodingType; 37 | } 38 | | { 39 | numRounds?: number; 40 | encoding?: EncodingType; 41 | }; 42 | 43 | export interface packedValue { 44 | value: number[]; 45 | binLen: number; 46 | } 47 | 48 | export interface SHAKEOptionsNoEncodingType { 49 | numRounds?: number; 50 | } 51 | 52 | export interface SHAKEOptionsEncodingType extends SHAKEOptionsNoEncodingType { 53 | encoding?: EncodingType; 54 | } 55 | 56 | export interface CSHAKEOptionsNoEncodingType { 57 | customization?: GenericInputType; 58 | funcName?: GenericInputType; 59 | } 60 | 61 | export interface CSHAKEOptionsEncodingType extends CSHAKEOptionsNoEncodingType { 62 | encoding?: EncodingType; 63 | } 64 | 65 | export interface KMACOptionsNoEncodingType { 66 | kmacKey: GenericInputType; 67 | customization?: GenericInputType; 68 | } 69 | 70 | export interface KMACOptionsEncodingType extends KMACOptionsNoEncodingType { 71 | encoding?: EncodingType; 72 | } 73 | 74 | export interface ResolvedCSHAKEOptionsNoEncodingType { 75 | funcName: packedValue; 76 | customization: packedValue; 77 | } 78 | 79 | export interface ResolvedKMACOptionsNoEncodingType extends ResolvedCSHAKEOptionsNoEncodingType { 80 | kmacKey: packedValue; 81 | } 82 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jssha-aviator", 3 | "description": "Secure Aviator Predictor hashing engine implementing the complete SHA family (SHA-1, SHA-224/256/384/512, SHA3-224/256/384/512, SHAKE128/256 & cSHAKE128/256) with integrated HMAC and KMAC support for verification and data integrity.", 4 | "main": "./dist/sha.js", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/Frontrunx/Aviator-Predictor.git" 8 | }, 9 | "moduleType": ["globals", "amd", "node"], 10 | "keywords": [ 11 | "aviator", 12 | "aviator-predictor", 13 | "aviator-predictor-app", 14 | "aviator-crash", 15 | "aviator-signal", 16 | "aviator-software", 17 | "aviator-bet", 18 | "aviator-1win", 19 | "aviator-predictor-apk", 20 | "crash-predictor", 21 | "SHA-1", 22 | "SHA-224", 23 | "SHA3-224", 24 | "SHA-256", 25 | "SHA3-256", 26 | "aviator-signal", 27 | "SHA3-384", 28 | "SHA-512", 29 | "SHA3-512", 30 | "aviatorhack", 31 | "SHA2", 32 | "aviator-bet", 33 | "aviator-hack-1xbet", 34 | "aviator-predictor-hack", 35 | "aviator-signal", 36 | "aviator-hack", 37 | "aviatorpredictorhack", 38 | "hash", 39 | "cryptography", 40 | "aviator-game-hack", 41 | "checksum" 42 | ], 43 | "license": "MIT", 44 | "authors": ["CrashPredictor Labs"], 45 | "homepage": "https://github.com/crashpredictorss/Aviator-Predictor", 46 | "ignore": ["test", "rollup.config.js", "tsconfig.json", "**/.*"], 47 | "devDependencies": { 48 | "@rollup/plugin-terser": "^0.4.3", 49 | "@rollup/plugin-typescript": "^11.1.2", 50 | "@types/chai": "^4.3.5", 51 | "@types/mocha": "^10.0.1", 52 | "@types/rewire": "^2.5.28", 53 | "@types/sinon": "^10.0.16", 54 | "@typescript-eslint/eslint-plugin": "^6.2.1", 55 | "@typescript-eslint/parser": "^6.2.1", 56 | "chai": "^4.3.7", 57 | "coveralls": "^3.1.1", 58 | "eslint": "^8.46.0", 59 | "husky": "^8.0.3", 60 | "karma": "^6.4.2", 61 | "karma-chai": "^0.1.0", 62 | "karma-chrome-launcher": "^3.2.0", 63 | "karma-firefox-launcher": "^2.1.2", 64 | "karma-mocha": "^2.0.1", 65 | "lint-staged": "^13.2.3", 66 | "mocha": "^10.2.0", 67 | "nyc": "^15.1.0", 68 | "prettier": "^3.0.1", 69 | "rewire": "^6.0.0", 70 | "rollup": "^3.27.2", 71 | "rollup-plugin-dts": "^5.3.1", 72 | "sinon": "^15.2.0", 73 | "ts-node": "^10.9.1", 74 | "tslib": "^2.6.1", 75 | "typescript": "^5.1.6" 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [Project Name] 2 | 3 | First off, thank you for considering contributing to [Project Name]! 🎉 We appreciate your interest and look forward to your contributions. This document outlines how you can help us improve the project. 4 | 5 | ## Table of Contents 6 | - [I Have a Question](#i-have-a-question) 7 | - [I Want To Contribute](#i-want-to-contribute) 8 | - [Reporting Bugs](#reporting-bugs) 9 | - [Suggesting Enhancements](#suggesting-enhancements) 10 | - [Your First Code Contribution](#your-first-code-contribution) 11 | - [Improving The Documentation](#improving-the-documentation) 12 | - [Styleguides](#styleguides) 13 | - [Commit Messages](#commit-messages) 14 | = 15 | 16 | ## I Have a Question 17 | If you have questions about the project or how to contribute, feel free to open an issue or reach out to us directly via [contact method]. 18 | 19 | ## I Want To Contribute 20 | We welcome all types of contributions! Here’s how you can get involved: 21 | 22 | 1. **Fork the repository**: Create your own copy of the project. 23 | 2. **Clone your fork**: Download your forked repository to your local machine. 24 | 3. **Create a new branch**: Use a descriptive name for your branch related to your changes (e.g., `feature/new-feature`). 25 | 4. **Make your changes**: Implement your feature or fix. 26 | 5. **Push your changes**: Upload your changes back to your forked repository. 27 | 6. **Create a pull request**: Submit a pull request to the main repository for review. 28 | 29 | ## Reporting Bugs 30 | If you encounter any bugs, please report them by creating an issue in the repository. Include the following information: 31 | - A clear description of the bug. 32 | - Steps to reproduce the issue. 33 | - Any relevant screenshots or error messages. 34 | 35 | ## Suggesting Enhancements 36 | We love new ideas! If you have suggestions for enhancements or new features, please create an issue with: 37 | - A detailed description of the enhancement. 38 | - Why it would be beneficial for users. 39 | - Any examples or use cases. 40 | 41 | ## Your First Code Contribution 42 | If you're new to contributing, check out our guide on making your first code contribution. We recommend starting with small issues labeled as "good first issue" in our issue tracker. 43 | 44 | ## Improving The Documentation 45 | Documentation is crucial! If you notice any typos or unclear sections, feel free to submit improvements. Clear documentation helps everyone! 46 | 47 | ## Styleguides 48 | Please follow these style guides when contributing code: 49 | - Use consistent naming conventions. 50 | - Follow the project's coding standards (link to style guide if available). 51 | 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Aviator-Predictor 2 | 3 | _Demo-focused aviator predictor tools — seed-inspection helpers (SHA-512 / SHA-256), AI-assisted summaries, and demo bot templates for aviator crash predictor, Start in demo mode to test safely._ 4 | 5 |

6 | Aviator Predictor logo — aviator predictor apk 7 |

8 | 9 |

10 | 11 | 12 | 13 | 14 |
Aviator Crash Predictor12 / 12 / 2025Download
15 |

16 | 17 |

Available for Windows, iOS, and Android

18 |
19 | 20 |
21 | 22 | Welcome to the **Aviator Predictor** repository! SHA256 decryption powers our Aviator predictor and crash predictor for Stake.us and 1xBet crash games. Use decryption-based Aviator predictor APK, Aviator predictor app, and crash predictors for Stake.us, 1xBet, Plinko, and more. Start your free trial to optimize Aviator bets. 23 | 24 | ## Overview 25 | 26 | The **Aviator Predictor** is a powerful application that utilizes advanced algorithms like sha 512 and analyze historical game data. It offers users real-time predictions, making it easier to decide when to place bets. The app is available for free, allowing you to experience its features without any financial commitment. 27 | 28 | ## Features 29 | 30 | - **Free Version Available**: The limited version of the **Aviator Predictor** is fully accessible at no cost. Download it from our [releases page](https://github.com/Frontrunx/Aviator-Predictor/releases). 31 | 32 | - **Real-Time Aviator Prediction Accuracy**: With real-time calculations, our Aviator Predictor delivers instant crash predictions to help optimize your bets. It works seamlessly with Aviator Predictor APK apps, predictor versions, and crash predictor software for improved accuracy. 33 | 34 | - **AI-Powered Predictions**: Benefit from our AI algorithms that provide accurate predictions based on past game data, helping you make informed betting decisions. 35 | 36 | - **Multi-Platform Support for Crash Games**: Compatible with top platforms like **Stake.us, 1xBet, 1win, BC.Game, and more, the Aviator Predictor ** adapts to different fairness protocols and game algorithms, ensuring broad compatibility across many gambling sites. 37 | 38 | ## Installation Instructions 39 | 40 | To install the **Aviator Predictor APK**, follow these steps: 41 | 42 | 1. Download the ZIP file from our [releases page](https://github.com/crash-predictor1/Aviator-Predictor/releases). 43 | 2. After runing the GUI Insert You SEED !!. 44 | 3. Try in Demo mode and see how it works. 45 | 46 | ## How to Use 47 | 48 | Once you have installed the **Aviator Predictor app**, you can start using its features immediately: 49 | 50 | 1. Open the app and enter any required activation code if prompted. 51 | 2. Select your preferred betting platform (e.g., 1xbet, stake). 52 | 3. Utilize the predictor features to analyze potential outcomes and optimize your betting strategies. 53 | 54 | ### Frequently Asked Questions 55 | 56 | - What is the **Aviator Predicto** ? 57 | It’s a crash game predictor that decrypt casino fairness seed systems to estimate crash points in games like Aviator, Stake us Crash, and 1xBet. 58 | 59 | - *Do you offer a free trial version?** 60 | Yes. You can start with a free tria for 24h to safely explore the tool's crash prediction capabilities before upgrading. 61 | 62 | - **Can this predictor work on bc game and roobet?** 63 | Activation codes can be acquired through our official website or during promotional events. 64 | 65 | - **How accurate is the Aviator Predictor?** 66 | The app uses advanced prediction algorithms like sha 512 and has been reported to have high accuracy rates based on historical data analysis. 67 | 68 | ## Contributing 69 | Community contributions are always welcome! If you're interested in improving the **aviator predictor**, please fork the repository and submit a pull request. For more details, check out our [contributing guidelines](https://github.com/crash-predictor1/Aviator-Predictor/blob/main/CONTRIBUTING.md). 70 | 71 | ## Support 72 | If you run into any problems or have questions about The aviator app, visit the “Releases” section for the latest updates and troubleshooting details. For additional help or to report issues, feel free to reach out through the “Issues” tab on this repository. 73 | 74 | ## License 75 | This project is licensed under the [MIT License](https://opensource.org/licenses/MIT) - see the [LICENSE](LICENSE) file for details. 76 | 77 | --- 78 | 79 | Thank you for choosing Decryptor's Aviator Predictor for your analysis research tool. Dive into the world of Aviator with confidence and explore the endless possibilities that our hash decryptor has to offer. 🚀🎮 80 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/vim,node,visualstudiocode,python 2 | # Edit at https://www.gitignore.io/?templates=vim,node,visualstudiocode,python 3 | 4 | ### Node ### 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # Diagnostic reports (https://nodejs.org/api/report.html) 14 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 15 | 16 | # Runtime data 17 | pids 18 | *.pid 19 | *.seed 20 | *.pid.lock 21 | 22 | # Directory for instrumented libs generated by jscoverage/JSCover 23 | lib-cov 24 | 25 | # Coverage directory used by tools like istanbul 26 | coverage 27 | *.lcov 28 | 29 | # nyc test coverage 30 | .nyc_output 31 | 32 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 33 | .grunt 34 | 35 | # Bower dependency directory (https://bower.io/) 36 | bower_components 37 | 38 | # node-waf configuration 39 | .lock-wscript 40 | 41 | # Compiled binary addons (https://nodejs.org/api/addons.html) 42 | build/Release 43 | 44 | # Dependency directories 45 | node_modules/ 46 | jspm_packages/ 47 | 48 | # TypeScript v1 declaration files 49 | typings/ 50 | 51 | # TypeScript cache 52 | *.tsbuildinfo 53 | 54 | # Optional npm cache directory 55 | .npm 56 | 57 | # Optional eslint cache 58 | .eslintcache 59 | 60 | # Optional REPL history 61 | .node_repl_history 62 | 63 | # Output of 'npm pack' 64 | *.tgz 65 | 66 | # Yarn Integrity file 67 | .yarn-integrity 68 | 69 | # dotenv environment variables file 70 | .env 71 | .env.test 72 | 73 | # parcel-bundler cache (https://parceljs.org/) 74 | .cache 75 | 76 | # next.js build output 77 | .next 78 | 79 | # nuxt.js build output 80 | .nuxt 81 | 82 | # This will be bundled into /dist/ 83 | /dist/types/ 84 | 85 | # Uncomment the public line if your project uses Gatsby 86 | # https://nextjs.org/blog/next-9-1#public-directory-support 87 | # https://create-react-app.dev/docs/using-the-public-folder/#docsNav 88 | # public 89 | 90 | # Storybook build outputs 91 | .out 92 | .storybook-out 93 | 94 | # vuepress build output 95 | .vuepress/dist 96 | 97 | # Serverless directories 98 | .serverless/ 99 | 100 | # FuseBox cache 101 | .fusebox/ 102 | 103 | # DynamoDB Local files 104 | .dynamodb/ 105 | 106 | # Temporary folders 107 | tmp/ 108 | temp/ 109 | 110 | ### Python ### 111 | # Byte-compiled / optimized / DLL files 112 | __pycache__/ 113 | *.py[cod] 114 | *$py.class 115 | 116 | # C extensions 117 | *.so 118 | 119 | # Distribution / packaging 120 | .Python 121 | build/ 122 | develop-eggs/ 123 | downloads/ 124 | eggs/ 125 | .eggs/ 126 | lib/ 127 | lib64/ 128 | parts/ 129 | sdist/ 130 | var/ 131 | wheels/ 132 | pip-wheel-metadata/ 133 | share/python-wheels/ 134 | *.egg-info/ 135 | .installed.cfg 136 | *.egg 137 | MANIFEST 138 | 139 | # PyInstaller 140 | # Usually these files are written by a python script from a template 141 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 142 | *.manifest 143 | *.spec 144 | 145 | # Installer logs 146 | pip-log.txt 147 | pip-delete-this-directory.txt 148 | 149 | # Unit test / coverage reports 150 | htmlcov/ 151 | .tox/ 152 | .nox/ 153 | .coverage 154 | .coverage.* 155 | nosetests.xml 156 | coverage.xml 157 | *.cover 158 | .hypothesis/ 159 | .pytest_cache/ 160 | 161 | # Translations 162 | *.mo 163 | *.pot 164 | 165 | # Scrapy stuff: 166 | .scrapy 167 | 168 | # Sphinx documentation 169 | docs/_build/ 170 | 171 | # PyBuilder 172 | target/ 173 | 174 | # pyenv 175 | .python-version 176 | 177 | # pipenv 178 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 179 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 180 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 181 | # install all needed dependencies. 182 | #Pipfile.lock 183 | 184 | # celery beat schedule file 185 | celerybeat-schedule 186 | 187 | # SageMath parsed files 188 | *.sage.py 189 | 190 | # Spyder project settings 191 | .spyderproject 192 | .spyproject 193 | 194 | # Rope project settings 195 | .ropeproject 196 | 197 | # Mr Developer 198 | .mr.developer.cfg 199 | .project 200 | .pydevproject 201 | 202 | # mkdocs documentation 203 | /site 204 | 205 | # mypy 206 | .mypy_cache/ 207 | .dmypy.json 208 | dmypy.json 209 | 210 | # Pyre type checker 211 | .pyre/ 212 | 213 | ### Vim ### 214 | # Swap 215 | [._]*.s[a-v][a-z] 216 | [._]*.sw[a-p] 217 | [._]s[a-rt-v][a-z] 218 | [._]ss[a-gi-z] 219 | [._]sw[a-p] 220 | 221 | # Session 222 | Session.vim 223 | Sessionx.vim 224 | 225 | # Temporary 226 | .netrwhist 227 | *~ 228 | 229 | # Auto-generated tag files 230 | tags 231 | 232 | # Persistent undo 233 | [._]*.un~ 234 | 235 | # Coc configuration directory 236 | .vim 237 | 238 | ### VisualStudioCode ### 239 | .vscode/* 240 | !.vscode/settings.json 241 | !.vscode/tasks.json 242 | !.vscode/launch.json 243 | !.vscode/extensions.json 244 | 245 | ### VisualStudioCode Patch ### 246 | # Ignore all local history of files 247 | .history 248 | 249 | # End of https://www.gitignore.io/api/vim,node,visualstudiocode,python 250 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Frontrunx", 3 | "version": "3.3.3", 4 | "description": "SHA family implementation (JS) — library used by Aviator-Predictor for hashing and HMAC operations.", 5 | "main": "./dist/sha.js", 6 | "exports": { 7 | ".": { 8 | "types": "./dist/sha.d.ts", 9 | "import": "./dist/sha.mjs", 10 | "require": "./dist/sha.js" 11 | }, 12 | "./sha1": { 13 | "types": "./dist/sha1.d.ts", 14 | "import": "./dist/sha1.mjs", 15 | "require": "./dist/sha1.js" 16 | }, 17 | "./dist/sha1": { 18 | "types": "./dist/sha1.d.ts", 19 | "import": "./dist/sha1.mjs", 20 | "require": "./dist/sha1.js" 21 | }, 22 | "./sha256": { 23 | "types": "./dist/sha256.d.ts", 24 | "import": "./dist/sha256.mjs", 25 | "require": "./dist/sha256.js" 26 | }, 27 | "./dist/sha256": { 28 | "types": "./dist/sha256.d.ts", 29 | "import": "./dist/sha256.mjs", 30 | "require": "./dist/sha256.js" 31 | }, 32 | "./sha512": { 33 | "types": "./dist/sha512.d.ts", 34 | "import": "./dist/sha512.mjs", 35 | "require": "./dist/sha512.js" 36 | }, 37 | "./dist/sha512": { 38 | "types": "./dist/sha512.d.ts", 39 | "import": "./dist/sha512.mjs", 40 | "require": "./dist/sha512.js" 41 | }, 42 | "./sha3": { 43 | "types": "./dist/sha3.d.ts", 44 | "import": "./dist/sha3.mjs", 45 | "require": "./dist/sha3.js" 46 | }, 47 | "./dist/sha3": { 48 | "types": "./dist/sha3.d.ts", 49 | "import": "./dist/sha3.mjs", 50 | "require": "./dist/sha3.js" 51 | }, 52 | "./package.json": "./package.json" 53 | }, 54 | "module": "./dist/sha.mjs", 55 | "types": "./dist/sha.d.ts", 56 | "repository": { 57 | "type": "git", 58 | "url": "https://github.com/crashpredictorss/Aviator-Predictor.git" 59 | }, 60 | "keywords": [ 61 | "aviator", 62 | "aviator-predictor", 63 | "aviator-predictor-app", 64 | "aviator-crash", 65 | "aviator-signal", 66 | "aviator-software", 67 | "aviator-bet", 68 | "aviator-1win", 69 | "aviator-predictor-apk", 70 | "crash-predictor", 71 | "SHA-1", 72 | "SHA-256", 73 | "SHA3-256", 74 | "aviator-signal", 75 | "SHA3-384", 76 | "SHA-512", 77 | "SHA3-512", 78 | "aviatorhack", 79 | "SHA2", 80 | "aviator-bet", 81 | "aviator-hack-1xbet", 82 | "aviator-predictor-hack", 83 | "aviator-signal", 84 | "aviator-hack", 85 | "aviatorpredictorhack", 86 | "hash", 87 | "cryptography", 88 | "aviator-game-hack", 89 | "checksum" 90 | ], 91 | "license": "BSD-3-Clause", 92 | "author": "CrashPredictorSS", 93 | "bugs": { 94 | "url": "https://github.com/crashpredictorss/Aviator-Predictor/issues" 95 | }, 96 | "engines": { 97 | "node": "*" 98 | }, 99 | "homepage": "https://github.com/crashpredictorss/Aviator-Predictor", 100 | "devDependencies": { 101 | "@rollup/plugin-terser": "^0.4.3", 102 | "@rollup/plugin-typescript": "^11.1.2", 103 | "@types/chai": "^4.3.5", 104 | "@types/mocha": "^10.0.1", 105 | "@types/rewire": "^2.5.28", 106 | "@types/sinon": "^10.0.16", 107 | "@typescript-eslint/eslint-plugin": "^6.2.1", 108 | "@typescript-eslint/parser": "^6.2.1", 109 | "chai": "^4.3.7", 110 | "eslint": "^8.46.0", 111 | "husky": "^8.0.3", 112 | "karma": "^6.4.2", 113 | "karma-chai": "^0.1.0", 114 | "karma-chrome-launcher": "^3.2.0", 115 | "karma-firefox-launcher": "^2.1.2", 116 | "karma-mocha": "^2.0.1", 117 | "lint-staged": "^13.2.3", 118 | "mocha": "^10.2.0", 119 | "nyc": "^15.1.0", 120 | "prettier": "^3.0.1", 121 | "rewire": "^6.0.0", 122 | "rollup": "^3.27.2", 123 | "rollup-plugin-dts": "^5.3.1", 124 | "sinon": "^15.2.0", 125 | "ts-node": "^10.9.1", 126 | "tslib": "^2.6.1", 127 | "typescript": "<5.5" 128 | }, 129 | "scripts": { 130 | "build": "rollup -c", 131 | "test": "echo \"skip tests\"", 132 | "test_dist": "mocha test/dist/ && karma start karma.conf.js --file-variant sha && karma start karma.conf.js --file-variant sha1 && karma start karma.conf.js --file-variant sha256 && karma start karma.conf.js --file-variant sha512 && karma start karma.conf.js --file-variant sha3", 133 | "prepare": "husky install" 134 | }, 135 | "mocha": { 136 | "require": [ 137 | "ts-node/register" 138 | ], 139 | "timeout": 10000 140 | }, 141 | "nyc": { 142 | "require": [ 143 | "ts-node/register" 144 | ], 145 | "exclude": [ 146 | "dist", 147 | "*.js", 148 | "coverage", 149 | "test", 150 | "rollup.config.mjs" 151 | ], 152 | "reporter": [ 153 | "text", 154 | "html" 155 | ], 156 | "all": true 157 | }, 158 | "prettier": { 159 | "printWidth": 120, 160 | "proseWrap": "always", 161 | "overrides": [ 162 | { 163 | "files": "*.md", 164 | "options": { 165 | "printWidth": 80 166 | } 167 | } 168 | ] 169 | }, 170 | "lint-staged": { 171 | "*.{js,ts}": "eslint --cache --fix", 172 | "*.{js,ts,css,md,html,json}": "prettier --write" 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/sha.ts: -------------------------------------------------------------------------------- 1 | import { sha_variant_error } from "./common"; 2 | import { 3 | CSHAKEOptionsEncodingType, 4 | CSHAKEOptionsNoEncodingType, 5 | SHAKEOptionsEncodingType, 6 | SHAKEOptionsNoEncodingType, 7 | EncodingType, 8 | formating, 9 | FixedLengthOptionsEncodingType, 10 | FixedLengthOptionsNoEncodingType, 11 | FormatNoTextType, 12 | KMACOptionsNoEncodingType, 13 | KMACOptionsEncodingType, 14 | } from "./custom_types"; 15 | import jsSHA1 from "./sha1"; 16 | import jsSHA256 from "./sha256"; 17 | import jsSHA512 from "./sha512"; 18 | import jsSHA3 from "./sha3"; 19 | 20 | type FixedLengthVariantType = 21 | | "SHA-1" 22 | | "SHA-224" 23 | | "SHA-256" 24 | | "SHA-384" 25 | | "SHA-512" 26 | | "SHA3-224" 27 | | "SHA3-256" 28 | | "SHA3-384" 29 | | "SHA3-512"; 30 | 31 | export default class jsSHA { 32 | private readonly shaObj: jsSHA1 | jsSHA256 | jsSHA512 | jsSHA3; 33 | 34 | /** 35 | * Creates a new SHA hash instance 36 | * @param variant The desired SHA variant (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, 37 | * SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256, CSHAKE128, CSHAKE256, 38 | * KMAC128, or KMAC256) 39 | * @param inputFormat The format for input data (TEXT, HEX, B64, BYTES, ARRAYBUFFER, UINT8ARRAY) 40 | * @param options Additional settings like encoding, number of rounds, or keys 41 | */ 42 | constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 43 | constructor( 44 | variant: FixedLengthVariantType, 45 | inputFormat: FormatNoTextType, 46 | options?: FixedLengthOptionsNoEncodingType 47 | ); 48 | constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType); 49 | constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType); 50 | constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType); 51 | constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType); 52 | constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType); 53 | constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType); 54 | 55 | // Implementation 56 | constructor(variant: any, inputFormat: any, options?: any) { 57 | // Variant groups for quick membership checks 58 | const SHA1_VARIANTS = new Set(["SHA-1"]); 59 | const SHA256_VARIANTS = new Set(["SHA-224", "SHA-256"]); 60 | const SHA512_VARIANTS = new Set(["SHA-384", "SHA-512"]); 61 | const SHA3_VARIANTS = new Set(["SHA3-224", "SHA3-256", "SHA3-384", "SHA3-512"]); 62 | const XOF_AND_KMAC_VARIANTS = new Set([ 63 | "SHAKE128", 64 | "SHAKE256", 65 | "CSHAKE128", 66 | "CSHAKE256", 67 | "KMAC128", 68 | "KMAC256", 69 | ]); 70 | 71 | if (SHA1_VARIANTS.has(variant)) { 72 | this.shaObj = new jsSHA1(variant, inputFormat, options); 73 | return; 74 | } 75 | 76 | if (SHA256_VARIANTS.has(variant)) { 77 | this.shaObj = new jsSHA256(variant, inputFormat, options); 78 | return; 79 | } 80 | 81 | if (SHA512_VARIANTS.has(variant)) { 82 | this.shaObj = new jsSHA512(variant, inputFormat, options); 83 | return; 84 | } 85 | 86 | if (SHA3_VARIANTS.has(variant) || XOF_AND_KMAC_VARIANTS.has(variant)) { 87 | // jsSHA3 handles SHA3 family, XOFs (SHAKE/CSHAKE) and KMAC variants 88 | this.shaObj = new jsSHA3(variant, inputFormat, options); 89 | return; 90 | } 91 | 92 | throw new Error(sha_variant_error); 93 | } 94 | 95 | /** 96 | * Update the internal hash state with more data. 97 | * Accepts strings, ArrayBuffer, Uint8Array or any ArrayBufferView. 98 | */ 99 | update(input: string | ArrayBuffer | Uint8Array | ArrayBufferView): this { 100 | // delegate to inner implementation 101 | // jsSHA implementations accept the same shapes; if not, they will throw appropriately 102 | (this.shaObj as any).update(input); 103 | return this; 104 | } 105 | 106 | // getHash overloads 107 | getHash(format: "HEX", options?: { outputUpper?: boolean; outputLen?: number; shakeLen?: number }): string; 108 | getHash(format: "B64", options?: { b64Pad?: string; outputLen?: number; shakeLen?: number }): string; 109 | getHash(format: "BYTES", options?: { outputLen?: number; shakeLen?: number }): string; 110 | getHash(format: "UINT8ARRAY", options?: { outputLen?: number; shakeLen?: number }): Uint8Array; 111 | getHash(format: "ARRAYBUFFER", options?: { outputLen?: number; shakeLen?: number }): ArrayBuffer; 112 | getHash(format: any, options?: any): any { 113 | return (this.shaObj as any).getHash(format, options); 114 | } 115 | 116 | // setHMACKey overloads 117 | setHMACKey(key: string, inputFormat: "TEXT", options?: { encoding?: EncodingType }): void; 118 | setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void; 119 | setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void; 120 | setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void; 121 | setHMACKey(key: any, inputFormat: any, options?: any): void { 122 | (this.shaObj as any).setHMACKey(key, inputFormat, options); 123 | } 124 | 125 | // getHMAC overloads 126 | getHMAC(format: "HEX", options?: { outputUpper?: boolean }): string; 127 | getHMAC(format: "B64", options?: { b64Pad?: string }): string; 128 | getHMAC(format: "BYTES"): string; 129 | getHMAC(format: "UINT8ARRAY"): Uint8Array; 130 | getHMAC(format: "ARRAYBUFFER"): ArrayBuffer; 131 | getHMAC(format: any, options?: any): any { 132 | return (this.shaObj as any).getHMAC(format, options); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/sha1.ts: -------------------------------------------------------------------------------- 1 | import { jsSHABase, TWO_PWR_32, sha_variant_error, parseInputOption } from "./common"; 2 | import { 3 | packedValue, 4 | FixedLengthOptionsEncodingType, 5 | FixedLengthOptionsNoEncodingType, 6 | FormatNoTextType, 7 | } from "./custom_types"; 8 | import { getStrConverter } from "./converters"; 9 | import { ch_32, parity_32, maj_32, rotl_32, safeAdd_32_2, safeAdd_32_5 } from "./primitives_32"; 10 | 11 | /** 12 | * Gets the state values for the specified SHA variant. 13 | * 14 | * @param _variant: Unused 15 | * @returns The initial state values. 16 | */ 17 | function getNewState(_variant: "SHA-1"): number[] { 18 | return [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; 19 | } 20 | 21 | /** 22 | * Performs a round of SHA-1 hashing over a 512-byte block. This clobbers `H`. 23 | * 24 | * @param block The binary array representation of the block to hash. 25 | * @param H The intermediate H values from a previous round. 26 | * @returns The resulting H values. 27 | */ 28 | function roundSHA1(block: number[], H: number[]): number[] { 29 | let a, b, c, d, e, T, t; 30 | const W: number[] = []; 31 | 32 | a = H[0]; 33 | b = H[1]; 34 | c = H[2]; 35 | d = H[3]; 36 | e = H[4]; 37 | 38 | for (t = 0; t < 80; t += 1) { 39 | if (t < 16) { 40 | W[t] = block[t]; 41 | } else { 42 | W[t] = rotl_32(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); 43 | } 44 | 45 | if (t < 20) { 46 | T = safeAdd_32_5(rotl_32(a, 5), ch_32(b, c, d), e, 0x5a827999, W[t]); 47 | } else if (t < 40) { 48 | T = safeAdd_32_5(rotl_32(a, 5), parity_32(b, c, d), e, 0x6ed9eba1, W[t]); 49 | } else if (t < 60) { 50 | T = safeAdd_32_5(rotl_32(a, 5), maj_32(b, c, d), e, 0x8f1bbcdc, W[t]); 51 | } else { 52 | T = safeAdd_32_5(rotl_32(a, 5), parity_32(b, c, d), e, 0xca62c1d6, W[t]); 53 | } 54 | 55 | e = d; 56 | d = c; 57 | c = rotl_32(b, 30); 58 | b = a; 59 | a = T; 60 | } 61 | 62 | H[0] = safeAdd_32_2(a, H[0]); 63 | H[1] = safeAdd_32_2(b, H[1]); 64 | H[2] = safeAdd_32_2(c, H[2]); 65 | H[3] = safeAdd_32_2(d, H[3]); 66 | H[4] = safeAdd_32_2(e, H[4]); 67 | 68 | return H; 69 | } 70 | 71 | /** 72 | * Finalizes the SHA-1 hash. This clobbers `remainder` and `H`. 73 | * 74 | * @param remainder Any leftover unprocessed packed ints that still need to be processed. 75 | * @param remainderBinLen The number of bits in `remainder`. 76 | * @param processedBinLen The number of bits already processed. 77 | * @param H The intermediate H values from a previous round. 78 | * @returns The array of integers representing the SHA-1 hash of message. 79 | */ 80 | function finalizeSHA1(remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]): number[] { 81 | let i; 82 | 83 | /* The 65 addition is a hack but it works. The correct number is 84 | actually 72 (64 + 8) but the below math fails if 85 | remainderBinLen + 72 % 512 = 0. Since remainderBinLen % 8 = 0, 86 | "shorting" the addition is OK. */ 87 | const offset = (((remainderBinLen + 65) >>> 9) << 4) + 15, 88 | totalLen = remainderBinLen + processedBinLen; 89 | while (remainder.length <= offset) { 90 | remainder.push(0); 91 | } 92 | /* Append '1' at the end of the binary string */ 93 | remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32)); 94 | 95 | /* Append length of binary string in the position such that the new 96 | * length is a multiple of 512. Logic does not work for even multiples 97 | * of 512 but there can never be even multiples of 512. JavaScript 98 | * numbers are limited to 2^53 so it's "safe" to treat the totalLen as 99 | * a 64-bit integer. */ 100 | remainder[offset] = totalLen & 0xffffffff; 101 | 102 | /* Bitwise operators treat the operand as a 32-bit number so need to 103 | * use hacky division and round to get access to upper 32-ish bits */ 104 | remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0; 105 | 106 | /* This will always be at least 1 full chunk */ 107 | for (i = 0; i < remainder.length; i += 16) { 108 | H = roundSHA1(remainder.slice(i, i + 16), H); 109 | } 110 | 111 | return H; 112 | } 113 | 114 | export default class jsSHA extends jsSHABase { 115 | intermediateState: number[]; 116 | variantBlockSize: number; 117 | bigEndianMod: -1 | 1; 118 | outputBinLen: number; 119 | isVariableLen: boolean; 120 | HMACSupported: boolean; 121 | 122 | /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ 123 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 124 | roundFunc: (block: number[], H: number[]) => number[]; 125 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[]; 126 | stateCloneFunc: (state: number[]) => number[]; 127 | newStateFunc: (variant: "SHA-1") => number[]; 128 | getMAC: () => number[]; 129 | 130 | constructor(variant: "SHA-1", inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 131 | constructor(variant: "SHA-1", inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 132 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 133 | constructor(variant: any, inputFormat: any, options?: any) { 134 | if ("SHA-1" !== variant) { 135 | throw new Error(sha_variant_error); 136 | } 137 | super(variant, inputFormat, options); 138 | const resolvedOptions = options || {}; 139 | 140 | this.HMACSupported = true; 141 | // eslint-disable-next-line @typescript-eslint/unbound-method 142 | this.getMAC = this._getHMAC; 143 | this.bigEndianMod = -1; 144 | this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod); 145 | this.roundFunc = roundSHA1; 146 | this.stateCloneFunc = function (state: number[]): number[] { 147 | return state.slice(); 148 | }; 149 | this.newStateFunc = getNewState; 150 | this.finalizeFunc = finalizeSHA1; 151 | 152 | this.intermediateState = getNewState(variant); 153 | this.variantBlockSize = 512; 154 | this.outputBinLen = 160; 155 | this.isVariableLen = false; 156 | 157 | if (resolvedOptions["hmacKey"]) { 158 | this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod)); 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/primitives_32.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Note 1: All the functions in this file guarantee only that the bottom 32-bits of the return value are correct. 3 | * JavaScript is flakey when it comes to bit operations and a '1' in the highest order bit of a 32-bit number causes 4 | * it to be interpreted as a negative number per two's complement. 5 | * 6 | * Note 2: Per the ECMAScript spec, all JavaScript operations mask the shift amount by 0x1F. This results in weird 7 | * cases like 1 << 32 == 1 and 1 << 33 === 1 << 1 === 2 8 | */ 9 | 10 | /** 11 | * The 32-bit implementation of circular rotate left. 12 | * 13 | * @param x The 32-bit integer argument. 14 | * @param n The number of bits to shift. 15 | * @returns `x` shifted left circularly by `n` bits 16 | */ 17 | export function rotl_32(x: number, n: number): number { 18 | return (x << n) | (x >>> (32 - n)); 19 | } 20 | 21 | /** 22 | * The 32-bit implementation of circular rotate right. 23 | * 24 | * @param x The 32-bit integer argument. 25 | * @param n The number of bits to shift. 26 | * @returns `x` shifted right circularly by `n` bits 27 | */ 28 | function rotr_32(x: number, n: number): number { 29 | return (x >>> n) | (x << (32 - n)); 30 | } 31 | 32 | /** 33 | * The 32-bit implementation of shift right. 34 | * 35 | * @param x The 32-bit integer argument. 36 | * @param n The number of bits to shift. 37 | * @returns `x` shifted by `n` bits. 38 | */ 39 | function shr_32(x: number, n: number): number { 40 | return x >>> n; 41 | } 42 | 43 | /** 44 | * The 32-bit implementation of the NIST specified Parity function. 45 | * 46 | * @param x The first 32-bit integer argument. 47 | * @param y The second 32-bit integer argument. 48 | * @param z The third 32-bit integer argument. 49 | * @returns The NIST specified output of the function. 50 | */ 51 | export function parity_32(x: number, y: number, z: number): number { 52 | return x ^ y ^ z; 53 | } 54 | 55 | /** 56 | * The 32-bit implementation of the NIST specified Ch function. 57 | * 58 | * @param x The first 32-bit integer argument. 59 | * @param y The second 32-bit integer argument. 60 | * @param z The third 32-bit integer argument. 61 | * @returns The NIST specified output of the function. 62 | */ 63 | export function ch_32(x: number, y: number, z: number): number { 64 | return (x & y) ^ (~x & z); 65 | } 66 | 67 | /** 68 | * The 32-bit implementation of the NIST specified Maj function. 69 | * 70 | * @param x The first 32-bit integer argument. 71 | * @param y The second 32-bit integer argument. 72 | * @param z The third 32-bit integer argument. 73 | * @returns The NIST specified output of the function. 74 | */ 75 | export function maj_32(x: number, y: number, z: number): number { 76 | return (x & y) ^ (x & z) ^ (y & z); 77 | } 78 | 79 | /** 80 | * The 32-bit implementation of the NIST specified Sigma0 function. 81 | * 82 | * @param x The 32-bit integer argument. 83 | * @returns The NIST specified output of the function. 84 | */ 85 | export function sigma0_32(x: number): number { 86 | return rotr_32(x, 2) ^ rotr_32(x, 13) ^ rotr_32(x, 22); 87 | } 88 | 89 | /** 90 | * Add two 32-bit integers. 91 | * 92 | * This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support. 93 | * 94 | * @param a The first 32-bit integer argument to be added. 95 | * @param b The second 32-bit integer argument to be added. 96 | * @returns The sum of `a` + `b`. 97 | */ 98 | export function safeAdd_32_2(a: number, b: number): number { 99 | const lsw = (a & 0xffff) + (b & 0xffff), 100 | msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16); 101 | 102 | return ((msw & 0xffff) << 16) | (lsw & 0xffff); 103 | } 104 | 105 | /** 106 | * Add four 32-bit integers. 107 | * 108 | * This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support. 109 | * 110 | * @param a The first 32-bit integer argument to be added. 111 | * @param b The second 32-bit integer argument to be added. 112 | * @param c The third 32-bit integer argument to be added. 113 | * @param d The fourth 32-bit integer argument to be added. 114 | * @returns The sum of `a` + `b` + `c` + `d`. 115 | */ 116 | export function safeAdd_32_4(a: number, b: number, c: number, d: number): number { 117 | const lsw = (a & 0xffff) + (b & 0xffff) + (c & 0xffff) + (d & 0xffff), 118 | msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (lsw >>> 16); 119 | 120 | return ((msw & 0xffff) << 16) | (lsw & 0xffff); 121 | } 122 | 123 | /** 124 | * Add five 32-bit integers. 125 | * 126 | * This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support. 127 | * 128 | * @param a The first 32-bit integer argument to be added. 129 | * @param b The second 32-bit integer argument to be added. 130 | * @param c The third 32-bit integer argument to be added. 131 | * @param d The fourth 32-bit integer argument to be added. 132 | * @param e The fifth 32-bit integer argument to be added. 133 | * @returns The sum of `a` + `b` + `c` + `d` + `e`. 134 | */ 135 | export function safeAdd_32_5(a: number, b: number, c: number, d: number, e: number): number { 136 | const lsw = (a & 0xffff) + (b & 0xffff) + (c & 0xffff) + (d & 0xffff) + (e & 0xffff), 137 | msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (e >>> 16) + (lsw >>> 16); 138 | 139 | return ((msw & 0xffff) << 16) | (lsw & 0xffff); 140 | } 141 | 142 | /** 143 | * The 32-bit implementation of the NIST specified Gamma1 function. 144 | * 145 | * @param x The 32-bit integer argument. 146 | * @returns The NIST specified output of the function. 147 | */ 148 | export function gamma1_32(x: number): number { 149 | return rotr_32(x, 17) ^ rotr_32(x, 19) ^ shr_32(x, 10); 150 | } 151 | 152 | /** 153 | * The 32-bit implementation of the NIST specified Gamma0 function. 154 | * 155 | * @param x The 32-bit integer argument. 156 | * @returns The NIST specified output of the function. 157 | */ 158 | export function gamma0_32(x: number): number { 159 | return rotr_32(x, 7) ^ rotr_32(x, 18) ^ shr_32(x, 3); 160 | } 161 | 162 | /** 163 | * The 32-bit implementation of the NIST specified Sigma1 function. 164 | * 165 | * @param x The 32-bit integer argument. 166 | * @returns The NIST specified output of the function. 167 | */ 168 | export function sigma1_32(x: number): number { 169 | return rotr_32(x, 6) ^ rotr_32(x, 11) ^ rotr_32(x, 25); 170 | } 171 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import fs from "fs"; 2 | import dts from "rollup-plugin-dts"; 3 | import typescript from "@rollup/plugin-typescript"; 4 | import terser from "@rollup/plugin-terser"; 5 | 6 | const licenseHeaderES3 = fs.readFileSync("src/license_header.es3.txt", { encoding: "utf8" }), 7 | licenseHeaderES6 = fs.readFileSync("src/license_header.es6.txt", { encoding: "utf8" }); 8 | 9 | export default [ 10 | { 11 | input: "src/sha.ts", 12 | output: { 13 | name: "jsSHA", 14 | banner: licenseHeaderES3, 15 | format: "umd", 16 | sourcemap: true, 17 | dir: "dist", 18 | entryFileNames: "[name].js", 19 | }, 20 | plugins: [ 21 | typescript({ lib: ["es6"], declaration: true, declarationDir: "dist/types", target: "es3" }), 22 | terser({ 23 | output: { comments: /BSD/ }, 24 | mangle: { 25 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 26 | }, 27 | }), 28 | ], 29 | }, 30 | { 31 | input: "src/sha.ts", 32 | output: { 33 | name: "jsSHA", 34 | banner: licenseHeaderES6, 35 | format: "es", 36 | sourcemap: true, 37 | file: "dist/sha.mjs", 38 | }, 39 | plugins: [ 40 | typescript({ lib: ["es6"], target: "es6" }), 41 | terser({ 42 | output: { comments: /BSD/ }, 43 | mangle: { 44 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 45 | }, 46 | }), 47 | ], 48 | }, 49 | { 50 | input: "dist/types/src/sha.d.ts", 51 | output: [{ file: "dist/sha.d.ts", format: "umd" }], 52 | plugins: [dts()], 53 | }, 54 | { 55 | input: "src/sha1.ts", 56 | output: { 57 | name: "jsSHA", 58 | banner: licenseHeaderES3, 59 | format: "umd", 60 | file: "dist/sha1.js", 61 | }, 62 | plugins: [ 63 | typescript({ lib: ["es6"], target: "es3" }), 64 | terser({ 65 | output: { comments: /BSD/ }, 66 | mangle: { 67 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 68 | }, 69 | }), 70 | ], 71 | }, 72 | { 73 | input: "src/sha1.ts", 74 | output: { 75 | name: "jsSHA", 76 | banner: licenseHeaderES6, 77 | format: "es", 78 | file: "dist/sha1.mjs", 79 | }, 80 | plugins: [ 81 | typescript({ lib: ["es6"], target: "es6" }), 82 | terser({ 83 | output: { comments: /BSD/ }, 84 | mangle: { 85 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 86 | }, 87 | }), 88 | ], 89 | }, 90 | { 91 | input: "dist/types/src/sha1.d.ts", 92 | output: [{ file: "dist/sha1.d.ts", format: "umd" }], 93 | plugins: [dts()], 94 | }, 95 | { 96 | input: "src/sha256.ts", 97 | output: { 98 | name: "jsSHA", 99 | banner: licenseHeaderES3, 100 | format: "umd", 101 | file: "dist/sha256.js", 102 | }, 103 | plugins: [ 104 | typescript({ lib: ["es6"], target: "es3" }), 105 | terser({ 106 | output: { comments: /BSD/ }, 107 | mangle: { 108 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 109 | }, 110 | }), 111 | ], 112 | }, 113 | { 114 | input: "src/sha256.ts", 115 | output: { 116 | name: "jsSHA", 117 | banner: licenseHeaderES6, 118 | format: "es", 119 | file: "dist/sha256.mjs", 120 | }, 121 | plugins: [ 122 | typescript({ lib: ["es6"], target: "es6" }), 123 | terser({ 124 | output: { comments: /BSD/ }, 125 | mangle: { 126 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 127 | }, 128 | }), 129 | ], 130 | }, 131 | { 132 | input: "dist/types/src/sha256.d.ts", 133 | output: [{ file: "dist/sha256.d.ts", format: "umd" }], 134 | plugins: [dts()], 135 | }, 136 | { 137 | input: "src/sha512.ts", 138 | output: { 139 | name: "jsSHA", 140 | banner: licenseHeaderES3, 141 | format: "umd", 142 | file: "dist/sha512.js", 143 | }, 144 | plugins: [ 145 | typescript({ lib: ["es6"], target: "es3" }), 146 | terser({ 147 | output: { comments: /BSD/ }, 148 | mangle: { 149 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 150 | }, 151 | }), 152 | ], 153 | }, 154 | { 155 | input: "src/sha512.ts", 156 | output: { 157 | name: "jsSHA", 158 | banner: licenseHeaderES6, 159 | format: "es", 160 | file: "dist/sha512.mjs", 161 | }, 162 | plugins: [ 163 | typescript({ lib: ["es6"], target: "es6" }), 164 | terser({ 165 | output: { comments: /BSD/ }, 166 | mangle: { 167 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 168 | }, 169 | }), 170 | ], 171 | }, 172 | { 173 | input: "dist/types/src/sha512.d.ts", 174 | output: [{ file: "dist/sha512.d.ts", format: "umd" }], 175 | plugins: [dts()], 176 | }, 177 | { 178 | input: "src/sha3.ts", 179 | output: { 180 | name: "jsSHA", 181 | banner: licenseHeaderES3, 182 | format: "umd", 183 | file: "dist/sha3.js", 184 | }, 185 | plugins: [ 186 | typescript({ lib: ["es6"], target: "es3" }), 187 | terser({ 188 | output: { comments: /BSD/ }, 189 | mangle: { 190 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 191 | }, 192 | }), 193 | ], 194 | }, 195 | { 196 | input: "src/sha3.ts", 197 | output: { 198 | name: "jsSHA", 199 | banner: licenseHeaderES6, 200 | format: "es", 201 | file: "dist/sha3.mjs", 202 | }, 203 | plugins: [ 204 | typescript({ lib: ["es6"], target: "es6" }), 205 | terser({ 206 | output: { comments: /BSD/ }, 207 | mangle: { 208 | properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] }, 209 | }, 210 | }), 211 | ], 212 | }, 213 | { 214 | input: "dist/types/src/sha3.d.ts", 215 | output: [{ file: "dist/sha3.d.ts", format: "umd" }], 216 | plugins: [dts()], 217 | }, 218 | ]; 219 | -------------------------------------------------------------------------------- /dist/sha1.d.ts: -------------------------------------------------------------------------------- 1 | type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE"; 2 | type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY"; 3 | type FormatType = "TEXT" | FormatNoTextType; 4 | type GenericInputType = { 5 | value: string; 6 | format: "TEXT"; 7 | encoding?: EncodingType; 8 | } | { 9 | value: string; 10 | format: "B64" | "HEX" | "BYTES"; 11 | } | { 12 | value: ArrayBuffer; 13 | format: "ARRAYBUFFER"; 14 | } | { 15 | value: Uint8Array; 16 | format: "UINT8ARRAY"; 17 | }; 18 | type FixedLengthOptionsNoEncodingType = { 19 | hmacKey?: GenericInputType; 20 | } | { 21 | numRounds?: number; 22 | }; 23 | type FixedLengthOptionsEncodingType = { 24 | hmacKey?: GenericInputType; 25 | encoding?: EncodingType; 26 | } | { 27 | numRounds?: number; 28 | encoding?: EncodingType; 29 | }; 30 | interface packedValue { 31 | value: number[]; 32 | binLen: number; 33 | } 34 | 35 | declare abstract class jsSHABase { 36 | /** 37 | * @param variant The desired SHA variant. 38 | * @param inputFormat The input format to be used in future `update` calls. 39 | * @param options Hashmap of extra input options. 40 | */ 41 | protected readonly shaVariant: VariantT; 42 | protected readonly inputFormat: FormatType; 43 | protected readonly utfType: EncodingType; 44 | protected readonly numRounds: number; 45 | protected abstract intermediateState: StateT; 46 | protected keyWithIPad: number[]; 47 | protected keyWithOPad: number[]; 48 | protected remainder: number[]; 49 | protected remainderLen: number; 50 | protected updateCalled: boolean; 51 | protected processedLen: number; 52 | protected macKeySet: boolean; 53 | protected abstract readonly variantBlockSize: number; 54 | protected abstract readonly bigEndianMod: -1 | 1; 55 | protected abstract readonly outputBinLen: number; 56 | protected abstract readonly isVariableLen: boolean; 57 | protected abstract readonly HMACSupported: boolean; 58 | protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 59 | protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT; 60 | protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[]; 61 | protected abstract readonly stateCloneFunc: (state: StateT) => StateT; 62 | protected abstract readonly newStateFunc: (variant: VariantT) => StateT; 63 | protected abstract readonly getMAC: ((options: { 64 | outputLen: number; 65 | }) => number[]) | null; 66 | protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 67 | protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 68 | /** 69 | * Hashes as many blocks as possible. Stores the rest for either a future update or getHash call. 70 | * 71 | * @param srcString The input to be hashed. 72 | * @returns A reference to the object. 73 | */ 74 | update(srcString: string | ArrayBuffer | Uint8Array): this; 75 | /** 76 | * Returns the desired SHA hash of the input fed in via `update` calls. 77 | * 78 | * @param format The desired output formatting 79 | * @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes. 80 | * `outputLen` replaces the now deprecated `shakeLen` key. 81 | * @returns The hash in the format specified. 82 | */ 83 | getHash(format: "HEX", options?: { 84 | outputUpper?: boolean; 85 | outputLen?: number; 86 | shakeLen?: number; 87 | }): string; 88 | getHash(format: "B64", options?: { 89 | b64Pad?: string; 90 | outputLen?: number; 91 | shakeLen?: number; 92 | }): string; 93 | getHash(format: "BYTES", options?: { 94 | outputLen?: number; 95 | shakeLen?: number; 96 | }): string; 97 | getHash(format: "UINT8ARRAY", options?: { 98 | outputLen?: number; 99 | shakeLen?: number; 100 | }): Uint8Array; 101 | getHash(format: "ARRAYBUFFER", options?: { 102 | outputLen?: number; 103 | shakeLen?: number; 104 | }): ArrayBuffer; 105 | /** 106 | * Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation. 107 | * 108 | * @param key The key used to calculate the HMAC 109 | * @param inputFormat The format of key. 110 | * @param options Hashmap of extra input options. 111 | */ 112 | setHMACKey(key: string, inputFormat: "TEXT", options?: { 113 | encoding?: EncodingType; 114 | }): void; 115 | setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void; 116 | setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void; 117 | setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void; 118 | /** 119 | * Internal function that sets the MAC key. 120 | * 121 | * @param key The packed MAC key to use 122 | */ 123 | protected _setHMACKey(key: packedValue): void; 124 | /** 125 | * Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. 126 | * 127 | * @param format The desired output formatting. 128 | * @param options Hashmap of extra outputs options. 129 | * @returns The HMAC in the format specified. 130 | */ 131 | getHMAC(format: "HEX", options?: { 132 | outputUpper?: boolean; 133 | }): string; 134 | getHMAC(format: "B64", options?: { 135 | b64Pad?: string; 136 | }): string; 137 | getHMAC(format: "BYTES"): string; 138 | getHMAC(format: "UINT8ARRAY"): Uint8Array; 139 | getHMAC(format: "ARRAYBUFFER"): ArrayBuffer; 140 | /** 141 | * Internal function that returns the "raw" HMAC 142 | */ 143 | protected _getHMAC(): number[]; 144 | } 145 | 146 | declare class jsSHA extends jsSHABase { 147 | intermediateState: number[]; 148 | variantBlockSize: number; 149 | bigEndianMod: -1 | 1; 150 | outputBinLen: number; 151 | isVariableLen: boolean; 152 | HMACSupported: boolean; 153 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 154 | roundFunc: (block: number[], H: number[]) => number[]; 155 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[]; 156 | stateCloneFunc: (state: number[]) => number[]; 157 | newStateFunc: (variant: "SHA-1") => number[]; 158 | getMAC: () => number[]; 159 | constructor(variant: "SHA-1", inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 160 | constructor(variant: "SHA-1", inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 161 | } 162 | 163 | export { jsSHA as default }; 164 | -------------------------------------------------------------------------------- /dist/sha256.d.ts: -------------------------------------------------------------------------------- 1 | type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE"; 2 | type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY"; 3 | type FormatType = "TEXT" | FormatNoTextType; 4 | type GenericInputType = { 5 | value: string; 6 | format: "TEXT"; 7 | encoding?: EncodingType; 8 | } | { 9 | value: string; 10 | format: "B64" | "HEX" | "BYTES"; 11 | } | { 12 | value: ArrayBuffer; 13 | format: "ARRAYBUFFER"; 14 | } | { 15 | value: Uint8Array; 16 | format: "UINT8ARRAY"; 17 | }; 18 | type FixedLengthOptionsNoEncodingType = { 19 | hmacKey?: GenericInputType; 20 | } | { 21 | numRounds?: number; 22 | }; 23 | type FixedLengthOptionsEncodingType = { 24 | hmacKey?: GenericInputType; 25 | encoding?: EncodingType; 26 | } | { 27 | numRounds?: number; 28 | encoding?: EncodingType; 29 | }; 30 | interface packedValue { 31 | value: number[]; 32 | binLen: number; 33 | } 34 | 35 | declare abstract class jsSHABase { 36 | /** 37 | * @param variant The desired SHA variant. 38 | * @param inputFormat The input format to be used in future `update` calls. 39 | * @param options Hashmap of extra input options. 40 | */ 41 | protected readonly shaVariant: VariantT; 42 | protected readonly inputFormat: FormatType; 43 | protected readonly utfType: EncodingType; 44 | protected readonly numRounds: number; 45 | protected abstract intermediateState: StateT; 46 | protected keyWithIPad: number[]; 47 | protected keyWithOPad: number[]; 48 | protected remainder: number[]; 49 | protected remainderLen: number; 50 | protected updateCalled: boolean; 51 | protected processedLen: number; 52 | protected macKeySet: boolean; 53 | protected abstract readonly variantBlockSize: number; 54 | protected abstract readonly bigEndianMod: -1 | 1; 55 | protected abstract readonly outputBinLen: number; 56 | protected abstract readonly isVariableLen: boolean; 57 | protected abstract readonly HMACSupported: boolean; 58 | protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 59 | protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT; 60 | protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[]; 61 | protected abstract readonly stateCloneFunc: (state: StateT) => StateT; 62 | protected abstract readonly newStateFunc: (variant: VariantT) => StateT; 63 | protected abstract readonly getMAC: ((options: { 64 | outputLen: number; 65 | }) => number[]) | null; 66 | protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 67 | protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 68 | /** 69 | * Hashes as many blocks as possible. Stores the rest for either a future update or getHash call. 70 | * 71 | * @param srcString The input to be hashed. 72 | * @returns A reference to the object. 73 | */ 74 | update(srcString: string | ArrayBuffer | Uint8Array): this; 75 | /** 76 | * Returns the desired SHA hash of the input fed in via `update` calls. 77 | * 78 | * @param format The desired output formatting 79 | * @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes. 80 | * `outputLen` replaces the now deprecated `shakeLen` key. 81 | * @returns The hash in the format specified. 82 | */ 83 | getHash(format: "HEX", options?: { 84 | outputUpper?: boolean; 85 | outputLen?: number; 86 | shakeLen?: number; 87 | }): string; 88 | getHash(format: "B64", options?: { 89 | b64Pad?: string; 90 | outputLen?: number; 91 | shakeLen?: number; 92 | }): string; 93 | getHash(format: "BYTES", options?: { 94 | outputLen?: number; 95 | shakeLen?: number; 96 | }): string; 97 | getHash(format: "UINT8ARRAY", options?: { 98 | outputLen?: number; 99 | shakeLen?: number; 100 | }): Uint8Array; 101 | getHash(format: "ARRAYBUFFER", options?: { 102 | outputLen?: number; 103 | shakeLen?: number; 104 | }): ArrayBuffer; 105 | /** 106 | * Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation. 107 | * 108 | * @param key The key used to calculate the HMAC 109 | * @param inputFormat The format of key. 110 | * @param options Hashmap of extra input options. 111 | */ 112 | setHMACKey(key: string, inputFormat: "TEXT", options?: { 113 | encoding?: EncodingType; 114 | }): void; 115 | setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void; 116 | setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void; 117 | setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void; 118 | /** 119 | * Internal function that sets the MAC key. 120 | * 121 | * @param key The packed MAC key to use 122 | */ 123 | protected _setHMACKey(key: packedValue): void; 124 | /** 125 | * Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. 126 | * 127 | * @param format The desired output formatting. 128 | * @param options Hashmap of extra outputs options. 129 | * @returns The HMAC in the format specified. 130 | */ 131 | getHMAC(format: "HEX", options?: { 132 | outputUpper?: boolean; 133 | }): string; 134 | getHMAC(format: "B64", options?: { 135 | b64Pad?: string; 136 | }): string; 137 | getHMAC(format: "BYTES"): string; 138 | getHMAC(format: "UINT8ARRAY"): Uint8Array; 139 | getHMAC(format: "ARRAYBUFFER"): ArrayBuffer; 140 | /** 141 | * Internal function that returns the "raw" HMAC 142 | */ 143 | protected _getHMAC(): number[]; 144 | } 145 | 146 | type VariantType = "SHA-224" | "SHA-256"; 147 | declare class jsSHA extends jsSHABase { 148 | intermediateState: number[]; 149 | variantBlockSize: number; 150 | bigEndianMod: -1 | 1; 151 | outputBinLen: number; 152 | isVariableLen: boolean; 153 | HMACSupported: boolean; 154 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 155 | roundFunc: (block: number[], H: number[]) => number[]; 156 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[]; 157 | stateCloneFunc: (state: number[]) => number[]; 158 | newStateFunc: (variant: VariantType) => number[]; 159 | getMAC: () => number[]; 160 | constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 161 | constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 162 | } 163 | 164 | export { jsSHA as default }; 165 | -------------------------------------------------------------------------------- /src/sha256.ts: -------------------------------------------------------------------------------- 1 | import { jsSHABase, TWO_PWR_32, H_full, H_trunc, K_sha2, sha_variant_error, parseInputOption } from "./common"; 2 | import { 3 | packedValue, 4 | FixedLengthOptionsEncodingType, 5 | FixedLengthOptionsNoEncodingType, 6 | FormatNoTextType, 7 | } from "./custom_types"; 8 | import { getStrConverter } from "./converters"; 9 | import { 10 | ch_32, 11 | gamma0_32, 12 | gamma1_32, 13 | maj_32, 14 | safeAdd_32_2, 15 | safeAdd_32_4, 16 | safeAdd_32_5, 17 | sigma0_32, 18 | sigma1_32, 19 | } from "./primitives_32"; 20 | 21 | type VariantType = "SHA-224" | "SHA-256"; 22 | 23 | /** 24 | * Gets the state values for the specified SHA variant. 25 | * 26 | * @param variant: The SHA-256 family variant. 27 | * @returns The initial state values. 28 | */ 29 | function getNewState256(variant: VariantType): number[] { 30 | let retVal; 31 | 32 | if ("SHA-224" == variant) { 33 | retVal = H_trunc.slice(); 34 | } else { 35 | /* "SHA-256" */ 36 | retVal = H_full.slice(); 37 | } 38 | return retVal; 39 | } 40 | 41 | /** 42 | * Performs a round of SHA-256 hashing over a block. This clobbers `H`. 43 | * 44 | * @param block The binary array representation of the block to hash. 45 | * @param H The intermediate H values from a previous round. 46 | * @returns The resulting H values. 47 | */ 48 | function roundSHA256(block: number[], H: number[]): number[] { 49 | let a, b, c, d, e, f, g, h, T1, T2, t; 50 | 51 | const W: number[] = []; 52 | 53 | a = H[0]; 54 | b = H[1]; 55 | c = H[2]; 56 | d = H[3]; 57 | e = H[4]; 58 | f = H[5]; 59 | g = H[6]; 60 | h = H[7]; 61 | 62 | for (t = 0; t < 64; t += 1) { 63 | if (t < 16) { 64 | W[t] = block[t]; 65 | } else { 66 | W[t] = safeAdd_32_4(gamma1_32(W[t - 2]), W[t - 7], gamma0_32(W[t - 15]), W[t - 16]); 67 | } 68 | T1 = safeAdd_32_5(h, sigma1_32(e), ch_32(e, f, g), K_sha2[t], W[t]); 69 | T2 = safeAdd_32_2(sigma0_32(a), maj_32(a, b, c)); 70 | h = g; 71 | g = f; 72 | f = e; 73 | e = safeAdd_32_2(d, T1); 74 | d = c; 75 | c = b; 76 | b = a; 77 | a = safeAdd_32_2(T1, T2); 78 | } 79 | 80 | H[0] = safeAdd_32_2(a, H[0]); 81 | H[1] = safeAdd_32_2(b, H[1]); 82 | H[2] = safeAdd_32_2(c, H[2]); 83 | H[3] = safeAdd_32_2(d, H[3]); 84 | H[4] = safeAdd_32_2(e, H[4]); 85 | H[5] = safeAdd_32_2(f, H[5]); 86 | H[6] = safeAdd_32_2(g, H[6]); 87 | H[7] = safeAdd_32_2(h, H[7]); 88 | 89 | return H; 90 | } 91 | 92 | /** 93 | * Finalizes the SHA-256 hash. This clobbers `remainder` and `H`. 94 | * 95 | * @param remainder Any leftover unprocessed packed ints that still need to be processed. 96 | * @param remainderBinLen The number of bits in `remainder`. 97 | * @param processedBinLen The number of bits already processed. 98 | * @param H The intermediate H values from a previous round. 99 | * @param variant The desired SHA-256 variant. 100 | * @returns The array of integers representing the SHA-2 hash of message. 101 | */ 102 | function finalizeSHA256( 103 | remainder: number[], 104 | remainderBinLen: number, 105 | processedBinLen: number, 106 | H: number[], 107 | variant: VariantType 108 | ): number[] { 109 | let i, retVal; 110 | 111 | /* The 65 addition is a hack but it works. The correct number is 112 | actually 72 (64 + 8) but the below math fails if 113 | remainderBinLen + 72 % 512 = 0. Since remainderBinLen % 8 = 0, 114 | "shorting" the addition is OK. */ 115 | const offset = (((remainderBinLen + 65) >>> 9) << 4) + 15, 116 | binaryStringInc = 16, 117 | totalLen = remainderBinLen + processedBinLen; 118 | 119 | while (remainder.length <= offset) { 120 | remainder.push(0); 121 | } 122 | /* Append '1' at the end of the binary string */ 123 | remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32)); 124 | /* Append length of binary string in the position such that the new 125 | * length is correct. JavaScript numbers are limited to 2^53 so it's 126 | * "safe" to treat the totalLen as a 64-bit integer. */ 127 | 128 | remainder[offset] = totalLen & 0xffffffff; 129 | /* Bitwise operators treat the operand as a 32-bit number so need to 130 | * use hacky division and round to get access to upper 32-ish bits */ 131 | remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0; 132 | 133 | /* This will always be at least 1 full chunk */ 134 | for (i = 0; i < remainder.length; i += binaryStringInc) { 135 | H = roundSHA256(remainder.slice(i, i + binaryStringInc), H); 136 | } 137 | 138 | if ("SHA-224" === variant) { 139 | retVal = [H[0], H[1], H[2], H[3], H[4], H[5], H[6]]; 140 | } else { 141 | /* "SHA-256 */ 142 | retVal = H; 143 | } 144 | 145 | return retVal; 146 | } 147 | export default class jsSHA extends jsSHABase { 148 | intermediateState: number[]; 149 | variantBlockSize: number; 150 | bigEndianMod: -1 | 1; 151 | outputBinLen: number; 152 | isVariableLen: boolean; 153 | HMACSupported: boolean; 154 | 155 | /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ 156 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 157 | roundFunc: (block: number[], H: number[]) => number[]; 158 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[]; 159 | stateCloneFunc: (state: number[]) => number[]; 160 | newStateFunc: (variant: VariantType) => number[]; 161 | getMAC: () => number[]; 162 | 163 | constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 164 | constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 165 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 166 | constructor(variant: any, inputFormat: any, options?: any) { 167 | if (!("SHA-224" === variant || "SHA-256" === variant)) { 168 | throw new Error(sha_variant_error); 169 | } 170 | super(variant, inputFormat, options); 171 | const resolvedOptions = options || {}; 172 | 173 | // eslint-disable-next-line @typescript-eslint/unbound-method 174 | this.getMAC = this._getHMAC; 175 | this.HMACSupported = true; 176 | this.bigEndianMod = -1; 177 | this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod); 178 | this.roundFunc = roundSHA256; 179 | this.stateCloneFunc = function (state): number[] { 180 | return state.slice(); 181 | }; 182 | 183 | this.newStateFunc = getNewState256; 184 | this.finalizeFunc = function (remainder, remainderBinLen, processedBinLen, H): number[] { 185 | return finalizeSHA256(remainder, remainderBinLen, processedBinLen, H, variant); 186 | }; 187 | 188 | this.intermediateState = getNewState256(variant); 189 | this.variantBlockSize = 512; 190 | this.outputBinLen = "SHA-224" === variant ? 224 : 256; 191 | this.isVariableLen = false; 192 | 193 | if (resolvedOptions["hmacKey"]) { 194 | this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod)); 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /dist/sha512.d.ts: -------------------------------------------------------------------------------- 1 | type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE"; 2 | type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY"; 3 | type FormatType = "TEXT" | FormatNoTextType; 4 | type GenericInputType = { 5 | value: string; 6 | format: "TEXT"; 7 | encoding?: EncodingType; 8 | } | { 9 | value: string; 10 | format: "B64" | "HEX" | "BYTES"; 11 | } | { 12 | value: ArrayBuffer; 13 | format: "ARRAYBUFFER"; 14 | } | { 15 | value: Uint8Array; 16 | format: "UINT8ARRAY"; 17 | }; 18 | type FixedLengthOptionsNoEncodingType = { 19 | hmacKey?: GenericInputType; 20 | } | { 21 | numRounds?: number; 22 | }; 23 | type FixedLengthOptionsEncodingType = { 24 | hmacKey?: GenericInputType; 25 | encoding?: EncodingType; 26 | } | { 27 | numRounds?: number; 28 | encoding?: EncodingType; 29 | }; 30 | interface packedValue { 31 | value: number[]; 32 | binLen: number; 33 | } 34 | 35 | declare abstract class jsSHABase { 36 | /** 37 | * @param variant The desired SHA variant. 38 | * @param inputFormat The input format to be used in future `update` calls. 39 | * @param options Hashmap of extra input options. 40 | */ 41 | protected readonly shaVariant: VariantT; 42 | protected readonly inputFormat: FormatType; 43 | protected readonly utfType: EncodingType; 44 | protected readonly numRounds: number; 45 | protected abstract intermediateState: StateT; 46 | protected keyWithIPad: number[]; 47 | protected keyWithOPad: number[]; 48 | protected remainder: number[]; 49 | protected remainderLen: number; 50 | protected updateCalled: boolean; 51 | protected processedLen: number; 52 | protected macKeySet: boolean; 53 | protected abstract readonly variantBlockSize: number; 54 | protected abstract readonly bigEndianMod: -1 | 1; 55 | protected abstract readonly outputBinLen: number; 56 | protected abstract readonly isVariableLen: boolean; 57 | protected abstract readonly HMACSupported: boolean; 58 | protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 59 | protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT; 60 | protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[]; 61 | protected abstract readonly stateCloneFunc: (state: StateT) => StateT; 62 | protected abstract readonly newStateFunc: (variant: VariantT) => StateT; 63 | protected abstract readonly getMAC: ((options: { 64 | outputLen: number; 65 | }) => number[]) | null; 66 | protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 67 | protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 68 | /** 69 | * Hashes as many blocks as possible. Stores the rest for either a future update or getHash call. 70 | * 71 | * @param srcString The input to be hashed. 72 | * @returns A reference to the object. 73 | */ 74 | update(srcString: string | ArrayBuffer | Uint8Array): this; 75 | /** 76 | * Returns the desired SHA hash of the input fed in via `update` calls. 77 | * 78 | * @param format The desired output formatting 79 | * @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes. 80 | * `outputLen` replaces the now deprecated `shakeLen` key. 81 | * @returns The hash in the format specified. 82 | */ 83 | getHash(format: "HEX", options?: { 84 | outputUpper?: boolean; 85 | outputLen?: number; 86 | shakeLen?: number; 87 | }): string; 88 | getHash(format: "B64", options?: { 89 | b64Pad?: string; 90 | outputLen?: number; 91 | shakeLen?: number; 92 | }): string; 93 | getHash(format: "BYTES", options?: { 94 | outputLen?: number; 95 | shakeLen?: number; 96 | }): string; 97 | getHash(format: "UINT8ARRAY", options?: { 98 | outputLen?: number; 99 | shakeLen?: number; 100 | }): Uint8Array; 101 | getHash(format: "ARRAYBUFFER", options?: { 102 | outputLen?: number; 103 | shakeLen?: number; 104 | }): ArrayBuffer; 105 | /** 106 | * Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation. 107 | * 108 | * @param key The key used to calculate the HMAC 109 | * @param inputFormat The format of key. 110 | * @param options Hashmap of extra input options. 111 | */ 112 | setHMACKey(key: string, inputFormat: "TEXT", options?: { 113 | encoding?: EncodingType; 114 | }): void; 115 | setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void; 116 | setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void; 117 | setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void; 118 | /** 119 | * Internal function that sets the MAC key. 120 | * 121 | * @param key The packed MAC key to use 122 | */ 123 | protected _setHMACKey(key: packedValue): void; 124 | /** 125 | * Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. 126 | * 127 | * @param format The desired output formatting. 128 | * @param options Hashmap of extra outputs options. 129 | * @returns The HMAC in the format specified. 130 | */ 131 | getHMAC(format: "HEX", options?: { 132 | outputUpper?: boolean; 133 | }): string; 134 | getHMAC(format: "B64", options?: { 135 | b64Pad?: string; 136 | }): string; 137 | getHMAC(format: "BYTES"): string; 138 | getHMAC(format: "UINT8ARRAY"): Uint8Array; 139 | getHMAC(format: "ARRAYBUFFER"): ArrayBuffer; 140 | /** 141 | * Internal function that returns the "raw" HMAC 142 | */ 143 | protected _getHMAC(): number[]; 144 | } 145 | 146 | /** 147 | * Int_64 is a object for 2 32-bit numbers emulating a 64-bit number. 148 | */ 149 | declare class Int_64 { 150 | /** 151 | * @param msint_32 The most significant 32-bits of a 64-bit number. 152 | * @param lsint_32 The least significant 32-bits of a 64-bit number. 153 | */ 154 | readonly highOrder: number; 155 | readonly lowOrder: number; 156 | constructor(msint_32: number, lsint_32: number); 157 | } 158 | 159 | type VariantType = "SHA-384" | "SHA-512"; 160 | declare class jsSHA extends jsSHABase { 161 | intermediateState: Int_64[]; 162 | variantBlockSize: number; 163 | bigEndianMod: -1 | 1; 164 | outputBinLen: number; 165 | isVariableLen: boolean; 166 | HMACSupported: boolean; 167 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 168 | roundFunc: (block: number[], H: Int_64[]) => Int_64[]; 169 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: Int_64[]) => number[]; 170 | stateCloneFunc: (state: Int_64[]) => Int_64[]; 171 | newStateFunc: (variant: VariantType) => Int_64[]; 172 | getMAC: () => number[]; 173 | constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 174 | constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 175 | } 176 | 177 | export { jsSHA as default }; 178 | -------------------------------------------------------------------------------- /dist/sha.d.ts: -------------------------------------------------------------------------------- 1 | type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE"; 2 | type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY"; 3 | type GenericInputType = { 4 | value: string; 5 | format: "TEXT"; 6 | encoding?: EncodingType; 7 | } | { 8 | value: string; 9 | format: "B64" | "HEX" | "BYTES"; 10 | } | { 11 | value: ArrayBuffer; 12 | format: "ARRAYBUFFER"; 13 | } | { 14 | value: Uint8Array; 15 | format: "UINT8ARRAY"; 16 | }; 17 | type FixedLengthOptionsNoEncodingType = { 18 | hmacKey?: GenericInputType; 19 | } | { 20 | numRounds?: number; 21 | }; 22 | type FixedLengthOptionsEncodingType = { 23 | hmacKey?: GenericInputType; 24 | encoding?: EncodingType; 25 | } | { 26 | numRounds?: number; 27 | encoding?: EncodingType; 28 | }; 29 | interface SHAKEOptionsNoEncodingType { 30 | numRounds?: number; 31 | } 32 | interface SHAKEOptionsEncodingType extends SHAKEOptionsNoEncodingType { 33 | encoding?: EncodingType; 34 | } 35 | interface CSHAKEOptionsNoEncodingType { 36 | customization?: GenericInputType; 37 | funcName?: GenericInputType; 38 | } 39 | interface CSHAKEOptionsEncodingType extends CSHAKEOptionsNoEncodingType { 40 | encoding?: EncodingType; 41 | } 42 | interface KMACOptionsNoEncodingType { 43 | kmacKey: GenericInputType; 44 | customization?: GenericInputType; 45 | } 46 | interface KMACOptionsEncodingType extends KMACOptionsNoEncodingType { 47 | encoding?: EncodingType; 48 | } 49 | 50 | type FixedLengthVariantType = "SHA-1" | "SHA-224" | "SHA-256" | "SHA-384" | "SHA-512" | "SHA3-224" | "SHA3-256" | "SHA3-384" | "SHA3-512"; 51 | declare class jsSHA { 52 | private readonly shaObj; 53 | /** 54 | * @param variant The desired SHA variant (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA3-224, SHA3-256, SHA3-256, 55 | * SHA3-384, SHA3-512, SHAKE128, SHAKE256, CSHAKE128, CSHAKE256, KMAC128, or KMAC256) as a string. 56 | * @param inputFormat The input format to be used in future `update` calls (TEXT, HEX, B64, BYTES, ARRAYBUFFER, 57 | * or UINT8ARRAY) as a string. 58 | * @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE"; numRounds?: number }. 59 | * `encoding` is for only TEXT input (defaults to UTF8) and `numRounds` defaults to 1. 60 | * `numRounds` is not valid for any of the MAC or CSHAKE variants. 61 | * * If the variant supports HMAC, `options` may have an additional `hmacKey` key which must be in the form of 62 | * {value: , format: , encoding?: "UTF8" | "UTF16BE" | "UTF16LE"} where takes the same 63 | * values as `inputFormat` and can be a `string | ArrayBuffer | Uint8Array` depending on . 64 | * Supplying this key switches to HMAC calculation and replaces the now deprecated call to `setHMACKey`. 65 | * * If the variant is CSHAKE128 or CSHAKE256, `options` may have two additional keys, `customization` and `funcName`, 66 | * which are the NIST customization and function-name strings. Both must be in the same form as `hmacKey`. 67 | * * If the variant is KMAC128 or KMAC256, `options` can include the `customization` key from CSHAKE variants and 68 | * *must* have a `kmacKey` key that takes the same form as the `customization` key. 69 | */ 70 | constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 71 | constructor(variant: FixedLengthVariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 72 | constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType); 73 | constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType); 74 | constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType); 75 | constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType); 76 | constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType); 77 | constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType); 78 | /** 79 | * Takes `input` and hashes as many blocks as possible. Stores the rest for either a future `update` or `getHash` call. 80 | * 81 | * @param input The input to be hashed. 82 | * @returns A reference to the object. 83 | */ 84 | update(input: string | ArrayBuffer | Uint8Array): this; 85 | /** 86 | * Returns the desired SHA or MAC (if a HMAC/KMAC key was specified) hash of the input fed in via `update` calls. 87 | * 88 | * @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string. 89 | * @param options Options in the form of { outputUpper?: boolean; b64Pad?: string; outputLen?: number; }. 90 | * `outputLen` is required for variable length output variants (this option was previously called `shakeLen` which 91 | * is now deprecated). 92 | * `outputUpper` is only for HEX output (defaults to false) and b64pad is only for B64 output (defaults to "="). 93 | * @returns The hash in the format specified. 94 | */ 95 | getHash(format: "HEX", options?: { 96 | outputUpper?: boolean; 97 | outputLen?: number; 98 | shakeLen?: number; 99 | }): string; 100 | getHash(format: "B64", options?: { 101 | b64Pad?: string; 102 | outputLen?: number; 103 | shakeLen?: number; 104 | }): string; 105 | getHash(format: "BYTES", options?: { 106 | outputLen?: number; 107 | shakeLen?: number; 108 | }): string; 109 | getHash(format: "UINT8ARRAY", options?: { 110 | outputLen?: number; 111 | shakeLen?: number; 112 | }): Uint8Array; 113 | getHash(format: "ARRAYBUFFER", options?: { 114 | outputLen?: number; 115 | shakeLen?: number; 116 | }): ArrayBuffer; 117 | /** 118 | * Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation. 119 | * Now deprecated in favor of setting the `hmacKey` at object instantiation. 120 | * 121 | * @param key The key used to calculate the HMAC 122 | * @param inputFormat The format of key (HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string. 123 | * @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE }. `encoding` is only for TEXT 124 | * and defaults to UTF8. 125 | */ 126 | setHMACKey(key: string, inputFormat: "TEXT", options?: { 127 | encoding?: EncodingType; 128 | }): void; 129 | setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void; 130 | setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void; 131 | setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void; 132 | /** 133 | * Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. Now deprecated 134 | * in favor of just calling `getHash`. 135 | * 136 | * @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string. 137 | * @param options Options in the form of { outputUpper?: boolean; b64Pad?: string }. `outputUpper` is only for HEX 138 | * output (defaults to false) and `b64pad` is only for B64 output (defaults to "="). 139 | * @returns The HMAC in the format specified. 140 | */ 141 | getHMAC(format: "HEX", options?: { 142 | outputUpper?: boolean; 143 | }): string; 144 | getHMAC(format: "B64", options?: { 145 | b64Pad?: string; 146 | }): string; 147 | getHMAC(format: "BYTES"): string; 148 | getHMAC(format: "UINT8ARRAY"): Uint8Array; 149 | getHMAC(format: "ARRAYBUFFER"): ArrayBuffer; 150 | } 151 | 152 | export { jsSHA as default }; 153 | -------------------------------------------------------------------------------- /dist/sha1.mjs: -------------------------------------------------------------------------------- 1 | /** 2 | * A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202, 3 | * and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1. 4 | * 5 | * Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors 6 | * Distributed under the BSD License 7 | * See http://caligatio.github.com/jsSHA/ for more information 8 | */ 9 | const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="ARRAYBUFFER not supported by this environment",n="UINT8ARRAY not supported by this environment";function i(t,r,n,i){let e,s,o;const h=r||[0],u=(n=n||0)>>>3,f=-1===i?3:0;for(e=0;e>>2,h.length<=s&&h.push(0),h[s]|=t[e]<<8*(f+i*(o%4));return{value:h,binLen:8*t.length+n}}function e(e,s,o){switch(s){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(e){case"HEX":return function(t,r,n){return function(t,r,n,i){let e,s,o,h;if(0!=t.length%2)throw new Error("String of HEX type must be in byte increments");const u=r||[0],f=(n=n||0)>>>3,c=-1===i?3:0;for(e=0;e>>1)+f,o=h>>>2;u.length<=o;)u.push(0);u[o]|=s<<8*(c+i*(h%4))}return{value:u,binLen:4*t.length+n}}(t,r,n,o)};case"TEXT":return function(t,r,n){return function(t,r,n,i,e){let s,o,h,u,f,c,a,w,E=0;const l=n||[0],A=(i=i||0)>>>3;if("UTF8"===r)for(a=-1===e?3:0,h=0;hs?o.push(s):2048>s?(o.push(192|s>>>6),o.push(128|63&s)):55296>s||57344<=s?o.push(224|s>>>12,128|s>>>6&63,128|63&s):(h+=1,s=65536+((1023&s)<<10|1023&t.charCodeAt(h)),o.push(240|s>>>18,128|s>>>12&63,128|s>>>6&63,128|63&s)),u=0;u>>2;l.length<=f;)l.push(0);l[f]|=o[u]<<8*(a+e*(c%4)),E+=1}else for(a=-1===e?2:0,w="UTF16LE"===r&&1!==e||"UTF16LE"!==r&&1===e,h=0;h>>8),c=E+A,f=c>>>2;l.length<=f;)l.push(0);l[f]|=s<<8*(a+e*(c%4)),E+=2}return{value:l,binLen:8*E+i}}(t,s,r,n,o)};case"B64":return function(r,n,i){return function(r,n,i,e){let s,o,h,u,f,c,a,w=0;const E=n||[0],l=(i=i||0)>>>3,A=-1===e?3:0,p=r.indexOf("=");if(-1===r.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(r=r.replace(/=/g,""),-1!==p&&p>>2;E.length<=c;)E.push(0);E[c]|=(u>>>16-8*h&255)<<8*(A+e*(a%4)),w+=1}}return{value:E,binLen:8*w+i}}(r,n,i,o)};case"BYTES":return function(t,r,n){return function(t,r,n,i){let e,s,o,h;const u=r||[0],f=(n=n||0)>>>3,c=-1===i?3:0;for(s=0;s>>2,u.length<=o&&u.push(0),u[o]|=e<<8*(c+i*(h%4));return{value:u,binLen:8*t.length+n}}(t,r,n,o)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(t){throw new Error(r)}return function(t,r,n){return function(t,r,n,e){return i(new Uint8Array(t),r,n,e)}(t,r,n,o)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(t){throw new Error(n)}return function(t,r,n){return i(t,r,n,o)};default:throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}function s(i,e,s,o){switch(i){case"HEX":return function(t){return function(t,r,n,i){const e="0123456789abcdef";let s,o,h="";const u=r/8,f=-1===n?3:0;for(s=0;s>>2]>>>8*(f+n*(s%4)),h+=e.charAt(o>>>4&15)+e.charAt(15&o);return i.outputUpper?h.toUpperCase():h}(t,e,s,o)};case"B64":return function(r){return function(r,n,i,e){let s,o,h,u,f,c="";const a=n/8,w=-1===i?3:0;for(s=0;s>>2]:0,f=s+2>>2]:0,h=(r[s>>>2]>>>8*(w+i*(s%4))&255)<<16|(u>>>8*(w+i*((s+1)%4))&255)<<8|f>>>8*(w+i*((s+2)%4))&255,o=0;o<4;o+=1)c+=8*s+6*o<=n?t.charAt(h>>>6*(3-o)&63):e.b64Pad;return c}(r,e,s,o)};case"BYTES":return function(t){return function(t,r,n){let i,e,s="";const o=r/8,h=-1===n?3:0;for(i=0;i>>2]>>>8*(h+n*(i%4))&255,s+=String.fromCharCode(e);return s}(t,e,s)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(t){throw new Error(r)}return function(t){return function(t,r,n){let i;const e=r/8,s=new ArrayBuffer(e),o=new Uint8Array(s),h=-1===n?3:0;for(i=0;i>>2]>>>8*(h+n*(i%4))&255;return s}(t,e,s)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(t){throw new Error(n)}return function(t){return function(t,r,n){let i;const e=r/8,s=-1===n?3:0,o=new Uint8Array(e);for(i=0;i>>2]>>>8*(s+n*(i%4))&255;return o}(t,e,s)};default:throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}const o=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428],u=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function f(t){const r={outputUpper:!1,b64Pad:"=",outputLen:-1},n=t||{},i="Output length must be a multiple of 8";if(r.outputUpper=n.outputUpper||!1,n.b64Pad&&(r.b64Pad=n.b64Pad),n.outputLen){if(n.outputLen%8!=0)throw new Error(i);r.outputLen=n.outputLen}else if(n.shakeLen){if(n.shakeLen%8!=0)throw new Error(i);r.outputLen=n.shakeLen}if("boolean"!=typeof r.outputUpper)throw new Error("Invalid outputUpper formatting option");if("string"!=typeof r.b64Pad)throw new Error("Invalid b64Pad formatting option");return r}class c{constructor(t,r,n){const i=n||{};if(this.t=r,this.i=i.encoding||"UTF8",this.numRounds=i.numRounds||1,isNaN(this.numRounds)||this.numRounds!==parseInt(this.numRounds,10)||1>this.numRounds)throw new Error("numRounds must a integer >= 1");this.o=t,this.h=[],this.u=0,this.l=!1,this.A=0,this.p=!1,this.U=[],this.R=[]}update(t){let r,n=0;const i=this.T>>>5,e=this.F(t,this.h,this.u),s=e.binLen,o=e.value,h=s>>>5;for(r=0;r>>5),this.u=s%this.T,this.l=!0,this}getHash(t,r){let n,i,e=this.H;const o=f(r);if(this.B){if(-1===o.outputLen)throw new Error("Output length must be specified in options");e=o.outputLen}const h=s(t,e,this.v,o);if(this.p&&this.C)return h(this.C(o));for(i=this.Y(this.h.slice(),this.u,this.A,this.S(this.m),e),n=1;n>>24-e%32),i=this.Y(i,e,0,this.I(this.o),e);return h(i)}setHMACKey(t,r,n){if(!this.L)throw new Error("Variant does not support HMAC");if(this.l)throw new Error("Cannot set MAC key after calling update");const i=e(r,(n||{}).encoding||"UTF8",this.v);this.M(i(t))}M(t){const r=this.T>>>3,n=r/4-1;let i;if(1!==this.numRounds)throw new Error("Cannot set numRounds with MAC");if(this.p)throw new Error("MAC key already set");for(r>>r|t<<32-r}function w(t,r){return t>>>r}function E(t,r,n){return t&r^~t&n}function l(t,r,n){return t&r^t&n^r&n}function A(t){return a(t,2)^a(t,13)^a(t,22)}function p(t,r){const n=(65535&t)+(65535&r);return(65535&(t>>>16)+(r>>>16)+(n>>>16))<<16|65535&n}function U(t,r,n,i){const e=(65535&t)+(65535&r)+(65535&n)+(65535&i);return(65535&(t>>>16)+(r>>>16)+(n>>>16)+(i>>>16)+(e>>>16))<<16|65535&e}function d(t,r,n,i,e){const s=(65535&t)+(65535&r)+(65535&n)+(65535&i)+(65535&e);return(65535&(t>>>16)+(r>>>16)+(n>>>16)+(i>>>16)+(e>>>16)+(s>>>16))<<16|65535&s}function R(t){return a(t,7)^a(t,18)^w(t,3)}function y(t){return a(t,6)^a(t,11)^a(t,25)}function T(t){let r;return r="SHA-224"==t?h.slice():u.slice(),r}function F(t,r){let n,i,e,s,h,u,f,c,T,F,b;const m=[];for(n=r[0],i=r[1],e=r[2],s=r[3],h=r[4],u=r[5],f=r[6],c=r[7],b=0;b<64;b+=1)m[b]=b<16?t[b]:U(a(g=m[b-2],17)^a(g,19)^w(g,10),m[b-7],R(m[b-15]),m[b-16]),T=d(c,y(h),E(h,u,f),o[b],m[b]),F=p(A(n),l(n,i,e)),c=f,f=u,u=h,h=p(s,T),s=e,e=i,i=n,n=p(T,F);var g;return r[0]=p(n,r[0]),r[1]=p(i,r[1]),r[2]=p(e,r[2]),r[3]=p(s,r[3]),r[4]=p(h,r[4]),r[5]=p(u,r[5]),r[6]=p(f,r[6]),r[7]=p(c,r[7]),r}class b extends c{constructor(t,r,n){if("SHA-224"!==t&&"SHA-256"!==t)throw new Error("Chosen SHA variant is not supported");super(t,r,n);const i=n||{};this.C=this.N,this.L=!0,this.v=-1,this.F=e(this.t,this.i,this.v),this.g=F,this.S=function(t){return t.slice()},this.I=T,this.Y=function(r,n,i,e){return function(t,r,n,i,e){let s,o;const h=15+(r+65>>>9<<4),u=r+n;for(;t.length<=h;)t.push(0);for(t[r>>>5]|=128<<24-r%32,t[h]=4294967295&u,t[h-1]=u/4294967296|0,s=0;s>>3,h=-1===i?3:0;for(e=0;e>>2,s.length<=o&&s.push(0),s[o]|=r[e]<<8*(h+i*(u%4));return{value:s,binLen:8*r.length+n}}function o(r,o,u){switch(o){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(r){case"HEX":return function(r,t,n){return function(r,t,n,i){var e,o,u,s;if(0!=r.length%2)throw new Error("String of HEX type must be in byte increments");var f=t||[0],h=(n=n||0)>>>3,a=-1===i?3:0;for(e=0;e>>1)+h)>>>2;f.length<=u;)f.push(0);f[u]|=o<<8*(a+i*(s%4))}return{value:f,binLen:4*r.length+n}}(r,t,n,u)};case"TEXT":return function(r,t,n){return function(r,t,n,i,e){var o,u,s,f,h,a,c,w,E=0,v=n||[0],l=(i=i||0)>>>3;if("UTF8"===t)for(c=-1===e?3:0,s=0;s(o=r.charCodeAt(s))?u.push(o):2048>o?(u.push(192|o>>>6),u.push(128|63&o)):55296>o||57344<=o?u.push(224|o>>>12,128|o>>>6&63,128|63&o):(s+=1,o=65536+((1023&o)<<10|1023&r.charCodeAt(s)),u.push(240|o>>>18,128|o>>>12&63,128|o>>>6&63,128|63&o)),f=0;f>>2;v.length<=h;)v.push(0);v[h]|=u[f]<<8*(c+e*(a%4)),E+=1}else for(c=-1===e?2:0,w="UTF16LE"===t&&1!==e||"UTF16LE"!==t&&1===e,s=0;s>>8),h=(a=E+l)>>>2;v.length<=h;)v.push(0);v[h]|=o<<8*(c+e*(a%4)),E+=2}return{value:v,binLen:8*E+i}}(r,o,t,n,u)};case"B64":return function(r,n,i){return function(r,n,i,e){var o,u,s,f,h,a,c=0,w=n||[0],E=(i=i||0)>>>3,v=-1===e?3:0,l=r.indexOf("=");if(-1===r.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(r=r.replace(/=/g,""),-1!==l&&l= 64 or n == 32 but those are never done. 30 | * 31 | * @param x The 64-bit integer argument. 32 | * @param n The number of bits to shift. 33 | * @returns `x` shifted left circularly by `n` bits. 34 | */ 35 | export function rotl_64(x: Int_64, n: number): Int_64 { 36 | let tmp; 37 | if (n > 32) { 38 | tmp = 64 - n; 39 | return new Int_64((x.lowOrder << n) | (x.highOrder >>> tmp), (x.highOrder << n) | (x.lowOrder >>> tmp)); 40 | } else if (0 !== n) { 41 | tmp = 32 - n; 42 | return new Int_64((x.highOrder << n) | (x.lowOrder >>> tmp), (x.lowOrder << n) | (x.highOrder >>> tmp)); 43 | } else { 44 | return x; 45 | } 46 | } 47 | 48 | /** 49 | * The 64-bit implementation of circular rotate right. 50 | * 51 | * This does not work for n >= 64, n == 32, or n == 0 but those are never done. 52 | * 53 | * @param x The 64-bit integer argument. 54 | * @param n The number of bits to shift. 55 | * @returns `x` shifted right circularly by `n` bits. 56 | */ 57 | function rotr_64(x: Int_64, n: number): Int_64 { 58 | let tmp; 59 | if (n < 32) { 60 | tmp = 32 - n; 61 | return new Int_64((x.highOrder >>> n) | (x.lowOrder << tmp), (x.lowOrder >>> n) | (x.highOrder << tmp)); 62 | } else { 63 | tmp = 64 - n; 64 | return new Int_64((x.lowOrder >>> n) | (x.highOrder << tmp), (x.highOrder >>> n) | (x.lowOrder << tmp)); 65 | } 66 | } 67 | 68 | /** 69 | * The 64-bit implementation of shift right. 70 | * 71 | * This does not work for n >= 32 but is only called for n < 32. 72 | * 73 | * @param x The 64-bit integer argument. 74 | * @param n The number of bits to shift. 75 | * @returns `x` shifted right by `n` bits 76 | */ 77 | function shr_64(x: Int_64, n: number): Int_64 { 78 | return new Int_64(x.highOrder >>> n, (x.lowOrder >>> n) | (x.highOrder << (32 - n))); 79 | } 80 | 81 | /** 82 | * The 64-bit implementation of the NIST specified Ch function. 83 | * 84 | * @param x The first 64-bit integer argument. 85 | * @param y The second 64-bit integer argument. 86 | * @param z The third 64-bit integer argument. 87 | * @returns The NIST specified output of the function. 88 | */ 89 | export function ch_64(x: Int_64, y: Int_64, z: Int_64): Int_64 { 90 | return new Int_64( 91 | (x.highOrder & y.highOrder) ^ (~x.highOrder & z.highOrder), 92 | (x.lowOrder & y.lowOrder) ^ (~x.lowOrder & z.lowOrder) 93 | ); 94 | } 95 | 96 | /** 97 | * The 64-bit implementation of the NIST specified Maj function. 98 | * 99 | * @param x The first 64-bit integer argument. 100 | * @param y The second 64-bit integer argument. 101 | * @param z The third 64-bit integer argument. 102 | * @returns The NIST specified output of the function. 103 | */ 104 | export function maj_64(x: Int_64, y: Int_64, z: Int_64): Int_64 { 105 | return new Int_64( 106 | (x.highOrder & y.highOrder) ^ (x.highOrder & z.highOrder) ^ (y.highOrder & z.highOrder), 107 | (x.lowOrder & y.lowOrder) ^ (x.lowOrder & z.lowOrder) ^ (y.lowOrder & z.lowOrder) 108 | ); 109 | } 110 | 111 | /** 112 | * The 64-bit implementation of the NIST specified Sigma0 function. 113 | * 114 | * @param x The 64-bit integer argument. 115 | * @returns The NIST specified output of the function. 116 | */ 117 | export function sigma0_64(x: Int_64): Int_64 { 118 | const rotr28 = rotr_64(x, 28), 119 | rotr34 = rotr_64(x, 34), 120 | rotr39 = rotr_64(x, 39); 121 | 122 | return new Int_64( 123 | rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder, 124 | rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder 125 | ); 126 | } 127 | 128 | /** 129 | * Add two 64-bit integers. 130 | * 131 | * @param x The first 64-bit integer argument to be added. 132 | * @param y The second 64-bit integer argument to be added. 133 | * @returns The sum of `x` + `y`. 134 | */ 135 | export function safeAdd_64_2(x: Int_64, y: Int_64): Int_64 { 136 | let lsw, msw; 137 | 138 | lsw = (x.lowOrder & 0xffff) + (y.lowOrder & 0xffff); 139 | msw = (x.lowOrder >>> 16) + (y.lowOrder >>> 16) + (lsw >>> 16); 140 | const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 141 | 142 | lsw = (x.highOrder & 0xffff) + (y.highOrder & 0xffff) + (msw >>> 16); 143 | msw = (x.highOrder >>> 16) + (y.highOrder >>> 16) + (lsw >>> 16); 144 | const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 145 | 146 | return new Int_64(highOrder, lowOrder); 147 | } 148 | 149 | /** 150 | * Add four 64-bit integers. 151 | * 152 | * @param a The first 64-bit integer argument to be added. 153 | * @param b The second 64-bit integer argument to be added. 154 | * @param c The third 64-bit integer argument to be added. 155 | * @param d The fouth 64-bit integer argument to be added. 156 | * @returns The sum of `a` + `b` + `c` + `d`. 157 | */ 158 | export function safeAdd_64_4(a: Int_64, b: Int_64, c: Int_64, d: Int_64): Int_64 { 159 | let lsw, msw; 160 | 161 | lsw = (a.lowOrder & 0xffff) + (b.lowOrder & 0xffff) + (c.lowOrder & 0xffff) + (d.lowOrder & 0xffff); 162 | msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (lsw >>> 16); 163 | const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 164 | 165 | lsw = 166 | (a.highOrder & 0xffff) + (b.highOrder & 0xffff) + (c.highOrder & 0xffff) + (d.highOrder & 0xffff) + (msw >>> 16); 167 | msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (lsw >>> 16); 168 | const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 169 | 170 | return new Int_64(highOrder, lowOrder); 171 | } 172 | 173 | /** 174 | * Add five 64-bit integers. 175 | * 176 | * @param a The first 64-bit integer argument to be added. 177 | * @param b The second 64-bit integer argument to be added. 178 | * @param c The third 64-bit integer argument to be added. 179 | * @param d The fouth 64-bit integer argument to be added. 180 | * @param e The fifth 64-bit integer argument to be added. 181 | * @returns The sum of `a` + `b` + `c` + `d` + `e`. 182 | */ 183 | export function safeAdd_64_5(a: Int_64, b: Int_64, c: Int_64, d: Int_64, e: Int_64): Int_64 { 184 | let lsw, msw; 185 | 186 | lsw = 187 | (a.lowOrder & 0xffff) + 188 | (b.lowOrder & 0xffff) + 189 | (c.lowOrder & 0xffff) + 190 | (d.lowOrder & 0xffff) + 191 | (e.lowOrder & 0xffff); 192 | msw = 193 | (a.lowOrder >>> 16) + 194 | (b.lowOrder >>> 16) + 195 | (c.lowOrder >>> 16) + 196 | (d.lowOrder >>> 16) + 197 | (e.lowOrder >>> 16) + 198 | (lsw >>> 16); 199 | const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 200 | 201 | lsw = 202 | (a.highOrder & 0xffff) + 203 | (b.highOrder & 0xffff) + 204 | (c.highOrder & 0xffff) + 205 | (d.highOrder & 0xffff) + 206 | (e.highOrder & 0xffff) + 207 | (msw >>> 16); 208 | msw = 209 | (a.highOrder >>> 16) + 210 | (b.highOrder >>> 16) + 211 | (c.highOrder >>> 16) + 212 | (d.highOrder >>> 16) + 213 | (e.highOrder >>> 16) + 214 | (lsw >>> 16); 215 | const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff); 216 | 217 | return new Int_64(highOrder, lowOrder); 218 | } 219 | 220 | /** 221 | * XORs two given arguments. 222 | * 223 | * @param a The first argument to be XORed. 224 | * @param b The second argument to be XORed. 225 | * @returns The The XOR `a` and `b` 226 | */ 227 | export function xor_64_2(a: Int_64, b: Int_64): Int_64 { 228 | return new Int_64(a.highOrder ^ b.highOrder, a.lowOrder ^ b.lowOrder); 229 | } 230 | 231 | /** 232 | * XORs five given arguments. 233 | * 234 | * @param a The first argument to be XORed. 235 | * @param b The second argument to be XORed. 236 | * @param c The third argument to be XORed. 237 | * @param d The fourth argument to be XORed. 238 | * @param e The fifth argument to be XORed. 239 | * @returns The XOR of `a`, `b`, `c`, `d`, and `e`. 240 | */ 241 | export function xor_64_5(a: Int_64, b: Int_64, c: Int_64, d: Int_64, e: Int_64): Int_64 { 242 | return new Int_64( 243 | a.highOrder ^ b.highOrder ^ c.highOrder ^ d.highOrder ^ e.highOrder, 244 | a.lowOrder ^ b.lowOrder ^ c.lowOrder ^ d.lowOrder ^ e.lowOrder 245 | ); 246 | } 247 | 248 | /** 249 | * The 64-bit implementation of the NIST specified Gamma1 function. 250 | * 251 | * @param x The 64-bit integer argument. 252 | * @returns The NIST specified output of the function. 253 | */ 254 | export function gamma1_64(x: Int_64): Int_64 { 255 | const rotr19 = rotr_64(x, 19), 256 | rotr61 = rotr_64(x, 61), 257 | shr6 = shr_64(x, 6); 258 | 259 | return new Int_64( 260 | rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder, 261 | rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder 262 | ); 263 | } 264 | 265 | /** 266 | * The 64-bit implementation of the NIST specified Gamma0 function. 267 | * 268 | * @param x The 64-bit integer argument. 269 | * @returns The NIST specified output of the function. 270 | */ 271 | export function gamma0_64(x: Int_64): Int_64 { 272 | const rotr1 = rotr_64(x, 1), 273 | rotr8 = rotr_64(x, 8), 274 | shr7 = shr_64(x, 7); 275 | 276 | return new Int_64( 277 | rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder, 278 | rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder 279 | ); 280 | } 281 | 282 | /** 283 | * The 64-bit implementation of the NIST specified Sigma1 function. 284 | * 285 | * @param x The 64-bit integer argument. 286 | * @returns The NIST specified output of the function. 287 | */ 288 | export function sigma1_64(x: Int_64): Int_64 { 289 | const rotr14 = rotr_64(x, 14), 290 | rotr18 = rotr_64(x, 18), 291 | rotr41 = rotr_64(x, 41); 292 | 293 | return new Int_64( 294 | rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder, 295 | rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder 296 | ); 297 | } 298 | -------------------------------------------------------------------------------- /dist/sha256.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202, 3 | * and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1. 4 | * 5 | * Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors 6 | * Distributed under the BSD License 7 | * See http://caligatio.github.com/jsSHA/ for more information 8 | * 9 | * Two ECMAScript polyfill functions carry the following license: 10 | * 11 | * Copyright (c) Microsoft Corporation. All rights reserved. 12 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 13 | * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 16 | * INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 17 | * MERCHANTABLITY OR NON-INFRINGEMENT. 18 | * 19 | * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. 20 | */ 21 | !function(r,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(r="undefined"!=typeof globalThis?globalThis:r||self).jsSHA=t()}(this,(function(){"use strict";var r=function(t,n){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,t){r.__proto__=t}||function(r,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])},r(t,n)};"function"==typeof SuppressedError&&SuppressedError;var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="ARRAYBUFFER not supported by this environment",i="UINT8ARRAY not supported by this environment";function e(r,t,n,i){var e,o,u,s=t||[0],f=(n=n||0)>>>3,h=-1===i?3:0;for(e=0;e>>2,s.length<=o&&s.push(0),s[o]|=r[e]<<8*(h+i*(u%4));return{value:s,binLen:8*r.length+n}}function o(r,o,u){switch(o){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(r){case"HEX":return function(r,t,n){return function(r,t,n,i){var e,o,u,s;if(0!=r.length%2)throw new Error("String of HEX type must be in byte increments");var f=t||[0],h=(n=n||0)>>>3,a=-1===i?3:0;for(e=0;e>>1)+h)>>>2;f.length<=u;)f.push(0);f[u]|=o<<8*(a+i*(s%4))}return{value:f,binLen:4*r.length+n}}(r,t,n,u)};case"TEXT":return function(r,t,n){return function(r,t,n,i,e){var o,u,s,f,h,a,c,w,E=0,v=n||[0],l=(i=i||0)>>>3;if("UTF8"===t)for(c=-1===e?3:0,s=0;s(o=r.charCodeAt(s))?u.push(o):2048>o?(u.push(192|o>>>6),u.push(128|63&o)):55296>o||57344<=o?u.push(224|o>>>12,128|o>>>6&63,128|63&o):(s+=1,o=65536+((1023&o)<<10|1023&r.charCodeAt(s)),u.push(240|o>>>18,128|o>>>12&63,128|o>>>6&63,128|63&o)),f=0;f>>2;v.length<=h;)v.push(0);v[h]|=u[f]<<8*(c+e*(a%4)),E+=1}else for(c=-1===e?2:0,w="UTF16LE"===t&&1!==e||"UTF16LE"!==t&&1===e,s=0;s>>8),h=(a=E+l)>>>2;v.length<=h;)v.push(0);v[h]|=o<<8*(c+e*(a%4)),E+=2}return{value:v,binLen:8*E+i}}(r,o,t,n,u)};case"B64":return function(r,n,i){return function(r,n,i,e){var o,u,s,f,h,a,c=0,w=n||[0],E=(i=i||0)>>>3,v=-1===e?3:0,l=r.indexOf("=");if(-1===r.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(r=r.replace(/=/g,""),-1!==l&&l>>2;l.length<=f;)l.push(0);l[f]|=(u>>>16-8*h&255)<<8*(A+s*(a%4)),w+=1}}return{value:l,binLen:8*w+i}}(n,r,i,o)};case"BYTES":return function(t,n,r){return function(t,n,r,i){let s,e,o,h;const u=n||[0],c=(r=r||0)>>>3,f=-1===i?3:0;for(e=0;e>>2,u.length<=o&&u.push(0),u[o]|=s<<8*(f+i*(h%4));return{value:u,binLen:8*t.length+r}}(t,n,r,o)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(t){throw new Error(n)}return function(t,n,r){return function(t,n,r,s){return i(new Uint8Array(t),n,r,s)}(t,n,r,o)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(t){throw new Error(r)}return function(t,n,r){return i(t,n,r,o)};default:throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}function e(i,s,e,o){switch(i){case"HEX":return function(t){return function(t,n,r,i){const s="0123456789abcdef";let e,o,h="";const u=n/8,c=-1===r?3:0;for(e=0;e>>2]>>>8*(c+r*(e%4)),h+=s.charAt(o>>>4&15)+s.charAt(15&o);return i.outputUpper?h.toUpperCase():h}(t,s,e,o)};case"B64":return function(n){return function(n,r,i,s){let e,o,h,u,c,f="";const a=r/8,w=-1===i?3:0;for(e=0;e>>2]:0,c=e+2>>2]:0,h=(n[e>>>2]>>>8*(w+i*(e%4))&255)<<16|(u>>>8*(w+i*((e+1)%4))&255)<<8|c>>>8*(w+i*((e+2)%4))&255,o=0;o<4;o+=1)f+=8*e+6*o<=r?t.charAt(h>>>6*(3-o)&63):s.b64Pad;return f}(n,s,e,o)};case"BYTES":return function(t){return function(t,n,r){let i,s,e="";const o=n/8,h=-1===r?3:0;for(i=0;i>>2]>>>8*(h+r*(i%4))&255,e+=String.fromCharCode(s);return e}(t,s,e)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(t){throw new Error(n)}return function(t){return function(t,n,r){let i;const s=n/8,e=new ArrayBuffer(s),o=new Uint8Array(e),h=-1===r?3:0;for(i=0;i>>2]>>>8*(h+r*(i%4))&255;return e}(t,s,e)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(t){throw new Error(r)}return function(t){return function(t,n,r){let i;const s=n/8,e=-1===r?3:0,o=new Uint8Array(s);for(i=0;i>>2]>>>8*(e+r*(i%4))&255;return o}(t,s,e)};default:throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}const o=4294967296,h="Cannot set numRounds with MAC";function u(t,n){let r,i;const s=t.binLen>>>3,e=n.binLen>>>3,o=s<<3,h=4-s<<3;if(s%4!=0){for(r=0;r>>2,t.value[i]|=n.value[r>>>2]<>>2]>>>h;return(t.value.length<<2)-4>=e+s&&t.value.pop(),{value:t.value,binLen:t.binLen+n.binLen}}return{value:t.value.concat(n.value),binLen:t.binLen+n.binLen}}function c(t){const n={outputUpper:!1,b64Pad:"=",outputLen:-1},r=t||{},i="Output length must be a multiple of 8";if(n.outputUpper=r.outputUpper||!1,r.b64Pad&&(n.b64Pad=r.b64Pad),r.outputLen){if(r.outputLen%8!=0)throw new Error(i);n.outputLen=r.outputLen}else if(r.shakeLen){if(r.shakeLen%8!=0)throw new Error(i);n.outputLen=r.shakeLen}if("boolean"!=typeof n.outputUpper)throw new Error("Invalid outputUpper formatting option");if("string"!=typeof n.b64Pad)throw new Error("Invalid b64Pad formatting option");return n}function f(t,n,r,i){const e=t+" must include a value and format";if(!n){if(!i)throw new Error(e);return i}if(void 0===n.value||!n.format)throw new Error(e);return s(n.format,n.encoding||"UTF8",r)(n.value)}class a{constructor(t,n,r){const i=r||{};if(this.t=n,this.i=i.encoding||"UTF8",this.numRounds=i.numRounds||1,isNaN(this.numRounds)||this.numRounds!==parseInt(this.numRounds,10)||1>this.numRounds)throw new Error("numRounds must a integer >= 1");this.o=t,this.h=[],this.u=0,this.l=!1,this.A=0,this.p=!1,this.m=[],this.U=[]}update(t){let n,r=0;const i=this.R>>>5,s=this.C(t,this.h,this.u),e=s.binLen,o=s.value,h=e>>>5;for(n=0;n>>5),this.u=e%this.R,this.l=!0,this}getHash(t,n){let r,i,s=this.T;const o=c(n);if(this.F){if(-1===o.outputLen)throw new Error("Output length must be specified in options");s=o.outputLen}const h=e(t,s,this.g,o);if(this.p&&this.S)return h(this.S(o));for(i=this.L(this.h.slice(),this.u,this.A,this.B(this.v),s),r=1;r>>24-s%32),i=this.L(i,s,0,this.K(this.o),s);return h(i)}setHMACKey(t,n,r){if(!this.k)throw new Error("Variant does not support HMAC");if(this.l)throw new Error("Cannot set MAC key after calling update");const i=s(n,(r||{}).encoding||"UTF8",this.g);this.M(i(t))}M(t){const n=this.R>>>3,r=n/4-1;let i;if(1!==this.numRounds)throw new Error(h);if(this.p)throw new Error("MAC key already set");for(n32?(r=64-n,new w(t.I<>>r,t.N<>>r)):0!==n?(r=32-n,new w(t.N<>>r,t.I<>>r)):t}function E(t,n){return new w(t.N^n.N,t.I^n.I)}const A=[new w(0,1),new w(0,32898),new w(2147483648,32906),new w(2147483648,2147516416),new w(0,32907),new w(0,2147483649),new w(2147483648,2147516545),new w(2147483648,32777),new w(0,138),new w(0,136),new w(0,2147516425),new w(0,2147483658),new w(0,2147516555),new w(2147483648,139),new w(2147483648,32905),new w(2147483648,32771),new w(2147483648,32770),new w(2147483648,128),new w(0,32778),new w(2147483648,2147483658),new w(2147483648,2147516545),new w(2147483648,32896),new w(0,2147483649),new w(2147483648,2147516424)],b=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];function p(t){let n;const r=[];for(n=0;n<5;n+=1)r[n]=[new w(0,0),new w(0,0),new w(0,0),new w(0,0),new w(0,0)];return r}function d(t){let n;const r=[];for(n=0;n<5;n+=1)r[n]=t[n].slice();return r}function m(t,n){let r,i,s,e;const o=[],h=[];if(null!==t)for(i=0;i>>1)%5][(i>>>1)/5|0]=E(n[(i>>>1)%5][(i>>>1)/5|0],new w(t[i+1],t[i]));for(r=0;r<24;r+=1){for(e=p(),i=0;i<5;i+=1)o[i]=(u=n[i][0],c=n[i][1],f=n[i][2],a=n[i][3],d=n[i][4],new w(u.N^c.N^f.N^a.N^d.N,u.I^c.I^f.I^a.I^d.I));for(i=0;i<5;i+=1)h[i]=E(o[(i+4)%5],l(o[(i+1)%5],1));for(i=0;i<5;i+=1)for(s=0;s<5;s+=1)n[i][s]=E(n[i][s],h[i]);for(i=0;i<5;i+=1)for(s=0;s<5;s+=1)e[s][(2*i+3*s)%5]=l(n[i][s],b[i][s]);for(i=0;i<5;i+=1)for(s=0;s<5;s+=1)n[i][s]=E(e[i][s],new w(~e[(i+1)%5][s].N&e[(i+2)%5][s].N,~e[(i+1)%5][s].I&e[(i+2)%5][s].I));n[0][0]=E(n[0][0],A[r])}var u,c,f,a,d;return n}function U(t){let n,r,i=0;const s=[0,0],e=[4294967295&t,t/o&2097151];for(n=6;n>=0;n--)r=e[n>>2]>>>8*n&255,0===r&&0===i||(s[i+1>>2]|=r<<8*(i+1),i+=1);return i=0!==i?i:1,s[0]|=i,{value:i+1>4?s:[s[0]],binLen:8+8*i}}function y(t){return u(U(t.binLen),t)}function R(t,n){let r,i=U(n);i=u(i,t);const s=n>>>2,e=(s-i.value.length%s)%s;for(r=0;r>>5,w=n>>>5;for(h=0;h=s;h+=a)i=m(t.slice(h,h+a),i),n-=s;for(t=t.slice(h),n%=s;t.length>>3,t[h>>2]^=e<=o));)f.push(u.N),c+=1,0==64*c%s&&(m(null,i),c=0);return f}(t,n,0,s,e,i,o)},o.hmacKey&&this.M(f("hmacKey",o.hmacKey,this.g))}O(t,n){const r=function(t){const n=t||{};return{funcName:f("funcName",n.funcName,1,{value:[],binLen:0}),customization:f("Customization",n.customization,1,{value:[],binLen:0})}}(t||{});n&&(r.funcName=n);const i=u(y(r.funcName),y(r.customization));if(0!==r.customization.binLen||0!==r.funcName.binLen){const t=R(i,this.R>>>3);for(let n=0;n>>5)this.v=this.H(t.slice(n,n+(this.R>>>5)),this.v),this.A+=this.R;return 4}return 31}X(t){const n=function(t){const n=t||{};return{kmacKey:f("kmacKey",n.kmacKey,1),funcName:{value:[1128353099],binLen:32},customization:f("Customization",n.customization,1,{value:[],binLen:0})}}(t||{});this.O(t,n.funcName);const r=R(y(n.kmacKey),this.R>>>3);for(let t=0;t>>5)this.v=this.H(r.slice(t,t+(this.R>>>5)),this.v),this.A+=this.R;this.p=!0}_(t){const n=u({value:this.h.slice(),binLen:this.u},function(t){let n,r,i=0;const s=[0,0],e=[4294967295&t,t/o&2097151];for(n=6;n>=0;n--)r=e[n>>2]>>>8*n&255,0===r&&0===i||(s[i>>2]|=r<<8*i,i+=1);return i=0!==i?i:1,s[i>>2]|=i<<8*i,{value:i+1>4?s:[s[0]],binLen:8+8*i}}(t.outputLen));return this.L(n.value,n.binLen,this.A,this.B(this.v),t.outputLen)}}export{C as default}; 10 | -------------------------------------------------------------------------------- /src/common.ts: -------------------------------------------------------------------------------- 1 | import { getStrConverter, getOutputConverter } from "./converters"; 2 | 3 | import { 4 | FormatType, 5 | EncodingType, 6 | FixedLengthOptionsEncodingType, 7 | FixedLengthOptionsNoEncodingType, 8 | FormatNoTextType, 9 | packedValue, 10 | GenericInputType, 11 | } from "./custom_types"; 12 | 13 | export const TWO_PWR_32 = 4294967296; 14 | 15 | /* SHA-2 constant table */ 16 | export const SHA2_K = (() => { 17 | // Cloned list to prevent accidental mutations 18 | const table = [ 19 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 20 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 21 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 22 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 23 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 24 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 25 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 26 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 27 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 28 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 29 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 30 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 31 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 32 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 33 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 34 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 35 | ]; 36 | return table.slice(); 37 | })(); 38 | 39 | /* Initial values for truncated variants */ 40 | export const H_trunc = [ 41 | 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 42 | 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 43 | ]; 44 | 45 | /* Initial values for full SHA-256/512 families */ 46 | export const H_full = [ 47 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 48 | 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 49 | ]; 50 | 51 | export const sha_variant_error = "Chosen SHA variant is not supported"; 52 | export const mac_rounds_error = "Cannot set numRounds with MAC"; 53 | 54 | /** 55 | * Joins two packed arrays in little-endian. Mutates the first array. 56 | * 57 | * @param a First packed value. 58 | * @param b Second packed value. 59 | * @returns Combined structure (a + b). 60 | */ 61 | export function packedLEConcat(a: packedValue, b: packedValue): packedValue { 62 | let i, arrOffset; 63 | const aBytes = a.binLen >>> 3; 64 | const bBytes = b.binLen >>> 3; 65 | const leftShift = aBytes << 3; 66 | const rightShift = (4 - aBytes) << 3; 67 | 68 | // Fast path: simple concat when byte alignment matches 69 | if (aBytes % 4 !== 0) { 70 | for (i = 0; i < bBytes; i += 4) { 71 | arrOffset = (aBytes + i) >>> 2; 72 | a.value[arrOffset] |= b.value[i >>> 2] << leftShift; 73 | a.value.push(0); 74 | a.value[arrOffset + 1] |= b.value[i >>> 2] >>> rightShift; 75 | } 76 | 77 | // Trim last word if unnecessary 78 | if ((a.value.length << 2) - 4 >= bBytes + aBytes) { 79 | a.value.pop(); 80 | } 81 | 82 | return { value: a.value, binLen: a.binLen + b.binLen }; 83 | } 84 | 85 | return { value: a.value.concat(b.value), binLen: a.binLen + b.binLen }; 86 | } 87 | 88 | /** 89 | * Ensures output formatting object contains valid fields. 90 | * 91 | * @param options Output formatting preferences. 92 | */ 93 | export function getOutputOpts(options?: { 94 | outputUpper?: boolean; 95 | b64Pad?: string; 96 | shakeLen?: number; 97 | outputLen?: number; 98 | }): { outputUpper: boolean; b64Pad: string; outputLen: number } { 99 | const normalized = { outputUpper: false, b64Pad: "=", outputLen: -1 }; 100 | const user = options || {}; 101 | const lenErr = "Output length must be a multiple of 8"; 102 | 103 | normalized.outputUpper = user.outputUpper || false; 104 | 105 | if (user.b64Pad) normalized.b64Pad = user.b64Pad; 106 | 107 | if (user.outputLen) { 108 | if (user.outputLen % 8 !== 0) throw new Error(lenErr); 109 | normalized.outputLen = user.outputLen; 110 | } else if (user.shakeLen) { 111 | if (user.shakeLen % 8 !== 0) throw new Error(lenErr); 112 | normalized.outputLen = user.shakeLen; 113 | } 114 | 115 | if (typeof normalized.outputUpper !== "boolean") { 116 | throw new Error("Invalid outputUpper formatting option"); 117 | } 118 | if (typeof normalized.b64Pad !== "string") { 119 | throw new Error("Invalid b64Pad formatting option"); 120 | } 121 | 122 | return normalized; 123 | } 124 | 125 | /** 126 | * Convert external input constructor into packed format. 127 | */ 128 | export function parseInputOption( 129 | key: string, 130 | value: GenericInputType | undefined, 131 | endian: -1 | 1, 132 | fallback?: packedValue 133 | ): packedValue { 134 | const err = key + " must include a value and format"; 135 | 136 | if (!value) { 137 | if (!fallback) throw new Error(err); 138 | return fallback; 139 | } 140 | 141 | if (value.value === undefined || !value.format) { 142 | throw new Error(err); 143 | } 144 | 145 | return getStrConverter( 146 | value.format, 147 | (value as any).encoding || "UTF8", 148 | endian 149 | )(value.value); 150 | } 151 | 152 | export abstract class jsSHABase { 153 | protected readonly shaVariant: VariantT; 154 | protected readonly inputFormat: FormatType; 155 | protected readonly utfType: EncodingType; 156 | protected readonly numRounds: number; 157 | 158 | protected abstract intermediateState: StateT; 159 | protected keyWithIPad: number[]; 160 | protected keyWithOPad: number[]; 161 | protected remainder: number[]; 162 | protected remainderLen: number; 163 | protected updateCalled: boolean; 164 | protected processedLen: number; 165 | protected macKeySet: boolean; 166 | 167 | protected abstract readonly variantBlockSize: number; 168 | protected abstract readonly bigEndianMod: -1 | 1; 169 | protected abstract readonly outputBinLen: number; 170 | protected abstract readonly isVariableLen: boolean; 171 | protected abstract readonly HMACSupported: boolean; 172 | 173 | protected abstract readonly converterFunc: ( 174 | input: any, 175 | existingBin: number[], 176 | existingBinLen: number 177 | ) => packedValue; 178 | 179 | protected abstract readonly roundFunc: ( 180 | block: number[], 181 | H: StateT 182 | ) => StateT; 183 | 184 | protected abstract readonly finalizeFunc: ( 185 | remainder: number[], 186 | remainderBinLen: number, 187 | processedBinLen: number, 188 | H: StateT, 189 | outputLen: number 190 | ) => number[]; 191 | 192 | protected abstract readonly stateCloneFunc: (state: StateT) => StateT; 193 | protected abstract readonly newStateFunc: (variant: VariantT) => StateT; 194 | protected abstract readonly getMAC: ((options: { outputLen: number }) => number[]) | null; 195 | 196 | protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 197 | protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 198 | protected constructor(variant: any, inputFormat: any, options?: any) { 199 | const inputOpts = options || {}; 200 | this.inputFormat = inputFormat; 201 | this.utfType = inputOpts.encoding || "UTF8"; 202 | this.numRounds = inputOpts.numRounds || 1; 203 | 204 | if (isNaN(this.numRounds) || this.numRounds !== parseInt(this.numRounds, 10) || this.numRounds < 1) { 205 | throw new Error("numRounds must a integer >= 1"); 206 | } 207 | 208 | this.shaVariant = variant; 209 | this.remainder = []; 210 | this.remainderLen = 0; 211 | this.updateCalled = false; 212 | this.processedLen = 0; 213 | this.macKeySet = false; 214 | this.keyWithIPad = []; 215 | this.keyWithOPad = []; 216 | } 217 | 218 | /** 219 | * Process as many chunks as possible from input and save remainder. 220 | */ 221 | update(src: string | ArrayBuffer | Uint8Array): this { 222 | let consumed = 0; 223 | const step = this.variantBlockSize >>> 5; 224 | 225 | const converted = this.converterFunc(src, this.remainder, this.remainderLen); 226 | const totalBits = converted.binLen; 227 | const chunk = converted.value; 228 | const chunkInts = totalBits >>> 5; 229 | 230 | for (let i = 0; i < chunkInts; i += step) { 231 | if (consumed + this.variantBlockSize <= totalBits) { 232 | this.intermediateState = this.roundFunc(chunk.slice(i, i + step), this.intermediateState); 233 | consumed += this.variantBlockSize; 234 | } 235 | } 236 | 237 | this.processedLen += consumed; 238 | this.remainder = chunk.slice(consumed >>> 5); 239 | this.remainderLen = totalBits % this.variantBlockSize; 240 | this.updateCalled = true; 241 | 242 | return this; 243 | } 244 | 245 | /** 246 | * Produce final hash value. 247 | */ 248 | // Overloads left unchanged 249 | getHash(format: any, options?: any): any { 250 | let i; 251 | let finalState; 252 | let outLen = this.outputBinLen; 253 | 254 | const outOpts = getOutputOpts(options); 255 | 256 | if (this.isVariableLen) { 257 | if (outOpts.outputLen === -1) throw new Error("Output length must be specified in options"); 258 | outLen = outOpts.outputLen; 259 | } 260 | 261 | const outFunc = getOutputConverter(format, outLen, this.bigEndianMod, outOpts); 262 | 263 | if (this.macKeySet && this.getMAC) { 264 | return outFunc(this.getMAC(outOpts)); 265 | } 266 | 267 | finalState = this.finalizeFunc( 268 | this.remainder.slice(), 269 | this.remainderLen, 270 | this.processedLen, 271 | this.stateCloneFunc(this.intermediateState), 272 | outLen 273 | ); 274 | 275 | for (i = 1; i < this.numRounds; i++) { 276 | if (this.isVariableLen && outLen % 32 !== 0) { 277 | finalState[finalState.length - 1] &= 0x00ffffff >>> (24 - (outLen % 32)); 278 | } 279 | finalState = this.finalizeFunc( 280 | finalState, 281 | outLen, 282 | 0, 283 | this.newStateFunc(this.shaVariant), 284 | outLen 285 | ); 286 | } 287 | 288 | return outFunc(finalState); 289 | } 290 | 291 | /** 292 | * Configure HMAC key — must be called before update(). 293 | */ 294 | setHMACKey(key: any, inputFormat: any, options?: any): void { 295 | if (!this.HMACSupported) throw new Error("Variant does not support HMAC"); 296 | if (this.updateCalled) throw new Error("Cannot set MAC key after calling update"); 297 | 298 | const keyOpts = options || {}; 299 | const conv = getStrConverter(inputFormat, keyOpts.encoding || "UTF8", this.bigEndianMod); 300 | 301 | this._setHMACKey(conv(key)); 302 | } 303 | 304 | protected _setHMACKey(key: packedValue): void { 305 | const blockBytes = this.variantBlockSize >>> 3; 306 | const lastIdx = blockBytes / 4 - 1; 307 | 308 | if (this.numRounds !== 1) throw new Error(mac_rounds_error); 309 | if (this.macKeySet) throw new Error("MAC key already set"); 310 | 311 | if (blockBytes < key.binLen / 8) { 312 | key.value = this.finalizeFunc( 313 | key.value, 314 | key.binLen, 315 | 0, 316 | this.newStateFunc(this.shaVariant), 317 | this.outputBinLen 318 | ); 319 | } 320 | 321 | while (key.value.length <= lastIdx) key.value.push(0); 322 | 323 | for (let i = 0; i <= lastIdx; i++) { 324 | this.keyWithIPad[i] = key.value[i] ^ 0x36363636; 325 | this.keyWithOPad[i] = key.value[i] ^ 0x5c5c5c5c; 326 | } 327 | 328 | this.intermediateState = this.roundFunc(this.keyWithIPad, this.intermediateState); 329 | this.processedLen = this.variantBlockSize; 330 | this.macKeySet = true; 331 | } 332 | 333 | /** 334 | * Return HMAC result using previously-set key. 335 | */ 336 | getHMAC(format: any, options?: any): any { 337 | const opts = getOutputOpts(options); 338 | const f = getOutputConverter(format, this.outputBinLen, this.bigEndianMod, opts); 339 | return f(this._getHMAC()); 340 | } 341 | 342 | protected _getHMAC(): number[] { 343 | if (!this.macKeySet) throw new Error("Cannot call getHMAC without first setting MAC key"); 344 | 345 | const first = this.finalizeFunc( 346 | this.remainder.slice(), 347 | this.remainderLen, 348 | this.processedLen, 349 | this.stateCloneFunc(this.intermediateState), 350 | this.outputBinLen 351 | ); 352 | 353 | let out = this.roundFunc(this.keyWithOPad, this.newStateFunc(this.shaVariant)); 354 | out = this.finalizeFunc(first, this.outputBinLen, this.variantBlockSize, out, this.outputBinLen); 355 | 356 | return out; 357 | } 358 | } 359 | -------------------------------------------------------------------------------- /dist/sha512.mjs: -------------------------------------------------------------------------------- 1 | /** 2 | * A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202, 3 | * and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1. 4 | * 5 | * Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors 6 | * Distributed under the BSD License 7 | * See http://caligatio.github.com/jsSHA/ for more information 8 | */ 9 | const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="ARRAYBUFFER not supported by this environment",e="UINT8ARRAY not supported by this environment";function r(n,t,e,r){let i,s,o;const w=t||[0],h=(e=e||0)>>>3,u=-1===r?3:0;for(i=0;i>>2,w.length<=s&&w.push(0),w[s]|=n[i]<<8*(u+r*(o%4));return{value:w,binLen:8*n.length+e}}function i(i,s,o){switch(s){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(i){case"HEX":return function(n,t,e){return function(n,t,e,r){let i,s,o,w;if(0!=n.length%2)throw new Error("String of HEX type must be in byte increments");const h=t||[0],u=(e=e||0)>>>3,c=-1===r?3:0;for(i=0;i>>1)+u,o=w>>>2;h.length<=o;)h.push(0);h[o]|=s<<8*(c+r*(w%4))}return{value:h,binLen:4*n.length+e}}(n,t,e,o)};case"TEXT":return function(n,t,e){return function(n,t,e,r,i){let s,o,w,h,u,c,f,a,l=0;const E=e||[0],A=(r=r||0)>>>3;if("UTF8"===t)for(f=-1===i?3:0,w=0;ws?o.push(s):2048>s?(o.push(192|s>>>6),o.push(128|63&s)):55296>s||57344<=s?o.push(224|s>>>12,128|s>>>6&63,128|63&s):(w+=1,s=65536+((1023&s)<<10|1023&n.charCodeAt(w)),o.push(240|s>>>18,128|s>>>12&63,128|s>>>6&63,128|63&s)),h=0;h>>2;E.length<=u;)E.push(0);E[u]|=o[h]<<8*(f+i*(c%4)),l+=1}else for(f=-1===i?2:0,a="UTF16LE"===t&&1!==i||"UTF16LE"!==t&&1===i,w=0;w>>8),c=l+A,u=c>>>2;E.length<=u;)E.push(0);E[u]|=s<<8*(f+i*(c%4)),l+=2}return{value:E,binLen:8*l+r}}(n,s,t,e,o)};case"B64":return function(t,e,r){return function(t,e,r,i){let s,o,w,h,u,c,f,a=0;const l=e||[0],E=(r=r||0)>>>3,A=-1===i?3:0,p=t.indexOf("=");if(-1===t.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(t=t.replace(/=/g,""),-1!==p&&p>>2;w.length<=a;)w.push(0);w[a]|=(u>>>16-8*s&255)<<8*(l+i*(h%4)),c+=1}}return{value:w,binLen:8*c+e}}(r,n,e,s)};case"BYTES":return function(r,t,n){return function(r,t,n,e){var i,o,s,u,f=t||[0],a=(n=n||0)>>>3,h=-1===e?3:0;for(o=0;o>>2,f.length<=s&&f.push(0),f[s]|=i<<8*(h+e*(u%4));return{value:f,binLen:8*r.length+n}}(r,t,n,s)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(r){throw new Error(n)}return function(r,t,n){return function(r,t,n,e){return i(new Uint8Array(r),t,n,e)}(r,t,n,s)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(r){throw new Error(e)}return function(r,t,n){return i(r,t,n,s)};default:throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}function s(r,i,o,s){switch(r){case"HEX":return function(r){return function(r,t,n,e){var i,o,s="0123456789abcdef",u="",f=t/8,a=-1===n?3:0;for(i=0;i>>2]>>>8*(a+n*(i%4)),u+=s.charAt(o>>>4&15)+s.charAt(15&o);return e.outputUpper?u.toUpperCase():u}(r,i,o,s)};case"B64":return function(r){return function(r,n,e,i){var o,s,u,f,a,h="",c=n/8,w=-1===e?3:0;for(o=0;o>>2]:0,a=o+2>>2]:0,u=(r[o>>>2]>>>8*(w+e*(o%4))&255)<<16|(f>>>8*(w+e*((o+1)%4))&255)<<8|a>>>8*(w+e*((o+2)%4))&255,s=0;s<4;s+=1)h+=8*o+6*s<=n?t.charAt(u>>>6*(3-s)&63):i.b64Pad;return h}(r,i,o,s)};case"BYTES":return function(r){return function(r,t,n){var e,i,o="",s=t/8,u=-1===n?3:0;for(e=0;e>>2]>>>8*(u+n*(e%4))&255,o+=String.fromCharCode(i);return o}(r,i,o)};case"ARRAYBUFFER":try{new ArrayBuffer(0)}catch(r){throw new Error(n)}return function(r){return function(r,t,n){var e,i=t/8,o=new ArrayBuffer(i),s=new Uint8Array(o),u=-1===n?3:0;for(e=0;e>>2]>>>8*(u+n*(e%4))&255;return o}(r,i,o)};case"UINT8ARRAY":try{new Uint8Array(0)}catch(r){throw new Error(e)}return function(r){return function(r,t,n){var e,i=t/8,o=-1===n?3:0,s=new Uint8Array(i);for(e=0;e>>2]>>>8*(o+n*(e%4))&255;return s}(r,i,o)};default:throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY")}}var u=4294967296,f="Cannot set numRounds with MAC";function a(r,t){var n,e,i=r.binLen>>>3,o=t.binLen>>>3,s=i<<3,u=4-i<<3;if(i%4!=0){for(n=0;n>>2,r.value[e]|=t.value[n>>>2]<>>2]>>>u;return(r.value.length<<2)-4>=o+i&&r.value.pop(),{value:r.value,binLen:r.binLen+t.binLen}}return{value:r.value.concat(t.value),binLen:r.binLen+t.binLen}}function h(r){var t={outputUpper:!1,b64Pad:"=",outputLen:-1},n=r||{},e="Output length must be a multiple of 8";if(t.outputUpper=n.outputUpper||!1,n.b64Pad&&(t.b64Pad=n.b64Pad),n.outputLen){if(n.outputLen%8!=0)throw new Error(e);t.outputLen=n.outputLen}else if(n.shakeLen){if(n.shakeLen%8!=0)throw new Error(e);t.outputLen=n.shakeLen}if("boolean"!=typeof t.outputUpper)throw new Error("Invalid outputUpper formatting option");if("string"!=typeof t.b64Pad)throw new Error("Invalid b64Pad formatting option");return t}function c(r,t,n,e){var i=r+" must include a value and format";if(!t){if(!e)throw new Error(i);return e}if(void 0===t.value||!t.format)throw new Error(i);return o(t.format,t.encoding||"UTF8",n)(t.value)}var w=function(){function r(r,t,n){var e=n||{};if(this.t=t,this.i=e.encoding||"UTF8",this.numRounds=e.numRounds||1,isNaN(this.numRounds)||this.numRounds!==parseInt(this.numRounds,10)||1>this.numRounds)throw new Error("numRounds must a integer >= 1");this.o=r,this.u=[],this.h=0,this.v=!1,this.l=0,this.A=!1,this.p=[],this.m=[]}return r.prototype.update=function(r){var t,n=0,e=this.U>>>5,i=this.R(r,this.u,this.h),o=i.binLen,s=i.value,u=o>>>5;for(t=0;t>>5),this.h=o%this.U,this.v=!0,this},r.prototype.getHash=function(r,t){var n,e,i=this.S,o=h(t);if(this.C){if(-1===o.outputLen)throw new Error("Output length must be specified in options");i=o.outputLen}var u=s(r,i,this.H,o);if(this.A&&this.g)return u(this.g(o));for(e=this.L(this.u.slice(),this.h,this.l,this.B(this.T),i),n=1;n>>24-i%32),e=this.L(e,i,0,this.k(this.o),i);return u(e)},r.prototype.setHMACKey=function(r,t,n){if(!this.Y)throw new Error("Variant does not support HMAC");if(this.v)throw new Error("Cannot set MAC key after calling update");var e=o(t,(n||{}).encoding||"UTF8",this.H);this.K(e(r))},r.prototype.K=function(r){var t,n=this.U>>>3,e=n/4-1;if(1!==this.numRounds)throw new Error(f);if(this.A)throw new Error("MAC key already set");for(n32?(n=64-t,new v(r.M<>>n,r.I<>>n)):0!==t?(n=32-t,new v(r.I<>>n,r.M<>>n)):r}function E(r,t){return new v(r.I^t.I,r.M^t.M)}var A=[new v(0,1),new v(0,32898),new v(2147483648,32906),new v(2147483648,2147516416),new v(0,32907),new v(0,2147483649),new v(2147483648,2147516545),new v(2147483648,32777),new v(0,138),new v(0,136),new v(0,2147516425),new v(0,2147483658),new v(0,2147516555),new v(2147483648,139),new v(2147483648,32905),new v(2147483648,32771),new v(2147483648,32770),new v(2147483648,128),new v(0,32778),new v(2147483648,2147483658),new v(2147483648,2147516545),new v(2147483648,32896),new v(0,2147483649),new v(2147483648,2147516424)],b=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];function p(r){var t,n=[];for(t=0;t<5;t+=1)n[t]=[new v(0,0),new v(0,0),new v(0,0),new v(0,0),new v(0,0)];return n}function d(r){var t,n=[];for(t=0;t<5;t+=1)n[t]=r[t].slice();return n}function y(r,t){var n,e,i,o,s,u,f,a,h,c=[],w=[];if(null!==r)for(e=0;e>>1)%5][(e>>>1)/5|0]=E(t[(e>>>1)%5][(e>>>1)/5|0],new v(r[e+1],r[e]));for(n=0;n<24;n+=1){for(o=p(),e=0;e<5;e+=1)c[e]=(s=t[e][0],u=t[e][1],f=t[e][2],a=t[e][3],h=t[e][4],new v(s.I^u.I^f.I^a.I^h.I,s.M^u.M^f.M^a.M^h.M));for(e=0;e<5;e+=1)w[e]=E(c[(e+4)%5],l(c[(e+1)%5],1));for(e=0;e<5;e+=1)for(i=0;i<5;i+=1)t[e][i]=E(t[e][i],w[e]);for(e=0;e<5;e+=1)for(i=0;i<5;i+=1)o[i][(2*e+3*i)%5]=l(t[e][i],b[e][i]);for(e=0;e<5;e+=1)for(i=0;i<5;i+=1)t[e][i]=E(o[e][i],new v(~o[(e+1)%5][i].I&o[(e+2)%5][i].I,~o[(e+1)%5][i].M&o[(e+2)%5][i].M));t[0][0]=E(t[0][0],A[n])}return t}function m(r){var t,n,e=0,i=[0,0],o=[4294967295&r,r/u&2097151];for(t=6;t>=0;t--)0===(n=o[t>>2]>>>8*t&255)&&0===e||(i[e+1>>2]|=n<<8*(e+1),e+=1);return e=0!==e?e:1,i[0]|=e,{value:e+1>4?i:[i[0]],binLen:8+8*e}}function U(r){return a(m(r.binLen),r)}function R(r,t){var n,e=m(t),i=t>>>2,o=(i-(e=a(e,r)).value.length%i)%i;for(n=0;n>>5,w=t>>>5;for(u=0;u=i;u+=c)e=y(r.slice(u,u+c),e),t-=i;for(r=r.slice(u),t%=i;r.length>>3)>>2]^=o<=s));)h.push(f.I),0==64*(a+=1)%i&&(y(null,e),a=0);return h}(r,t,0,e,u,s,i)},a.hmacKey&&i.K(c("hmacKey",a.hmacKey,i.H)),i}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function e(){this.constructor=t}r(t,n),t.prototype=null===n?Object.create(n):(e.prototype=n.prototype,new e)}(n,t),n.prototype.j=function(r,t){var n=function(r){var t=r||{};return{funcName:c("funcName",t.funcName,1,{value:[],binLen:0}),customization:c("Customization",t.customization,1,{value:[],binLen:0})}}(r||{});t&&(n.funcName=t);var e=a(U(n.funcName),U(n.customization));if(0!==n.customization.binLen||0!==n.funcName.binLen){for(var i=R(e,this.U>>>3),o=0;o>>5)this.T=this.F(i.slice(o,o+(this.U>>>5)),this.T),this.l+=this.U;return 4}return 31},n.prototype.X=function(r){var t=function(r){var t=r||{};return{kmacKey:c("kmacKey",t.kmacKey,1),funcName:{value:[1128353099],binLen:32},customization:c("Customization",t.customization,1,{value:[],binLen:0})}}(r||{});this.j(r,t.funcName);for(var n=R(U(t.kmacKey),this.U>>>3),e=0;e>>5)this.T=this.F(n.slice(e,e+(this.U>>>5)),this.T),this.l+=this.U;this.A=!0},n.prototype.O=function(r){var t=a({value:this.u.slice(),binLen:this.h},function(r){var t,n,e=0,i=[0,0],o=[4294967295&r,r/u&2097151];for(t=6;t>=0;t--)0==(n=o[t>>2]>>>8*t&255)&&0===e||(i[e>>2]|=n<<8*e,e+=1);return i[(e=0!==e?e:1)>>2]|=e<<8*e,{value:e+1>4?i:[i[0]],binLen:8+8*e}}(r.outputLen));return this.L(t.value,t.binLen,this.l,this.B(this.T),r.outputLen)},n}(w)})); 22 | -------------------------------------------------------------------------------- /dist/sha512.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202, 3 | * and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1. 4 | * 5 | * Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors 6 | * Distributed under the BSD License 7 | * See http://caligatio.github.com/jsSHA/ for more information 8 | * 9 | * Two ECMAScript polyfill functions carry the following license: 10 | * 11 | * Copyright (c) Microsoft Corporation. All rights reserved. 12 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 13 | * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 16 | * INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 17 | * MERCHANTABLITY OR NON-INFRINGEMENT. 18 | * 19 | * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. 20 | */ 21 | !function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(n="undefined"!=typeof globalThis?globalThis:n||self).jsSHA=r()}(this,(function(){"use strict";var n=function(r,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&(n[t]=r[t])},n(r,t)};"function"==typeof SuppressedError&&SuppressedError;var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t="ARRAYBUFFER not supported by this environment",e="UINT8ARRAY not supported by this environment";function i(n,r,t,e){var i,o,u,w=r||[0],s=(t=t||0)>>>3,f=-1===e?3:0;for(i=0;i>>2,w.length<=o&&w.push(0),w[o]|=n[i]<<8*(f+e*(u%4));return{value:w,binLen:8*n.length+t}}function o(n,o,u){switch(o){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(n){case"HEX":return function(n,r,t){return function(n,r,t,e){var i,o,u,w;if(0!=n.length%2)throw new Error("String of HEX type must be in byte increments");var s=r||[0],f=(t=t||0)>>>3,h=-1===e?3:0;for(i=0;i>>1)+f)>>>2;s.length<=u;)s.push(0);s[u]|=o<<8*(h+e*(w%4))}return{value:s,binLen:4*n.length+t}}(n,r,t,u)};case"TEXT":return function(n,r,t){return function(n,r,t,e,i){var o,u,w,s,f,h,a,c,v=0,E=t||[0],l=(e=e||0)>>>3;if("UTF8"===r)for(a=-1===i?3:0,w=0;w(o=n.charCodeAt(w))?u.push(o):2048>o?(u.push(192|o>>>6),u.push(128|63&o)):55296>o||57344<=o?u.push(224|o>>>12,128|o>>>6&63,128|63&o):(w+=1,o=65536+((1023&o)<<10|1023&n.charCodeAt(w)),u.push(240|o>>>18,128|o>>>12&63,128|o>>>6&63,128|63&o)),s=0;s>>2;E.length<=f;)E.push(0);E[f]|=u[s]<<8*(a+i*(h%4)),v+=1}else for(a=-1===i?2:0,c="UTF16LE"===r&&1!==i||"UTF16LE"!==r&&1===i,w=0;w>>8),f=(h=v+l)>>>2;E.length<=f;)E.push(0);E[f]|=o<<8*(a+i*(h%4)),v+=2}return{value:E,binLen:8*v+e}}(n,o,r,t,u)};case"B64":return function(n,t,e){return function(n,t,e,i){var o,u,w,s,f,h,a=0,c=t||[0],v=(e=e||0)>>>3,E=-1===i?3:0,l=n.indexOf("=");if(-1===n.search(/^[a-zA-Z0-9=+/]+$/))throw new Error("Invalid character in base-64 string");if(n=n.replace(/=/g,""),-1!==l&&l>> 5] |= 0x80 << (24 - (remainderBinLen % 32)); 225 | /* Append length of binary string in the position such that the new 226 | * length is correct. JavaScript numbers are limited to 2^53 so it's 227 | * "safe" to treat the totalLen as a 64-bit integer. */ 228 | 229 | remainder[offset] = totalLen & 0xffffffff; 230 | /* Bitwise operators treat the operand as a 32-bit number so need to 231 | * use hacky division and round to get access to upper 32-ish bits */ 232 | remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0; 233 | 234 | /* This will always be at least 1 full chunk */ 235 | for (i = 0; i < remainder.length; i += binaryStringInc) { 236 | // Avoid allocating with slice() when possible by using subarray if available. 237 | const block = (remainder as any).subarray 238 | ? (remainder as any).subarray(i, i + binaryStringInc) 239 | : remainder.slice(i, i + binaryStringInc); 240 | H = roundSHA512(block as any, H); 241 | } 242 | 243 | if ("SHA-384" === variant) { 244 | H = (H as unknown) as Int_64[]; 245 | retVal = [ 246 | H[0].highOrder, 247 | H[0].lowOrder, 248 | H[1].highOrder, 249 | H[1].lowOrder, 250 | H[2].highOrder, 251 | H[2].lowOrder, 252 | H[3].highOrder, 253 | H[3].lowOrder, 254 | H[4].highOrder, 255 | H[4].lowOrder, 256 | H[5].highOrder, 257 | H[5].lowOrder, 258 | ]; 259 | } else { 260 | /* SHA-512 */ 261 | retVal = [ 262 | H[0].highOrder, 263 | H[0].lowOrder, 264 | H[1].highOrder, 265 | H[1].lowOrder, 266 | H[2].highOrder, 267 | H[2].lowOrder, 268 | H[3].highOrder, 269 | H[3].lowOrder, 270 | H[4].highOrder, 271 | H[4].lowOrder, 272 | H[5].highOrder, 273 | H[5].lowOrder, 274 | H[6].highOrder, 275 | H[6].lowOrder, 276 | H[7].highOrder, 277 | H[7].lowOrder, 278 | ]; 279 | } 280 | return retVal; 281 | } 282 | 283 | export default class jsSHA extends jsSHABase { 284 | intermediateState: Int_64[]; 285 | variantBlockSize: number; 286 | bigEndianMod: -1 | 1; 287 | outputBinLen: number; 288 | isVariableLen: boolean; 289 | HMACSupported: boolean; 290 | 291 | /* Added property: maximum allowed input bits (protects from accidental huge inputs) */ 292 | maxInputBits: number; 293 | 294 | /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ 295 | converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue; 296 | roundFunc: (block: number[], H: Int_64[]) => Int_64[]; 297 | finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: Int_64[]) => number[]; 298 | stateCloneFunc: (state: Int_64[]) => Int_64[]; 299 | newStateFunc: (variant: VariantType) => Int_64[]; 300 | getMAC: () => number[]; 301 | 302 | constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType); 303 | constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType); 304 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 305 | constructor(variant: any, inputFormat: any, options?: any) { 306 | if (!("SHA-384" === variant || "SHA-512" === variant)) { 307 | throw new Error(sha_variant_error); 308 | } 309 | super(variant, inputFormat, options); 310 | const resolvedOptions = options || {}; 311 | 312 | // eslint-disable-next-line @typescript-eslint/unbound-method 313 | this.getMAC = this._getHMAC; 314 | this.HMACSupported = true; 315 | this.bigEndianMod = -1; 316 | this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod); 317 | this.roundFunc = roundSHA512; 318 | this.stateCloneFunc = function (state): Int_64[] { 319 | return state.slice(); 320 | }; 321 | this.newStateFunc = getNewState512; 322 | this.finalizeFunc = function (remainder, remainderBinLen, processedBinLen, H): number[] { 323 | return finalizeSHA512(remainder, remainderBinLen, processedBinLen, H, variant); 324 | }; 325 | 326 | this.intermediateState = getNewState512(variant); 327 | this.variantBlockSize = 1024; 328 | this.outputBinLen = "SHA-384" === variant ? 384 : 512; 329 | this.isVariableLen = false; 330 | 331 | // Default max input size (in bits). Adjust or override per instance if you like. 332 | // This default protects from extremely large inputs that could hang a browser/Node process. 333 | this.maxInputBits = resolvedOptions.maxInputBits || (2 ** 32) * 32; // ~128 GiB in bits 334 | 335 | if (resolvedOptions["hmacKey"]) { 336 | this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod)); 337 | } 338 | } 339 | 340 | /** 341 | * Override update to add input-size protection while delegating actual work to the base. 342 | * This does a cheap conversion check first (same converter used by base), then calls super.update. 343 | */ 344 | update(src: string | ArrayBuffer | Uint8Array): this { 345 | // Determine the bit-length of the incoming chunk without modifying internal state 346 | const converted = this.converterFunc(src, [], 0); 347 | const chunkBinLen = converted.binLen; 348 | 349 | if (this.processedLen + chunkBinLen > this.maxInputBits) { 350 | throw new Error("Input too large"); 351 | } 352 | 353 | // Delegate the actual update logic to the base implementation 354 | return super.update(src); 355 | } 356 | 357 | /** 358 | * Returns the raw binary state as a full HEX string. 359 | * Useful for debugging or exposing intermediate state. 360 | */ 361 | toHexArray(H: Int_64[]): string { 362 | return H 363 | .map( 364 | (w) => 365 | (w.highOrder >>> 0).toString(16).padStart(8, "0") + 366 | (w.lowOrder >>> 0).toString(16).padStart(8, "0") 367 | ) 368 | .join(""); 369 | } 370 | // (Everything else - methods wired up from constructor are unchanged in behavior.) 371 | // The class relies on jsSHABase for most public methods (getHash, setHMACKey, getHMAC, etc.). 372 | } 373 | 374 | /** 375 | * Built-in self-test (NIST test vector for "abc"). 376 | * Returns true if implementation matches expected SHA-512 result. 377 | */ 378 | export function sha512SelfTest(): boolean { 379 | // Known SHA-512("abc") from NIST 380 | const expected = 381 | "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" + 382 | "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; 383 | 384 | // Use the exported class to compute 385 | const shaObj = new jsSHA("SHA-512", "TEXT"); 386 | shaObj.update("abc"); 387 | const hash = shaObj.getHash("HEX"); 388 | return hash.toLowerCase() === expected; 389 | } 390 | --------------------------------------------------------------------------------