first commit

This commit is contained in:
2025-10-26 23:10:15 +08:00
commit 8f0345b7be
14961 changed files with 2356381 additions and 0 deletions

256
node_modules/jssha/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,256 @@
# jsSHA - ChangeLog
## 3.3.1 (2023-08-04)
- Support latest method of defining type imports (#103, thanks @faljse!).
## 3.3.0 (2022-10-10)
- `.update()` method now returns a reference to the jsSHA object to allow for
method chaining (#100, thanks @ADTC!).
- Correct bad URL in README (#99, thanks @jbjulia!).
## 3.2.0 (2020-12-07)
- Added ESM versions of all variants (thanks wKovacs64!).
## 3.1.2 (2020-08-08)
- Added explicit package.json export to support React (thanks canpoyrazoglu!).
## 3.1.1 (2020-07-22)
- Added dist subpath exports to provide forward compatibility with newer node
versions (thanks aravinth2094!).
## 3.1.0 - Still-At-Home Edition (2020-04-15)
- Added support for cSHAKE128/256 and KMAC128/256 (thanks paulg446 for the
ticket and mrecachinas for the test vector help!).
- Added TypeScript declarations for all variant files (thanks wKovacs64!).
- Deprecated `setHMACKey` and `getHMAC` in order to unify MAC API. See the
[jsSHA Wiki] for more information.
[jssha wiki]: https://github.com/Caligatio/jsSHA/wiki
## 3.0.0 - Stay-At-Home Order Edition (2020-04-09)
- Transitioned codebase to [TypeScript] while still maintaining v2 backwards
compatible output files (thanks for the solid start oberondelafay!).
- v2 backwards compatible files now use the [Universal Module Definition
(UMD)][umd] format which should support all well-known loaders.
- Added a oft-requested ECMAScript 2015 (ES6) ECMAScript Module (ESM) version of
the library (dist/sha.mjs).
- Reworked package exports to allow Node.js and other tools to smartly choose
between ES6 ESM module and ES3 UMD versions of the library.
- TypeScript declarations are now included with the library for the default
entry points (dist/sha.js and dist/sha.mjs).
- Source maps are now included with the library for the default entry points.
- Limited hash variant files (sha1.js, sha256.js, sha512.js, and sha3.js) are
now accessed via exports rather than file path (e.g. using
`require("jssha/sha1")` rather than the previous
`require("jssha/src/sha1.js"`).
- Changed build system from [Google Closure Compiler][gcc] to [Rollup] with
[terser] as the minifier/uglifer (thanks blikblum!). This resulted in slightly
larger output files but infinitely better maintainability.
- Optimized 64-bit functions by removing unneeded logical/arithmetic/bit
operations.
- Completely overhauled testing due to transition to TypeScript. This resulted
in the ability to get true 100% unit test coverage and identification of a few
lurking/obscure bugs (see v2.4.2 and v2.4.1).
[typescript]: https://www.typescriptlang.org/
[rollup]: https://rollupjs.org/
[terser]: https://github.com/terser/terser
[umd]: https://github.com/umdjs/umd
## 2.4.2 (2020-04-08)
This marks the last v2.X feature release. The codebase is transitioning to
TypeScript and, while the API is intended to be fully backwards-compatible, the
version will be bumped to v3 as a safety precaution.
- Fixed incorrect SHAKE128 results when output length was greater than 1344-bits
and SHAKE256 results when output length was greater than 1088-bits (1344 and
1088 being internal state size for each variant).
## 2.4.1 (2020-04-04)
- Fixed incorrect HMAC results when using SHA-3 if the key was 1-4 bytes shorter
than the internal block size of the chosen SHA-3 variant.
## 2.4.0 (2020-03-26)
- Reduced ECMAScript dependency to v3 (thanks TitusInfo!)
- Added support for Uint8Array input/output as UINT8ARRAY (thanks nazar-pc!)
## 1.6.3 (2020-03-26)
- Reduced ECMAScript dependency to v3 (thanks TitusInfo!)
## 2.3.1 (2017-06-10)
- Fix issue with SHA-3 and using a combination of TEXT/UTF-16 input (thanks
frostschutz!)
## 2.3.0 (2017-05-13)
- Sped up SHA-3 implementation by adding little-endian capability to conversion
functions
- Further sped up SHA-3 implementation by decomposing xor_64 function (thanks
frostschutz!)
- Fixed incorrect results when using ArrayBuffers (thanks conref!)
- Added externs/sha.js for [Google Closure Compiler][gcc] users (thanks IvanRF!)
## 2.2.0 (2016-07-10)
- Added support for the SHA-3 family of hashes (SHA3-224, SHA3-256, SHA3-384,
SHA3-512, SHAKE128, and SHAKE256)
- Fixed bug with using ARRAYBUFFER as a HMAC key type
- Switched testing framework to Mocha and Chai
## 2.1.0 (2016-05-13)
- Added ability to call `update` on hashes between `getHash` and `getHMAC` calls
- Added new input and output type, "ARRAYBUFFER" which is a JavaScript
ArrayBuffer
- Now keeping smaller build files in NPM (thanks vogievetsky!)
- Fixed problem with hashing strings over 4 billion bits (thanks Eicar!)
## 2.0.2 (2015-10-31)
- Fixed inability to have a blank "b64Pad" (thanks xlc!)
- Added file hashing test (thanks kofalt!)
## 2.0.1 (2015-06-25)
- Fixed major issue with all hashes failing if raw input was a particular size
(thanks treus!)
## 2.0.0 (2015-06-13)
- Completely reworked API to support streaming inputs
- Exceptions now throw Errors instead of strings (thanks jclem!)
## 1.6.1 (2015-06-25)
- Fixed issue with SHA-512 family of hashes failing if raw input was a
particular size
## 1.6.0 (2015-03-08)
This marks the last v1.X new feature release. The API is changing significantly
with upcoming v2.0 to support streaming and it will be too difficult to support
the older API style with new features.
- Added a BYTES input and output format that is a raw byte string
- Fixed broken AMD support (thanks drewcovi!)
- Fixed broken UTF-8 parsing on non-BMP Unicode characters
- Changed array references to remove warnings on Icedove
- Replaced "UTF16" encoding with "UTF16BE" (big endian) and "UTF16LE" (little
endian) to remove confusion
## 1.5.1 (2013-12-15)
- Changed [Google Closure Compiler][gcc] options to produce "strict" compatible
code
## 1.5 (2013-12-15)
- Added optional numRounds argument to getHash
- Note: this necessitated removing the hash result caching functionality
- Reduced file size by optimizing internal constants
- Removed charSize input and replaced with encoding to handle Unicode. NOTE:
Only Code points up to 0xFFFF are supported.
- charSize = 16 is effectively replaced by encoding = "UTF16"
- charSize = 8 was wrong in terms of handling UTF-8 and has been replaced by
encoding = "UTF8"
- Changed method of referencing "window" to be compatible with WebWorkers,
Node.js, and AMD (thanks piranna!)
## 1.42 (2012-12-28)
- Readded v1.4 Safari patch to support older versions
## 1.41 (2012-12-23)
- Fixed incorrect hash issue with Chrome x64 v25 (Dev channel), also provides
stable patch to v1.4 Safari issue.
## 1.4 (2012-12-08)
- Added new input type, TEXT, that is functionally identical to ASCII\*
- Added new input type, B64, for base-64 encoded strings
- Added new input and output formatting parameters
- `getHash` and `getHMAC` take an optional parameter, outputFormatOpts, that
is a hash list containing the keys "outputUpper" (boolean, only applicable
to HEX output) and "b64Pad" (string, only applicable to Base-64 output) that
have default values of false and "=", respectively
- jsSHA constructor takes an optional parameter, charSize (8 or 16) that
specifies the character width of the input (TEXT and ASCII input only)
- Modified comments to be [Google Closure Compiler][gcc] compliant
- Added a SUPPORTED_ALGS flag that, when used with the Google Closure Compiler,
will remove unused functions/function portions
- Removed all src/\*\_nice.js files as the SUPPORTED_ALGS flag renders them
obsolete
- All production-ready files are now produced using the Google Closure Compiler
with ADVANCED_OPTIMIZATIONS resulting in further reduced filesizes
- The SHA-1 only implementation now requires that that "SHA-1" be specified as
the variant when using getHash and getHMAC
- Removed test/HMAC.py as new NIST tests made the need for it obsolete
- Significantly changed the test/test.html to make it easier to understand and
to allow for easier adding of test cases
- Replaced previous error returning code with thrown exceptions
- Fix for 64-bit Safari issue (thanks Ron Garret and Chris Warren-Smith!)
- NOTE: While this fix works, it is merely a workaround for a WebKit
JavaScript optimizer bug, see https://bugs.webkit.org/show_bug.cgi?id=88673
for more detail
\* This library misused the term ASCII so input type of TEXT was added with the
intention of deprecating ASCII
[gcc]: https://developers.google.com/closure/compiler/
## 1.31 (2012-07-21)
- Updated project URL to point to new GitHub repository
- Added a compressed version of sha.js
## 1.3 (2010-09-01)
- Changed method of declaring objects/classes
- Moved non-instance specific variables and methods to class scope
- Removed logically correct but unneeded conditionals
## 1.2 (2009-07-22)
- Added the HMAC algorithm for all supported hashes (using both ASCII and hex
keys)
- As a result of adding HMAC, added support for hash input text to be hex (ASCII
representation of hex)
- Added multiple variants of safeAdd functions, resulting in a significant
performance gain
- Removed wrapper.js file
- Used a different JavaScript compressor resulting in smaller file sizes
## 1.11 (2008-12-07)
- Fixed a base-64 encoding issue resulting from a missing capital 'X'
## 1.1 (2008-09-25)
- Fixed an issue with incorrect hashes being generated when jsSHA ojbects were
used to generate multiple hashes
## 1.0 (2008-09-25)
- Made all functions/variables follow an object-orientated methodology
- Removed support for string hash output as the hash is rarely ASCII friendly
- Changed the interface to calculate hashes (see README)
- Made sha.js validate against [JSLint] using "Recommended" settings
[jslint]: http://www.jslint.com
## 0.1 (2008-02-21)
- Initial public release

33
node_modules/jssha/CONTRIBUTING.md generated vendored Normal file
View File

@@ -0,0 +1,33 @@
# How to Contribute
jsSHA welcomes all contributions whether they are bug reports, feature requests,
or pull requests (PR). Please note the scope of this library is limited to
official SHA variants or their direct descendants.
In order to speed up the process, please adhere to the following guidelines:
## Bug Reports
When submitting bug reports please ensure your report has the minimum following
information:
- JavaScript engine name and version (i.e. the browser or Node.js version).
- Whether the module is being imported as a ECMAScript Module (ESM) or via other
means.
- The full error reported, if applicable.
- If the code is not sensitive, the code snippet that caused the error.
## Pull Requests
First off, thank you for being willing to contribute code directly to jsSHA! We
tried to make the tooling take care of all the mundane issues like code
formatting to make it easy to contribute. That being said, we ask that you
follow these guidelines when submitting PRs:
- Please do not include any files in the `dist/` directory. For security
reasons, only `dist` files created by the maintainer(s) are distributed.
- Although the CI/CD pipeline should take care of this, please, at minimum, run
`npm build && npm test` before submitting your PR.
- Some of our users still use JavaScript engines that only support ECMAScript 3
(ES3) which was adopted back in 1999. Please try to make sure that any new
code is compatible with ES3.

26
node_modules/jssha/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,26 @@
Copyright (c) 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

192
node_modules/jssha/README.md generated vendored Normal file
View File

@@ -0,0 +1,192 @@
# jsSHA
A pure TypeScript/JavaScript streaming implementation of the complete Secure
Hash Standard (SHA) family (SHA-1, SHA-224/256/384/512, SHA3-224/256/384/512,
SHAKE128/256, cSHAKE128/256, and KMAC128/256) with HMAC.
[![npm](https://img.shields.io/npm/v/jssha)](https://www.npmjs.com/package/jssha)
[![Build Status](https://travis-ci.org/Caligatio/jsSHA.svg?branch=master)](https://travis-ci.org/Caligatio/jsSHA)
[![Coverage Status](https://coveralls.io/repos/github/Caligatio/jsSHA/badge.svg?branch=master)](https://coveralls.io/github/Caligatio/jsSHA?branch=master)
[![NPM](https://img.shields.io/npm/l/jssha)](https://opensource.org/licenses/BSD-3-Clause)
## Usage
More complete documentation can be found on the
[jsSHA Wiki](https://github.com/Caligatio/jsSHA/wiki) but below are common
use-cases.
### Installation
#### Browser
Include the desired JavaScript file (sha.js, sha1.js, sha256.js, sha512.js, or
sha3.js) in your header:
```html
<script type="text/javascript" src="/path/to/sha.js"></script>
```
#### Node.js
jsSHA is available through NPM and be installed by simply doing
```console
npm install jssha
```
To use the module, first require it using:
```javascript
const jsSHA = require("jssha");
/* The limited variant files are also exported (sha1, sha256, sha512, and sha3)
* using conditional subpath exports in Node.js v13+ or using --experimental-modules
* in v12 */
const jsSHA1 = require("jssha/sha1");
/* For Node.js versions that don't support subpath exports, you can do the
* following instead: */
const jsSHA1 = require("jssha/dist/sha1");
/* Alternatively, you can load it as an ESM (Node.js v13+ or using
* --experimental-modules in v12) */
import jsSHA from "jssha";
```
### Hashing
Instantiate a new `jsSHA` object with the desired hash variant, input format,
and options as parameters. The hash variant can be one of SHA-1, SHA-224,
SHA3-224, SHA-256, SHA3-256, SHA-384, SHA3-384, SHA-512, SHA3-512, SHAKE128, or
SHAKE256. The input format can be one of HEX, TEXT, B64, BYTES, ARRAYBUFFER, or
UINT8ARRAY. You can then stream in input using the `update` object function,
calling it multiple times if needed. Finally, simply call `getHash` with the
output type as a parameter (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY).
Example to calculate the SHA-512 of "This is a test":
```javascript
const shaObj = new jsSHA("SHA-512", "TEXT", { encoding: "UTF8" });
/* .update() can be chained */
shaObj.update("This is").update(" a ");
shaObj.update("test");
const hash = shaObj.getHash("HEX");
```
The constructor takes a hashmap as a optional third argument with defaults
`{"encoding" : "UTF8", "numRounds" : 1}`. `numRounds` controls the number of
hashing iterations/rounds performed and `encoding` specifies the encoding used
to encode TEXT-type inputs. Valid `encoding` values are "UTF8", "UTF16BE", and
"UTF16LE".
`getHash` also takes a hashmap as an optional second argument with defaults
`{"outputUpper" : false, "b64Pad" : "="}`. `outputUpper` is only used for "HEX"
outputs and `b64Pad` only for "B64" outputs.
**_Important_**: SHAKE128 and SHAKE256 require `outputLen` to be in the hashmap
where `outputLen` is the desired output length of the SHAKE algorithm in a
multiple of 8 bits.
### HMAC
Instantiate a new `jsSHA` object similiar to hashing but with the third argument
in the form of `{ "hmacKey": { "value": VALUE, "format": FORMAT } }`. FORMAT
takes the same values as the input format from hashing and the VALUE is then
either a `string`, `ArrayBuffer`, or `Uint8Array`. You can stream in the input
using the `update` object function just like hashing. Finally, get the HMAC by
calling the `getHash` function with the output type as its argument. Example to
calculate the SHA-512 HMAC of the string "This is a test" with the key "abc":
```javascript
const shaObj = new jsSHA("SHA-512", "TEXT", {
hmacKey: { value: "abc", format: "TEXT" },
});
shaObj.update("This is a ");
shaObj.update("test");
const hmac = shaObj.getHash("HEX");
```
Note: You cannot specify `numRounds` with HMAC.
### cSHAKE
Instantiate a new `jsSHA` object similiar to HMAC but first argument being
either "CSHAKE128" or "CSHAKE256" and the third argument in the form of
`{ "customization"?: { "value": VALUE, "format": FORMAT }, "funcName"?: { "value": VALUE, "format": FORMAT } }`.
FORMAT takes the same values as the input format from hashing and the VALUE is
then either a `string`, `ArrayBuffer`, or `Uint8Array`. Per the NIST
specification, both `customization` and `funcName` are optional. You can stream
in the input using the `update` object function just like hashing. Finally, get
the hash by calling the `getHash` function with the output type and length as
arguments. Example to calculate the cSHAKE128 of the string "This is a test"
with the customization string "My Tagged Application" and an output size of
256-bits.
```javascript
const shaObj = new jsSHA("CSHAKE128", "TEXT", {
customization: { value: "My Tagged Application", format: "TEXT" },
});
shaObj.update("This is a ");
shaObj.update("test");
const cshake = shaObj.getHash("HEX", { outputLen: 256 });
```
Note: You cannot specify `numRounds` with cSHAKE.
**_Important_**: `outputLen` is required to be in the hashmap where `outputLen`
is the desired output length of the cSHAKE algorithm in a multiple of 8 bits.
### KMAC
Instantiate a new `jsSHA` object similiar to cSHAKE but first argument being
either "KMAC128" or "KMAC256" and the third argument in the form of
`{ "customization"?: { "value": VALUE, "format": FORMAT }, "kmacKey?: { "value": VALUE, "format": FORMAT } }`.
FORMAT takes the same values as the input format from hashing and the VALUE is
then either a `string`, `ArrayBuffer`, or `Uint8Array`. Per the NIST
specification `customization` is optional whereas `kmacKey` is required. You can
stream in the input using the `update` object function just like hashing.
Finally, get the hash by calling the `getHash` function with the output type and
length as arguments. Example to calculate the KMAC128 of the string "This is a
test" with the customization string "My Tagged Application", key "abc", and an
output size of 256-bits.
```javascript
const shaObj = new jsSHA("KMAC128", "TEXT", {
customization: { value: "My Tagged Application", format: "TEXT" },
kmacKey: { value: "abc", format: "TEXT" },
});
shaObj.update("This is a ");
shaObj.update("test");
const kmac = shaObj.getHash("HEX", { outputLen: 256 });
```
Note: You cannot specify `numRounds` with KMAC.
**_Important_**: `outputLen` is required to be in the hashmap where `outputLen`
is the desired output length of the KMAC algorithm in a multiple of 8 bits.
## Files
- **dist/sha.js** - The minified ECMAScript 3 (ES3) compatible [Universal Module
Definition (UMD)][umd] version of the library with support for all hash
variants. Its accompanying source map can be found in dist/sha.js.map and its
TypeScript declarations in dist/sha.d.ts.
- **dist/sha.mjs** - The minified ECMAScript 2015 (ES6) compatible ESM version
of the library with support for all hash variants. Its accompanying source map
can be found in dist/sha.mjs.map and its TypeScript declarations in
dist/sha.d.ts.
- **dist/sha1.{js,mjs}** - The minified UMD and ESM versions of the library with
support for only the SHA-1 hash variant. Its accompanying TypeScript
declarations can be found in dist/sha1.d.ts.
- **dist/sha256.{js,mjs}** - The minified UMD and ESM versions of the library
with support for only the SHA-224 and SHA-256 hash variants. Its accompanying
TypeScript declarations can be found in dist/sha256.d.ts.
- **dist/sha512.{js,mjs}** - The minified UMD and ESM versions of the library
with support for only the SHA-384 and SHA-512 hash variants. Its accompanying
TypeScript declarations can be found in dist/sha513.d.ts.
- **dist/sha3.{js,mjs}** - The minified UMD and ESM versions of the library with
support for only the SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128,
SHAKE256, cSHAKE128, cSHAKE256, KMAC128, and KMAC256 hash variants. Its
accompanying TypeScript declarations can be found in dist/sha3.d.ts.
## Contact Info
The project's website is located at https://caligatio.github.io/jsSHA/
[umd]: https://github.com/umdjs/umd

21
node_modules/jssha/SECURITY.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
# Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 3.1.x | :white_check_mark: |
| <3.1,>2 | :x: |
| 2.4.x | :white_check_mark: |
| <2.4,>1 | :x: |
| 1.6.x | :white_check_mark: |
| <1.6 | :x: |
## Reporting a Vulnerability
Please file a placeholder [issue] saying there is a security-related bug and
contact me via email (my email address is in my [profile]) with the sensitive
details.
[issue]: https://github.com/Caligatio/jsSHA/issues/new
[profile]: https://github.com/Caligatio

152
node_modules/jssha/dist/sha.d.ts generated vendored Normal file
View File

@@ -0,0 +1,152 @@
type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
type GenericInputType = {
value: string;
format: "TEXT";
encoding?: EncodingType;
} | {
value: string;
format: "B64" | "HEX" | "BYTES";
} | {
value: ArrayBuffer;
format: "ARRAYBUFFER";
} | {
value: Uint8Array;
format: "UINT8ARRAY";
};
type FixedLengthOptionsNoEncodingType = {
hmacKey?: GenericInputType;
} | {
numRounds?: number;
};
type FixedLengthOptionsEncodingType = {
hmacKey?: GenericInputType;
encoding?: EncodingType;
} | {
numRounds?: number;
encoding?: EncodingType;
};
interface SHAKEOptionsNoEncodingType {
numRounds?: number;
}
interface SHAKEOptionsEncodingType extends SHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
interface CSHAKEOptionsNoEncodingType {
customization?: GenericInputType;
funcName?: GenericInputType;
}
interface CSHAKEOptionsEncodingType extends CSHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
interface KMACOptionsNoEncodingType {
kmacKey: GenericInputType;
customization?: GenericInputType;
}
interface KMACOptionsEncodingType extends KMACOptionsNoEncodingType {
encoding?: EncodingType;
}
type FixedLengthVariantType = "SHA-1" | "SHA-224" | "SHA-256" | "SHA-384" | "SHA-512" | "SHA3-224" | "SHA3-256" | "SHA3-384" | "SHA3-512";
declare class jsSHA {
private readonly shaObj;
/**
* @param variant The desired SHA variant (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA3-224, SHA3-256, SHA3-256,
* SHA3-384, SHA3-512, SHAKE128, SHAKE256, CSHAKE128, CSHAKE256, KMAC128, or KMAC256) as a string.
* @param inputFormat The input format to be used in future `update` calls (TEXT, HEX, B64, BYTES, ARRAYBUFFER,
* or UINT8ARRAY) as a string.
* @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE"; numRounds?: number }.
* `encoding` is for only TEXT input (defaults to UTF8) and `numRounds` defaults to 1.
* `numRounds` is not valid for any of the MAC or CSHAKE variants.
* * If the variant supports HMAC, `options` may have an additional `hmacKey` key which must be in the form of
* {value: <INPUT>, format: <FORMAT>, encoding?: "UTF8" | "UTF16BE" | "UTF16LE"} where <FORMAT> takes the same
* values as `inputFormat` and <INPUT> can be a `string | ArrayBuffer | Uint8Array` depending on <FORMAT>.
* Supplying this key switches to HMAC calculation and replaces the now deprecated call to `setHMACKey`.
* * If the variant is CSHAKE128 or CSHAKE256, `options` may have two additional keys, `customization` and `funcName`,
* which are the NIST customization and function-name strings. Both must be in the same form as `hmacKey`.
* * If the variant is KMAC128 or KMAC256, `options` can include the `customization` key from CSHAKE variants and
* *must* have a `kmacKey` key that takes the same form as the `customization` key.
*/
constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: FixedLengthVariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType);
/**
* Takes `input` and hashes as many blocks as possible. Stores the rest for either a future `update` or `getHash` call.
*
* @param input The input to be hashed.
* @returns A reference to the object.
*/
update(input: string | ArrayBuffer | Uint8Array): this;
/**
* Returns the desired SHA or MAC (if a HMAC/KMAC key was specified) hash of the input fed in via `update` calls.
*
* @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { outputUpper?: boolean; b64Pad?: string; outputLen?: number; }.
* `outputLen` is required for variable length output variants (this option was previously called `shakeLen` which
* is now deprecated).
* `outputUpper` is only for HEX output (defaults to false) and b64pad is only for B64 output (defaults to "=").
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: {
outputUpper?: boolean;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "B64", options?: {
b64Pad?: string;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "BYTES", options?: {
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "UINT8ARRAY", options?: {
outputLen?: number;
shakeLen?: number;
}): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: {
outputLen?: number;
shakeLen?: number;
}): ArrayBuffer;
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
* Now deprecated in favor of setting the `hmacKey` at object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key (HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE }. `encoding` is only for TEXT
* and defaults to UTF8.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: {
encoding?: EncodingType;
}): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. Now deprecated
* in favor of just calling `getHash`.
*
* @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { outputUpper?: boolean; b64Pad?: string }. `outputUpper` is only for HEX
* output (defaults to false) and `b64pad` is only for B64 output (defaults to "=").
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: {
outputUpper?: boolean;
}): string;
getHMAC(format: "B64", options?: {
b64Pad?: string;
}): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
}
export { jsSHA as default };

22
node_modules/jssha/dist/sha.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/jssha/dist/sha.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

10
node_modules/jssha/dist/sha.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/jssha/dist/sha.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

163
node_modules/jssha/dist/sha1.d.ts generated vendored Normal file
View File

@@ -0,0 +1,163 @@
type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
type FormatType = "TEXT" | FormatNoTextType;
type GenericInputType = {
value: string;
format: "TEXT";
encoding?: EncodingType;
} | {
value: string;
format: "B64" | "HEX" | "BYTES";
} | {
value: ArrayBuffer;
format: "ARRAYBUFFER";
} | {
value: Uint8Array;
format: "UINT8ARRAY";
};
type FixedLengthOptionsNoEncodingType = {
hmacKey?: GenericInputType;
} | {
numRounds?: number;
};
type FixedLengthOptionsEncodingType = {
hmacKey?: GenericInputType;
encoding?: EncodingType;
} | {
numRounds?: number;
encoding?: EncodingType;
};
interface packedValue {
value: number[];
binLen: number;
}
declare abstract class jsSHABase<StateT, VariantT> {
/**
* @param variant The desired SHA variant.
* @param inputFormat The input format to be used in future `update` calls.
* @param options Hashmap of extra input options.
*/
protected readonly shaVariant: VariantT;
protected readonly inputFormat: FormatType;
protected readonly utfType: EncodingType;
protected readonly numRounds: number;
protected abstract intermediateState: StateT;
protected keyWithIPad: number[];
protected keyWithOPad: number[];
protected remainder: number[];
protected remainderLen: number;
protected updateCalled: boolean;
protected processedLen: number;
protected macKeySet: boolean;
protected abstract readonly variantBlockSize: number;
protected abstract readonly bigEndianMod: -1 | 1;
protected abstract readonly outputBinLen: number;
protected abstract readonly isVariableLen: boolean;
protected abstract readonly HMACSupported: boolean;
protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT;
protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[];
protected abstract readonly stateCloneFunc: (state: StateT) => StateT;
protected abstract readonly newStateFunc: (variant: VariantT) => StateT;
protected abstract readonly getMAC: ((options: {
outputLen: number;
}) => number[]) | null;
protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
/**
* Hashes as many blocks as possible. Stores the rest for either a future update or getHash call.
*
* @param srcString The input to be hashed.
* @returns A reference to the object.
*/
update(srcString: string | ArrayBuffer | Uint8Array): this;
/**
* Returns the desired SHA hash of the input fed in via `update` calls.
*
* @param format The desired output formatting
* @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes.
* `outputLen` replaces the now deprecated `shakeLen` key.
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: {
outputUpper?: boolean;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "B64", options?: {
b64Pad?: string;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "BYTES", options?: {
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "UINT8ARRAY", options?: {
outputLen?: number;
shakeLen?: number;
}): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: {
outputLen?: number;
shakeLen?: number;
}): ArrayBuffer;
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key.
* @param options Hashmap of extra input options.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: {
encoding?: EncodingType;
}): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
/**
* Internal function that sets the MAC key.
*
* @param key The packed MAC key to use
*/
protected _setHMACKey(key: packedValue): void;
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call.
*
* @param format The desired output formatting.
* @param options Hashmap of extra outputs options.
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: {
outputUpper?: boolean;
}): string;
getHMAC(format: "B64", options?: {
b64Pad?: string;
}): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
/**
* Internal function that returns the "raw" HMAC
*/
protected _getHMAC(): number[];
}
declare class jsSHA extends jsSHABase<number[], "SHA-1"> {
intermediateState: number[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: number[]) => number[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[];
stateCloneFunc: (state: number[]) => number[];
newStateFunc: (variant: "SHA-1") => number[];
getMAC: () => number[];
constructor(variant: "SHA-1", inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: "SHA-1", inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
}
export { jsSHA as default };

21
node_modules/jssha/dist/sha1.js generated vendored Normal file

File diff suppressed because one or more lines are too long

9
node_modules/jssha/dist/sha1.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

164
node_modules/jssha/dist/sha256.d.ts generated vendored Normal file
View File

@@ -0,0 +1,164 @@
type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
type FormatType = "TEXT" | FormatNoTextType;
type GenericInputType = {
value: string;
format: "TEXT";
encoding?: EncodingType;
} | {
value: string;
format: "B64" | "HEX" | "BYTES";
} | {
value: ArrayBuffer;
format: "ARRAYBUFFER";
} | {
value: Uint8Array;
format: "UINT8ARRAY";
};
type FixedLengthOptionsNoEncodingType = {
hmacKey?: GenericInputType;
} | {
numRounds?: number;
};
type FixedLengthOptionsEncodingType = {
hmacKey?: GenericInputType;
encoding?: EncodingType;
} | {
numRounds?: number;
encoding?: EncodingType;
};
interface packedValue {
value: number[];
binLen: number;
}
declare abstract class jsSHABase<StateT, VariantT> {
/**
* @param variant The desired SHA variant.
* @param inputFormat The input format to be used in future `update` calls.
* @param options Hashmap of extra input options.
*/
protected readonly shaVariant: VariantT;
protected readonly inputFormat: FormatType;
protected readonly utfType: EncodingType;
protected readonly numRounds: number;
protected abstract intermediateState: StateT;
protected keyWithIPad: number[];
protected keyWithOPad: number[];
protected remainder: number[];
protected remainderLen: number;
protected updateCalled: boolean;
protected processedLen: number;
protected macKeySet: boolean;
protected abstract readonly variantBlockSize: number;
protected abstract readonly bigEndianMod: -1 | 1;
protected abstract readonly outputBinLen: number;
protected abstract readonly isVariableLen: boolean;
protected abstract readonly HMACSupported: boolean;
protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT;
protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[];
protected abstract readonly stateCloneFunc: (state: StateT) => StateT;
protected abstract readonly newStateFunc: (variant: VariantT) => StateT;
protected abstract readonly getMAC: ((options: {
outputLen: number;
}) => number[]) | null;
protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
/**
* Hashes as many blocks as possible. Stores the rest for either a future update or getHash call.
*
* @param srcString The input to be hashed.
* @returns A reference to the object.
*/
update(srcString: string | ArrayBuffer | Uint8Array): this;
/**
* Returns the desired SHA hash of the input fed in via `update` calls.
*
* @param format The desired output formatting
* @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes.
* `outputLen` replaces the now deprecated `shakeLen` key.
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: {
outputUpper?: boolean;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "B64", options?: {
b64Pad?: string;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "BYTES", options?: {
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "UINT8ARRAY", options?: {
outputLen?: number;
shakeLen?: number;
}): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: {
outputLen?: number;
shakeLen?: number;
}): ArrayBuffer;
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key.
* @param options Hashmap of extra input options.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: {
encoding?: EncodingType;
}): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
/**
* Internal function that sets the MAC key.
*
* @param key The packed MAC key to use
*/
protected _setHMACKey(key: packedValue): void;
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call.
*
* @param format The desired output formatting.
* @param options Hashmap of extra outputs options.
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: {
outputUpper?: boolean;
}): string;
getHMAC(format: "B64", options?: {
b64Pad?: string;
}): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
/**
* Internal function that returns the "raw" HMAC
*/
protected _getHMAC(): number[];
}
type VariantType = "SHA-224" | "SHA-256";
declare class jsSHA extends jsSHABase<number[], VariantType> {
intermediateState: number[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: number[]) => number[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[];
stateCloneFunc: (state: number[]) => number[];
newStateFunc: (variant: VariantType) => number[];
getMAC: () => number[];
constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
}
export { jsSHA as default };

21
node_modules/jssha/dist/sha256.js generated vendored Normal file

File diff suppressed because one or more lines are too long

9
node_modules/jssha/dist/sha256.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

229
node_modules/jssha/dist/sha3.d.ts generated vendored Normal file
View File

@@ -0,0 +1,229 @@
type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
type FormatType = "TEXT" | FormatNoTextType;
type GenericInputType = {
value: string;
format: "TEXT";
encoding?: EncodingType;
} | {
value: string;
format: "B64" | "HEX" | "BYTES";
} | {
value: ArrayBuffer;
format: "ARRAYBUFFER";
} | {
value: Uint8Array;
format: "UINT8ARRAY";
};
type FixedLengthOptionsNoEncodingType = {
hmacKey?: GenericInputType;
} | {
numRounds?: number;
};
type FixedLengthOptionsEncodingType = {
hmacKey?: GenericInputType;
encoding?: EncodingType;
} | {
numRounds?: number;
encoding?: EncodingType;
};
interface packedValue {
value: number[];
binLen: number;
}
interface SHAKEOptionsNoEncodingType {
numRounds?: number;
}
interface SHAKEOptionsEncodingType extends SHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
interface CSHAKEOptionsNoEncodingType {
customization?: GenericInputType;
funcName?: GenericInputType;
}
interface CSHAKEOptionsEncodingType extends CSHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
interface KMACOptionsNoEncodingType {
kmacKey: GenericInputType;
customization?: GenericInputType;
}
interface KMACOptionsEncodingType extends KMACOptionsNoEncodingType {
encoding?: EncodingType;
}
declare abstract class jsSHABase<StateT, VariantT> {
/**
* @param variant The desired SHA variant.
* @param inputFormat The input format to be used in future `update` calls.
* @param options Hashmap of extra input options.
*/
protected readonly shaVariant: VariantT;
protected readonly inputFormat: FormatType;
protected readonly utfType: EncodingType;
protected readonly numRounds: number;
protected abstract intermediateState: StateT;
protected keyWithIPad: number[];
protected keyWithOPad: number[];
protected remainder: number[];
protected remainderLen: number;
protected updateCalled: boolean;
protected processedLen: number;
protected macKeySet: boolean;
protected abstract readonly variantBlockSize: number;
protected abstract readonly bigEndianMod: -1 | 1;
protected abstract readonly outputBinLen: number;
protected abstract readonly isVariableLen: boolean;
protected abstract readonly HMACSupported: boolean;
protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT;
protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[];
protected abstract readonly stateCloneFunc: (state: StateT) => StateT;
protected abstract readonly newStateFunc: (variant: VariantT) => StateT;
protected abstract readonly getMAC: ((options: {
outputLen: number;
}) => number[]) | null;
protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
/**
* Hashes as many blocks as possible. Stores the rest for either a future update or getHash call.
*
* @param srcString The input to be hashed.
* @returns A reference to the object.
*/
update(srcString: string | ArrayBuffer | Uint8Array): this;
/**
* Returns the desired SHA hash of the input fed in via `update` calls.
*
* @param format The desired output formatting
* @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes.
* `outputLen` replaces the now deprecated `shakeLen` key.
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: {
outputUpper?: boolean;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "B64", options?: {
b64Pad?: string;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "BYTES", options?: {
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "UINT8ARRAY", options?: {
outputLen?: number;
shakeLen?: number;
}): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: {
outputLen?: number;
shakeLen?: number;
}): ArrayBuffer;
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key.
* @param options Hashmap of extra input options.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: {
encoding?: EncodingType;
}): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
/**
* Internal function that sets the MAC key.
*
* @param key The packed MAC key to use
*/
protected _setHMACKey(key: packedValue): void;
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call.
*
* @param format The desired output formatting.
* @param options Hashmap of extra outputs options.
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: {
outputUpper?: boolean;
}): string;
getHMAC(format: "B64", options?: {
b64Pad?: string;
}): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
/**
* Internal function that returns the "raw" HMAC
*/
protected _getHMAC(): number[];
}
/**
* Int_64 is a object for 2 32-bit numbers emulating a 64-bit number.
*/
declare class Int_64 {
/**
* @param msint_32 The most significant 32-bits of a 64-bit number.
* @param lsint_32 The least significant 32-bits of a 64-bit number.
*/
readonly highOrder: number;
readonly lowOrder: number;
constructor(msint_32: number, lsint_32: number);
}
type FixedLengthVariantType = "SHA3-224" | "SHA3-256" | "SHA3-384" | "SHA3-512" | "SHAKE128" | "SHAKE256";
type VariantType = FixedLengthVariantType | "SHAKE128" | "SHAKE256" | "CSHAKE128" | "CSHAKE256" | "KMAC128" | "KMAC256";
declare class jsSHA extends jsSHABase<Int_64[][], VariantType> {
intermediateState: Int_64[][];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: Int_64[][]) => Int_64[][];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: Int_64[][], outputLen: number) => number[];
stateCloneFunc: (state: Int_64[][]) => Int_64[][];
newStateFunc: (variant: VariantType) => Int_64[][];
getMAC: ((options: {
outputLen: number;
}) => number[]) | null;
constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: FixedLengthVariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType);
/**
* Initialize CSHAKE variants.
*
* @param options Options containing CSHAKE params.
* @param funcNameOverride Overrides any "funcName" present in `options` (used with KMAC)
* @returns The delimiter to be used
*/
protected _initializeCSHAKE(options?: CSHAKEOptionsNoEncodingType, funcNameOverride?: packedValue): number;
/**
* Initialize KMAC variants.
*
* @param options Options containing KMAC params.
*/
protected _initializeKMAC(options: KMACOptionsNoEncodingType): void;
/**
* Returns the the KMAC in the specified format.
*
* @param options Hashmap of extra outputs options. `outputLen` must be specified.
* @returns The KMAC in the format specified.
*/
protected _getKMAC(options: {
outputLen: number;
}): number[];
}
export { jsSHA as default };

21
node_modules/jssha/dist/sha3.js generated vendored Normal file

File diff suppressed because one or more lines are too long

9
node_modules/jssha/dist/sha3.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

177
node_modules/jssha/dist/sha512.d.ts generated vendored Normal file
View File

@@ -0,0 +1,177 @@
type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
type FormatType = "TEXT" | FormatNoTextType;
type GenericInputType = {
value: string;
format: "TEXT";
encoding?: EncodingType;
} | {
value: string;
format: "B64" | "HEX" | "BYTES";
} | {
value: ArrayBuffer;
format: "ARRAYBUFFER";
} | {
value: Uint8Array;
format: "UINT8ARRAY";
};
type FixedLengthOptionsNoEncodingType = {
hmacKey?: GenericInputType;
} | {
numRounds?: number;
};
type FixedLengthOptionsEncodingType = {
hmacKey?: GenericInputType;
encoding?: EncodingType;
} | {
numRounds?: number;
encoding?: EncodingType;
};
interface packedValue {
value: number[];
binLen: number;
}
declare abstract class jsSHABase<StateT, VariantT> {
/**
* @param variant The desired SHA variant.
* @param inputFormat The input format to be used in future `update` calls.
* @param options Hashmap of extra input options.
*/
protected readonly shaVariant: VariantT;
protected readonly inputFormat: FormatType;
protected readonly utfType: EncodingType;
protected readonly numRounds: number;
protected abstract intermediateState: StateT;
protected keyWithIPad: number[];
protected keyWithOPad: number[];
protected remainder: number[];
protected remainderLen: number;
protected updateCalled: boolean;
protected processedLen: number;
protected macKeySet: boolean;
protected abstract readonly variantBlockSize: number;
protected abstract readonly bigEndianMod: -1 | 1;
protected abstract readonly outputBinLen: number;
protected abstract readonly isVariableLen: boolean;
protected abstract readonly HMACSupported: boolean;
protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT;
protected abstract readonly finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: StateT, outputLen: number) => number[];
protected abstract readonly stateCloneFunc: (state: StateT) => StateT;
protected abstract readonly newStateFunc: (variant: VariantT) => StateT;
protected abstract readonly getMAC: ((options: {
outputLen: number;
}) => number[]) | null;
protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
/**
* Hashes as many blocks as possible. Stores the rest for either a future update or getHash call.
*
* @param srcString The input to be hashed.
* @returns A reference to the object.
*/
update(srcString: string | ArrayBuffer | Uint8Array): this;
/**
* Returns the desired SHA hash of the input fed in via `update` calls.
*
* @param format The desired output formatting
* @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes.
* `outputLen` replaces the now deprecated `shakeLen` key.
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: {
outputUpper?: boolean;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "B64", options?: {
b64Pad?: string;
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "BYTES", options?: {
outputLen?: number;
shakeLen?: number;
}): string;
getHash(format: "UINT8ARRAY", options?: {
outputLen?: number;
shakeLen?: number;
}): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: {
outputLen?: number;
shakeLen?: number;
}): ArrayBuffer;
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key.
* @param options Hashmap of extra input options.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: {
encoding?: EncodingType;
}): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
/**
* Internal function that sets the MAC key.
*
* @param key The packed MAC key to use
*/
protected _setHMACKey(key: packedValue): void;
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call.
*
* @param format The desired output formatting.
* @param options Hashmap of extra outputs options.
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: {
outputUpper?: boolean;
}): string;
getHMAC(format: "B64", options?: {
b64Pad?: string;
}): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
/**
* Internal function that returns the "raw" HMAC
*/
protected _getHMAC(): number[];
}
/**
* Int_64 is a object for 2 32-bit numbers emulating a 64-bit number.
*/
declare class Int_64 {
/**
* @param msint_32 The most significant 32-bits of a 64-bit number.
* @param lsint_32 The least significant 32-bits of a 64-bit number.
*/
readonly highOrder: number;
readonly lowOrder: number;
constructor(msint_32: number, lsint_32: number);
}
type VariantType = "SHA-384" | "SHA-512";
declare class jsSHA extends jsSHABase<Int_64[], VariantType> {
intermediateState: Int_64[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: Int_64[]) => Int_64[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: Int_64[]) => number[];
stateCloneFunc: (state: Int_64[]) => Int_64[];
newStateFunc: (variant: VariantType) => Int_64[];
getMAC: () => number[];
constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
}
export { jsSHA as default };

21
node_modules/jssha/dist/sha512.js generated vendored Normal file

File diff suppressed because one or more lines are too long

9
node_modules/jssha/dist/sha512.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

183
node_modules/jssha/package.json generated vendored Normal file
View File

@@ -0,0 +1,183 @@
{
"name": "jssha",
"version": "3.3.1",
"description": "jsSHA implements the complete Secure Hash Standard (SHA) family (SHA-1, SHA-224/256/384/512, SHA3-224/256/384/512, SHAKE128/256, cSHAKE128/256, and KMAC128/256) with HMAC",
"main": "./dist/sha.js",
"exports": {
".": {
"types": "./dist/sha.d.ts",
"import": "./dist/sha.mjs",
"require": "./dist/sha.js"
},
"./sha1": {
"types": "./dist/sha1.d.ts",
"import": "./dist/sha1.mjs",
"require": "./dist/sha1.js"
},
"./dist/sha1": {
"types": "./dist/sha1.d.ts",
"import": "./dist/sha1.mjs",
"require": "./dist/sha1.js"
},
"./sha256": {
"types": "./dist/sha256.d.ts",
"import": "./dist/sha256.mjs",
"require": "./dist/sha256.js"
},
"./dist/sha256": {
"types": "./dist/sha256.d.ts",
"import": "./dist/sha256.mjs",
"require": "./dist/sha256.js"
},
"./sha512": {
"types": "./dist/sha512.d.ts",
"import": "./dist/sha512.mjs",
"require": "./dist/sha512.js"
},
"./dist/sha512": {
"types": "./dist/sha512.d.ts",
"import": "./dist/sha512.mjs",
"require": "./dist/sha512.js"
},
"./sha3": {
"types": "./dist/sha3.d.ts",
"import": "./dist/sha3.mjs",
"require": "./dist/sha3.js"
},
"./dist/sha3": {
"types": "./dist/sha3.d.ts",
"import": "./dist/sha3.mjs",
"require": "./dist/sha3.js"
},
"./package.json": "./package.json"
},
"module": "./dist/sha.mjs",
"types": "./dist/sha.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/Caligatio/jsSHA.git"
},
"keywords": [
"SHA-1",
"SHA-224",
"SHA3-224",
"SHA-256",
"SHA3-256",
"SHA-384",
"SHA3-384",
"SHA-512",
"SHA3-512",
"SHAKE-128",
"SHAKE-256",
"SHAKE128",
"SHAKE256",
"cSHAKE128",
"cSHAKE256",
"KMAC128",
"KMAC256",
"SHA1",
"SHA224",
"SHA256",
"SHA384",
"SHA512",
"SHA-2",
"SHA2",
"SHA-3",
"SHA3",
"SHAKE",
"cSHAKE",
"cSHAKE-128",
"cSHAKE-256",
"HMAC",
"KMAC",
"KMAC-128",
"KMAC-256",
"hash",
"cryptography"
],
"license": "BSD-3-Clause",
"author": "Brian Turek <brian.turek@gmail.com>",
"bugs": {
"url": "https://github.com/Caligatio/jsSHA/issues"
},
"engines": {
"node": "*"
},
"homepage": "https://github.com/Caligatio/jsSHA",
"devDependencies": {
"@rollup/plugin-terser": "^0.4.3",
"@rollup/plugin-typescript": "^11.1.2",
"@types/chai": "^4.3.5",
"@types/mocha": "^10.0.1",
"@types/rewire": "^2.5.28",
"@types/sinon": "^10.0.16",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"chai": "^4.3.7",
"coveralls": "^3.1.1",
"eslint": "^8.46.0",
"husky": "^8.0.3",
"karma": "^6.4.2",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.2.0",
"karma-firefox-launcher": "^2.1.2",
"karma-mocha": "^2.0.1",
"lint-staged": "^13.2.3",
"mocha": "^10.2.0",
"nyc": "^15.1.0",
"prettier": "^3.0.1",
"rewire": "^6.0.0",
"rollup": "^3.27.2",
"rollup-plugin-dts": "^5.3.1",
"sinon": "^15.2.0",
"ts-node": "^10.9.1",
"tslib": "^2.6.1",
"typescript": "^5.1.6"
},
"scripts": {
"build": "rollup -c",
"test": "nyc --reporter=html --reporter=text mocha test/src/*.ts",
"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",
"coverage": "nyc report --reporter=text-lcov | coveralls",
"prepare": "husky install"
},
"mocha": {
"require": [
"ts-node/register"
],
"timeout": 10000
},
"nyc": {
"require": [
"ts-node/register"
],
"exclude": [
"dist",
"*.js",
"coverage",
"test",
"rollup.config.mjs"
],
"reporter": [
"text",
"html"
],
"all": true
},
"prettier": {
"printWidth": 120,
"proseWrap": "always",
"overrides": [
{
"files": "*.md",
"options": {
"printWidth": 80
}
}
]
},
"lint-staged": {
"*.{js,ts}": "eslint --cache --fix",
"*.{js,ts,css,md,html,json}": "prettier --write"
}
}

218
node_modules/jssha/rollup.config.mjs generated vendored Normal file
View File

@@ -0,0 +1,218 @@
import fs from "fs";
import dts from "rollup-plugin-dts";
import typescript from "@rollup/plugin-typescript";
import terser from "@rollup/plugin-terser";
const licenseHeaderES3 = fs.readFileSync("src/license_header.es3.txt", { encoding: "utf8" }),
licenseHeaderES6 = fs.readFileSync("src/license_header.es6.txt", { encoding: "utf8" });
export default [
{
input: "src/sha.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES3,
format: "umd",
sourcemap: true,
dir: "dist",
entryFileNames: "[name].js",
},
plugins: [
typescript({ lib: ["es6"], declaration: true, declarationDir: "dist/types", target: "es3" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "src/sha.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES6,
format: "es",
sourcemap: true,
file: "dist/sha.mjs",
},
plugins: [
typescript({ lib: ["es6"], target: "es6" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "dist/types/src/sha.d.ts",
output: [{ file: "dist/sha.d.ts", format: "umd" }],
plugins: [dts()],
},
{
input: "src/sha1.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES3,
format: "umd",
file: "dist/sha1.js",
},
plugins: [
typescript({ lib: ["es6"], target: "es3" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "src/sha1.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES6,
format: "es",
file: "dist/sha1.mjs",
},
plugins: [
typescript({ lib: ["es6"], target: "es6" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "dist/types/src/sha1.d.ts",
output: [{ file: "dist/sha1.d.ts", format: "umd" }],
plugins: [dts()],
},
{
input: "src/sha256.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES3,
format: "umd",
file: "dist/sha256.js",
},
plugins: [
typescript({ lib: ["es6"], target: "es3" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "src/sha256.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES6,
format: "es",
file: "dist/sha256.mjs",
},
plugins: [
typescript({ lib: ["es6"], target: "es6" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "dist/types/src/sha256.d.ts",
output: [{ file: "dist/sha256.d.ts", format: "umd" }],
plugins: [dts()],
},
{
input: "src/sha512.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES3,
format: "umd",
file: "dist/sha512.js",
},
plugins: [
typescript({ lib: ["es6"], target: "es3" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "src/sha512.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES6,
format: "es",
file: "dist/sha512.mjs",
},
plugins: [
typescript({ lib: ["es6"], target: "es6" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "dist/types/src/sha512.d.ts",
output: [{ file: "dist/sha512.d.ts", format: "umd" }],
plugins: [dts()],
},
{
input: "src/sha3.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES3,
format: "umd",
file: "dist/sha3.js",
},
plugins: [
typescript({ lib: ["es6"], target: "es3" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "src/sha3.ts",
output: {
name: "jsSHA",
banner: licenseHeaderES6,
format: "es",
file: "dist/sha3.mjs",
},
plugins: [
typescript({ lib: ["es6"], target: "es6" }),
terser({
output: { comments: /BSD/ },
mangle: {
properties: { keep_quoted: true, reserved: ["jsSHA", "getHash", "setHMACKey", "getHMAC", "update"] },
},
}),
],
},
{
input: "dist/types/src/sha3.d.ts",
output: [{ file: "dist/sha3.d.ts", format: "umd" }],
plugins: [dts()],
},
];

429
node_modules/jssha/src/common.ts generated vendored Normal file
View File

@@ -0,0 +1,429 @@
import { getStrConverter, getOutputConverter } from "./converters";
import {
FormatType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
packedValue,
GenericInputType,
} from "./custom_types";
export const TWO_PWR_32 = 4294967296;
/* Constant used in SHA-2 families */
export const K_sha2 = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
/* Constant used in SHA-2 families */
export const H_trunc = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4];
/* Constant used in SHA-2 families */
export const H_full = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
export const sha_variant_error = "Chosen SHA variant is not supported";
export const mac_rounds_error = "Cannot set numRounds with MAC";
/**
* Concatenates 2 packed arrays. Clobbers array `a`.
*
* @param a First array to concatenate.
* @param b Second array to concatenate.
* @returns The concatentation of `a` + `b`.
*/
export function packedLEConcat(a: packedValue, b: packedValue): packedValue {
let i, arrOffset;
const aByteLen = a["binLen"] >>> 3,
bByteLen = b["binLen"] >>> 3,
leftShiftAmount = aByteLen << 3,
rightShiftAmount = (4 - aByteLen) << 3;
/* If a only contains "full" integers, we can just use concat which is so much easier */
if (aByteLen % 4 !== 0) {
for (i = 0; i < bByteLen; i += 4) {
arrOffset = (aByteLen + i) >>> 2;
/* Left shift chops off bits over 32-bits */
a["value"][arrOffset] |= b["value"][i >>> 2] << leftShiftAmount;
a["value"].push(0);
a["value"][arrOffset + 1] |= b["value"][i >>> 2] >>> rightShiftAmount;
}
/* Since an unconditional push was performed above, we may have pushed an extra value if it could have been
encoded without it. Check if popping an int off (reducing total length by 4 bytes) is still bigger than the
needed size. */
if ((a["value"].length << 2) - 4 >= bByteLen + aByteLen) {
a["value"].pop();
}
return { value: a["value"], binLen: a["binLen"] + b["binLen"] };
} else {
return { value: a["value"].concat(b["value"]), binLen: a["binLen"] + b["binLen"] };
}
}
/**
* Validate hash list containing output formatting options, ensuring presence of every option or adding the default
* value.
*
* @param options Hashmap of output formatting options from user.
* @returns Validated hashmap containing output formatting options.
*/
export function getOutputOpts(options?: {
outputUpper?: boolean;
b64Pad?: string;
shakeLen?: number;
outputLen?: number;
}): { outputUpper: boolean; b64Pad: string; outputLen: number } {
const retVal = { outputUpper: false, b64Pad: "=", outputLen: -1 },
outputOptions: { outputUpper?: boolean; b64Pad?: string; shakeLen?: number; outputLen?: number } = options || {},
lenErrstr = "Output length must be a multiple of 8";
retVal["outputUpper"] = outputOptions["outputUpper"] || false;
if (outputOptions["b64Pad"]) {
retVal["b64Pad"] = outputOptions["b64Pad"];
}
if (outputOptions["outputLen"]) {
if (outputOptions["outputLen"] % 8 !== 0) {
throw new Error(lenErrstr);
}
retVal["outputLen"] = outputOptions["outputLen"];
} else if (outputOptions["shakeLen"]) {
if (outputOptions["shakeLen"] % 8 !== 0) {
throw new Error(lenErrstr);
}
retVal["outputLen"] = outputOptions["shakeLen"];
}
if ("boolean" !== typeof retVal["outputUpper"]) {
throw new Error("Invalid outputUpper formatting option");
}
if ("string" !== typeof retVal["b64Pad"]) {
throw new Error("Invalid b64Pad formatting option");
}
return retVal;
}
/**
* Parses an external constructor object and returns a packed number, if possible.
*
* @param key The human-friendly key name to prefix any errors with
* @param value The input value object to parse
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param fallback Fallback value if `value` is undefined. If not present and `value` is undefined, an Error is thrown
*/
export function parseInputOption(
key: string,
value: GenericInputType | undefined,
bigEndianMod: -1 | 1,
fallback?: packedValue
): packedValue {
const errStr = key + " must include a value and format";
if (!value) {
if (!fallback) {
throw new Error(errStr);
}
return fallback;
}
if (typeof value["value"] === "undefined" || !value["format"]) {
throw new Error(errStr);
}
return getStrConverter(
value["format"],
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - the value of encoding gets value checked by getStrConverter
value["encoding"] || "UTF8",
bigEndianMod
)(value["value"]);
}
export abstract class jsSHABase<StateT, VariantT> {
/**
* @param variant The desired SHA variant.
* @param inputFormat The input format to be used in future `update` calls.
* @param options Hashmap of extra input options.
*/
/* Needed inputs */
protected readonly shaVariant: VariantT;
protected readonly inputFormat: FormatType;
protected readonly utfType: EncodingType;
protected readonly numRounds: number;
/* State */
protected abstract intermediateState: StateT;
protected keyWithIPad: number[];
protected keyWithOPad: number[];
protected remainder: number[];
protected remainderLen: number;
protected updateCalled: boolean;
protected processedLen: number;
protected macKeySet: boolean;
/* Variant specifics */
protected abstract readonly variantBlockSize: number;
protected abstract readonly bigEndianMod: -1 | 1;
protected abstract readonly outputBinLen: number;
protected abstract readonly isVariableLen: boolean;
protected abstract readonly HMACSupported: boolean;
/* Functions */
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
protected abstract readonly converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
protected abstract readonly roundFunc: (block: number[], H: StateT) => StateT;
protected abstract readonly finalizeFunc: (
remainder: number[],
remainderBinLen: number,
processedBinLen: number,
H: StateT,
outputLen: number
) => number[];
protected abstract readonly stateCloneFunc: (state: StateT) => StateT;
protected abstract readonly newStateFunc: (variant: VariantT) => StateT;
protected abstract readonly getMAC: ((options: { outputLen: number }) => number[]) | null;
protected constructor(variant: VariantT, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
protected constructor(variant: VariantT, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected constructor(variant: any, inputFormat: any, options?: any) {
const inputOptions = options || {};
this.inputFormat = inputFormat;
this.utfType = inputOptions["encoding"] || "UTF8";
this.numRounds = inputOptions["numRounds"] || 1;
/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
// @ts-ignore - The spec actually says ToString is called on the first parseInt argument so it's OK to use it here
// to check if an arugment is an integer. This cheat would break if it's used to get the value of the argument.
if (isNaN(this.numRounds) || this.numRounds !== parseInt(this.numRounds, 10) || 1 > this.numRounds) {
throw new Error("numRounds must a integer >= 1");
}
this.shaVariant = variant;
this.remainder = [];
this.remainderLen = 0;
this.updateCalled = false;
this.processedLen = 0;
this.macKeySet = false;
this.keyWithIPad = [];
this.keyWithOPad = [];
}
/**
* Hashes as many blocks as possible. Stores the rest for either a future update or getHash call.
*
* @param srcString The input to be hashed.
* @returns A reference to the object.
*/
update(srcString: string | ArrayBuffer | Uint8Array): this {
let i,
updateProcessedLen = 0;
const variantBlockIntInc = this.variantBlockSize >>> 5,
convertRet = this.converterFunc(srcString, this.remainder, this.remainderLen),
chunkBinLen = convertRet["binLen"],
chunk = convertRet["value"],
chunkIntLen = chunkBinLen >>> 5;
for (i = 0; i < chunkIntLen; i += variantBlockIntInc) {
if (updateProcessedLen + this.variantBlockSize <= chunkBinLen) {
this.intermediateState = this.roundFunc(chunk.slice(i, i + variantBlockIntInc), this.intermediateState);
updateProcessedLen += this.variantBlockSize;
}
}
this.processedLen += updateProcessedLen;
this.remainder = chunk.slice(updateProcessedLen >>> 5);
this.remainderLen = chunkBinLen % this.variantBlockSize;
this.updateCalled = true;
return this;
}
/**
* Returns the desired SHA hash of the input fed in via `update` calls.
*
* @param format The desired output formatting
* @param options Hashmap of output formatting options. `outputLen` must be specified for variable length hashes.
* `outputLen` replaces the now deprecated `shakeLen` key.
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: { outputUpper?: boolean; outputLen?: number; shakeLen?: number }): string;
getHash(format: "B64", options?: { b64Pad?: string; outputLen?: number; shakeLen?: number }): string;
getHash(format: "BYTES", options?: { outputLen?: number; shakeLen?: number }): string;
getHash(format: "UINT8ARRAY", options?: { outputLen?: number; shakeLen?: number }): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: { outputLen?: number; shakeLen?: number }): ArrayBuffer;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getHash(format: any, options?: any): any {
let i,
finalizedState,
outputBinLen = this.outputBinLen;
const outputOptions = getOutputOpts(options);
if (this.isVariableLen) {
if (outputOptions["outputLen"] === -1) {
throw new Error("Output length must be specified in options");
}
outputBinLen = outputOptions["outputLen"];
}
const formatFunc = getOutputConverter(format, outputBinLen, this.bigEndianMod, outputOptions);
if (this.macKeySet && this.getMAC) {
return formatFunc(this.getMAC(outputOptions));
}
finalizedState = this.finalizeFunc(
this.remainder.slice(),
this.remainderLen,
this.processedLen,
this.stateCloneFunc(this.intermediateState),
outputBinLen
);
for (i = 1; i < this.numRounds; i += 1) {
/* Need to mask out bits that should be zero due to output not being a multiple of 32 */
if (this.isVariableLen && outputBinLen % 32 !== 0) {
finalizedState[finalizedState.length - 1] &= 0x00ffffff >>> (24 - (outputBinLen % 32));
}
finalizedState = this.finalizeFunc(
finalizedState,
outputBinLen,
0,
this.newStateFunc(this.shaVariant),
outputBinLen
);
}
return formatFunc(finalizedState);
}
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key.
* @param options Hashmap of extra input options.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: { encoding?: EncodingType }): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setHMACKey(key: any, inputFormat: any, options?: any): void {
if (!this.HMACSupported) {
throw new Error("Variant does not support HMAC");
}
if (this.updateCalled) {
throw new Error("Cannot set MAC key after calling update");
}
const keyOptions = options || {},
keyConverterFunc = getStrConverter(inputFormat, keyOptions["encoding"] || "UTF8", this.bigEndianMod);
this._setHMACKey(keyConverterFunc(key));
}
/**
* Internal function that sets the MAC key.
*
* @param key The packed MAC key to use
*/
protected _setHMACKey(key: packedValue): void {
const blockByteSize = this.variantBlockSize >>> 3,
lastArrayIndex = blockByteSize / 4 - 1;
let i;
if (this.numRounds !== 1) {
throw new Error(mac_rounds_error);
}
if (this.macKeySet) {
throw new Error("MAC key already set");
}
/* Figure out what to do with the key based on its size relative to
* the hash's block size */
if (blockByteSize < key["binLen"] / 8) {
key["value"] = this.finalizeFunc(
key["value"],
key["binLen"],
0,
this.newStateFunc(this.shaVariant),
this.outputBinLen
);
}
while (key["value"].length <= lastArrayIndex) {
key["value"].push(0);
}
/* Create ipad and opad */
for (i = 0; i <= lastArrayIndex; i += 1) {
this.keyWithIPad[i] = key["value"][i] ^ 0x36363636;
this.keyWithOPad[i] = key["value"][i] ^ 0x5c5c5c5c;
}
this.intermediateState = this.roundFunc(this.keyWithIPad, this.intermediateState);
this.processedLen = this.variantBlockSize;
this.macKeySet = true;
}
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call.
*
* @param format The desired output formatting.
* @param options Hashmap of extra outputs options.
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: { outputUpper?: boolean }): string;
getHMAC(format: "B64", options?: { b64Pad?: string }): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getHMAC(format: any, options?: any): any {
const outputOptions = getOutputOpts(options),
formatFunc = getOutputConverter(format, this.outputBinLen, this.bigEndianMod, outputOptions);
return formatFunc(this._getHMAC());
}
/**
* Internal function that returns the "raw" HMAC
*/
protected _getHMAC(): number[] {
let finalizedState;
if (!this.macKeySet) {
throw new Error("Cannot call getHMAC without first setting MAC key");
}
const firstHash = this.finalizeFunc(
this.remainder.slice(),
this.remainderLen,
this.processedLen,
this.stateCloneFunc(this.intermediateState),
this.outputBinLen
);
finalizedState = this.roundFunc(this.keyWithOPad, this.newStateFunc(this.shaVariant));
finalizedState = this.finalizeFunc(
firstHash,
this.outputBinLen,
this.variantBlockSize,
finalizedState,
this.outputBinLen
);
return finalizedState;
}
}

615
node_modules/jssha/src/converters.ts generated vendored Normal file
View File

@@ -0,0 +1,615 @@
import { packedValue, EncodingType, FormatType } from "./custom_types";
/**
* Return type for all the *2packed functions
*/
const b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const arraybuffer_error = "ARRAYBUFFER not supported by this environment";
const uint8array_error = "UINT8ARRAY not supported by this environment";
/**
* Convert a string to an array of words.
*
* There is a known bug with an odd number of existing bytes and using a UTF-16 encoding. However, this function is
* used such that the existing bytes are always a result of a previous UTF-16 str2packed call and therefore there
* should never be an odd number of existing bytes.
* @param str Unicode string to be converted to binary representation.
* @param utfType The Unicode type to use to encode the source string.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked`.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function str2packed(
str: string,
utfType: EncodingType,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let codePnt,
codePntArr,
byteCnt = 0,
i,
j,
intOffset,
byteOffset,
shiftModifier,
transposeBytes;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3;
if ("UTF8" === utfType) {
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
codePntArr = [];
if (0x80 > codePnt) {
codePntArr.push(codePnt);
} else if (0x800 > codePnt) {
codePntArr.push(0xc0 | (codePnt >>> 6));
codePntArr.push(0x80 | (codePnt & 0x3f));
} else if (0xd800 > codePnt || 0xe000 <= codePnt) {
codePntArr.push(0xe0 | (codePnt >>> 12), 0x80 | ((codePnt >>> 6) & 0x3f), 0x80 | (codePnt & 0x3f));
} else {
i += 1;
codePnt = 0x10000 + (((codePnt & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
codePntArr.push(
0xf0 | (codePnt >>> 18),
0x80 | ((codePnt >>> 12) & 0x3f),
0x80 | ((codePnt >>> 6) & 0x3f),
0x80 | (codePnt & 0x3f)
);
}
for (j = 0; j < codePntArr.length; j += 1) {
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
/* Known bug kicks in here */
packed[intOffset] |= codePntArr[j] << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 1;
}
}
} else {
/* UTF16BE or UTF16LE */
shiftModifier = bigEndianMod === -1 ? 2 : 0;
/* Internally strings are UTF-16BE so transpose bytes under two conditions:
* need LE and not switching endianness due to SHA-3
* need BE and switching endianness due to SHA-3 */
transposeBytes = ("UTF16LE" === utfType && bigEndianMod !== 1) || ("UTF16LE" !== utfType && bigEndianMod === 1);
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
if (transposeBytes === true) {
j = codePnt & 0xff;
codePnt = (j << 8) | (codePnt >>> 8);
}
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= codePnt << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 2;
}
}
return { value: packed, binLen: byteCnt * 8 + existingPackedLen };
}
/**
* Convert a hex string to an array of words.
*
* @param str Hexadecimal string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function hex2packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let i, num, intOffset, byteOffset;
if (0 !== str.length % 2) {
throw new Error("String of HEX type must be in byte increments");
}
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 2) {
num = parseInt(str.substr(i, 2), 16);
if (!isNaN(num)) {
byteOffset = (i >>> 1) + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= num << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
} else {
throw new Error("String of HEX type contains invalid characters");
}
}
return { value: packed, binLen: str.length * 4 + existingPackedLen };
}
/**
* Convert a string of raw bytes to an array of words.
*
* @param str String of raw bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function bytes2packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let codePnt, i, intOffset, byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= codePnt << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return { value: packed, binLen: str.length * 8 + existingPackedLen };
}
/**
* Convert a base-64 string to an array of words.
*
* @param str Base64-encoded string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function b642packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let byteCnt = 0,
index,
i,
j,
tmpInt,
strPart,
intOffset,
byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0,
firstEqual = str.indexOf("=");
if (-1 === str.search(/^[a-zA-Z0-9=+/]+$/)) {
throw new Error("Invalid character in base-64 string");
}
str = str.replace(/=/g, "");
if (-1 !== firstEqual && firstEqual < str.length) {
throw new Error("Invalid '=' found in base-64 string");
}
for (i = 0; i < str.length; i += 4) {
strPart = str.substr(i, 4);
tmpInt = 0;
for (j = 0; j < strPart.length; j += 1) {
index = b64Tab.indexOf(strPart.charAt(j));
tmpInt |= index << (18 - 6 * j);
}
for (j = 0; j < strPart.length - 1; j += 1) {
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |=
((tmpInt >>> (16 - j * 8)) & 0xff) << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 1;
}
}
return { value: packed, binLen: byteCnt * 8 + existingPackedLen };
}
/**
* Convert an Uint8Array to an array of words.
*
* @param arr Uint8Array to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function uint8array2packed(
arr: Uint8Array,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let i, intOffset, byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < arr.length; i += 1) {
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= arr[i] << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return { value: packed, binLen: arr.length * 8 + existingPackedLen };
}
/**
* Convert an ArrayBuffer to an array of words
*
* @param arr ArrayBuffer to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function arraybuffer2packed(
arr: ArrayBuffer,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
return uint8array2packed(new Uint8Array(arr), existingPacked, existingPackedLen, bigEndianMod);
}
/**
* Function that takes an input format and UTF encoding and returns the appropriate function used to convert the input.
*
* @param format The format of the input to be converted
* @param utfType The string encoding to use for TEXT inputs.
* @param bigEndianMod Modifier for whether hash function is big or small endian
* @returns Function that will convert an input to a packed int array.
*/
export function getStrConverter(
format: FormatType,
utfType: EncodingType,
bigEndianMod: -1 | 1
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
): (input: any, existingBin?: number[], existingBinLen?: number) => packedValue {
/* Validate encoding */
switch (utfType) {
case "UTF8":
/* Fallthrough */
case "UTF16BE":
/* Fallthrough */
case "UTF16LE":
/* Fallthrough */
break;
default:
throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE");
}
/* Map inputFormat to the appropriate converter */
switch (format) {
case "HEX":
/**
* @param str String of hexadecimal bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return hex2packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "TEXT":
/**
* @param str Unicode string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return str2packed(str, utfType, existingBin, existingBinLen, bigEndianMod);
};
case "B64":
/**
* @param str Base64-encoded string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return b642packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "BYTES":
/**
* @param str String of raw bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return bytes2packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "ARRAYBUFFER":
try {
new ArrayBuffer(0);
} catch (ignore) {
throw new Error(arraybuffer_error);
}
/**
* @param arr ArrayBuffer to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (arr: ArrayBuffer, existingBin?: number[], existingBinLen?: number): packedValue {
return arraybuffer2packed(arr, existingBin, existingBinLen, bigEndianMod);
};
case "UINT8ARRAY":
try {
new Uint8Array(0);
} catch (ignore) {
throw new Error(uint8array_error);
}
/**
* @param arr Uint8Array to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (arr: Uint8Array, existingBin?: number[], existingBinLen?: number): packedValue {
return uint8array2packed(arr, existingBin, existingBinLen, bigEndianMod);
};
default:
throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
}
}
/**
* Convert an array of words to a hexadecimal string.
*
* toString() won't work here because it removes preceding zeros (e.g. 0x00000001.toString === "1" rather than
* "00000001" and 0.toString(16) === "0" rather than "00").
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param formatOpts Hashmap containing validated output formatting options.
* @returns Hexadecimal representation of `packed`.
*/
export function packed2hex(
packed: number[],
outputLength: number,
bigEndianMod: -1 | 1,
formatOpts: { outputUpper: boolean; b64Pad: string }
): string {
const hex_tab = "0123456789abcdef";
let str = "",
i,
srcByte;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
/* The below is more than a byte but it gets taken care of later */
srcByte = packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)));
str += hex_tab.charAt((srcByte >>> 4) & 0xf) + hex_tab.charAt(srcByte & 0xf);
}
return formatOpts["outputUpper"] ? str.toUpperCase() : str;
}
/**
* Convert an array of words to a base-64 string.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param formatOpts Hashmap containing validated output formatting options.
* @returns Base64-encoded representation of `packed`.
*/
export function packed2b64(
packed: number[],
outputLength: number,
bigEndianMod: -1 | 1,
formatOpts: { outputUpper: boolean; b64Pad: string }
): string {
let str = "",
i,
j,
triplet,
int1,
int2;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 3) {
int1 = i + 1 < length ? packed[(i + 1) >>> 2] : 0;
int2 = i + 2 < length ? packed[(i + 2) >>> 2] : 0;
triplet =
(((packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff) << 16) |
(((int1 >>> (8 * (shiftModifier + bigEndianMod * ((i + 1) % 4)))) & 0xff) << 8) |
((int2 >>> (8 * (shiftModifier + bigEndianMod * ((i + 2) % 4)))) & 0xff);
for (j = 0; j < 4; j += 1) {
if (i * 8 + j * 6 <= outputLength) {
str += b64Tab.charAt((triplet >>> (6 * (3 - j))) & 0x3f);
} else {
str += formatOpts["b64Pad"];
}
}
}
return str;
}
/**
* Convert an array of words to raw bytes string.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Raw bytes representation of `packed`.
*/
export function packed2bytes(packed: number[], outputLength: number, bigEndianMod: -1 | 1): string {
let str = "",
i,
srcByte;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
srcByte = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
str += String.fromCharCode(srcByte);
}
return str;
}
/**
* Convert an array of words to an ArrayBuffer.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns An ArrayBuffer containing bytes from `packed.
*/
export function packed2arraybuffer(packed: number[], outputLength: number, bigEndianMod: -1 | 1): ArrayBuffer {
let i;
const length = outputLength / 8,
retVal = new ArrayBuffer(length),
arrView = new Uint8Array(retVal),
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
arrView[i] = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
}
return retVal;
}
/**
* Convert an array of words to an Uint8Array.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns An Uint8Array containing bytes from `packed.
*/
export function packed2uint8array(packed: number[], outputLength: number, bigEndianMod: -1 | 1): Uint8Array {
let i;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0,
retVal = new Uint8Array(length);
for (i = 0; i < length; i += 1) {
retVal[i] = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
}
return retVal;
}
/**
* Function that takes an output format and associated parameters and returns a function that converts packed integers
* to that format.
*
* @param format The desired output formatting.
* @param outputBinLen Output length in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param outputOptions Hashmap of output formatting options
* @returns Function that will convert a packed integer array to desired format.
*/
export function getOutputConverter(
format: "HEX" | "B64" | "BYTES",
outputBinLen: number,
bigEndianMod: -1 | 1,
outputOptions: { outputUpper: boolean; b64Pad: string }
): (binarray: number[]) => string;
export function getOutputConverter(
format: "ARRAYBUFFER",
outputBinLen: number,
bigEndianMod: -1 | 1,
outputOptions: { outputUpper: boolean; b64Pad: string }
): (binarray: number[]) => ArrayBuffer;
export function getOutputConverter(
format: "UINT8ARRAY",
outputBinLen: number,
bigEndianMod: -1 | 1,
outputOptions: { outputUpper: boolean; b64Pad: string }
): (binarray: number[]) => Uint8Array;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
export function getOutputConverter(format: any, outputBinLen: any, bigEndianMod: any, outputOptions: any): any {
switch (format) {
case "HEX":
return function (binarray: number[]): string {
return packed2hex(binarray, outputBinLen, bigEndianMod, outputOptions);
};
case "B64":
return function (binarray: number[]): string {
return packed2b64(binarray, outputBinLen, bigEndianMod, outputOptions);
};
case "BYTES":
return function (binarray: number[]): string {
return packed2bytes(binarray, outputBinLen, bigEndianMod);
};
case "ARRAYBUFFER":
try {
/* Need to test ArrayBuffer support */
new ArrayBuffer(0);
} catch (ignore) {
throw new Error(arraybuffer_error);
}
return function (binarray: number[]): ArrayBuffer {
return packed2arraybuffer(binarray, outputBinLen, bigEndianMod);
};
case "UINT8ARRAY":
try {
/* Need to test Uint8Array support */
new Uint8Array(0);
} catch (ignore) {
throw new Error(uint8array_error);
}
return function (binarray: number[]): Uint8Array {
return packed2uint8array(binarray, outputBinLen, bigEndianMod);
};
default:
throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
}
}

81
node_modules/jssha/src/custom_types.ts generated vendored Normal file
View File

@@ -0,0 +1,81 @@
/* No actual code can go in this file without changing rollup.config.js and .gitignore */
export type EncodingType = "UTF8" | "UTF16BE" | "UTF16LE";
export type FormatNoTextType = "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY";
export type FormatType = "TEXT" | FormatNoTextType;
export type GenericInputType =
| {
value: string;
format: "TEXT";
encoding?: EncodingType;
}
| {
value: string;
format: "B64" | "HEX" | "BYTES";
}
| {
value: ArrayBuffer;
format: "ARRAYBUFFER";
}
| {
value: Uint8Array;
format: "UINT8ARRAY";
};
export type FixedLengthOptionsNoEncodingType =
| {
hmacKey?: GenericInputType;
}
| {
numRounds?: number;
};
export type FixedLengthOptionsEncodingType =
| {
hmacKey?: GenericInputType;
encoding?: EncodingType;
}
| {
numRounds?: number;
encoding?: EncodingType;
};
export interface packedValue {
value: number[];
binLen: number;
}
export interface SHAKEOptionsNoEncodingType {
numRounds?: number;
}
export interface SHAKEOptionsEncodingType extends SHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
export interface CSHAKEOptionsNoEncodingType {
customization?: GenericInputType;
funcName?: GenericInputType;
}
export interface CSHAKEOptionsEncodingType extends CSHAKEOptionsNoEncodingType {
encoding?: EncodingType;
}
export interface KMACOptionsNoEncodingType {
kmacKey: GenericInputType;
customization?: GenericInputType;
}
export interface KMACOptionsEncodingType extends KMACOptionsNoEncodingType {
encoding?: EncodingType;
}
export interface ResolvedCSHAKEOptionsNoEncodingType {
funcName: packedValue;
customization: packedValue;
}
export interface ResolvedKMACOptionsNoEncodingType extends ResolvedCSHAKEOptionsNoEncodingType {
kmacKey: packedValue;
}

20
node_modules/jssha/src/license_header.es3.txt generated vendored Normal file
View File

@@ -0,0 +1,20 @@
/**
* A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202,
* and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1.
*
* Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors
* Distributed under the BSD License
* See http://caligatio.github.com/jsSHA/ for more information
*
* Two ECMAScript polyfill functions carry the following license:
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
* MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/

8
node_modules/jssha/src/license_header.es6.txt generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/**
* A JavaScript implementation of the SHA family of hashes - defined in FIPS PUB 180-4, FIPS PUB 202,
* and SP 800-185 - as well as the corresponding HMAC implementation as defined in FIPS PUB 198-1.
*
* Copyright 2008-2023 Brian Turek, 1998-2009 Paul Johnston & Contributors
* Distributed under the BSD License
* See http://caligatio.github.com/jsSHA/ for more information
*/

170
node_modules/jssha/src/primitives_32.ts generated vendored Normal file
View File

@@ -0,0 +1,170 @@
/*
* Note 1: All the functions in this file guarantee only that the bottom 32-bits of the return value are correct.
* JavaScript is flakey when it comes to bit operations and a '1' in the highest order bit of a 32-bit number causes
* it to be interpreted as a negative number per two's complement.
*
* Note 2: Per the ECMAScript spec, all JavaScript operations mask the shift amount by 0x1F. This results in weird
* cases like 1 << 32 == 1 and 1 << 33 === 1 << 1 === 2
*/
/**
* The 32-bit implementation of circular rotate left.
*
* @param x The 32-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted left circularly by `n` bits
*/
export function rotl_32(x: number, n: number): number {
return (x << n) | (x >>> (32 - n));
}
/**
* The 32-bit implementation of circular rotate right.
*
* @param x The 32-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted right circularly by `n` bits
*/
function rotr_32(x: number, n: number): number {
return (x >>> n) | (x << (32 - n));
}
/**
* The 32-bit implementation of shift right.
*
* @param x The 32-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted by `n` bits.
*/
function shr_32(x: number, n: number): number {
return x >>> n;
}
/**
* The 32-bit implementation of the NIST specified Parity function.
*
* @param x The first 32-bit integer argument.
* @param y The second 32-bit integer argument.
* @param z The third 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function parity_32(x: number, y: number, z: number): number {
return x ^ y ^ z;
}
/**
* The 32-bit implementation of the NIST specified Ch function.
*
* @param x The first 32-bit integer argument.
* @param y The second 32-bit integer argument.
* @param z The third 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function ch_32(x: number, y: number, z: number): number {
return (x & y) ^ (~x & z);
}
/**
* The 32-bit implementation of the NIST specified Maj function.
*
* @param x The first 32-bit integer argument.
* @param y The second 32-bit integer argument.
* @param z The third 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function maj_32(x: number, y: number, z: number): number {
return (x & y) ^ (x & z) ^ (y & z);
}
/**
* The 32-bit implementation of the NIST specified Sigma0 function.
*
* @param x The 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function sigma0_32(x: number): number {
return rotr_32(x, 2) ^ rotr_32(x, 13) ^ rotr_32(x, 22);
}
/**
* Add two 32-bit integers.
*
* This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support.
*
* @param a The first 32-bit integer argument to be added.
* @param b The second 32-bit integer argument to be added.
* @returns The sum of `a` + `b`.
*/
export function safeAdd_32_2(a: number, b: number): number {
const lsw = (a & 0xffff) + (b & 0xffff),
msw = (a >>> 16) + (b >>> 16) + (lsw >>> 16);
return ((msw & 0xffff) << 16) | (lsw & 0xffff);
}
/**
* Add four 32-bit integers.
*
* This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support.
*
* @param a The first 32-bit integer argument to be added.
* @param b The second 32-bit integer argument to be added.
* @param c The third 32-bit integer argument to be added.
* @param d The fourth 32-bit integer argument to be added.
* @returns The sum of `a` + `b` + `c` + `d`.
*/
export function safeAdd_32_4(a: number, b: number, c: number, d: number): number {
const lsw = (a & 0xffff) + (b & 0xffff) + (c & 0xffff) + (d & 0xffff),
msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (lsw >>> 16);
return ((msw & 0xffff) << 16) | (lsw & 0xffff);
}
/**
* Add five 32-bit integers.
*
* This uses 16-bit operations internally to work around sign problems due to JavaScript's lack of uint32 support.
*
* @param a The first 32-bit integer argument to be added.
* @param b The second 32-bit integer argument to be added.
* @param c The third 32-bit integer argument to be added.
* @param d The fourth 32-bit integer argument to be added.
* @param e The fifth 32-bit integer argument to be added.
* @returns The sum of `a` + `b` + `c` + `d` + `e`.
*/
export function safeAdd_32_5(a: number, b: number, c: number, d: number, e: number): number {
const lsw = (a & 0xffff) + (b & 0xffff) + (c & 0xffff) + (d & 0xffff) + (e & 0xffff),
msw = (a >>> 16) + (b >>> 16) + (c >>> 16) + (d >>> 16) + (e >>> 16) + (lsw >>> 16);
return ((msw & 0xffff) << 16) | (lsw & 0xffff);
}
/**
* The 32-bit implementation of the NIST specified Gamma1 function.
*
* @param x The 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function gamma1_32(x: number): number {
return rotr_32(x, 17) ^ rotr_32(x, 19) ^ shr_32(x, 10);
}
/**
* The 32-bit implementation of the NIST specified Gamma0 function.
*
* @param x The 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function gamma0_32(x: number): number {
return rotr_32(x, 7) ^ rotr_32(x, 18) ^ shr_32(x, 3);
}
/**
* The 32-bit implementation of the NIST specified Sigma1 function.
*
* @param x The 32-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function sigma1_32(x: number): number {
return rotr_32(x, 6) ^ rotr_32(x, 11) ^ rotr_32(x, 25);
}

297
node_modules/jssha/src/primitives_64.ts generated vendored Normal file
View File

@@ -0,0 +1,297 @@
/*
* Note 1: All the functions in this file guarantee only that the bottom 32-bits of the returned Int_64 are correct.
* JavaScript is flakey when it comes to bit operations and a '1' in the highest order bit of a 32-bit number causes
* it to be interpreted as a negative number per two's complement.
*
* Note 2: Per the ECMAScript spec, all JavaScript operations mask the shift amount by 0x1F. This results in weird
* cases like 1 << 32 == 1 and 1 << 33 === 1 << 1 === 2
*/
/**
* Int_64 is a object for 2 32-bit numbers emulating a 64-bit number.
*/
export class Int_64 {
/**
* @param msint_32 The most significant 32-bits of a 64-bit number.
* @param lsint_32 The least significant 32-bits of a 64-bit number.
*/
readonly highOrder: number;
readonly lowOrder: number;
constructor(msint_32: number, lsint_32: number) {
this.highOrder = msint_32;
this.lowOrder = lsint_32;
}
}
/**
* The 64-bit implementation of circular rotate left.
*
* This does not work for n >= 64 or n == 32 but those are never done.
*
* @param x The 64-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted left circularly by `n` bits.
*/
export function rotl_64(x: Int_64, n: number): Int_64 {
let tmp;
if (n > 32) {
tmp = 64 - n;
return new Int_64((x.lowOrder << n) | (x.highOrder >>> tmp), (x.highOrder << n) | (x.lowOrder >>> tmp));
} else if (0 !== n) {
tmp = 32 - n;
return new Int_64((x.highOrder << n) | (x.lowOrder >>> tmp), (x.lowOrder << n) | (x.highOrder >>> tmp));
} else {
return x;
}
}
/**
* The 64-bit implementation of circular rotate right.
*
* This does not work for n >= 64, n == 32, or n == 0 but those are never done.
*
* @param x The 64-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted right circularly by `n` bits.
*/
function rotr_64(x: Int_64, n: number): Int_64 {
let tmp;
if (n < 32) {
tmp = 32 - n;
return new Int_64((x.highOrder >>> n) | (x.lowOrder << tmp), (x.lowOrder >>> n) | (x.highOrder << tmp));
} else {
tmp = 64 - n;
return new Int_64((x.lowOrder >>> n) | (x.highOrder << tmp), (x.highOrder >>> n) | (x.lowOrder << tmp));
}
}
/**
* The 64-bit implementation of shift right.
*
* This does not work for n >= 32 but is only called for n < 32.
*
* @param x The 64-bit integer argument.
* @param n The number of bits to shift.
* @returns `x` shifted right by `n` bits
*/
function shr_64(x: Int_64, n: number): Int_64 {
return new Int_64(x.highOrder >>> n, (x.lowOrder >>> n) | (x.highOrder << (32 - n)));
}
/**
* The 64-bit implementation of the NIST specified Ch function.
*
* @param x The first 64-bit integer argument.
* @param y The second 64-bit integer argument.
* @param z The third 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function ch_64(x: Int_64, y: Int_64, z: Int_64): Int_64 {
return new Int_64(
(x.highOrder & y.highOrder) ^ (~x.highOrder & z.highOrder),
(x.lowOrder & y.lowOrder) ^ (~x.lowOrder & z.lowOrder)
);
}
/**
* The 64-bit implementation of the NIST specified Maj function.
*
* @param x The first 64-bit integer argument.
* @param y The second 64-bit integer argument.
* @param z The third 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function maj_64(x: Int_64, y: Int_64, z: Int_64): Int_64 {
return new Int_64(
(x.highOrder & y.highOrder) ^ (x.highOrder & z.highOrder) ^ (y.highOrder & z.highOrder),
(x.lowOrder & y.lowOrder) ^ (x.lowOrder & z.lowOrder) ^ (y.lowOrder & z.lowOrder)
);
}
/**
* The 64-bit implementation of the NIST specified Sigma0 function.
*
* @param x The 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function sigma0_64(x: Int_64): Int_64 {
const rotr28 = rotr_64(x, 28),
rotr34 = rotr_64(x, 34),
rotr39 = rotr_64(x, 39);
return new Int_64(
rotr28.highOrder ^ rotr34.highOrder ^ rotr39.highOrder,
rotr28.lowOrder ^ rotr34.lowOrder ^ rotr39.lowOrder
);
}
/**
* Add two 64-bit integers.
*
* @param x The first 64-bit integer argument to be added.
* @param y The second 64-bit integer argument to be added.
* @returns The sum of `x` + `y`.
*/
export function safeAdd_64_2(x: Int_64, y: Int_64): Int_64 {
let lsw, msw;
lsw = (x.lowOrder & 0xffff) + (y.lowOrder & 0xffff);
msw = (x.lowOrder >>> 16) + (y.lowOrder >>> 16) + (lsw >>> 16);
const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
lsw = (x.highOrder & 0xffff) + (y.highOrder & 0xffff) + (msw >>> 16);
msw = (x.highOrder >>> 16) + (y.highOrder >>> 16) + (lsw >>> 16);
const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
return new Int_64(highOrder, lowOrder);
}
/**
* Add four 64-bit integers.
*
* @param a The first 64-bit integer argument to be added.
* @param b The second 64-bit integer argument to be added.
* @param c The third 64-bit integer argument to be added.
* @param d The fouth 64-bit integer argument to be added.
* @returns The sum of `a` + `b` + `c` + `d`.
*/
export function safeAdd_64_4(a: Int_64, b: Int_64, c: Int_64, d: Int_64): Int_64 {
let lsw, msw;
lsw = (a.lowOrder & 0xffff) + (b.lowOrder & 0xffff) + (c.lowOrder & 0xffff) + (d.lowOrder & 0xffff);
msw = (a.lowOrder >>> 16) + (b.lowOrder >>> 16) + (c.lowOrder >>> 16) + (d.lowOrder >>> 16) + (lsw >>> 16);
const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
lsw =
(a.highOrder & 0xffff) + (b.highOrder & 0xffff) + (c.highOrder & 0xffff) + (d.highOrder & 0xffff) + (msw >>> 16);
msw = (a.highOrder >>> 16) + (b.highOrder >>> 16) + (c.highOrder >>> 16) + (d.highOrder >>> 16) + (lsw >>> 16);
const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
return new Int_64(highOrder, lowOrder);
}
/**
* Add five 64-bit integers.
*
* @param a The first 64-bit integer argument to be added.
* @param b The second 64-bit integer argument to be added.
* @param c The third 64-bit integer argument to be added.
* @param d The fouth 64-bit integer argument to be added.
* @param e The fifth 64-bit integer argument to be added.
* @returns The sum of `a` + `b` + `c` + `d` + `e`.
*/
export function safeAdd_64_5(a: Int_64, b: Int_64, c: Int_64, d: Int_64, e: Int_64): Int_64 {
let lsw, msw;
lsw =
(a.lowOrder & 0xffff) +
(b.lowOrder & 0xffff) +
(c.lowOrder & 0xffff) +
(d.lowOrder & 0xffff) +
(e.lowOrder & 0xffff);
msw =
(a.lowOrder >>> 16) +
(b.lowOrder >>> 16) +
(c.lowOrder >>> 16) +
(d.lowOrder >>> 16) +
(e.lowOrder >>> 16) +
(lsw >>> 16);
const lowOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
lsw =
(a.highOrder & 0xffff) +
(b.highOrder & 0xffff) +
(c.highOrder & 0xffff) +
(d.highOrder & 0xffff) +
(e.highOrder & 0xffff) +
(msw >>> 16);
msw =
(a.highOrder >>> 16) +
(b.highOrder >>> 16) +
(c.highOrder >>> 16) +
(d.highOrder >>> 16) +
(e.highOrder >>> 16) +
(lsw >>> 16);
const highOrder = ((msw & 0xffff) << 16) | (lsw & 0xffff);
return new Int_64(highOrder, lowOrder);
}
/**
* XORs two given arguments.
*
* @param a The first argument to be XORed.
* @param b The second argument to be XORed.
* @returns The The XOR `a` and `b`
*/
export function xor_64_2(a: Int_64, b: Int_64): Int_64 {
return new Int_64(a.highOrder ^ b.highOrder, a.lowOrder ^ b.lowOrder);
}
/**
* XORs five given arguments.
*
* @param a The first argument to be XORed.
* @param b The second argument to be XORed.
* @param c The third argument to be XORed.
* @param d The fourth argument to be XORed.
* @param e The fifth argument to be XORed.
* @returns The XOR of `a`, `b`, `c`, `d`, and `e`.
*/
export function xor_64_5(a: Int_64, b: Int_64, c: Int_64, d: Int_64, e: Int_64): Int_64 {
return new Int_64(
a.highOrder ^ b.highOrder ^ c.highOrder ^ d.highOrder ^ e.highOrder,
a.lowOrder ^ b.lowOrder ^ c.lowOrder ^ d.lowOrder ^ e.lowOrder
);
}
/**
* The 64-bit implementation of the NIST specified Gamma1 function.
*
* @param x The 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function gamma1_64(x: Int_64): Int_64 {
const rotr19 = rotr_64(x, 19),
rotr61 = rotr_64(x, 61),
shr6 = shr_64(x, 6);
return new Int_64(
rotr19.highOrder ^ rotr61.highOrder ^ shr6.highOrder,
rotr19.lowOrder ^ rotr61.lowOrder ^ shr6.lowOrder
);
}
/**
* The 64-bit implementation of the NIST specified Gamma0 function.
*
* @param x The 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function gamma0_64(x: Int_64): Int_64 {
const rotr1 = rotr_64(x, 1),
rotr8 = rotr_64(x, 8),
shr7 = shr_64(x, 7);
return new Int_64(
rotr1.highOrder ^ rotr8.highOrder ^ shr7.highOrder,
rotr1.lowOrder ^ rotr8.lowOrder ^ shr7.lowOrder
);
}
/**
* The 64-bit implementation of the NIST specified Sigma1 function.
*
* @param x The 64-bit integer argument.
* @returns The NIST specified output of the function.
*/
export function sigma1_64(x: Int_64): Int_64 {
const rotr14 = rotr_64(x, 14),
rotr18 = rotr_64(x, 18),
rotr41 = rotr_64(x, 41);
return new Int_64(
rotr14.highOrder ^ rotr18.highOrder ^ rotr41.highOrder,
rotr14.lowOrder ^ rotr18.lowOrder ^ rotr41.lowOrder
);
}

155
node_modules/jssha/src/sha.ts generated vendored Normal file
View File

@@ -0,0 +1,155 @@
import { sha_variant_error } from "./common";
import {
CSHAKEOptionsEncodingType,
CSHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
KMACOptionsNoEncodingType,
KMACOptionsEncodingType,
} from "./custom_types";
import jsSHA1 from "./sha1";
import jsSHA256 from "./sha256";
import jsSHA512 from "./sha512";
import jsSHA3 from "./sha3";
type FixedLengthVariantType =
| "SHA-1"
| "SHA-224"
| "SHA-256"
| "SHA-384"
| "SHA-512"
| "SHA3-224"
| "SHA3-256"
| "SHA3-384"
| "SHA3-512";
export default class jsSHA {
private readonly shaObj: jsSHA1 | jsSHA256 | jsSHA512 | jsSHA3;
/**
* @param variant The desired SHA variant (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA3-224, SHA3-256, SHA3-256,
* SHA3-384, SHA3-512, SHAKE128, SHAKE256, CSHAKE128, CSHAKE256, KMAC128, or KMAC256) as a string.
* @param inputFormat The input format to be used in future `update` calls (TEXT, HEX, B64, BYTES, ARRAYBUFFER,
* or UINT8ARRAY) as a string.
* @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE"; numRounds?: number }.
* `encoding` is for only TEXT input (defaults to UTF8) and `numRounds` defaults to 1.
* `numRounds` is not valid for any of the MAC or CSHAKE variants.
* * If the variant supports HMAC, `options` may have an additional `hmacKey` key which must be in the form of
* {value: <INPUT>, format: <FORMAT>, encoding?: "UTF8" | "UTF16BE" | "UTF16LE"} where <FORMAT> takes the same
* values as `inputFormat` and <INPUT> can be a `string | ArrayBuffer | Uint8Array` depending on <FORMAT>.
* Supplying this key switches to HMAC calculation and replaces the now deprecated call to `setHMACKey`.
* * If the variant is CSHAKE128 or CSHAKE256, `options` may have two additional keys, `customization` and `funcName`,
* which are the NIST customization and function-name strings. Both must be in the same form as `hmacKey`.
* * If the variant is KMAC128 or KMAC256, `options` can include the `customization` key from CSHAKE variants and
* *must* have a `kmacKey` key that takes the same form as the `customization` key.
*/
constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(
variant: FixedLengthVariantType,
inputFormat: FormatNoTextType,
options?: FixedLengthOptionsNoEncodingType
);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
if ("SHA-1" == variant) {
this.shaObj = new jsSHA1(variant, inputFormat, options);
} else if ("SHA-224" == variant || "SHA-256" == variant) {
this.shaObj = new jsSHA256(variant, inputFormat, options);
} else if ("SHA-384" == variant || "SHA-512" == variant) {
this.shaObj = new jsSHA512(variant, inputFormat, options);
} else if (
"SHA3-224" == variant ||
"SHA3-256" == variant ||
"SHA3-384" == variant ||
"SHA3-512" == variant ||
"SHAKE128" == variant ||
"SHAKE256" == variant ||
"CSHAKE128" == variant ||
"CSHAKE256" == variant ||
"KMAC128" == variant ||
"KMAC256" == variant
) {
this.shaObj = new jsSHA3(variant, inputFormat, options);
} else {
throw new Error(sha_variant_error);
}
}
/**
* Takes `input` and hashes as many blocks as possible. Stores the rest for either a future `update` or `getHash` call.
*
* @param input The input to be hashed.
* @returns A reference to the object.
*/
update(input: string | ArrayBuffer | Uint8Array): this {
this.shaObj.update(input);
return this;
}
/**
* Returns the desired SHA or MAC (if a HMAC/KMAC key was specified) hash of the input fed in via `update` calls.
*
* @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { outputUpper?: boolean; b64Pad?: string; outputLen?: number; }.
* `outputLen` is required for variable length output variants (this option was previously called `shakeLen` which
* is now deprecated).
* `outputUpper` is only for HEX output (defaults to false) and b64pad is only for B64 output (defaults to "=").
* @returns The hash in the format specified.
*/
getHash(format: "HEX", options?: { outputUpper?: boolean; outputLen?: number; shakeLen?: number }): string;
getHash(format: "B64", options?: { b64Pad?: string; outputLen?: number; shakeLen?: number }): string;
getHash(format: "BYTES", options?: { outputLen?: number; shakeLen?: number }): string;
getHash(format: "UINT8ARRAY", options?: { outputLen?: number; shakeLen?: number }): Uint8Array;
getHash(format: "ARRAYBUFFER", options?: { outputLen?: number; shakeLen?: number }): ArrayBuffer;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getHash(format: any, options?: any): any {
return this.shaObj.getHash(format, options);
}
/**
* Sets the HMAC key for an eventual `getHMAC` call. Must be called immediately after jsSHA object instantiation.
* Now deprecated in favor of setting the `hmacKey` at object instantiation.
*
* @param key The key used to calculate the HMAC
* @param inputFormat The format of key (HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE }. `encoding` is only for TEXT
* and defaults to UTF8.
*/
setHMACKey(key: string, inputFormat: "TEXT", options?: { encoding?: EncodingType }): void;
setHMACKey(key: string, inputFormat: "B64" | "HEX" | "BYTES"): void;
setHMACKey(key: ArrayBuffer, inputFormat: "ARRAYBUFFER"): void;
setHMACKey(key: Uint8Array, inputFormat: "UINT8ARRAY"): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setHMACKey(key: any, inputFormat: any, options?: any): void {
this.shaObj.setHMACKey(key, inputFormat, options);
}
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. Now deprecated
* in favor of just calling `getHash`.
*
* @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form of { outputUpper?: boolean; b64Pad?: string }. `outputUpper` is only for HEX
* output (defaults to false) and `b64pad` is only for B64 output (defaults to "=").
* @returns The HMAC in the format specified.
*/
getHMAC(format: "HEX", options?: { outputUpper?: boolean }): string;
getHMAC(format: "B64", options?: { b64Pad?: string }): string;
getHMAC(format: "BYTES"): string;
getHMAC(format: "UINT8ARRAY"): Uint8Array;
getHMAC(format: "ARRAYBUFFER"): ArrayBuffer;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getHMAC(format: any, options?: any): any {
return this.shaObj.getHMAC(format, options);
}
}

161
node_modules/jssha/src/sha1.ts generated vendored Normal file
View File

@@ -0,0 +1,161 @@
import { jsSHABase, TWO_PWR_32, sha_variant_error, parseInputOption } from "./common";
import {
packedValue,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
} from "./custom_types";
import { getStrConverter } from "./converters";
import { ch_32, parity_32, maj_32, rotl_32, safeAdd_32_2, safeAdd_32_5 } from "./primitives_32";
/**
* Gets the state values for the specified SHA variant.
*
* @param _variant: Unused
* @returns The initial state values.
*/
function getNewState(_variant: "SHA-1"): number[] {
return [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
}
/**
* Performs a round of SHA-1 hashing over a 512-byte block. This clobbers `H`.
*
* @param block The binary array representation of the block to hash.
* @param H The intermediate H values from a previous round.
* @returns The resulting H values.
*/
function roundSHA1(block: number[], H: number[]): number[] {
let a, b, c, d, e, T, t;
const W: number[] = [];
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
for (t = 0; t < 80; t += 1) {
if (t < 16) {
W[t] = block[t];
} else {
W[t] = rotl_32(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
}
if (t < 20) {
T = safeAdd_32_5(rotl_32(a, 5), ch_32(b, c, d), e, 0x5a827999, W[t]);
} else if (t < 40) {
T = safeAdd_32_5(rotl_32(a, 5), parity_32(b, c, d), e, 0x6ed9eba1, W[t]);
} else if (t < 60) {
T = safeAdd_32_5(rotl_32(a, 5), maj_32(b, c, d), e, 0x8f1bbcdc, W[t]);
} else {
T = safeAdd_32_5(rotl_32(a, 5), parity_32(b, c, d), e, 0xca62c1d6, W[t]);
}
e = d;
d = c;
c = rotl_32(b, 30);
b = a;
a = T;
}
H[0] = safeAdd_32_2(a, H[0]);
H[1] = safeAdd_32_2(b, H[1]);
H[2] = safeAdd_32_2(c, H[2]);
H[3] = safeAdd_32_2(d, H[3]);
H[4] = safeAdd_32_2(e, H[4]);
return H;
}
/**
* Finalizes the SHA-1 hash. This clobbers `remainder` and `H`.
*
* @param remainder Any leftover unprocessed packed ints that still need to be processed.
* @param remainderBinLen The number of bits in `remainder`.
* @param processedBinLen The number of bits already processed.
* @param H The intermediate H values from a previous round.
* @returns The array of integers representing the SHA-1 hash of message.
*/
function finalizeSHA1(remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]): number[] {
let i;
/* The 65 addition is a hack but it works. The correct number is
actually 72 (64 + 8) but the below math fails if
remainderBinLen + 72 % 512 = 0. Since remainderBinLen % 8 = 0,
"shorting" the addition is OK. */
const offset = (((remainderBinLen + 65) >>> 9) << 4) + 15,
totalLen = remainderBinLen + processedBinLen;
while (remainder.length <= offset) {
remainder.push(0);
}
/* Append '1' at the end of the binary string */
remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32));
/* Append length of binary string in the position such that the new
* length is a multiple of 512. Logic does not work for even multiples
* of 512 but there can never be even multiples of 512. JavaScript
* numbers are limited to 2^53 so it's "safe" to treat the totalLen as
* a 64-bit integer. */
remainder[offset] = totalLen & 0xffffffff;
/* Bitwise operators treat the operand as a 32-bit number so need to
* use hacky division and round to get access to upper 32-ish bits */
remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0;
/* This will always be at least 1 full chunk */
for (i = 0; i < remainder.length; i += 16) {
H = roundSHA1(remainder.slice(i, i + 16), H);
}
return H;
}
export default class jsSHA extends jsSHABase<number[], "SHA-1"> {
intermediateState: number[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: number[]) => number[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[];
stateCloneFunc: (state: number[]) => number[];
newStateFunc: (variant: "SHA-1") => number[];
getMAC: () => number[];
constructor(variant: "SHA-1", inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: "SHA-1", inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
if ("SHA-1" !== variant) {
throw new Error(sha_variant_error);
}
super(variant, inputFormat, options);
const resolvedOptions = options || {};
this.HMACSupported = true;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
this.bigEndianMod = -1;
this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod);
this.roundFunc = roundSHA1;
this.stateCloneFunc = function (state: number[]): number[] {
return state.slice();
};
this.newStateFunc = getNewState;
this.finalizeFunc = finalizeSHA1;
this.intermediateState = getNewState(variant);
this.variantBlockSize = 512;
this.outputBinLen = 160;
this.isVariableLen = false;
if (resolvedOptions["hmacKey"]) {
this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod));
}
}
}

197
node_modules/jssha/src/sha256.ts generated vendored Normal file
View File

@@ -0,0 +1,197 @@
import { jsSHABase, TWO_PWR_32, H_full, H_trunc, K_sha2, sha_variant_error, parseInputOption } from "./common";
import {
packedValue,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
} from "./custom_types";
import { getStrConverter } from "./converters";
import {
ch_32,
gamma0_32,
gamma1_32,
maj_32,
safeAdd_32_2,
safeAdd_32_4,
safeAdd_32_5,
sigma0_32,
sigma1_32,
} from "./primitives_32";
type VariantType = "SHA-224" | "SHA-256";
/**
* Gets the state values for the specified SHA variant.
*
* @param variant: The SHA-256 family variant.
* @returns The initial state values.
*/
function getNewState256(variant: VariantType): number[] {
let retVal;
if ("SHA-224" == variant) {
retVal = H_trunc.slice();
} else {
/* "SHA-256" */
retVal = H_full.slice();
}
return retVal;
}
/**
* Performs a round of SHA-256 hashing over a block. This clobbers `H`.
*
* @param block The binary array representation of the block to hash.
* @param H The intermediate H values from a previous round.
* @returns The resulting H values.
*/
function roundSHA256(block: number[], H: number[]): number[] {
let a, b, c, d, e, f, g, h, T1, T2, t;
const W: number[] = [];
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
f = H[5];
g = H[6];
h = H[7];
for (t = 0; t < 64; t += 1) {
if (t < 16) {
W[t] = block[t];
} else {
W[t] = safeAdd_32_4(gamma1_32(W[t - 2]), W[t - 7], gamma0_32(W[t - 15]), W[t - 16]);
}
T1 = safeAdd_32_5(h, sigma1_32(e), ch_32(e, f, g), K_sha2[t], W[t]);
T2 = safeAdd_32_2(sigma0_32(a), maj_32(a, b, c));
h = g;
g = f;
f = e;
e = safeAdd_32_2(d, T1);
d = c;
c = b;
b = a;
a = safeAdd_32_2(T1, T2);
}
H[0] = safeAdd_32_2(a, H[0]);
H[1] = safeAdd_32_2(b, H[1]);
H[2] = safeAdd_32_2(c, H[2]);
H[3] = safeAdd_32_2(d, H[3]);
H[4] = safeAdd_32_2(e, H[4]);
H[5] = safeAdd_32_2(f, H[5]);
H[6] = safeAdd_32_2(g, H[6]);
H[7] = safeAdd_32_2(h, H[7]);
return H;
}
/**
* Finalizes the SHA-256 hash. This clobbers `remainder` and `H`.
*
* @param remainder Any leftover unprocessed packed ints that still need to be processed.
* @param remainderBinLen The number of bits in `remainder`.
* @param processedBinLen The number of bits already processed.
* @param H The intermediate H values from a previous round.
* @param variant The desired SHA-256 variant.
* @returns The array of integers representing the SHA-2 hash of message.
*/
function finalizeSHA256(
remainder: number[],
remainderBinLen: number,
processedBinLen: number,
H: number[],
variant: VariantType
): number[] {
let i, retVal;
/* The 65 addition is a hack but it works. The correct number is
actually 72 (64 + 8) but the below math fails if
remainderBinLen + 72 % 512 = 0. Since remainderBinLen % 8 = 0,
"shorting" the addition is OK. */
const offset = (((remainderBinLen + 65) >>> 9) << 4) + 15,
binaryStringInc = 16,
totalLen = remainderBinLen + processedBinLen;
while (remainder.length <= offset) {
remainder.push(0);
}
/* Append '1' at the end of the binary string */
remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32));
/* Append length of binary string in the position such that the new
* length is correct. JavaScript numbers are limited to 2^53 so it's
* "safe" to treat the totalLen as a 64-bit integer. */
remainder[offset] = totalLen & 0xffffffff;
/* Bitwise operators treat the operand as a 32-bit number so need to
* use hacky division and round to get access to upper 32-ish bits */
remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0;
/* This will always be at least 1 full chunk */
for (i = 0; i < remainder.length; i += binaryStringInc) {
H = roundSHA256(remainder.slice(i, i + binaryStringInc), H);
}
if ("SHA-224" === variant) {
retVal = [H[0], H[1], H[2], H[3], H[4], H[5], H[6]];
} else {
/* "SHA-256 */
retVal = H;
}
return retVal;
}
export default class jsSHA extends jsSHABase<number[], VariantType> {
intermediateState: number[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: number[]) => number[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: number[]) => number[];
stateCloneFunc: (state: number[]) => number[];
newStateFunc: (variant: VariantType) => number[];
getMAC: () => number[];
constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
if (!("SHA-224" === variant || "SHA-256" === variant)) {
throw new Error(sha_variant_error);
}
super(variant, inputFormat, options);
const resolvedOptions = options || {};
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
this.HMACSupported = true;
this.bigEndianMod = -1;
this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod);
this.roundFunc = roundSHA256;
this.stateCloneFunc = function (state): number[] {
return state.slice();
};
this.newStateFunc = getNewState256;
this.finalizeFunc = function (remainder, remainderBinLen, processedBinLen, H): number[] {
return finalizeSHA256(remainder, remainderBinLen, processedBinLen, H, variant);
};
this.intermediateState = getNewState256(variant);
this.variantBlockSize = 512;
this.outputBinLen = "SHA-224" === variant ? 224 : 256;
this.isVariableLen = false;
if (resolvedOptions["hmacKey"]) {
this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod));
}
}
}

592
node_modules/jssha/src/sha3.ts generated vendored Normal file
View File

@@ -0,0 +1,592 @@
import { jsSHABase, packedLEConcat, sha_variant_error, mac_rounds_error, TWO_PWR_32, parseInputOption } from "./common";
import {
packedValue,
CSHAKEOptionsNoEncodingType,
CSHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
KMACOptionsNoEncodingType,
KMACOptionsEncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
ResolvedCSHAKEOptionsNoEncodingType,
ResolvedKMACOptionsNoEncodingType,
} from "./custom_types";
import { getStrConverter } from "./converters";
import { Int_64, rotl_64, xor_64_2, xor_64_5 } from "./primitives_64";
type FixedLengthVariantType = "SHA3-224" | "SHA3-256" | "SHA3-384" | "SHA3-512" | "SHAKE128" | "SHAKE256";
type VariantType = FixedLengthVariantType | "SHAKE128" | "SHAKE256" | "CSHAKE128" | "CSHAKE256" | "KMAC128" | "KMAC256";
const rc_sha3 = [
new Int_64(0x00000000, 0x00000001),
new Int_64(0x00000000, 0x00008082),
new Int_64(0x80000000, 0x0000808a),
new Int_64(0x80000000, 0x80008000),
new Int_64(0x00000000, 0x0000808b),
new Int_64(0x00000000, 0x80000001),
new Int_64(0x80000000, 0x80008081),
new Int_64(0x80000000, 0x00008009),
new Int_64(0x00000000, 0x0000008a),
new Int_64(0x00000000, 0x00000088),
new Int_64(0x00000000, 0x80008009),
new Int_64(0x00000000, 0x8000000a),
new Int_64(0x00000000, 0x8000808b),
new Int_64(0x80000000, 0x0000008b),
new Int_64(0x80000000, 0x00008089),
new Int_64(0x80000000, 0x00008003),
new Int_64(0x80000000, 0x00008002),
new Int_64(0x80000000, 0x00000080),
new Int_64(0x00000000, 0x0000800a),
new Int_64(0x80000000, 0x8000000a),
new Int_64(0x80000000, 0x80008081),
new Int_64(0x80000000, 0x00008080),
new Int_64(0x00000000, 0x80000001),
new Int_64(0x80000000, 0x80008008),
];
const r_sha3 = [
[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],
];
/**
* Gets the state values for the specified SHA-3 variant.
*
* @param _variant Unused for this family.
* @returns The initial state values.
*/
function getNewState(_variant: VariantType): Int_64[][] {
let i;
const retVal = [];
for (i = 0; i < 5; i += 1) {
retVal[i] = [new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0), new Int_64(0, 0)];
}
return retVal;
}
/**
* Returns a clone of the given SHA3 state.
*
* @param state The state to be cloned.
* @returns The cloned state.
*/
function cloneSHA3State(state: Int_64[][]): Int_64[][] {
let i;
const clone = [];
for (i = 0; i < 5; i += 1) {
clone[i] = state[i].slice();
}
return clone;
}
/**
* Performs a round of SHA-3 hashing over a block. This clobbers `state`.
*
* @param block The binary array representation of the block to hash.
* @param state Hash state from a previous round.
* @returns The resulting state value.
*/
function roundSHA3(block: number[] | null, state: Int_64[][]): Int_64[][] {
let round, x, y, B;
const C = [],
D = [];
if (null !== block) {
for (x = 0; x < block.length; x += 2) {
state[(x >>> 1) % 5][((x >>> 1) / 5) | 0] = xor_64_2(
state[(x >>> 1) % 5][((x >>> 1) / 5) | 0],
new Int_64(block[x + 1], block[x])
);
}
}
for (round = 0; round < 24; round += 1) {
/* Any SHA-3 variant name will do here */
B = getNewState("SHA3-384");
/* Perform theta step */
for (x = 0; x < 5; x += 1) {
C[x] = xor_64_5(state[x][0], state[x][1], state[x][2], state[x][3], state[x][4]);
}
for (x = 0; x < 5; x += 1) {
D[x] = xor_64_2(C[(x + 4) % 5], rotl_64(C[(x + 1) % 5], 1));
}
for (x = 0; x < 5; x += 1) {
for (y = 0; y < 5; y += 1) {
state[x][y] = xor_64_2(state[x][y], D[x]);
}
}
/* Perform combined ro and pi steps */
for (x = 0; x < 5; x += 1) {
for (y = 0; y < 5; y += 1) {
B[y][(2 * x + 3 * y) % 5] = rotl_64(state[x][y], r_sha3[x][y]);
}
}
/* Perform chi step */
for (x = 0; x < 5; x += 1) {
for (y = 0; y < 5; y += 1) {
state[x][y] = xor_64_2(
B[x][y],
new Int_64(
~B[(x + 1) % 5][y].highOrder & B[(x + 2) % 5][y].highOrder,
~B[(x + 1) % 5][y].lowOrder & B[(x + 2) % 5][y].lowOrder
)
);
}
}
/* Perform iota step */
state[0][0] = xor_64_2(state[0][0], rc_sha3[round]);
}
return state;
}
/**
* Finalizes the SHA-3 hash. This clobbers `remainder` and `state`.
*
* @param remainder Any leftover unprocessed packed ints that still need to be processed.
* @param remainderBinLen The number of bits in `remainder`.
* @param _processedBinLen Unused for this family.
* @param state The state from a previous round.
* @param blockSize The block size/rate of the variant in bits
* @param delimiter The delimiter value for the variant
* @param outputLen The output length for the variant in bits
* @returns The array of integers representing the SHA-3 hash of message.
*/
function finalizeSHA3(
remainder: number[],
remainderBinLen: number,
_processedBinLen: number,
state: Int_64[][],
blockSize: number,
delimiter: number,
outputLen: number
): number[] {
let i,
state_offset = 0,
temp;
const retVal = [],
binaryStringInc = blockSize >>> 5,
remainderIntLen = remainderBinLen >>> 5;
/* Process as many blocks as possible, some may be here for multiple rounds
with SHAKE
*/
for (i = 0; i < remainderIntLen && remainderBinLen >= blockSize; i += binaryStringInc) {
state = roundSHA3(remainder.slice(i, i + binaryStringInc), state);
remainderBinLen -= blockSize;
}
remainder = remainder.slice(i);
remainderBinLen = remainderBinLen % blockSize;
/* Pad out the remainder to a full block */
while (remainder.length < binaryStringInc) {
remainder.push(0);
}
/* Find the next "empty" byte for the 0x80 and append it via an xor */
i = remainderBinLen >>> 3;
remainder[i >> 2] ^= delimiter << (8 * (i % 4));
remainder[binaryStringInc - 1] ^= 0x80000000;
state = roundSHA3(remainder, state);
while (retVal.length * 32 < outputLen) {
temp = state[state_offset % 5][(state_offset / 5) | 0];
retVal.push(temp.lowOrder);
if (retVal.length * 32 >= outputLen) {
break;
}
retVal.push(temp.highOrder);
state_offset += 1;
if (0 === (state_offset * 64) % blockSize) {
roundSHA3(null, state);
state_offset = 0;
}
}
return retVal;
}
/**
* Performs NIST left_encode function returned with no extra garbage bits. `x` is limited to <= 9007199254740991.
*
* @param x 32-bit number to to encode.
* @returns The NIST specified output of the function.
*/
function left_encode(x: number): packedValue {
let byteOffset,
byte,
numEncodedBytes = 0;
/* JavaScript numbers max out at 0x1FFFFFFFFFFFFF (7 bytes) so this will return a maximum of 7 + 1 = 8 bytes */
const retVal = [0, 0],
x_64 = [x & 0xffffffff, (x / TWO_PWR_32) & 0x1fffff];
for (byteOffset = 6; byteOffset >= 0; byteOffset--) {
/* This will surprisingly work for large shifts because JavaScript masks the shift amount by 0x1F */
byte = (x_64[byteOffset >> 2] >>> (8 * byteOffset)) & 0xff;
/* Starting from the most significant byte of a 64-bit number, start recording the first non-0 byte and then
every byte thereafter */
if (byte !== 0 || numEncodedBytes !== 0) {
retVal[(numEncodedBytes + 1) >> 2] |= byte << ((numEncodedBytes + 1) * 8);
numEncodedBytes += 1;
}
}
numEncodedBytes = numEncodedBytes !== 0 ? numEncodedBytes : 1;
retVal[0] |= numEncodedBytes;
return { value: numEncodedBytes + 1 > 4 ? retVal : [retVal[0]], binLen: 8 + numEncodedBytes * 8 };
}
/**
* Performs NIST right_encode function returned with no extra garbage bits. `x` is limited to <= 9007199254740991.
*
* @param x 32-bit number to to encode.
* @returns The NIST specified output of the function.
*/
function right_encode(x: number): packedValue {
let byteOffset,
byte,
numEncodedBytes = 0;
/* JavaScript numbers max out at 0x1FFFFFFFFFFFFF (7 bytes) so this will return a maximum of 7 + 1 = 8 bytes */
const retVal = [0, 0],
x_64 = [x & 0xffffffff, (x / TWO_PWR_32) & 0x1fffff];
for (byteOffset = 6; byteOffset >= 0; byteOffset--) {
/* This will surprisingly work for large shifts because JavaScript masks the shift amount by 0x1F */
byte = (x_64[byteOffset >> 2] >>> (8 * byteOffset)) & 0xff;
/* Starting from the most significant byte of a 64-bit number, start recording the first non-0 byte and then
every byte thereafter */
if (byte !== 0 || numEncodedBytes !== 0) {
retVal[numEncodedBytes >> 2] |= byte << (numEncodedBytes * 8);
numEncodedBytes += 1;
}
}
numEncodedBytes = numEncodedBytes !== 0 ? numEncodedBytes : 1;
retVal[numEncodedBytes >> 2] |= numEncodedBytes << (numEncodedBytes * 8);
return { value: numEncodedBytes + 1 > 4 ? retVal : [retVal[0]], binLen: 8 + numEncodedBytes * 8 };
}
/**
* Performs NIST encode_string function.
*
* @param input Packed array of integers.
* @returns NIST encode_string output.
*/
function encode_string(input: packedValue): packedValue {
return packedLEConcat(left_encode(input["binLen"]), input);
}
/**
* Performs NIST byte_pad function.
*
* @param packed Packed array of integers.
* @param outputByteLen Desired length of the output in bytes, assumed to be a multiple of 4.
* @returns NIST byte_pad output.
*/
function byte_pad(packed: packedValue, outputByteLen: number): number[] {
let encodedLen = left_encode(outputByteLen),
i;
encodedLen = packedLEConcat(encodedLen, packed);
const outputIntLen = outputByteLen >>> 2,
intsToAppend = (outputIntLen - (encodedLen["value"].length % outputIntLen)) % outputIntLen;
for (i = 0; i < intsToAppend; i++) {
encodedLen["value"].push(0);
}
return encodedLen["value"];
}
/**
* Parses/validate constructor options for a CSHAKE variant
*
* @param options Option given to constructor
*/
function resolveCSHAKEOptions(options: CSHAKEOptionsNoEncodingType): ResolvedCSHAKEOptionsNoEncodingType {
const resolvedOptions = options || {};
return {
funcName: parseInputOption("funcName", resolvedOptions["funcName"], 1, { value: [], binLen: 0 }),
customization: parseInputOption("Customization", resolvedOptions["customization"], 1, { value: [], binLen: 0 }),
};
}
/**
* Parses/validate constructor options for a KMAC variant
*
* @param options Option given to constructor
*/
function resolveKMACOptions(options: KMACOptionsNoEncodingType): ResolvedKMACOptionsNoEncodingType {
const resolvedOptions = options || {};
return {
kmacKey: parseInputOption("kmacKey", resolvedOptions["kmacKey"], 1),
/* This is little-endian packed "KMAC" */
funcName: { value: [0x43414d4b], binLen: 32 },
customization: parseInputOption("Customization", resolvedOptions["customization"], 1, { value: [], binLen: 0 }),
};
}
export default class jsSHA extends jsSHABase<Int_64[][], VariantType> {
intermediateState: Int_64[][];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: Int_64[][]) => Int_64[][];
finalizeFunc: (
remainder: number[],
remainderBinLen: number,
processedBinLen: number,
H: Int_64[][],
outputLen: number
) => number[];
stateCloneFunc: (state: Int_64[][]) => Int_64[][];
newStateFunc: (variant: VariantType) => Int_64[][];
getMAC: ((options: { outputLen: number }) => number[]) | null;
constructor(variant: FixedLengthVariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(
variant: FixedLengthVariantType,
inputFormat: FormatNoTextType,
options?: FixedLengthOptionsNoEncodingType
);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: "TEXT", options?: SHAKEOptionsEncodingType);
constructor(variant: "SHAKE128" | "SHAKE256", inputFormat: FormatNoTextType, options?: SHAKEOptionsNoEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: FormatNoTextType, options?: CSHAKEOptionsNoEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
let delimiter = 0x06,
variantBlockSize = 0;
super(variant, inputFormat, options);
const resolvedOptions = options || {};
/* In other variants, this was done after variable initialization but need to do it earlier here becaue we want to
avoid KMAC initialization */
if (this.numRounds !== 1) {
if (resolvedOptions["kmacKey"] || resolvedOptions["hmacKey"]) {
throw new Error(mac_rounds_error);
} else if (this.shaVariant === "CSHAKE128" || this.shaVariant === "CSHAKE256") {
throw new Error("Cannot set numRounds for CSHAKE variants");
}
}
this.bigEndianMod = 1;
this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod);
this.roundFunc = roundSHA3;
this.stateCloneFunc = cloneSHA3State;
this.newStateFunc = getNewState;
this.intermediateState = getNewState(variant);
this.isVariableLen = false;
switch (variant) {
case "SHA3-224":
this.variantBlockSize = variantBlockSize = 1152;
this.outputBinLen = 224;
this.HMACSupported = true;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
break;
case "SHA3-256":
this.variantBlockSize = variantBlockSize = 1088;
this.outputBinLen = 256;
this.HMACSupported = true;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
break;
case "SHA3-384":
this.variantBlockSize = variantBlockSize = 832;
this.outputBinLen = 384;
this.HMACSupported = true;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
break;
case "SHA3-512":
this.variantBlockSize = variantBlockSize = 576;
this.outputBinLen = 512;
this.HMACSupported = true;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
break;
case "SHAKE128":
delimiter = 0x1f;
this.variantBlockSize = variantBlockSize = 1344;
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
this.getMAC = null;
break;
case "SHAKE256":
delimiter = 0x1f;
this.variantBlockSize = variantBlockSize = 1088;
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
this.getMAC = null;
break;
case "KMAC128":
delimiter = 0x4;
this.variantBlockSize = variantBlockSize = 1344;
this._initializeKMAC(options);
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getKMAC;
break;
case "KMAC256":
delimiter = 0x4;
this.variantBlockSize = variantBlockSize = 1088;
this._initializeKMAC(options);
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getKMAC;
break;
case "CSHAKE128":
this.variantBlockSize = variantBlockSize = 1344;
delimiter = this._initializeCSHAKE(options);
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
this.getMAC = null;
break;
case "CSHAKE256":
this.variantBlockSize = variantBlockSize = 1088;
delimiter = this._initializeCSHAKE(options);
/* This will be set in getHash */
this.outputBinLen = -1;
this.isVariableLen = true;
this.HMACSupported = false;
this.getMAC = null;
break;
default:
throw new Error(sha_variant_error);
}
/* This needs to be down here as CSHAKE can change its delimiter */
this.finalizeFunc = function (remainder, remainderBinLen, processedBinLen, state, outputBinLen): number[] {
return finalizeSHA3(
remainder,
remainderBinLen,
processedBinLen,
state,
variantBlockSize,
delimiter,
outputBinLen
);
};
if (resolvedOptions["hmacKey"]) {
this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod));
}
}
/**
* Initialize CSHAKE variants.
*
* @param options Options containing CSHAKE params.
* @param funcNameOverride Overrides any "funcName" present in `options` (used with KMAC)
* @returns The delimiter to be used
*/
protected _initializeCSHAKE(options?: CSHAKEOptionsNoEncodingType, funcNameOverride?: packedValue): number {
const resolvedOptions = resolveCSHAKEOptions(options || {});
if (funcNameOverride) {
resolvedOptions["funcName"] = funcNameOverride;
}
const packedParams = packedLEConcat(
encode_string(resolvedOptions["funcName"]),
encode_string(resolvedOptions["customization"])
);
/* CSHAKE is defined to be a call to SHAKE iff both the customization and function-name string are both empty. This
can be accomplished by processing nothing in this step. */
if (resolvedOptions["customization"]["binLen"] !== 0 || resolvedOptions["funcName"]["binLen"] !== 0) {
const byte_pad_out = byte_pad(packedParams, this.variantBlockSize >>> 3);
for (let i = 0; i < byte_pad_out.length; i += this.variantBlockSize >>> 5) {
this.intermediateState = this.roundFunc(
byte_pad_out.slice(i, i + (this.variantBlockSize >>> 5)),
this.intermediateState
);
this.processedLen += this.variantBlockSize;
}
return 0x04;
} else {
return 0x1f;
}
}
/**
* Initialize KMAC variants.
*
* @param options Options containing KMAC params.
*/
protected _initializeKMAC(options: KMACOptionsNoEncodingType): void {
const resolvedOptions = resolveKMACOptions(options || {});
this._initializeCSHAKE(options, resolvedOptions["funcName"]);
const byte_pad_out = byte_pad(encode_string(resolvedOptions["kmacKey"]), this.variantBlockSize >>> 3);
for (let i = 0; i < byte_pad_out.length; i += this.variantBlockSize >>> 5) {
this.intermediateState = this.roundFunc(
byte_pad_out.slice(i, i + (this.variantBlockSize >>> 5)),
this.intermediateState
);
this.processedLen += this.variantBlockSize;
}
this.macKeySet = true;
}
/**
* Returns the the KMAC in the specified format.
*
* @param options Hashmap of extra outputs options. `outputLen` must be specified.
* @returns The KMAC in the format specified.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected _getKMAC(options: { outputLen: number }): number[] {
const concatedRemainder = packedLEConcat(
{ value: this.remainder.slice(), binLen: this.remainderLen },
right_encode(options["outputLen"])
);
return this.finalizeFunc(
concatedRemainder["value"],
concatedRemainder["binLen"],
this.processedLen,
this.stateCloneFunc(this.intermediateState),
options["outputLen"]
);
}
}

327
node_modules/jssha/src/sha512.ts generated vendored Normal file
View File

@@ -0,0 +1,327 @@
import { jsSHABase, TWO_PWR_32, H_trunc, H_full, K_sha2, sha_variant_error, parseInputOption } from "./common";
import {
packedValue,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
} from "./custom_types";
import { getStrConverter } from "./converters";
import {
ch_64,
gamma0_64,
gamma1_64,
Int_64,
maj_64,
safeAdd_64_2,
safeAdd_64_4,
safeAdd_64_5,
sigma0_64,
sigma1_64,
} from "./primitives_64";
type VariantType = "SHA-384" | "SHA-512";
const K_sha512 = [
new Int_64(K_sha2[0], 0xd728ae22),
new Int_64(K_sha2[1], 0x23ef65cd),
new Int_64(K_sha2[2], 0xec4d3b2f),
new Int_64(K_sha2[3], 0x8189dbbc),
new Int_64(K_sha2[4], 0xf348b538),
new Int_64(K_sha2[5], 0xb605d019),
new Int_64(K_sha2[6], 0xaf194f9b),
new Int_64(K_sha2[7], 0xda6d8118),
new Int_64(K_sha2[8], 0xa3030242),
new Int_64(K_sha2[9], 0x45706fbe),
new Int_64(K_sha2[10], 0x4ee4b28c),
new Int_64(K_sha2[11], 0xd5ffb4e2),
new Int_64(K_sha2[12], 0xf27b896f),
new Int_64(K_sha2[13], 0x3b1696b1),
new Int_64(K_sha2[14], 0x25c71235),
new Int_64(K_sha2[15], 0xcf692694),
new Int_64(K_sha2[16], 0x9ef14ad2),
new Int_64(K_sha2[17], 0x384f25e3),
new Int_64(K_sha2[18], 0x8b8cd5b5),
new Int_64(K_sha2[19], 0x77ac9c65),
new Int_64(K_sha2[20], 0x592b0275),
new Int_64(K_sha2[21], 0x6ea6e483),
new Int_64(K_sha2[22], 0xbd41fbd4),
new Int_64(K_sha2[23], 0x831153b5),
new Int_64(K_sha2[24], 0xee66dfab),
new Int_64(K_sha2[25], 0x2db43210),
new Int_64(K_sha2[26], 0x98fb213f),
new Int_64(K_sha2[27], 0xbeef0ee4),
new Int_64(K_sha2[28], 0x3da88fc2),
new Int_64(K_sha2[29], 0x930aa725),
new Int_64(K_sha2[30], 0xe003826f),
new Int_64(K_sha2[31], 0x0a0e6e70),
new Int_64(K_sha2[32], 0x46d22ffc),
new Int_64(K_sha2[33], 0x5c26c926),
new Int_64(K_sha2[34], 0x5ac42aed),
new Int_64(K_sha2[35], 0x9d95b3df),
new Int_64(K_sha2[36], 0x8baf63de),
new Int_64(K_sha2[37], 0x3c77b2a8),
new Int_64(K_sha2[38], 0x47edaee6),
new Int_64(K_sha2[39], 0x1482353b),
new Int_64(K_sha2[40], 0x4cf10364),
new Int_64(K_sha2[41], 0xbc423001),
new Int_64(K_sha2[42], 0xd0f89791),
new Int_64(K_sha2[43], 0x0654be30),
new Int_64(K_sha2[44], 0xd6ef5218),
new Int_64(K_sha2[45], 0x5565a910),
new Int_64(K_sha2[46], 0x5771202a),
new Int_64(K_sha2[47], 0x32bbd1b8),
new Int_64(K_sha2[48], 0xb8d2d0c8),
new Int_64(K_sha2[49], 0x5141ab53),
new Int_64(K_sha2[50], 0xdf8eeb99),
new Int_64(K_sha2[51], 0xe19b48a8),
new Int_64(K_sha2[52], 0xc5c95a63),
new Int_64(K_sha2[53], 0xe3418acb),
new Int_64(K_sha2[54], 0x7763e373),
new Int_64(K_sha2[55], 0xd6b2b8a3),
new Int_64(K_sha2[56], 0x5defb2fc),
new Int_64(K_sha2[57], 0x43172f60),
new Int_64(K_sha2[58], 0xa1f0ab72),
new Int_64(K_sha2[59], 0x1a6439ec),
new Int_64(K_sha2[60], 0x23631e28),
new Int_64(K_sha2[61], 0xde82bde9),
new Int_64(K_sha2[62], 0xb2c67915),
new Int_64(K_sha2[63], 0xe372532b),
new Int_64(0xca273ece, 0xea26619c),
new Int_64(0xd186b8c7, 0x21c0c207),
new Int_64(0xeada7dd6, 0xcde0eb1e),
new Int_64(0xf57d4f7f, 0xee6ed178),
new Int_64(0x06f067aa, 0x72176fba),
new Int_64(0x0a637dc5, 0xa2c898a6),
new Int_64(0x113f9804, 0xbef90dae),
new Int_64(0x1b710b35, 0x131c471b),
new Int_64(0x28db77f5, 0x23047d84),
new Int_64(0x32caab7b, 0x40c72493),
new Int_64(0x3c9ebe0a, 0x15c9bebc),
new Int_64(0x431d67c4, 0x9c100d4c),
new Int_64(0x4cc5d4be, 0xcb3e42b6),
new Int_64(0x597f299c, 0xfc657e2a),
new Int_64(0x5fcb6fab, 0x3ad6faec),
new Int_64(0x6c44198c, 0x4a475817),
];
/**
* Gets the state values for the specified SHA variant.
*
* @param variant: The SHA-512 family variant.
* @returns The initial state values.
*/
function getNewState512(variant: VariantType): Int_64[] {
if ("SHA-384" === variant) {
return [
new Int_64(0xcbbb9d5d, H_trunc[0]),
new Int_64(0x0629a292a, H_trunc[1]),
new Int_64(0x9159015a, H_trunc[2]),
new Int_64(0x0152fecd8, H_trunc[3]),
new Int_64(0x67332667, H_trunc[4]),
new Int_64(0x98eb44a87, H_trunc[5]),
new Int_64(0xdb0c2e0d, H_trunc[6]),
new Int_64(0x047b5481d, H_trunc[7]),
];
} else {
/* SHA-512 */
return [
new Int_64(H_full[0], 0xf3bcc908),
new Int_64(H_full[1], 0x84caa73b),
new Int_64(H_full[2], 0xfe94f82b),
new Int_64(H_full[3], 0x5f1d36f1),
new Int_64(H_full[4], 0xade682d1),
new Int_64(H_full[5], 0x2b3e6c1f),
new Int_64(H_full[6], 0xfb41bd6b),
new Int_64(H_full[7], 0x137e2179),
];
}
}
/**
* Performs a round of SHA-512 hashing over a block. This clobbers `H`.
*
* @param block The binary array representation of the block to hash.
* @param H The intermediate H values from a previous round.
* @returns The resulting H values.
*/
function roundSHA512(block: number[], H: Int_64[]): Int_64[] {
let a, b, c, d, e, f, g, h, T1, T2, t, offset;
const W: Int_64[] = [];
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
f = H[5];
g = H[6];
h = H[7];
for (t = 0; t < 80; t += 1) {
if (t < 16) {
offset = t * 2;
W[t] = new Int_64(block[offset], block[offset + 1]);
} else {
W[t] = safeAdd_64_4(gamma1_64(W[t - 2]), W[t - 7], gamma0_64(W[t - 15]), W[t - 16]);
}
T1 = safeAdd_64_5(h, sigma1_64(e), ch_64(e, f, g), K_sha512[t], W[t]);
T2 = safeAdd_64_2(sigma0_64(a), maj_64(a, b, c));
h = g;
g = f;
f = e;
e = safeAdd_64_2(d, T1);
d = c;
c = b;
b = a;
a = safeAdd_64_2(T1, T2);
}
H[0] = safeAdd_64_2(a, H[0]);
H[1] = safeAdd_64_2(b, H[1]);
H[2] = safeAdd_64_2(c, H[2]);
H[3] = safeAdd_64_2(d, H[3]);
H[4] = safeAdd_64_2(e, H[4]);
H[5] = safeAdd_64_2(f, H[5]);
H[6] = safeAdd_64_2(g, H[6]);
H[7] = safeAdd_64_2(h, H[7]);
return H;
}
/**
* Finalizes the SHA-512 hash. This clobbers `remainder` and `H`.
*
* @param remainder Any leftover unprocessed packed ints that still need to be processed.
* @param remainderBinLen The number of bits in `remainder`.
* @param processedBinLen The number of bits already processed.
* @param H The intermediate H values from a previous round.
* @param variant The desired SHA-512 variant.
* @returns The array of integers representing the SHA-512 hash of message.
*/
function finalizeSHA512(
remainder: number[],
remainderBinLen: number,
processedBinLen: number,
H: Int_64[],
variant: VariantType
): number[] {
let i, retVal;
/* The 129 addition is a hack but it works. The correct number is
actually 136 (128 + 8) but the below math fails if
remainderBinLen + 136 % 1024 = 0. Since remainderBinLen % 8 = 0,
"shorting" the addition is OK. */
const offset = (((remainderBinLen + 129) >>> 10) << 5) + 31,
binaryStringInc = 32,
totalLen = remainderBinLen + processedBinLen;
while (remainder.length <= offset) {
remainder.push(0);
}
/* Append '1' at the end of the binary string */
remainder[remainderBinLen >>> 5] |= 0x80 << (24 - (remainderBinLen % 32));
/* Append length of binary string in the position such that the new
* length is correct. JavaScript numbers are limited to 2^53 so it's
* "safe" to treat the totalLen as a 64-bit integer. */
remainder[offset] = totalLen & 0xffffffff;
/* Bitwise operators treat the operand as a 32-bit number so need to
* use hacky division and round to get access to upper 32-ish bits */
remainder[offset - 1] = (totalLen / TWO_PWR_32) | 0;
/* This will always be at least 1 full chunk */
for (i = 0; i < remainder.length; i += binaryStringInc) {
H = roundSHA512(remainder.slice(i, i + binaryStringInc), H);
}
if ("SHA-384" === variant) {
H = (H as unknown) as Int_64[];
retVal = [
H[0].highOrder,
H[0].lowOrder,
H[1].highOrder,
H[1].lowOrder,
H[2].highOrder,
H[2].lowOrder,
H[3].highOrder,
H[3].lowOrder,
H[4].highOrder,
H[4].lowOrder,
H[5].highOrder,
H[5].lowOrder,
];
} else {
/* SHA-512 */
retVal = [
H[0].highOrder,
H[0].lowOrder,
H[1].highOrder,
H[1].lowOrder,
H[2].highOrder,
H[2].lowOrder,
H[3].highOrder,
H[3].lowOrder,
H[4].highOrder,
H[4].lowOrder,
H[5].highOrder,
H[5].lowOrder,
H[6].highOrder,
H[6].lowOrder,
H[7].highOrder,
H[7].lowOrder,
];
}
return retVal;
}
export default class jsSHA extends jsSHABase<Int_64[], VariantType> {
intermediateState: Int_64[];
variantBlockSize: number;
bigEndianMod: -1 | 1;
outputBinLen: number;
isVariableLen: boolean;
HMACSupported: boolean;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
converterFunc: (input: any, existingBin: number[], existingBinLen: number) => packedValue;
roundFunc: (block: number[], H: Int_64[]) => Int_64[];
finalizeFunc: (remainder: number[], remainderBinLen: number, processedBinLen: number, H: Int_64[]) => number[];
stateCloneFunc: (state: Int_64[]) => Int_64[];
newStateFunc: (variant: VariantType) => Int_64[];
getMAC: () => number[];
constructor(variant: VariantType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(variant: VariantType, inputFormat: FormatNoTextType, options?: FixedLengthOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
if (!("SHA-384" === variant || "SHA-512" === variant)) {
throw new Error(sha_variant_error);
}
super(variant, inputFormat, options);
const resolvedOptions = options || {};
// eslint-disable-next-line @typescript-eslint/unbound-method
this.getMAC = this._getHMAC;
this.HMACSupported = true;
this.bigEndianMod = -1;
this.converterFunc = getStrConverter(this.inputFormat, this.utfType, this.bigEndianMod);
this.roundFunc = roundSHA512;
this.stateCloneFunc = function (state): Int_64[] {
return state.slice();
};
this.newStateFunc = getNewState512;
this.finalizeFunc = function (remainder, remainderBinLen, processedBinLen, H): number[] {
return finalizeSHA512(remainder, remainderBinLen, processedBinLen, H, variant);
};
this.intermediateState = getNewState512(variant);
this.variantBlockSize = 1024;
this.outputBinLen = "SHA-384" === variant ? 384 : 512;
this.isVariableLen = false;
if (resolvedOptions["hmacKey"]) {
this._setHMACKey(parseInputOption("hmacKey", resolvedOptions["hmacKey"], this.bigEndianMod));
}
}
}