first commit
This commit is contained in:
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "checkbox",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/crypto-js": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmmirror.com/crypto-js/-/crypto-js-4.2.0.tgz",
|
||||
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+607
@@ -0,0 +1,607 @@
|
||||
# noble-ciphers
|
||||
|
||||
Audited & minimal JS implementation of Salsa20, ChaCha and AES.
|
||||
|
||||
- 🔒 [**Audited**](#security) by an independent security firm
|
||||
- 🔻 Tree-shakeable: unused code is excluded from your builds
|
||||
- 🏎 Fast: hand-optimized for caveats of JS engines
|
||||
- 🔍 Reliable: property-based / cross-library / wycheproof tests ensure correctness
|
||||
- 💼 AES: ECB, CBC, CTR, CFB, GCM, SIV (nonce misuse-resistant), AESKW, AESKWP
|
||||
- 💃 Salsa20, ChaCha, XSalsa20, XChaCha, ChaCha8, ChaCha12, Poly1305
|
||||
- 🥈 Two AES implementations: pure JS or friendly WebCrypto wrapper
|
||||
- 🪶 11KB (gzipped) for everything, 3KB for ChaCha-only build
|
||||
|
||||
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative. Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
|
||||
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-ciphers/discussions) for questions and support.
|
||||
|
||||
### This library belongs to _noble_ cryptography
|
||||
|
||||
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
|
||||
|
||||
- Zero or minimal dependencies
|
||||
- Highly readable TypeScript / JS code
|
||||
- PGP-signed releases and transparent NPM builds
|
||||
- All libraries:
|
||||
[ciphers](https://github.com/paulmillr/noble-ciphers),
|
||||
[curves](https://github.com/paulmillr/noble-curves),
|
||||
[hashes](https://github.com/paulmillr/noble-hashes),
|
||||
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
|
||||
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
|
||||
[ed25519](https://github.com/paulmillr/noble-ed25519)
|
||||
- [Check out the homepage](https://paulmillr.com/noble/)
|
||||
for reading resources, documentation, and apps built with noble
|
||||
|
||||
## Usage
|
||||
|
||||
> `npm install @noble/ciphers`
|
||||
|
||||
> `deno add jsr:@noble/ciphers`
|
||||
|
||||
We support all major platforms and runtimes.
|
||||
For React Native, you may need a
|
||||
[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
|
||||
A standalone file
|
||||
[noble-ciphers.js](https://github.com/paulmillr/noble-ciphers/releases) is also available.
|
||||
|
||||
```ts
|
||||
// import * from '@noble/ciphers'; // Error: use sub-imports, to ensure small app size
|
||||
import { gcm, gcmsiv } from '@noble/ciphers/aes.js';
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; // KW
|
||||
import { bytesToHex, hexToBytes, managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
```
|
||||
|
||||
- [Examples](#examples)
|
||||
- [XChaCha20-Poly1305 encryption](#xchacha20-poly1305-encryption)
|
||||
- [AES-256-GCM encryption](#aes-256-gcm-encryption)
|
||||
- [managedNonce: automatic nonce handling](#managednonce-automatic-nonce-handling)
|
||||
- [AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw](#aes-gcm-siv-ctr-cfb-cbc-ecb-aeskw)
|
||||
- [AES: friendly WebCrypto wrapper](#aes-friendly-webcrypto-wrapper)
|
||||
- [Reuse array for input and output](#reuse-array-for-input-and-output)
|
||||
- [Use password for encryption](#use-password-for-encryption)
|
||||
- [Internals](#internals)
|
||||
- [Picking a cipher](#picking-a-cipher)
|
||||
- [How to encrypt properly](#how-to-encrypt-properly)
|
||||
- [Nonces](#nonces)
|
||||
- [Encryption limits](#encryption-limits)
|
||||
- [AES block modes](#aes-block-modes)
|
||||
- [Implemented primitives](#implemented-primitives)
|
||||
- [Security](#security)
|
||||
- [Speed](#speed)
|
||||
- [Upgrading](#upgrading)
|
||||
- [Contributing & testing](#contributing--testing)
|
||||
- [License](#license)
|
||||
|
||||
## Examples
|
||||
|
||||
> [!NOTE]
|
||||
> Use different nonce every time `encrypt()` is done.
|
||||
|
||||
#### XChaCha20-Poly1305 encryption
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const key = randomBytes(32); // random key
|
||||
// const key = new Uint8Array([ // existing key
|
||||
// 169, 88, 160, 139, 168, 29, 147, 196, 14, 88, 237, 76, 243, 177, 109, 140,
|
||||
// 195, 140, 80, 10, 216, 134, 215, 71, 191, 48, 20, 104, 189, 37, 38, 55,
|
||||
// ]);
|
||||
// import { hexToBytes } from '@noble/ciphers/utils.js'; // hex key
|
||||
// const key = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999');
|
||||
const nonce = randomBytes(24);
|
||||
const chacha = xchacha20poly1305(key, nonce);
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
|
||||
```
|
||||
|
||||
#### AES-256-GCM encryption
|
||||
|
||||
```js
|
||||
import { gcm } from '@noble/ciphers/aes.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const key = randomBytes(32);
|
||||
const nonce = randomBytes(24);
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const aes = gcm(key, nonce);
|
||||
const ciphertext = aes.encrypt(data);
|
||||
const data_ = aes.decrypt(ciphertext); // new TextDecoder().decode(data_) === data
|
||||
```
|
||||
|
||||
#### managedNonce: automatic nonce handling
|
||||
|
||||
We provide API that manages nonce internally instead of exposing them to library's user.
|
||||
|
||||
For `encrypt`: a `nonceBytes`-length buffer is fetched from CSPRNG and prenended to encrypted ciphertext.
|
||||
|
||||
For `decrypt`: first `nonceBytes` of ciphertext are treated as nonce.
|
||||
|
||||
> [!NOTE]
|
||||
> AES-GCM & ChaCha (NOT XChaCha) [limit amount of messages](#encryption-limits)
|
||||
> encryptable under the same key.
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { hexToBytes, managedNonce } from '@noble/ciphers/utils.js';
|
||||
const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1');
|
||||
const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext);
|
||||
```
|
||||
|
||||
#### AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw
|
||||
|
||||
```js
|
||||
import { gcm, gcmsiv, aessiv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const plaintext = new Uint8Array(32).fill(16);
|
||||
for (let cipher of [gcm, gcmsiv, aessiv]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const nonce = randomBytes(12);
|
||||
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ctr, cbc, cfb]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const nonce = randomBytes(16);
|
||||
const ciphertext_ = cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ecb]) {
|
||||
const key = randomBytes(32); // 24 for AES-192, 16 for AES-128
|
||||
const ciphertext_ = cipher(key).encrypt(plaintext);
|
||||
const plaintext_ = cipher(key).decrypt(ciphertext_);
|
||||
}
|
||||
|
||||
// AESKW, AESKWP
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
import { hexToBytes } from '@noble/ciphers/utils.js';
|
||||
|
||||
const kek = hexToBytes('000102030405060708090A0B0C0D0E0F');
|
||||
const keyData = hexToBytes('00112233445566778899AABBCCDDEEFF');
|
||||
const ciphertext = aeskw(kek).encrypt(keyData);
|
||||
```
|
||||
|
||||
#### AES: friendly WebCrypto wrapper
|
||||
|
||||
Noble implements AES. Sometimes people want to use built-in `crypto.subtle` instead. However, it has terrible API. We simplify access to built-ins.
|
||||
|
||||
> [!NOTE]
|
||||
> Webcrypto methods are always async.
|
||||
|
||||
```js
|
||||
import { gcm, ctr, cbc } from '@noble/ciphers/webcrypto.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
const plaintext = new Uint8Array(32).fill(16);
|
||||
const key = randomBytes(32);
|
||||
for (const cipher of [gcm]) {
|
||||
const nonce = randomBytes(12);
|
||||
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
for (const cipher of [ctr, cbc]) {
|
||||
const nonce = randomBytes(16);
|
||||
const ciphertext_ = await cipher(key, nonce).encrypt(plaintext);
|
||||
const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_);
|
||||
}
|
||||
```
|
||||
|
||||
#### Reuse array for input and output
|
||||
|
||||
To avoid additional allocations, Uint8Array can be reused
|
||||
between encryption and decryption calls.
|
||||
|
||||
> [!NOTE]
|
||||
> Some ciphers don't support unaligned (`byteOffset % 4 !== 0`) Uint8Array as
|
||||
> destination. It can decrease performance, making the optimization pointless.
|
||||
|
||||
```js
|
||||
import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
|
||||
const key = randomBytes(32);
|
||||
const nonce = randomBytes(12);
|
||||
const chacha = chacha20poly1305(key, nonce);
|
||||
|
||||
const input = new TextEncoder().encode('hello noble'); // length == 12
|
||||
const inputLength = input.length;
|
||||
const tagLength = 16;
|
||||
|
||||
const buf = new Uint8Array(inputLength + tagLength);
|
||||
const start = buf.subarray(0, inputLength);
|
||||
start.set(input); // copy input to buf
|
||||
|
||||
chacha.encrypt(start, buf); // encrypt into `buf`
|
||||
chacha.decrypt(buf, start); // decrypt into `start`
|
||||
```
|
||||
|
||||
xsalsa20poly1305 also supports this, but requires 32 additional bytes for encryption / decryption,
|
||||
due to its inner workings.
|
||||
|
||||
#### Randomness generation
|
||||
|
||||
We provide userspace CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
It's best to limit their usage to non-production, non-critical cases: for example, test-only usage.
|
||||
ChaCha-based CSPRNG does not have a specification as per 2025, which makes it less secure.
|
||||
|
||||
```js
|
||||
import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
|
||||
import { rngChacha8, rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// 1. Best: WebCrypto
|
||||
const rnd1 = randomBytes(32);
|
||||
// 2. AES-CTR DRBG
|
||||
const seed2 = randomBytes(48);
|
||||
const rnd2 = rngAesCtrDrbg256(seed2).randomBytes(1024);
|
||||
// 3. ChaCha8 CSPRNG
|
||||
const seed3 = randomBytes(32);
|
||||
const rnd3 = rngChacha8(seed3).randomBytes(1024);
|
||||
```
|
||||
|
||||
#### Use password for encryption
|
||||
|
||||
It is not safe to convert password into Uint8Array.
|
||||
Instead, KDF stretching function like PBKDF2 / Scrypt / Argon2id
|
||||
should be applied to convert password to AES key.
|
||||
Make sure to use salt (app-specific secret) in addition to password.
|
||||
|
||||
> `npm install @noble/hashes`
|
||||
|
||||
```js
|
||||
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
import { managedNonce } from '@noble/ciphers/utils.js';
|
||||
import { scrypt } from '@noble/hashes/scrypt.js';
|
||||
|
||||
// Convert password into 32-byte key using scrypt
|
||||
const PASSWORD = 'correct-horse-battery-staple';
|
||||
const APP_SPECIFIC_SECRET = 'salt-12345678-secret';
|
||||
const SECURITY_LEVEL = 2 ** 20; // requires 1GB of RAM to calculate
|
||||
// sync, but scryptAsync is also available
|
||||
const key = scrypt(PASSWORD, APP_SPECIFIC_SECRET, { N: SECURITY_LEVEL, r: 8, p: 1, dkLen: 32 });
|
||||
|
||||
// Use random, managed nonce
|
||||
const chacha = managedNonce(xchacha20poly1305)(key);
|
||||
|
||||
const data = new TextEncoder().encode('hello noble');
|
||||
const ciphertext = chacha.encrypt(data);
|
||||
const data_ = chacha.decrypt(ciphertext);
|
||||
```
|
||||
|
||||
## Internals
|
||||
|
||||
### Picking a cipher
|
||||
|
||||
We suggest to use **XChaCha20-Poly1305** because it's very fast and allows random keys.
|
||||
**AES-GCM-SIV** is also a good idea, because it provides resistance against nonce reuse.
|
||||
**AES-GCM** is a good option when those two are not available.
|
||||
|
||||
### How to encrypt properly
|
||||
|
||||
- Use unpredictable key with enough entropy
|
||||
- Random key must be using cryptographically secure random number generator (CSPRNG), not `Math.random` etc.
|
||||
- Non-random key generated from KDF is fine
|
||||
- Re-using key is fine, but be aware of rules for cryptographic key wear-out and [encryption limits](#encryption-limits)
|
||||
- Use new nonce every time and [don't repeat it](#nonces)
|
||||
- chacha and salsa20 are fine for sequential counters that _never_ repeat: `01, 02...`
|
||||
- xchacha and xsalsa20 can use random nonces instead
|
||||
- AES-GCM should use 12-byte nonces: smaller nonces are security risk
|
||||
- Prefer authenticated encryption (AEAD)
|
||||
- Good: chacha20poly1305, GCM, GCM-SIV, ChaCha+HMAC, CTR+HMAC, CBC+HMAC
|
||||
- Bad: chacha20, raw CTR, raw CBC
|
||||
- Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers
|
||||
- Polynomial MACs are not perfect for every situation:
|
||||
they lack Random Key Robustness: the MAC can be forged, and can't
|
||||
be used in PAKE schemes. See
|
||||
[invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
|
||||
To combat salamanders, `hash(key)` can be included in ciphertext,
|
||||
however, this would violate ciphertext indistinguishability:
|
||||
an attacker would know which key was used - so `HKDF(key, i)`
|
||||
could be used instead.
|
||||
- Don't re-use keys between different protocols
|
||||
- For example, using ECDH key in AES can be bad
|
||||
- Use hkdf or, at least, a hash function to create sub-key instead
|
||||
|
||||
### Nonces
|
||||
|
||||
Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data.
|
||||
Repeating (key, nonce) pair with different plaintexts would allow an attacker to decrypt it.
|
||||
|
||||
ciphertext_a = encrypt(plaintext_a, key, nonce)
|
||||
ciphertext_b = encrypt(plaintext_b, key, nonce)
|
||||
stream_diff = xor(ciphertext_a, ciphertext_b) # Break encryption
|
||||
|
||||
One way of not repeating nonces is using counters:
|
||||
|
||||
for i in 0..:
|
||||
ciphertext[i] = encrypt(plaintexts[i], key, i)
|
||||
|
||||
Another is generating random nonce every time:
|
||||
|
||||
for i in 0..:
|
||||
rand_nonces[i] = random()
|
||||
ciphertext[i] = encrypt(plaintexts[i], key, rand_nonces[i])
|
||||
|
||||
- Counters are OK, but it's not always possible to store current counter value:
|
||||
e.g. in decentralized, unsyncable systems.
|
||||
- Randomness is OK, but there's a catch:
|
||||
ChaCha20 and AES-GCM use 96-bit / 12-byte nonces, which implies higher chance of collision.
|
||||
In the example above, `random()` can collide and produce repeating nonce.
|
||||
Chance is even higher for 64-bit nonces, which GCM allows - don't use them.
|
||||
- To safely use random nonces, utilize XSalsa20 or XChaCha:
|
||||
they increased nonce length to 192-bit, minimizing a chance of collision.
|
||||
AES-SIV is also fine. In situations where you can't use eXtended-nonce
|
||||
algorithms, key rotation is advised. hkdf would work great for this case.
|
||||
|
||||
### Encryption limits
|
||||
|
||||
A "protected message" would mean a probability of `2**-50` that a passive attacker
|
||||
successfully distinguishes the ciphertext outputs of the AEAD scheme from the outputs
|
||||
of a random function.
|
||||
|
||||
- Max message size:
|
||||
- AES-GCM: ~68GB, `2**36-256`
|
||||
- Salsa, ChaCha, XSalsa, XChaCha: ~256GB, `2**38-64`
|
||||
- Max amount of protected messages, under same key:
|
||||
- AES-GCM: `2**32.5`
|
||||
- Salsa, ChaCha: `2**46`, but only integrity (MAC) is affected, not confidentiality (encryption)
|
||||
- XSalsa, XChaCha: `2**72`
|
||||
- Max amount of protected messages, across all keys:
|
||||
- AES-GCM: `2**69/B` where B is max blocks encrypted by a key. Meaning
|
||||
`2**59` for 1KB, `2**49` for 1MB, `2**39` for 1GB
|
||||
- Salsa, ChaCha, XSalsa, XChaCha: `2**100`
|
||||
- Max amount of protected messages, under same key, using **random nonce**:
|
||||
- Relevant for 12-byte nonces with `managedNonce`: AES-GCM, ChaCha
|
||||
- `2**23` (8M) messages for `2**-50` chance, `2**32.5` (4B) for `2**-32.5` chance
|
||||
|
||||
Check out [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details.
|
||||
|
||||
### Implemented primitives
|
||||
|
||||
- Salsa20 stream cipher, released in 2005.
|
||||
Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
which are hard to implement in a constant-time manner.
|
||||
Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
- [XSalsa20](https://cr.yp.to/snuffle/xsalsa-20110204.pdf), extended-nonce
|
||||
variant was released in 2008. It switched nonces from 96-bit to 192-bit,
|
||||
and became safe to be picked at random.
|
||||
- Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
We provide the alias and corresponding seal / open methods.
|
||||
"crypto_box" and "sealedbox" are available in package [noble-sodium](https://github.com/serenity-kit/noble-sodium).
|
||||
- Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf)
|
||||
and [website](https://cr.yp.to/snuffle.html).
|
||||
- ChaCha20 stream cipher, released in 2008. Developed after Salsa20,
|
||||
ChaCha aims to increase diffusion per round.
|
||||
- [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)
|
||||
extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
randomly-generated nonces.
|
||||
- Check out
|
||||
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439),
|
||||
[PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
|
||||
[website](https://cr.yp.to/chacha.html).
|
||||
- AES is a variant of Rijndael block cipher, standardized by NIST in 2001.
|
||||
We provide the fastest available pure JS implementation.
|
||||
- We support AES-128, AES-192 and AES-256: the mode is selected dynamically,
|
||||
based on key length (16, 24, 32).
|
||||
- AES-GCM-SIV nonce-misuse-resistant mode is also provided. Our implementation of SIV
|
||||
has the same speed as GCM: there is no performance hit.
|
||||
The mode is described in [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452).
|
||||
- There is a separate AES-SIV mode, described in [RFC 5297](https://www.rfc-editor.org/rfc/rfc5297)
|
||||
- We also have AESKW and AESKWP from
|
||||
[RFC 3394](https://www.rfc-editor.org/rfc/rfc3394) & [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649)
|
||||
- Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
[NIST SP 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf).
|
||||
- Check out [AES block modes](#aes-block-modes),
|
||||
[FIPS 197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf) and
|
||||
[original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf).
|
||||
- Polynomial-evaluation MACs are available: Poly1305, AES-GCM's GHash and AES-SIV's Polyval.
|
||||
- Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
|
||||
[website](https://cr.yp.to/mac.html))
|
||||
is a fast and parallel secret-key message-authentication code suitable for
|
||||
a wide variety of applications. It was standardized in
|
||||
[RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.
|
||||
- Ghash is used in AES-GCM: see NIST SP 800-38G
|
||||
- Polyval is used in AES-GCM-SIV: see [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452)
|
||||
|
||||
##### AES block modes
|
||||
|
||||
For non-deterministic (not ECB) schemes, initialization vector (IV) is mixed to block/key;
|
||||
and each new round either depends on previous block's key, or on some counter.
|
||||
|
||||
- **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield identical ciphertexts. Not secure due to pattern leakage. due to pattern leakage.
|
||||
See [AES Penguin](https://words.filippo.io/the-ecb-penguin/)
|
||||
- **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the previous block of ciphertext
|
||||
before encryption. Hard to use: requires proper padding and an IV. Unauthenticated: needs MAC.
|
||||
- **CTR** (Counter Mode): Turns a block cipher into a stream cipher using a counter and IV (nonce).
|
||||
Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
|
||||
- **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. Not perfect:
|
||||
a) conservative key wear-out is `2**32` (4B) msgs.
|
||||
b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
|
||||
c) MAC can be forged: see Poly1305 documentation.
|
||||
- **SIV** (Synthetic IV): GCM with nonce-misuse resistance; repeating nonces reveal only the fact plaintexts
|
||||
are identical. Also suffers from GCM issues: key wear-out limits & MAC forging.
|
||||
- **XTS**: Designed for disk encryption.
|
||||
Similar to ECB (deterministic), but has `[i][j]` tweak arguments corresponding to
|
||||
sector i and 16-byte block (part of sector) j. Lacks MAC.
|
||||
|
||||
## Security
|
||||
|
||||
The library has been audited:
|
||||
|
||||
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
|
||||
- Scope: everything
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/2.2.0..main)
|
||||
- at version 1.0.0, in Sep 2024, independently, by [cure53](https://cure53.de)
|
||||
- PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf)
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/1.0.0..main)
|
||||
- Scope: everything
|
||||
- The audit has been funded by [OpenSats](https://opensats.org)
|
||||
|
||||
It is tested against property-based, cross-library and Wycheproof vectors,
|
||||
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
|
||||
|
||||
If you see anything unusual: investigate and report.
|
||||
|
||||
### Constant-timeness
|
||||
|
||||
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
|
||||
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
|
||||
in a scripting language. Which means _any other JS library can't have
|
||||
constant-timeness_. Even statically typed Rust, a language without GC,
|
||||
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
|
||||
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
|
||||
Use low-level libraries & languages.
|
||||
|
||||
The library uses T-tables for AES, which
|
||||
[leak access timings](https://cr.yp.to/antiforgery/cachetiming-20050414.pdf).
|
||||
This is also done in [OpenSSL](https://github.com/openssl/openssl/blob/2f33265039cdbd0e4589c80970e02e208f3f94d2/crypto/aes/aes_core.c#L706) and
|
||||
[Go stdlib](https://cs.opensource.google/go/go/+/refs/tags/go1.22.6:src/crypto/aes/const.go;l=90) for performance reasons.
|
||||
The analysis was mentioned in [hal-04652991](https://hal.science/hal-04652991/document).
|
||||
|
||||
### Supply chain security
|
||||
|
||||
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
|
||||
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
|
||||
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
|
||||
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
|
||||
- We use as few dependencies as possible.
|
||||
- Version ranges are locked, and changes are checked with npm-diff.
|
||||
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
|
||||
|
||||
For this package, there are 0 dependencies; and a few dev dependencies:
|
||||
|
||||
- jsbt is used for benchmarking / testing / build tooling and developed by the same author
|
||||
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
|
||||
|
||||
### Randomness
|
||||
|
||||
We rely on the built-in
|
||||
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
|
||||
which is considered a cryptographically secure PRNG.
|
||||
|
||||
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
|
||||
|
||||
### Quantum computers
|
||||
|
||||
Cryptographically relevant quantum computer, if built, will allow to
|
||||
utilize Grover's algorithm to break ciphers in 2^n/2 operations, instead of 2^n.
|
||||
|
||||
This means AES128 should be replaced with AES256. Salsa and ChaCha are already safe.
|
||||
|
||||
Australian ASD prohibits AES128 [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
|
||||
|
||||
## Speed
|
||||
|
||||
```sh
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Benchmarks measured on Apple M4.
|
||||
If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
|
||||
|
||||
```
|
||||
64B
|
||||
xsalsa20poly1305 x 735,835 ops/sec @ 1μs/op
|
||||
chacha20poly1305 x 581,395 ops/sec @ 1μs/op
|
||||
xchacha20poly1305 x 468,384 ops/sec @ 2μs/op
|
||||
aes-256-gcm x 201,126 ops/sec @ 4μs/op
|
||||
aes-256-gcm-siv x 162,284 ops/sec @ 6μs/op
|
||||
# Unauthenticated encryption
|
||||
salsa20 x 1,655,629 ops/sec @ 604ns/op
|
||||
xsalsa20 x 1,400,560 ops/sec @ 714ns/op
|
||||
chacha20 x 1,996,007 ops/sec @ 501ns/op
|
||||
xchacha20 x 1,404,494 ops/sec @ 712ns/op
|
||||
chacha8 x 2,145,922 ops/sec @ 466ns/op
|
||||
chacha12 x 2,036,659 ops/sec @ 491ns/op
|
||||
aes-ecb-256 x 1,019,367 ops/sec @ 981ns/op
|
||||
aes-cbc-256 x 931,966 ops/sec @ 1μs/op
|
||||
aes-ctr-256 x 954,198 ops/sec @ 1μs/op
|
||||
|
||||
1MB
|
||||
xsalsa20poly1305 x 334 ops/sec @ 2ms/op
|
||||
chacha20poly1305 x 333 ops/sec @ 2ms/op
|
||||
xchacha20poly1305 x 334 ops/sec @ 2ms/op
|
||||
aes-256-gcm x 94 ops/sec @ 10ms/op
|
||||
aes-256-gcm-siv x 90 ops/sec @ 11ms/op
|
||||
# Unauthenticated encryption
|
||||
salsa20 x 831 ops/sec @ 1ms/op
|
||||
xsalsa20 x 830 ops/sec @ 1ms/op
|
||||
chacha20 x 804 ops/sec @ 1ms/op
|
||||
xchacha20 x 797 ops/sec @ 1ms/op
|
||||
chacha8 x 1,495 ops/sec @ 668μs/op
|
||||
chacha12 x 1,148 ops/sec @ 871μs/op
|
||||
aes-ecb-256 x 289 ops/sec @ 3ms/op
|
||||
aes-cbc-256 x 114 ops/sec @ 8ms/op
|
||||
aes-ctr-256 x 127 ops/sec @ 7ms/op
|
||||
# Wrapper over built-in webcrypto
|
||||
webcrypto ctr-256 x 6,508 ops/sec @ 153μs/op
|
||||
webcrypto cbc-256 x 1,820 ops/sec @ 549μs/op
|
||||
webcrypto gcm-256 x 5,106 ops/sec @ 195μs/op
|
||||
```
|
||||
|
||||
Compare to other implementations:
|
||||
|
||||
```
|
||||
xsalsa20poly1305 (encrypt, 1MB)
|
||||
├─tweetnacl x 196 mb/sec
|
||||
├─awasm-noble_threads x 2,318 mb/sec
|
||||
├─awasm-noble_no_threads x 1,196 mb/sec
|
||||
└─noble x 305 mb/sec
|
||||
|
||||
aes-ctr-256 (encrypt, 1MB)
|
||||
├─stablelib x 123 mb/sec
|
||||
├─aesjs x 42 mb/sec
|
||||
├─awasm-noble_thread x 2,105 mb/sec
|
||||
├─awasm-noble_no_threads x 272 mb/sec
|
||||
├─noble_webcrypto x 5,965 mb/sec
|
||||
└─noble x 124 mb/sec
|
||||
```
|
||||
|
||||
## Upgrading
|
||||
|
||||
Supported node.js versions:
|
||||
|
||||
- v2: v20.19+ (ESM-only)
|
||||
- v1: v14.21+ (ESM & CJS)
|
||||
|
||||
Changelog of v2, when upgrading from ciphers v1:
|
||||
|
||||
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
|
||||
- `.js` extension must be used for all modules
|
||||
- Old: `@noble/ciphers/aes`
|
||||
- New: `@noble/ciphers/aes.js`
|
||||
- This simplifies working in browsers natively without transpilers
|
||||
- webcrypto: move `randomBytes` and `managedNonce` to `utils.js`
|
||||
- ghash, poly1305, polyval: only allow Uint8Array as hash inputs, prohibit `string`
|
||||
- utils: new abytes; remove ahash, toBytes
|
||||
- Remove modules `_assert` (use `utils`), `_micro` and `crypto` (use `webcrypto`)
|
||||
- Bump TS compilation target from es2020 to es2022
|
||||
- Massively improve error messages, make them more descriptive
|
||||
|
||||
## Contributing & testing
|
||||
|
||||
- `npm install && npm run build && npm test` will build the code and run tests.
|
||||
- `npm run lint` / `npm run format` will run linter / fix linter issues.
|
||||
- `npm run bench` will run benchmarks
|
||||
- `npm run build:release` will build single file
|
||||
|
||||
See [paulmillr.com/noble](https://paulmillr.com/noble/)
|
||||
for useful resources, articles, documentation and demos
|
||||
related to the library.
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2023 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
|
||||
Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
|
||||
|
||||
See LICENSE file.
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import { type PRG, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export declare function rotl(a: number, b: number): number;
|
||||
/**
|
||||
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param nonce - Nonce and counter words prepared for the round function.
|
||||
* @param output - Output block written in place.
|
||||
* @param counter - Block counter value.
|
||||
* @param rounds - Optional round count override.
|
||||
*/
|
||||
export type CipherCoreFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, nonce: TArg<Uint32Array>, output: TArg<Uint32Array>, counter: number, rounds?: number) => void;
|
||||
/**
|
||||
* Nonce-extension function used by XChaCha and XSalsa.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param input - Input nonce words used for subkey derivation.
|
||||
* @param output - Output buffer written with the derived nonce words.
|
||||
*/
|
||||
export type ExtendNonceFn = (sigma: TArg<Uint32Array>, key: TArg<Uint32Array>, input: TArg<Uint32Array>, output: TArg<Uint32Array>) => void;
|
||||
/** ARX cipher options.
|
||||
* * `allowShortKeys` for 16-byte keys
|
||||
* * `counterLength` in bytes
|
||||
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
|
||||
* */
|
||||
export type CipherOpts = {
|
||||
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
|
||||
allowShortKeys?: boolean;
|
||||
/** Optional nonce-expansion hook used by extended-nonce variants. */
|
||||
extendNonceFn?: ExtendNonceFn;
|
||||
/** Counter length in bytes inside the nonce/counter layout. */
|
||||
counterLength?: number;
|
||||
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
|
||||
counterRight?: boolean;
|
||||
/** Number of core rounds to execute. */
|
||||
rounds?: number;
|
||||
};
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export declare function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream>;
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export declare class _XorStreamPRG implements PRG {
|
||||
readonly blockLen: number;
|
||||
readonly keyLen: number;
|
||||
readonly nonceLen: number;
|
||||
private state;
|
||||
private buf;
|
||||
private key;
|
||||
private nonce;
|
||||
private pos;
|
||||
private ctr;
|
||||
private cipher;
|
||||
constructor(cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number, seed: TArg<Uint8Array>);
|
||||
private reseed;
|
||||
addEntropy(seed: TArg<Uint8Array>): void;
|
||||
randomBytes(len: number): TRet<Uint8Array>;
|
||||
clone(): _XorStreamPRG;
|
||||
clean(): void;
|
||||
}
|
||||
/**
|
||||
* PRG constructor backed by an ARX stream cipher.
|
||||
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
|
||||
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
|
||||
* wrap those bytes through `reseed()`'s XOR schedule.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
*/
|
||||
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const createPRG: (cipher: TArg<XorStream>, blockLen: number, keyLen: number, nonceLen: number) => TRet<XorPRG>;
|
||||
//# sourceMappingURL=_arx.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EACL,KAAK,GAAG,EACR,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EAaf,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,EACzB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,KACtB,IAAI,CAAC;AAEV;;;;KAIK;AACL,MAAM,MAAM,UAAU,GAAG;IACvB,8EAA8E;IAC9E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,qEAAqE;IACrE,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AA8FF;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAoG9F;AAED,uEAAuE;AACvE,qBAAa,aAAc,YAAW,GAAG;IACvC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,GAAG,CAAmB;IAC9B,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,MAAM,CAAkB;gBAE9B,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EACvB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC;IAgBxB,OAAO,CAAC,MAAM;IASd,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IASxC,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IA+C1C,KAAK,IAAI,aAAa;IAYtB,KAAK,IAAI,IAAI;CAMd;AAED;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,aAAa,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,GACpB,QAAQ,IAAI,CAAC,SAAS,CAAC,EACvB,UAAU,MAAM,EAChB,QAAQ,MAAM,EACd,UAAU,MAAM,KACf,IAAI,CAAC,MAAM,CASb,CAAC"}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import { abool, abytes, anumber, checkOpts, clean, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from "./utils.js";
|
||||
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
|
||||
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
|
||||
const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
|
||||
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
|
||||
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
|
||||
// kept for legacy allowShortKeys Salsa/ChaCha variants.
|
||||
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
|
||||
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
|
||||
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export function rotl(a, b) {
|
||||
return (a << b) | (a >>> (32 - b));
|
||||
}
|
||||
// Salsa and Chacha block length is always 512-bit
|
||||
const BLOCK_LEN = 64;
|
||||
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
|
||||
const BLOCK_LEN32 = 16;
|
||||
// Counter policy for the shared public `counter` argument:
|
||||
// - RFC/IETF ChaCha20 uses a 32-bit counter.
|
||||
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
|
||||
// counter state and carry into the next word.
|
||||
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
|
||||
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
|
||||
// boundary instead of carrying.
|
||||
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
|
||||
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
|
||||
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
|
||||
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
|
||||
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
|
||||
// whatever wider carry / wrap policy they need on top.
|
||||
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
||||
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
||||
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
|
||||
const len = data.length;
|
||||
const block = new Uint8Array(BLOCK_LEN);
|
||||
const b32 = u32(block);
|
||||
// Make sure that buffers aligned to 4 bytes
|
||||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
||||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
||||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
||||
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
|
||||
// truncating the final partial block instead of materializing the whole keystream.
|
||||
if (!isLE) {
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(sigma, key, nonce, b32, counter, rounds);
|
||||
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
|
||||
swap32IfBE(b32);
|
||||
if (counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(sigma, key, nonce, b32, counter, rounds);
|
||||
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
|
||||
if (counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
// aligned to 4 bytes
|
||||
if (isAligned && take === BLOCK_LEN) {
|
||||
const pos32 = pos / 4;
|
||||
if (pos % 4 !== 0)
|
||||
throw new Error('arx: invalid block position');
|
||||
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
|
||||
posj = pos32 + j;
|
||||
o32[posj] = d32[posj] ^ b32[j];
|
||||
}
|
||||
pos += BLOCK_LEN;
|
||||
continue;
|
||||
}
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export function createCipher(core, opts) {
|
||||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
|
||||
if (typeof core !== 'function')
|
||||
throw new Error('core must be a function');
|
||||
anumber(counterLength);
|
||||
anumber(rounds);
|
||||
abool(counterRight);
|
||||
abool(allowShortKeys);
|
||||
return (key, nonce, data, output, counter = 0) => {
|
||||
abytes(key, undefined, 'key');
|
||||
abytes(nonce, undefined, 'nonce');
|
||||
abytes(data, undefined, 'data');
|
||||
const len = data.length;
|
||||
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
|
||||
// must match the logical result length exactly instead of returning an oversized workspace.
|
||||
output = getOutput(len, output, false);
|
||||
anumber(counter);
|
||||
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
|
||||
if (counter < 0 || counter >= MAX_COUNTER)
|
||||
throw new Error('arx: counter overflow');
|
||||
const toClean = [];
|
||||
// Key & sigma
|
||||
// key=16 -> sigma16, k=key|key
|
||||
// key=32 -> sigma32, k=key
|
||||
let l = key.length;
|
||||
let k;
|
||||
let sigma;
|
||||
if (l === 32) {
|
||||
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
|
||||
// final clean(...) all mutate or wipe the temporary buffer in place.
|
||||
toClean.push((k = copyBytes(key)));
|
||||
sigma = sigma32_32;
|
||||
}
|
||||
else if (l === 16 && allowShortKeys) {
|
||||
k = new Uint8Array(32);
|
||||
k.set(key);
|
||||
k.set(key, 16);
|
||||
sigma = sigma16_32;
|
||||
toClean.push(k);
|
||||
}
|
||||
else {
|
||||
abytes(key, 32, 'arx key');
|
||||
throw new Error('invalid key size');
|
||||
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
|
||||
}
|
||||
// Nonce
|
||||
// salsa20: 8 (8-byte counter)
|
||||
// chacha20orig: 8 (8-byte counter)
|
||||
// chacha20: 12 (4-byte counter)
|
||||
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
|
||||
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
|
||||
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
|
||||
// swap32IfBE(...) never mutates caller nonce bytes in place.
|
||||
if (!isLE || !isAligned32(nonce))
|
||||
toClean.push((nonce = copyBytes(nonce)));
|
||||
let k32 = u32(k);
|
||||
// hsalsa & hchacha: handle extended nonce
|
||||
if (extendNonceFn) {
|
||||
if (nonce.length !== 24)
|
||||
throw new Error(`arx: extended nonce must be 24 bytes`);
|
||||
const n16 = nonce.subarray(0, 16);
|
||||
if (isLE)
|
||||
extendNonceFn(sigma, k32, u32(n16), k32);
|
||||
else {
|
||||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
||||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
||||
clean(sigmaRaw);
|
||||
swap32IfBE(k32);
|
||||
}
|
||||
nonce = nonce.subarray(16);
|
||||
}
|
||||
else if (!isLE)
|
||||
swap32IfBE(k32);
|
||||
// Handle nonce counter
|
||||
const nonceNcLen = 16 - counterLength;
|
||||
if (nonceNcLen !== nonce.length)
|
||||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
||||
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
|
||||
// counter bytes, while Salsa/XSalsa append them after the nonce words.
|
||||
if (nonceNcLen !== 12) {
|
||||
const nc = new Uint8Array(12);
|
||||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
||||
nonce = nc;
|
||||
toClean.push(nonce);
|
||||
}
|
||||
const n32 = swap32IfBE(u32(nonce));
|
||||
// Ensure temporary key/nonce copies are wiped even if the remaining
|
||||
// runtime guard in runCipher(...) throws on counter overflow.
|
||||
try {
|
||||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
||||
return output;
|
||||
}
|
||||
finally {
|
||||
clean(...toClean);
|
||||
}
|
||||
};
|
||||
}
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export class _XorStreamPRG {
|
||||
blockLen;
|
||||
keyLen;
|
||||
nonceLen;
|
||||
state;
|
||||
buf;
|
||||
key;
|
||||
nonce;
|
||||
pos;
|
||||
ctr;
|
||||
cipher;
|
||||
constructor(cipher, blockLen, keyLen, nonceLen, seed) {
|
||||
this.cipher = cipher;
|
||||
this.blockLen = blockLen;
|
||||
this.keyLen = keyLen;
|
||||
this.nonceLen = nonceLen;
|
||||
this.state = new Uint8Array(this.keyLen + this.nonceLen);
|
||||
this.reseed(seed);
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
this.buf = new Uint8Array(this.blockLen);
|
||||
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
|
||||
// inputs in place through these subarray views.
|
||||
this.key = this.state.subarray(0, this.keyLen);
|
||||
this.nonce = this.state.subarray(this.keyLen);
|
||||
}
|
||||
reseed(seed) {
|
||||
abytes(seed);
|
||||
if (!seed || seed.length === 0)
|
||||
throw new Error('entropy required');
|
||||
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
|
||||
// keystream so buffered leftovers from the previous state are never reused.
|
||||
for (let i = 0; i < seed.length; i++)
|
||||
this.state[i % this.state.length] ^= seed[i];
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
}
|
||||
addEntropy(seed) {
|
||||
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
|
||||
abytes(seed);
|
||||
if (seed.length === 0)
|
||||
throw new Error('entropy required');
|
||||
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
|
||||
// state through reseed() so stale buffered bytes are discarded.
|
||||
this.state.set(this.randomBytes(this.state.length));
|
||||
this.reseed(seed);
|
||||
}
|
||||
randomBytes(len) {
|
||||
anumber(len);
|
||||
if (len === 0)
|
||||
return new Uint8Array(0);
|
||||
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
|
||||
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
|
||||
// Preflight overflow so failed reads don't partially consume keystream
|
||||
// and leave the PRG repeating blocks.
|
||||
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
|
||||
throw new Error('arx: counter overflow');
|
||||
const out = new Uint8Array(len);
|
||||
let outPos = 0;
|
||||
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
|
||||
// ciphers then emit raw keystream bytes directly into those buffers.
|
||||
// Serve buffered leftovers first so split reads stay identical to one larger read.
|
||||
if (this.pos < this.blockLen) {
|
||||
const take = Math.min(len, this.blockLen - this.pos);
|
||||
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
|
||||
this.pos += take;
|
||||
outPos += take;
|
||||
if (outPos === len)
|
||||
return out; // fast path
|
||||
}
|
||||
// Full blocks directly to out
|
||||
const full = Math.floor((len - outPos) / this.blockLen);
|
||||
if (full > 0) {
|
||||
const blockBytes = full * this.blockLen;
|
||||
const b = out.subarray(outPos, outPos + blockBytes);
|
||||
this.cipher(this.key, this.nonce, b, b, this.ctr);
|
||||
this.ctr += full;
|
||||
outPos += blockBytes;
|
||||
}
|
||||
// Save leftovers
|
||||
const left = len - outPos;
|
||||
if (left > 0) {
|
||||
this.buf.fill(0);
|
||||
// NOTE: cipher will handle overflow
|
||||
this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
|
||||
out.set(this.buf.subarray(0, left), outPos);
|
||||
this.pos = left;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Clone seeds the new instance from this stream, so the source PRG advances too.
|
||||
clone() {
|
||||
return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
|
||||
}
|
||||
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
|
||||
// Later reads first drain zeros from the cleared buffer and then continue
|
||||
// from zero key||nonce state.
|
||||
clean() {
|
||||
this.pos = 0;
|
||||
this.ctr = 0;
|
||||
this.buf.fill(0);
|
||||
this.state.fill(0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
|
||||
return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
|
||||
};
|
||||
//# sourceMappingURL=_arx.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+73
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class Poly1305 implements IHash2 {
|
||||
readonly blockLen = 16;
|
||||
readonly outputLen = 16;
|
||||
private buffer;
|
||||
private r;
|
||||
private h;
|
||||
private pad;
|
||||
private pos;
|
||||
protected finished: boolean;
|
||||
protected destroyed: boolean;
|
||||
constructor(key: TArg<Uint8Array>);
|
||||
private process;
|
||||
private finalize;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
destroy(): void;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
/** One-shot keyed hash helper with `.create()`. */
|
||||
export type CHash = CMac<Poly1305>;
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const poly1305: TRet<CHash>;
|
||||
//# sourceMappingURL=_poly1305.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAGe,KAAK,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EACjE,MAAM,YAAY,CAAC;AA2DpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,QAAS,YAAW,MAAM;IACrC,QAAQ,CAAC,QAAQ,MAAM;IACvB,QAAQ,CAAC,SAAS,MAAM;IACxB,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,GAAG,CAAK;IAChB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;gBAGhB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC;IA4BjC,OAAO,CAAC,OAAO;IA+Hf,OAAO,CAAC,QAAQ;IAmDhB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAwBpC,OAAO,IAAI,IAAI;IAKf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAqBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAQ3B;AAED,mDAAmD;AACnD,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAGhC,CAAC"}
|
||||
+364
@@ -0,0 +1,364 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
// prettier-ignore
|
||||
import { abytes, aexists, aoutput, bytesToHex, clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, wrapMacConstructor } from "./utils.js";
|
||||
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
|
||||
function u8to16(a, i) {
|
||||
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
|
||||
}
|
||||
function bytesToNumberLE(bytes) {
|
||||
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
|
||||
function poly1305_small(msg, key) {
|
||||
abytes(msg);
|
||||
abytes(key, 32, 'key');
|
||||
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
|
||||
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
|
||||
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
|
||||
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
|
||||
const s = bytesToNumberLE(key.subarray(16));
|
||||
// Process by 16 byte chunks
|
||||
let acc = BigInt(0);
|
||||
for (let i = 0; i < msg.length; i += 16) {
|
||||
const m = msg.subarray(i, i + 16);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
|
||||
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
|
||||
acc = ((acc + n) * r) % POW_2_130_5;
|
||||
}
|
||||
const res = (acc + s) & POW_2_128_1;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
|
||||
return numberToBytesBE(res, 16).reverse(); // LE
|
||||
}
|
||||
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
|
||||
// @ts-expect-error
|
||||
function poly1305_computeTag_small(authKey,
|
||||
// AEAD trailer must already be the 16-byte length block:
|
||||
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
|
||||
lengths, ciphertext, AAD) {
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
|
||||
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
|
||||
const res = [];
|
||||
const updatePadded2 = (msg) => {
|
||||
res.push(msg);
|
||||
const leftover = msg.length % 16;
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
|
||||
// inputs, else 16-(len%16) zero bytes.
|
||||
if (leftover)
|
||||
res.push(new Uint8Array(16).slice(leftover));
|
||||
};
|
||||
if (AAD)
|
||||
updatePadded2(AAD);
|
||||
updatePadded2(ciphertext);
|
||||
res.push(lengths);
|
||||
return poly1305_small(concatBytes(...res), authKey);
|
||||
}
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Poly1305 {
|
||||
blockLen = 16;
|
||||
outputLen = 16;
|
||||
buffer = new Uint8Array(16);
|
||||
r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
|
||||
h = new Uint16Array(10);
|
||||
pad = new Uint16Array(8);
|
||||
pos = 0;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
||||
constructor(key) {
|
||||
key = copyBytes(abytes(key, 32, 'key'));
|
||||
const t0 = u8to16(key, 0);
|
||||
const t1 = u8to16(key, 2);
|
||||
const t2 = u8to16(key, 4);
|
||||
const t3 = u8to16(key, 6);
|
||||
const t4 = u8to16(key, 8);
|
||||
const t5 = u8to16(key, 10);
|
||||
const t6 = u8to16(key, 12);
|
||||
const t7 = u8to16(key, 14);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
|
||||
// These masks unpack that clamped value into 13-bit limbs, while pad
|
||||
// keeps the raw s half for finalize().
|
||||
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
|
||||
this.r[0] = t0 & 0x1fff;
|
||||
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
|
||||
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
|
||||
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
|
||||
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
|
||||
this.r[5] = (t4 >>> 1) & 0x1ffe;
|
||||
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
|
||||
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
|
||||
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
|
||||
this.r[9] = (t7 >>> 5) & 0x007f;
|
||||
for (let i = 0; i < 8; i++)
|
||||
this.pad[i] = u8to16(key, 16 + 2 * i);
|
||||
}
|
||||
process(data, offset, isLast = false) {
|
||||
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
|
||||
// bit to every full 16-byte block. The final partial block gets its
|
||||
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
|
||||
const hibit = isLast ? 0 : 1 << 11;
|
||||
const { h, r } = this;
|
||||
const r0 = r[0];
|
||||
const r1 = r[1];
|
||||
const r2 = r[2];
|
||||
const r3 = r[3];
|
||||
const r4 = r[4];
|
||||
const r5 = r[5];
|
||||
const r6 = r[6];
|
||||
const r7 = r[7];
|
||||
const r8 = r[8];
|
||||
const r9 = r[9];
|
||||
const t0 = u8to16(data, offset + 0);
|
||||
const t1 = u8to16(data, offset + 2);
|
||||
const t2 = u8to16(data, offset + 4);
|
||||
const t3 = u8to16(data, offset + 6);
|
||||
const t4 = u8to16(data, offset + 8);
|
||||
const t5 = u8to16(data, offset + 10);
|
||||
const t6 = u8to16(data, offset + 12);
|
||||
const t7 = u8to16(data, offset + 14);
|
||||
let h0 = h[0] + (t0 & 0x1fff);
|
||||
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
|
||||
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
|
||||
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
|
||||
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
|
||||
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
|
||||
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
|
||||
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
|
||||
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
|
||||
let h9 = h[9] + ((t7 >>> 5) | hibit);
|
||||
let c = 0;
|
||||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
||||
c = d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
||||
c += d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
||||
c = d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
||||
c += d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
||||
c = d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
||||
c += d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
||||
c = d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
||||
c += d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
||||
c = d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
||||
c += d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
||||
c = d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
||||
c += d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
||||
c = d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
||||
c += d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
||||
c = d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
||||
c += d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
||||
c = d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
||||
c += d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
||||
c = d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
||||
c += d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
c = ((c << 2) + c) | 0;
|
||||
c = (c + d0) | 0;
|
||||
d0 = c & 0x1fff;
|
||||
c = c >>> 13;
|
||||
d1 += c;
|
||||
h[0] = d0;
|
||||
h[1] = d1;
|
||||
h[2] = d2;
|
||||
h[3] = d3;
|
||||
h[4] = d4;
|
||||
h[5] = d5;
|
||||
h[6] = d6;
|
||||
h[7] = d7;
|
||||
h[8] = d8;
|
||||
h[9] = d9;
|
||||
}
|
||||
finalize() {
|
||||
const { h, pad } = this;
|
||||
const g = new Uint16Array(10);
|
||||
let c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
for (let i = 2; i < 10; i++) {
|
||||
h[i] += c;
|
||||
c = h[i] >>> 13;
|
||||
h[i] &= 0x1fff;
|
||||
}
|
||||
h[0] += c * 5;
|
||||
c = h[0] >>> 13;
|
||||
h[0] &= 0x1fff;
|
||||
h[1] += c;
|
||||
c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
h[2] += c;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
|
||||
// to 16-bit words and adding the raw s half.
|
||||
g[0] = h[0] + 5;
|
||||
c = g[0] >>> 13;
|
||||
g[0] &= 0x1fff;
|
||||
for (let i = 1; i < 10; i++) {
|
||||
g[i] = h[i] + c;
|
||||
c = g[i] >>> 13;
|
||||
g[i] &= 0x1fff;
|
||||
}
|
||||
g[9] -= 1 << 13;
|
||||
let mask = (c ^ 1) - 1;
|
||||
for (let i = 0; i < 10; i++)
|
||||
g[i] &= mask;
|
||||
mask = ~mask;
|
||||
for (let i = 0; i < 10; i++)
|
||||
h[i] = (h[i] & mask) | g[i];
|
||||
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
|
||||
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
|
||||
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
|
||||
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
|
||||
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
|
||||
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
|
||||
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
|
||||
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
|
||||
let f = h[0] + pad[0];
|
||||
h[0] = f & 0xffff;
|
||||
for (let i = 1; i < 8; i++) {
|
||||
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
|
||||
h[i] = f & 0xffff;
|
||||
}
|
||||
clean(g);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const { buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
for (let pos = 0; pos < len;) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path: we have at least one block in input
|
||||
if (take === blockLen) {
|
||||
for (; blockLen <= len - pos; pos += blockLen)
|
||||
this.process(data, pos);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.process(buffer, 0, false);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy() {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
clean(this.h, this.r, this.buffer, this.pad);
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
const { buffer, h } = this;
|
||||
let { pos } = this;
|
||||
if (pos) {
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
|
||||
// single `0x01` byte and zero-fills the remaining bytes before the
|
||||
// last multiplication step.
|
||||
buffer[pos++] = 1;
|
||||
for (; pos < 16; pos++)
|
||||
buffer[pos] = 0;
|
||||
this.process(buffer, 0, true);
|
||||
}
|
||||
this.finalize();
|
||||
let opos = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[opos++] = h[i] >>> 0;
|
||||
out[opos++] = h[i] >>> 8;
|
||||
}
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Copy out before destroy() zeroes the internal buffer.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
|
||||
//# sourceMappingURL=_poly1305.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+121
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export declare function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
type Value = {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class GHASH implements IHash2 {
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
protected s0: number;
|
||||
protected s1: number;
|
||||
protected s2: number;
|
||||
protected s3: number;
|
||||
protected finished: boolean;
|
||||
protected destroyed: boolean;
|
||||
protected t: Value[];
|
||||
private W;
|
||||
private windowSize;
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number);
|
||||
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
destroy(): void;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare class Polyval extends GHASH {
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number);
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
}
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const ghash: TRet<CMac<GHASH, [expectedLength?: number]>>;
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const polyval: TRet<CMac<Polyval, [expectedLength?: number]>>;
|
||||
export {};
|
||||
//# sourceMappingURL=_polyval.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAWL,KAAK,IAAI,EACT,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAuCpB;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAcjE;AAED,KAAK,KAAK,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAUhE;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,KAAM,YAAW,MAAM;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAc;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAc;IACxC,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,EAAE,SAAK;IACjB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;IAC5B,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,CAAC,CAAS;IAClB,OAAO,CAAC,UAAU,CAAS;gBAEf,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAuC1D,SAAS,CAAC,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IA0B5E,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,OAAO,IAAI,IAAI;IAWf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAiBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAO3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,OAAQ,SAAQ,KAAK;gBACpB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAS1D,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;CAkBxC;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAK5D,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAKhE,CAAC"}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { abytes, aexists, aoutput, clean, copyBytes, createView, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from "./utils.js";
|
||||
const BLOCK_SIZE = 16;
|
||||
// TODO: rewrite
|
||||
// temporary padding buffer
|
||||
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
|
||||
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
|
||||
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
|
||||
const POLY = 0xe1;
|
||||
// v = 2*v % POLY
|
||||
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
|
||||
// Montgomery ladder can multiply any field element with this doubling step;
|
||||
// addition stays simple xor.
|
||||
const mul2 = (s0, s1, s2, s3) => {
|
||||
const hiBit = s3 & 1;
|
||||
return {
|
||||
s3: (s2 << 31) | (s3 >>> 1),
|
||||
s2: (s1 << 31) | (s2 >>> 1),
|
||||
s1: (s0 << 31) | (s1 >>> 1),
|
||||
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
|
||||
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
|
||||
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
|
||||
};
|
||||
};
|
||||
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
|
||||
const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
|
||||
(((n >>> 8) & 0xff) << 16) |
|
||||
(((n >>> 16) & 0xff) << 8) |
|
||||
((n >>> 24) & 0xff) |
|
||||
0;
|
||||
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
|
||||
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
|
||||
const swap8IfLE = (n) => swap8IfBE(swapLE(n));
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export function _toGHASHKey(k) {
|
||||
// The input is the original POLYVAL key H; reverse() materializes
|
||||
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
|
||||
k.reverse();
|
||||
const hiBit = k[15] & 1;
|
||||
// k >>= 1
|
||||
let carry = 0;
|
||||
for (let i = 0; i < k.length; i++) {
|
||||
const t = k[i];
|
||||
k[i] = (t >>> 1) | carry;
|
||||
carry = (t & 1) << 7;
|
||||
}
|
||||
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
|
||||
return k;
|
||||
}
|
||||
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
|
||||
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
|
||||
const estimateWindow = (bytes) => {
|
||||
if (bytes > 64 * 1024)
|
||||
return 8;
|
||||
if (bytes > 1024)
|
||||
return 4;
|
||||
return 2;
|
||||
};
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class GHASH {
|
||||
blockLen = BLOCK_SIZE;
|
||||
outputLen = BLOCK_SIZE;
|
||||
s0 = 0;
|
||||
s1 = 0;
|
||||
s2 = 0;
|
||||
s3 = 0;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
t;
|
||||
W;
|
||||
windowSize;
|
||||
// We select bits per window adaptively based on expectedLength
|
||||
constructor(key, expectedLength) {
|
||||
abytes(key, 16, 'key');
|
||||
key = copyBytes(key);
|
||||
const kView = createView(key);
|
||||
let k0 = kView.getUint32(0, false);
|
||||
let k1 = kView.getUint32(4, false);
|
||||
let k2 = kView.getUint32(8, false);
|
||||
let k3 = kView.getUint32(12, false);
|
||||
// generate table of doubled keys (half of montgomery ladder)
|
||||
const doubles = [];
|
||||
for (let i = 0; i < 128; i++) {
|
||||
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
|
||||
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
|
||||
}
|
||||
const W = estimateWindow(expectedLength || 1024);
|
||||
if (![1, 2, 4, 8].includes(W))
|
||||
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
|
||||
this.W = W;
|
||||
const bits = 128; // always 128 bits;
|
||||
const windows = bits / W;
|
||||
const windowSize = (this.windowSize = 2 ** W);
|
||||
const items = [];
|
||||
// Create precompute table for window of W bits
|
||||
for (let w = 0; w < windows; w++) {
|
||||
// truth table: 00, 01, 10, 11
|
||||
for (let byte = 0; byte < windowSize; byte++) {
|
||||
// prettier-ignore
|
||||
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
|
||||
for (let j = 0; j < W; j++) {
|
||||
const bit = (byte >>> (W - j - 1)) & 1;
|
||||
if (!bit)
|
||||
continue;
|
||||
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
|
||||
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
|
||||
}
|
||||
items.push({ s0, s1, s2, s3 });
|
||||
}
|
||||
}
|
||||
this.t = items;
|
||||
}
|
||||
_updateBlock(s0, s1, s2, s3) {
|
||||
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
|
||||
const { W, t, windowSize } = this;
|
||||
// prettier-ignore
|
||||
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
|
||||
const mask = (1 << W) - 1; // 2**W will kill performance.
|
||||
let w = 0;
|
||||
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
|
||||
// so the lookup walk consumes each word byte-by-byte from
|
||||
// least-significant to most-significant bits.
|
||||
for (const num of [s0, s1, s2, s3]) {
|
||||
for (let bytePos = 0; bytePos < 4; bytePos++) {
|
||||
const byte = (num >>> (8 * bytePos)) & 0xff;
|
||||
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
|
||||
const bit = (byte >>> (W * bitPos)) & mask;
|
||||
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
|
||||
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
|
||||
w += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.s0 = o0;
|
||||
this.s1 = o1;
|
||||
this.s2 = o2;
|
||||
this.s3 = o3;
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
|
||||
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
|
||||
this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
|
||||
clean(ZEROS32); // clean tmp buffer
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy() {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
const { t } = this;
|
||||
// Wipe the key-derived precompute table; scalar accumulator words remain,
|
||||
// but the destroyed guard blocks further use.
|
||||
// clean precompute table
|
||||
for (const elm of t) {
|
||||
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
|
||||
}
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only
|
||||
// out[0..15] may be touched.
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(out);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
}
|
||||
digest() {
|
||||
const res = new Uint8Array(BLOCK_SIZE);
|
||||
this.digestInto(res);
|
||||
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Polyval extends GHASH {
|
||||
constructor(key, expectedLength) {
|
||||
abytes(key);
|
||||
// RFC 8452 Appendix A converts the POLYVAL key with
|
||||
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
|
||||
// mutates in place.
|
||||
const ghKey = _toGHASHKey(copyBytes(key));
|
||||
super(ghKey, expectedLength);
|
||||
clean(ghKey);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
|
||||
// reverses the 32-bit word order in addition to the per-word byte swap.
|
||||
this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
|
||||
clean(ZEROS32);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
|
||||
const view = out.subarray(0, this.outputLen);
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(view);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
view.reverse();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const ghash =
|
||||
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const polyval =
|
||||
/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);
|
||||
//# sourceMappingURL=_polyval.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+462
@@ -0,0 +1,462 @@
|
||||
import { type Cipher, type CipherWithOutput, type CMac, type IHash2, type PRG, type TArg, type TRet, type Uint8ArrayBuffer } from './utils.ts';
|
||||
/**
|
||||
* Increments a counter block with wrap around.
|
||||
* AES call sites here currently use the big-endian branch, but the helper supports both layouts.
|
||||
* NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the
|
||||
* least-significant/rightmost bits.
|
||||
* `isLE=false` matches that standard counter-block layout, while `isLE=true`
|
||||
* is a generic extension for non-AES callers.
|
||||
* The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;
|
||||
* larger values throw instead of silently overflowing before the next-byte propagation step.
|
||||
*/
|
||||
declare const incBytes: (data: TArg<Uint8Array>, isLE: boolean, carry?: number) => void;
|
||||
/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */
|
||||
declare function expandKeyLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
|
||||
declare function expandKeyDecLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
|
||||
declare function encrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
declare function decrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
|
||||
s0: number;
|
||||
s1: number;
|
||||
s2: number;
|
||||
s3: number;
|
||||
};
|
||||
declare function ctrCounter(xk: TArg<Uint32Array>, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
declare function ctr32(xk: TArg<Uint32Array>, isLE: boolean, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* **CTR** (Counter Mode): turns a block cipher into a stream cipher using a
|
||||
* full 16-byte counter block.
|
||||
* Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block, incremented as a full AES block.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a short payload with a fresh AES key and counter block.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/** Options for ECB and CBC. */
|
||||
export type BlockOpts = {
|
||||
/** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */
|
||||
disablePadding?: boolean;
|
||||
};
|
||||
/**
|
||||
* **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield
|
||||
* identical ciphertexts. Not secure due to pattern leakage.
|
||||
* See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.
|
||||
* @param key - AES key bytes.
|
||||
* @param opts - Padding options. See {@link BlockOpts}.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.
|
||||
*
|
||||
* ```ts
|
||||
* import { ecb } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const cipher = ecb(key);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ecb: TRet<((key: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
/**
|
||||
* **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the
|
||||
* previous block of ciphertext before encryption.
|
||||
* Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte unpredictable initialization vector.
|
||||
* @param opts - Padding options. See {@link BlockOpts}.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a padded message with a fresh key and 16-byte IV.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the
|
||||
* block cipher is the previous cipher output.
|
||||
* Unauthenticated: needs MAC.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte unpredictable initialization vector.
|
||||
* @returns Cipher instance with `encrypt()` and `decrypt()`.
|
||||
* @example
|
||||
* Encrypts a short message with feedback mode and a fresh key/IV pair.
|
||||
*
|
||||
* ```ts
|
||||
* import { cfb } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cfb(key, iv);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const cfb: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
|
||||
* Not perfect:
|
||||
* a) conservative key wear-out is `2**32` (4B) msgs.
|
||||
* b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
|
||||
* c) MAC can be forged: see Poly1305 documentation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance with a fixed 16-byte tag.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
varSizeNonce: true;
|
||||
}>;
|
||||
/**
|
||||
* **SIV** (Synthetic IV): GCM with nonce-misuse resistance.
|
||||
* Repeating nonces reveal only the fact plaintexts are identical.
|
||||
* Also suffers from GCM issues: key wear-out limits & MAC forging.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
* RFC 8452 defines 16-byte and 32-byte AES keys for this mode.
|
||||
* This implementation also accepts 24-byte AES-192 keys as a local
|
||||
* extension; see the inline comment next to `validateKeyLength(key)` below
|
||||
* for the exact scope note.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcmsiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcmsiv(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcmsiv: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
varSizeNonce: true;
|
||||
}>;
|
||||
declare function encryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
declare function decryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
|
||||
* Reduces block size from 16 to 8 bytes.
|
||||
* Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.
|
||||
* 8-byte inputs use aeskwp.
|
||||
* Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.
|
||||
* For padded version, use aeskwp.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.
|
||||
* @param kek - AES key-encryption key.
|
||||
* @returns Key-wrap cipher instance.
|
||||
* As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per
|
||||
* instance.
|
||||
* @example
|
||||
* Wraps a 128-bit content-encryption key with a fresh key-encryption key.
|
||||
*
|
||||
* ```ts
|
||||
* import { aeskw } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const kek = randomBytes(16);
|
||||
* const cek = randomBytes(16);
|
||||
* const wrap = aeskw(kek);
|
||||
* wrap.encrypt(cek);
|
||||
* ```
|
||||
*/
|
||||
export declare const aeskw: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-KW, but with padding and allows random keys.
|
||||
* Uses the RFC 5649 alternative initial value; the second u32 stores the
|
||||
* 32-bit MLI in network order.
|
||||
* Wrapped ciphertext must be at least 16 bytes; malformed lengths are
|
||||
* rejected during AIV/padding checks.
|
||||
* See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
|
||||
* @param kek - AES key-encryption key.
|
||||
* @returns Padded key-wrap cipher instance.
|
||||
* @example
|
||||
* Wraps a short key blob using the padded variant and a fresh key-encryption key.
|
||||
*
|
||||
* ```ts
|
||||
* import { aeskwp } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const kek = randomBytes(16);
|
||||
* const wrap = aeskwp(kek);
|
||||
* wrap.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const aeskwp: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
|
||||
blockSize: number;
|
||||
}>;
|
||||
declare class _AesCtrDRBG implements PRG {
|
||||
readonly blockLen: number;
|
||||
private key;
|
||||
private nonce;
|
||||
private state;
|
||||
private reseedCnt;
|
||||
constructor(keyLen: number, seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>);
|
||||
private update;
|
||||
addEntropy(seed: TArg<Uint8Array>, info?: TArg<Uint8Array>): void;
|
||||
randomBytes(len: number, info?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
clean(): void;
|
||||
}
|
||||
/**
|
||||
* Factory for AES-CTR DRBG instances.
|
||||
* @param seed - Initial entropy input.
|
||||
* @param personalization - Optional personalization string mixed into the state.
|
||||
* @returns Seeded AES-CTR DRBG instance.
|
||||
*/
|
||||
export type AesCtrDrbg = (seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>) => TRet<_AesCtrDRBG>;
|
||||
/**
|
||||
* AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* @param seed - Initial 32-byte entropy input.
|
||||
* @param personalization - Optional personalization string.
|
||||
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
|
||||
* @example
|
||||
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngAesCtrDrbg128(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngAesCtrDrbg128: TRet<AesCtrDrbg>;
|
||||
/**
|
||||
* AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* @param seed - Initial 48-byte entropy input.
|
||||
* @param personalization - Optional personalization string.
|
||||
* @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
|
||||
* @example
|
||||
* Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(48);
|
||||
* const prg = rngAesCtrDrbg256(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngAesCtrDrbg256: TRet<AesCtrDrbg>;
|
||||
/**
|
||||
* Left-shift by one bit and conditionally XOR with 0x87:
|
||||
* ```
|
||||
* if MSB(L) is equal to 0
|
||||
* then K1 := L << 1;
|
||||
* else K1 := (L << 1) XOR const_Rb;
|
||||
* ```
|
||||
*
|
||||
* Specs:
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}
|
||||
*
|
||||
* @returns modified `block` (for chaining)
|
||||
*/
|
||||
declare function dbl<T extends Uint8Array>(block: T): T;
|
||||
/**
|
||||
* `a XOR b`, running in-place on `a`.
|
||||
* @param a left operand and output
|
||||
* @param b right operand
|
||||
* @returns `a` (for chaining)
|
||||
*/
|
||||
declare function xorBlock<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
|
||||
/**
|
||||
* xorend as defined in
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.
|
||||
*
|
||||
* ```
|
||||
* leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)
|
||||
* ```
|
||||
*
|
||||
* Mutates `a` in place so the left prefix stays untouched and only the
|
||||
* rightmost `len(B)` bytes are xored with `b`.
|
||||
*/
|
||||
declare function xorend<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
|
||||
/**
|
||||
* Internal CMAC class.
|
||||
*/
|
||||
declare class _CMAC implements IHash2 {
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
private buffer;
|
||||
private pos;
|
||||
private finished;
|
||||
private destroyed;
|
||||
private k1;
|
||||
private k2;
|
||||
private x;
|
||||
private xk;
|
||||
constructor(key: TArg<Uint8Array>);
|
||||
private process;
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): Uint8ArrayBuffer;
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* AES-CMAC (Cipher-based Message Authentication Code).
|
||||
* Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - AES key bytes.
|
||||
* @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as
|
||||
* the other keyed helpers in this repo, including `blockLen`,
|
||||
* `outputLen`, `digestInto()` and `destroy()`.
|
||||
* @example
|
||||
* Authenticates a message with AES-CMAC and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { cmac } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* cmac(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export declare const cmac: TRet<CMac<_CMAC>>;
|
||||
/**
|
||||
* S2V (Synthetic Initialization Vector) function as described in
|
||||
* {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.
|
||||
*
|
||||
* ```
|
||||
* S2V(K, S1, ..., Sn) {
|
||||
* if n = 0 then
|
||||
* return V = AES-CMAC(K, <one>)
|
||||
* fi
|
||||
* D = AES-CMAC(K, <zero>)
|
||||
* for i = 1 to n-1 do
|
||||
* D = dbl(D) xor AES-CMAC(K, Si)
|
||||
* done
|
||||
* if len(Sn) >= 128 then
|
||||
* T = Sn xorend D
|
||||
* else
|
||||
* T = dbl(D) xor pad(Sn)
|
||||
* fi
|
||||
* return V = AES-CMAC(K, T)
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.
|
||||
* The S2V function is used to generate a synthetic IV for AES-SIV.
|
||||
*
|
||||
* @param key - AES key (128, 192, or 256 bits)
|
||||
* @param strings - Array of byte arrays to process
|
||||
* @returns 128-bit synthetic IV
|
||||
*/
|
||||
declare function s2v(key: TArg<Uint8Array>, strings: TArg<Uint8Array[]>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Use `gcmsiv` or `aessiv`.
|
||||
* @returns Never; always throws with the migration hint.
|
||||
* @throws If called; `siv()` is a removed v1 alias. {@link Error}
|
||||
* @example
|
||||
* `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcmsiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcmsiv(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const siv: () => never;
|
||||
/**
|
||||
* **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption
|
||||
* Nonce is derived from the plaintext and AAD using the S2V function.
|
||||
* Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by
|
||||
* passing the nonce as the final AAD component before the plaintext.
|
||||
* See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.
|
||||
* @param key - 32-byte, 48-byte, or 64-byte key.
|
||||
* @param AAD - Additional authenticated data chunks (up to 126).
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.
|
||||
*
|
||||
* ```ts
|
||||
* import { aessiv } from '@noble/ciphers/aes.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const cipher = aessiv(key);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const aessiv: TRet<((key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>) => Cipher) & {
|
||||
blockSize: number;
|
||||
tagLength: number;
|
||||
}>;
|
||||
/**
|
||||
* Unsafe low-level internal methods. May change at any time.
|
||||
* Callers are expected to use reviewed expanded-key outputs, pass mutable and
|
||||
* aligned 16-byte blocks where required, and treat several helpers as in-place
|
||||
* mutations of their input buffers or counters.
|
||||
*/
|
||||
export declare const unsafe: {
|
||||
expandKeyLE: typeof expandKeyLE;
|
||||
expandKeyDecLE: typeof expandKeyDecLE;
|
||||
encrypt: typeof encrypt;
|
||||
decrypt: typeof decrypt;
|
||||
encryptBlock: typeof encryptBlock;
|
||||
decryptBlock: typeof decryptBlock;
|
||||
ctrCounter: typeof ctrCounter;
|
||||
ctr32: typeof ctr32;
|
||||
dbl: typeof dbl;
|
||||
xorBlock: typeof xorBlock;
|
||||
xorend: typeof xorend;
|
||||
s2v: typeof s2v;
|
||||
};
|
||||
export declare const __TESTS: {
|
||||
incBytes: typeof incBytes;
|
||||
};
|
||||
export {};
|
||||
//# sourceMappingURL=aes.d.ts.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1765
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+249
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type XorPRG } from './_arx.ts';
|
||||
import { type ARXCipher, type CipherWithOutput, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
declare const chachaCore_small: typeof chachaCore;
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
declare function chachaCore(s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds?: number): void;
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
export declare function hchacha(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20orig: TRet<XorStream>;
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20: TRet<XorStream>;
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const xchacha20: TRet<XorStream>;
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha8: TRet<XorStream>;
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha12: TRet<XorStream>;
|
||||
export declare const __TESTS: {
|
||||
chachaCore_small: typeof chachaCore_small;
|
||||
chachaCore: typeof chachaCore;
|
||||
};
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export declare const _poly1305_aead: (xorStream: TArg<XorStream>) => (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput;
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const chacha20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xchacha20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngChacha20: TRet<XorPRG>;
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export declare const rngChacha8: TRet<XorPRG>;
|
||||
export {};
|
||||
//# sourceMappingURL=chacha.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,KAAK,MAAM,EAAiC,MAAM,WAAW,CAAC;AAEvE,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAkEpB,sFAAsF;AAEtF,QAAA,MAAM,gBAAgB,EAAE,OAAO,UAE8C,CAAC;AAK9E,gFAAgF;AAEhF,iBAAS,UAAU,CACjB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,SAAK,GACjH,IAAI,CA6DN;AACD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CAqDN;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,SAAS,CAIvC,CAAC;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,SAAS,CAKpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAIlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAGH,eAAO,MAAM,OAAO,EAAE;IACpB,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;IAC1C,UAAU,EAAE,OAAO,UAAU,CAAC;CACmC,CAAC;AA0CpE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,IAAI,CAAC,SAAS,CAAC,MAC1B,KAAK,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC,UAAU,CAAC,KAAG,gBA+CzE,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAG5C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAG7C,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,MAAM,CAAsD,CAAC;AAC5F;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,MAAM,CAAkD,CAAC"}
|
||||
+575
@@ -0,0 +1,575 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, createPRG, rotl } from "./_arx.js";
|
||||
import { poly1305 } from "./_poly1305.js";
|
||||
import { abytes, clean, equalBytes, getOutput, swap8IfBE, swap32IfBE, u64Lengths, wrapCipher, } from "./utils.js";
|
||||
/**
|
||||
* ChaCha core function. It is implemented twice:
|
||||
* 1. Simple loop (chachaCore_small, hchacha_small)
|
||||
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
*/
|
||||
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
|
||||
// prettier-ignore
|
||||
function chachaQR(x, a, b, c, d) {
|
||||
x[a] = (x[a] + x[b]) | 0;
|
||||
x[d] = rotl(x[d] ^ x[a], 16);
|
||||
x[c] = (x[c] + x[d]) | 0;
|
||||
x[b] = rotl(x[b] ^ x[c], 12);
|
||||
x[a] = (x[a] + x[b]) | 0;
|
||||
x[d] = rotl(x[d] ^ x[a], 8);
|
||||
x[c] = (x[c] + x[d]) | 0;
|
||||
x[b] = rotl(x[b] ^ x[c], 7);
|
||||
}
|
||||
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
|
||||
function chachaRound(x, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
|
||||
chachaQR(x, 0, 4, 8, 12);
|
||||
chachaQR(x, 1, 5, 9, 13);
|
||||
chachaQR(x, 2, 6, 10, 14);
|
||||
chachaQR(x, 3, 7, 11, 15);
|
||||
chachaQR(x, 0, 5, 10, 15);
|
||||
chachaQR(x, 1, 6, 11, 12);
|
||||
chachaQR(x, 2, 7, 8, 13);
|
||||
chachaQR(x, 3, 4, 9, 14);
|
||||
}
|
||||
}
|
||||
// Shared scratch for the auditability-only helper below; only the test-only
|
||||
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
|
||||
const ctmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function chacha(s, k, i, out, isHChacha = true, rounds = 20) {
|
||||
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
|
||||
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
k[0], k[1], k[2], k[3], // Key Key Key Key
|
||||
k[4], k[5], k[6], k[7], // Key Key Key Key
|
||||
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
|
||||
]);
|
||||
const x = ctmp;
|
||||
x.set(y);
|
||||
chachaRound(x, rounds);
|
||||
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
|
||||
// block path adds the original state word-by-word.
|
||||
if (isHChacha) {
|
||||
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
|
||||
for (let i = 0; i < 8; i++)
|
||||
out[i] = x[xindexes[i]];
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < 16; i++)
|
||||
out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
// @ts-ignore
|
||||
const chachaCore_small = (s, k, n, out, cnt, rounds) =>
|
||||
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
|
||||
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
|
||||
/** Identical to `hchacha`. Unused. */
|
||||
// @ts-ignore
|
||||
const hchacha_small = chacha;
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
// prettier-ignore
|
||||
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
|
||||
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
|
||||
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 7);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 7);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 7);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 8);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 7);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 7);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 7);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 7);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 16);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0;
|
||||
out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0;
|
||||
out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0;
|
||||
out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0;
|
||||
out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0;
|
||||
out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0;
|
||||
out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0;
|
||||
out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0;
|
||||
out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hchacha(s, k, i, out) {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0;
|
||||
x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0;
|
||||
x04 = rotl(x04 ^ x08, 7);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0;
|
||||
x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0;
|
||||
x05 = rotl(x05 ^ x09, 7);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0;
|
||||
x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0;
|
||||
x06 = rotl(x06 ^ x10, 7);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0;
|
||||
x15 = rotl(x15 ^ x03, 8);
|
||||
x11 = (x11 + x15) | 0;
|
||||
x07 = rotl(x07 ^ x11, 7);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0;
|
||||
x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0;
|
||||
x05 = rotl(x05 ^ x10, 7);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0;
|
||||
x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0;
|
||||
x06 = rotl(x06 ^ x11, 7);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0;
|
||||
x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0;
|
||||
x07 = rotl(x07 ^ x08, 7);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 16);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0;
|
||||
x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0;
|
||||
x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
|
||||
let oi = 0;
|
||||
out[oi++] = x00;
|
||||
out[oi++] = x01;
|
||||
out[oi++] = x02;
|
||||
out[oi++] = x03;
|
||||
out[oi++] = x12;
|
||||
out[oi++] = x13;
|
||||
out[oi++] = x14;
|
||||
out[oi++] = x15;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
allowShortKeys: true,
|
||||
});
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
extendNonceFn: hchacha,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 8,
|
||||
});
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 12,
|
||||
});
|
||||
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
|
||||
export const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
|
||||
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
|
||||
const updatePadded = (h, msg) => {
|
||||
h.update(msg);
|
||||
const leftover = msg.length % 16;
|
||||
if (leftover)
|
||||
h.update(ZEROS16.subarray(leftover));
|
||||
};
|
||||
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
|
||||
// generation only needs 32 zero bytes.
|
||||
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
||||
function computeTag(fn, key, nonce, ciphertext, AAD) {
|
||||
if (AAD !== undefined)
|
||||
abytes(AAD, undefined, 'AAD');
|
||||
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
|
||||
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
|
||||
const authKey = fn(key, nonce, ZEROS32);
|
||||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
||||
// Methods below can be replaced with
|
||||
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
|
||||
const h = poly1305.create(authKey);
|
||||
if (AAD)
|
||||
updatePadded(h, AAD);
|
||||
updatePadded(h, ciphertext);
|
||||
h.update(lengths);
|
||||
const res = h.digest();
|
||||
clean(authKey, lengths);
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
|
||||
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
|
||||
// changes future encrypt/decrypt results.
|
||||
const tagLength = 16;
|
||||
return {
|
||||
encrypt(plaintext, output) {
|
||||
const plength = plaintext.length;
|
||||
output = getOutput(plength + tagLength, output, false);
|
||||
output.set(plaintext);
|
||||
const oPlain = output.subarray(0, -tagLength);
|
||||
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
|
||||
xorStream(key, nonce, oPlain, oPlain, 1);
|
||||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
||||
output.set(tag, plength); // append tag
|
||||
clean(tag);
|
||||
return output;
|
||||
},
|
||||
decrypt(ciphertext, output) {
|
||||
output = getOutput(ciphertext.length - tagLength, output, false);
|
||||
const data = ciphertext.subarray(0, -tagLength);
|
||||
const passedTag = ciphertext.subarray(-tagLength);
|
||||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
||||
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
|
||||
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(tag);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
output.set(ciphertext.subarray(0, -tagLength));
|
||||
// Actual decryption
|
||||
xorStream(key, nonce, output, output, 1); // start stream with i=1
|
||||
clean(tag);
|
||||
return output;
|
||||
},
|
||||
};
|
||||
};
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(chacha20));
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(xchacha20));
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
|
||||
//# sourceMappingURL=chacha.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+40
@@ -0,0 +1,40 @@
|
||||
import { type Cipher, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export declare function FF1(radix: number, key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): {
|
||||
encrypt(x: number[]): number[];
|
||||
decrypt(x: number[]): number[];
|
||||
};
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare function BinaryFF1(key: TArg<Uint8Array>, tweak?: TArg<Uint8Array>): TRet<Cipher>;
|
||||
//# sourceMappingURL=ff1.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAqGpB;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAkCpE;AAsBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC,IAAI,CAAC,MAAM,CAAC,CAQd"}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* FPE-FF1 (Format-preserving encryption algorithm) specified in
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
|
||||
* @module
|
||||
*/
|
||||
import { unsafe } from "./aes.js";
|
||||
import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE, } from "./utils.js";
|
||||
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
|
||||
// reuses the reviewed AES key schedule and single-block encryption helpers.
|
||||
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
|
||||
const { expandKeyLE, encryptBlock } = unsafe;
|
||||
// Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
|
||||
const BLOCK_LEN = 16;
|
||||
function mod(a, b) {
|
||||
const result = a % b;
|
||||
return result >= 0 ? result : b + result;
|
||||
}
|
||||
function NUMradix(radix, data) {
|
||||
let res = BigInt(0);
|
||||
for (let i of data)
|
||||
res = res * BigInt(radix) + BigInt(i);
|
||||
return res;
|
||||
}
|
||||
function getRound(radix, key, tweak, x) {
|
||||
if (radix > 2 ** 16 - 1)
|
||||
throw new Error('invalid radix ' + radix);
|
||||
// radix**minlen ≥ 100
|
||||
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
|
||||
const maxLen = 2 ** 32 - 1;
|
||||
// 2 ≤ minlen ≤ maxlen < 2**32
|
||||
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
|
||||
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
|
||||
if (!Array.isArray(x))
|
||||
throw new Error('invalid X');
|
||||
if (x.length < minLen || x.length > maxLen)
|
||||
throw new Error('X is outside minLen..maxLen bounds');
|
||||
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
|
||||
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
|
||||
for (const i of x) {
|
||||
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
|
||||
throw new Error('invalid X: digit outside radix');
|
||||
}
|
||||
const u = Math.floor(x.length / 2);
|
||||
const v = x.length - u;
|
||||
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
|
||||
const d = 4 * Math.ceil(b / 4) + 4;
|
||||
const padding = mod(-tweak.length - b - 1, 16);
|
||||
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
|
||||
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
const view = new DataView(P.buffer);
|
||||
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
|
||||
// 0x00 || uint16_be(radix).
|
||||
view.setUint16(4, radix, false);
|
||||
view.setUint32(8, x.length, false);
|
||||
view.setUint32(12, tweak.length, false);
|
||||
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
|
||||
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
|
||||
PQ.set(P);
|
||||
clean(P);
|
||||
PQ.set(tweak, P.length);
|
||||
const xk = expandKeyLE(key);
|
||||
const round = (A, B, i, decrypt = false) => {
|
||||
// Q = ... || [i]1 || [NUMradix(B)]b.
|
||||
PQ[PQ.length - b - 1] = i;
|
||||
if (b)
|
||||
PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
|
||||
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
|
||||
let r = new Uint8Array(16);
|
||||
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
|
||||
for (let i = 0; i < BLOCK_LEN; i++)
|
||||
r[i] ^= PQ[j * BLOCK_LEN + i];
|
||||
encryptBlock(xk, r);
|
||||
}
|
||||
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
|
||||
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
|
||||
let s = Array.from(r);
|
||||
for (let j = 1; s.length < d; j++) {
|
||||
const block = numberToBytesBE(BigInt(j), 16);
|
||||
for (let k = 0; k < BLOCK_LEN; k++)
|
||||
block[k] ^= r[k];
|
||||
s.push(...Array.from(encryptBlock(xk, block)));
|
||||
}
|
||||
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
|
||||
s.fill(0);
|
||||
if (decrypt)
|
||||
y = -y;
|
||||
const m = i % 2 === 0 ? u : v;
|
||||
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
|
||||
// STR(radix, m, c)
|
||||
const C = Array(m).fill(0);
|
||||
for (let i = 0; i < m; i++, c /= BigInt(radix))
|
||||
C[m - 1 - i] = Number(c % BigInt(radix));
|
||||
A.fill(0);
|
||||
A = B;
|
||||
B = C;
|
||||
return [A, B];
|
||||
};
|
||||
const destroy = () => {
|
||||
clean(xk, PQ);
|
||||
};
|
||||
return { u, round, destroy };
|
||||
}
|
||||
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export function FF1(radix, key, tweak = EMPTY_BUF) {
|
||||
anumber(radix);
|
||||
abytes(key);
|
||||
abytes(tweak);
|
||||
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
|
||||
// after construction changes later encrypt/decrypt outputs.
|
||||
const PQ = getRound.bind(null, radix, key, tweak);
|
||||
return {
|
||||
encrypt(x) {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
let [A, B] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 0; i < 10; i++)
|
||||
[A, B] = round(A, B, i);
|
||||
destroy();
|
||||
const res = A.concat(B);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
decrypt(x) {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
|
||||
// the differences are in Step 6, where:
|
||||
// 1) the order of the indices is reversed,
|
||||
// 2) the roles of A and B are swapped
|
||||
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
|
||||
let [B, A] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 9; i >= 0; i--)
|
||||
[A, B] = round(A, B, i, true);
|
||||
destroy();
|
||||
const res = B.concat(A);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
|
||||
// in the first numeral slot for this library-defined byte-array surface.
|
||||
const binLE = {
|
||||
encode(bytes) {
|
||||
const x = [];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1)
|
||||
x.push(tmp & 1);
|
||||
}
|
||||
return x;
|
||||
},
|
||||
decode(b) {
|
||||
if (!Array.isArray(b) || b.length % 8)
|
||||
throw new Error('Invalid binary string');
|
||||
const res = new Uint8Array(b.length / 8);
|
||||
for (let i = 0, j = 0; i < res.length; i++) {
|
||||
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
|
||||
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
|
||||
}
|
||||
return res;
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function BinaryFF1(key, tweak = EMPTY_BUF) {
|
||||
const ff1 = FF1(2, key, tweak);
|
||||
return {
|
||||
encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))),
|
||||
decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))),
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=ff1.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2
@@ -0,0 +1,2 @@
|
||||
export {};
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
|
||||
* @example
|
||||
```js
|
||||
import { gcm, aessiv } from '@noble/ciphers/aes.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// KW
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
|
||||
// Utilities
|
||||
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
|
||||
import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
|
||||
```
|
||||
* @module
|
||||
*/
|
||||
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
||||
export {};
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"name": "@noble/ciphers",
|
||||
"version": "2.2.0",
|
||||
"description": "Audited & minimal JS implementation of Salsa20, ChaCha and AES",
|
||||
"files": [
|
||||
"src",
|
||||
"*.js",
|
||||
"*.js.map",
|
||||
"*.d.ts",
|
||||
"*.d.ts.map"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@paulmillr/jsbt": "0.5.0",
|
||||
"@scure/base": "2.0.0",
|
||||
"@types/node": "25.3.0",
|
||||
"fast-check": "4.2.0",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "6.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"bench": "node test/benchmark/noble.ts",
|
||||
"bench:compare": "cd test/benchmark; npm install; node compare.ts",
|
||||
"build": "tsc",
|
||||
"build:release": "npx --no @paulmillr/jsbt esbuild test/build",
|
||||
"check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc",
|
||||
"check:readme": "npx --no @paulmillr/jsbt readme package.json",
|
||||
"check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake",
|
||||
"check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json",
|
||||
"build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null",
|
||||
"format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'",
|
||||
"test": "node test/index.ts",
|
||||
"test:bun": "bun test/index.ts",
|
||||
"test:deno": "deno --allow-env --allow-read test/index.ts",
|
||||
"test:node20": "cd test; npx tsc; node compiled/test/index.js",
|
||||
"test:slow": "node test/crosstest.test.ts slow"
|
||||
},
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./_arx.js": "./_arx.js",
|
||||
"./_poly1305.js": "./_poly1305.js",
|
||||
"./_polyval.js": "./_polyval.js",
|
||||
"./aes.js": "./aes.js",
|
||||
"./chacha.js": "./chacha.js",
|
||||
"./ff1.js": "./ff1.js",
|
||||
"./salsa.js": "./salsa.js",
|
||||
"./utils.js": "./utils.js",
|
||||
"./webcrypto.js": "./webcrypto.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"keywords": [
|
||||
"salsa20",
|
||||
"chacha",
|
||||
"aes",
|
||||
"cryptography",
|
||||
"crypto",
|
||||
"noble",
|
||||
"cipher",
|
||||
"ciphers",
|
||||
"xsalsa20",
|
||||
"xchacha20",
|
||||
"poly1305",
|
||||
"xsalsa20poly1305",
|
||||
"chacha20poly1305",
|
||||
"xchacha20poly1305",
|
||||
"secretbox",
|
||||
"rijndael",
|
||||
"siv",
|
||||
"ff1"
|
||||
],
|
||||
"homepage": "https://paulmillr.com/noble/",
|
||||
"funding": "https://paulmillr.com/funding/",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/paulmillr/noble-ciphers.git"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"module": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"sideEffects": false,
|
||||
"author": "Paul Miller (https://paulmillr.com)",
|
||||
"license": "MIT"
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { type ARXCipher, type TArg, type TRet, type XorStream } from './utils.ts';
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
export declare function hsalsa(s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>): void;
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export declare const salsa20: TRet<XorStream>;
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xsalsa20: TRet<XorStream>;
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const xsalsa20poly1305: TRet<ARXCipher>;
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare function secretbox(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}>;
|
||||
//# sourceMappingURL=salsa.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAqBA,OAAO,EAQL,KAAK,SAAS,EAEd,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAuHpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CA8BN;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAGlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAGnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAwD5C,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC;IACN,IAAI,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IACnF,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;CACrF,CAAC,CAMD"}
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* Salsa20 stream cipher, released in 2005.
|
||||
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
* which are hard to implement in a constant-time manner.
|
||||
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
*
|
||||
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
|
||||
* extended-nonce
|
||||
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
|
||||
* and became safe to be picked at random.
|
||||
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
* We provide the alias and corresponding seal / open methods.
|
||||
* "crypto_box" and "sealedbox" are available in package
|
||||
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
|
||||
* - Check out
|
||||
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
|
||||
* and {@link https://cr.yp.to/snuffle.html | website}.
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, rotl } from "./_arx.js";
|
||||
import { poly1305 } from "./_poly1305.js";
|
||||
import { abytes, clean, equalBytes, getOutput, swap32IfBE, swap8IfBE, wrapCipher, } from "./utils.js";
|
||||
/**
|
||||
* Salsa20 core function. It is implemented twice:
|
||||
* 1. Simple loop (salsaCore_small, hsalsa_small)
|
||||
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
* Performance numbers for 1MB inputs:
|
||||
* * default x 779 ops/sec @ 1ms/op
|
||||
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
|
||||
* * small x 132 ops/sec @ 7ms/op
|
||||
*/
|
||||
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
|
||||
function salsaQR(x, a, b, c, d) {
|
||||
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
|
||||
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
|
||||
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
|
||||
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
|
||||
}
|
||||
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
|
||||
function salsaRound(x, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
salsaQR(x, 0, 4, 8, 12);
|
||||
salsaQR(x, 5, 9, 13, 1);
|
||||
salsaQR(x, 10, 14, 2, 6);
|
||||
salsaQR(x, 15, 3, 7, 11);
|
||||
salsaQR(x, 0, 1, 2, 3);
|
||||
salsaQR(x, 5, 6, 7, 4);
|
||||
salsaQR(x, 10, 11, 8, 9);
|
||||
salsaQR(x, 15, 12, 13, 14);
|
||||
}
|
||||
}
|
||||
// Shared scratch for the unused auditability helper below; it would be
|
||||
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
|
||||
const stmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function salsa(s, k, i, out, isHSalsa = true, rounds = 20) {
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], k[0], k[1], k[2], // "expa" Key Key Key
|
||||
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
|
||||
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
|
||||
k[5], k[6], k[7], s[3], // Key Key Key "te k"
|
||||
]);
|
||||
const x = stmp;
|
||||
x.set(y);
|
||||
// const x = y.slice();
|
||||
salsaRound(x, rounds);
|
||||
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
|
||||
if (isHSalsa) {
|
||||
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
|
||||
for (let i = 0; i < 8; i++)
|
||||
out[i] = x[xindexes[i]];
|
||||
}
|
||||
else {
|
||||
for (let i = 0; i < 16; i++)
|
||||
out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `salsaCore`. Unused. */
|
||||
// @ts-ignore
|
||||
const salsaCore_small = (s, k, n, out, cnt, rounds) => salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
|
||||
/** Identical to `hsalsa`. Unused. */
|
||||
// @ts-ignore
|
||||
const hsalsa_small = salsa;
|
||||
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
|
||||
// prettier-ignore
|
||||
function salsaCore(s, k, n, out, cnt, rounds = 20) {
|
||||
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
|
||||
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
|
||||
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
|
||||
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
|
||||
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
|
||||
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7);
|
||||
x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13);
|
||||
x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7);
|
||||
x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13);
|
||||
x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7);
|
||||
x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13);
|
||||
x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7);
|
||||
x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13);
|
||||
x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7);
|
||||
x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13);
|
||||
x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7);
|
||||
x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13);
|
||||
x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7);
|
||||
x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13);
|
||||
x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7);
|
||||
x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13);
|
||||
x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
// Write output
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0;
|
||||
out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0;
|
||||
out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0;
|
||||
out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0;
|
||||
out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0;
|
||||
out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0;
|
||||
out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0;
|
||||
out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0;
|
||||
out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hsalsa(s, k, i, out) {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7);
|
||||
x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13);
|
||||
x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7);
|
||||
x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13);
|
||||
x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7);
|
||||
x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13);
|
||||
x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7);
|
||||
x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13);
|
||||
x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7);
|
||||
x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13);
|
||||
x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7);
|
||||
x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13);
|
||||
x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7);
|
||||
x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13);
|
||||
x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7);
|
||||
x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13);
|
||||
x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
let oi = 0;
|
||||
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
|
||||
out[oi++] = x00;
|
||||
out[oi++] = x05;
|
||||
out[oi++] = x10;
|
||||
out[oi++] = x15;
|
||||
out[oi++] = x06;
|
||||
out[oi++] = x07;
|
||||
out[oi++] = x08;
|
||||
out[oi++] = x09;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
allowShortKeys: true,
|
||||
counterRight: true,
|
||||
});
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
counterRight: true,
|
||||
extendNonceFn: hsalsa,
|
||||
});
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
|
||||
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
|
||||
// later encrypt/decrypt outputs.
|
||||
return {
|
||||
encrypt(plaintext, output) {
|
||||
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
|
||||
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
|
||||
// because 32 bytes is half-block of 64-byte salsa.
|
||||
// Need 32 extra bytes up front for the auth-key scratch area described above.
|
||||
output = getOutput(plaintext.length + 32, output, false);
|
||||
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
|
||||
const authKey = output.subarray(0, 32);
|
||||
const ciphPlaintext = output.subarray(32);
|
||||
output.set(plaintext, 32);
|
||||
// authKey is produced by xoring the first 32 bytes with zeros.
|
||||
clean(authKey);
|
||||
// output = stream ^ output; authKey = stream ^ zeros(32)
|
||||
xsalsa20(key, nonce, output, output);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
output.set(tag, 16);
|
||||
// Clean up auth-key remnants and the temporary tag copy.
|
||||
clean(output.subarray(0, 16), tag);
|
||||
// Return output[16..].
|
||||
return output.subarray(16);
|
||||
},
|
||||
decrypt(ciphertext, output) {
|
||||
// tmp part passed tag ciphertext
|
||||
// [0..32] [32..48] [48..]
|
||||
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
|
||||
// buffer may already contain copied ciphertext and derived auth-key material.
|
||||
abytes(ciphertext);
|
||||
output = getOutput(ciphertext.length + 32, output, false);
|
||||
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
|
||||
// output[48..] is ciphertext then plaintext.
|
||||
const tmp = output.subarray(0, 32);
|
||||
const passedTag = output.subarray(32, 48);
|
||||
const ciphPlaintext = output.subarray(48);
|
||||
output.set(ciphertext, 32);
|
||||
// authKey is produced by xoring the scratch area with zeros.
|
||||
clean(tmp);
|
||||
const authKey = xsalsa20(key, nonce, tmp, tmp);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(output);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
// output = stream ^ output[16..]
|
||||
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
|
||||
clean(tmp, passedTag, tag);
|
||||
// Return output[48..], skipping zeroized output[0..48].
|
||||
return ciphPlaintext;
|
||||
},
|
||||
};
|
||||
});
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function secretbox(key, nonce) {
|
||||
const xs = xsalsa20poly1305(key, nonce);
|
||||
return { seal: xs.encrypt, open: xs.decrypt };
|
||||
}
|
||||
//# sourceMappingURL=salsa.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+499
@@ -0,0 +1,499 @@
|
||||
/**
|
||||
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
||||
|
||||
RFC8439 requires multi-step cipher stream, where
|
||||
authKey starts with counter: 0, actual msg with counter: 1.
|
||||
|
||||
For this, we need a way to re-use nonce / counter:
|
||||
|
||||
const counter = new Uint8Array(4);
|
||||
chacha(..., counter, ...); // counter is now 1
|
||||
chacha(..., counter, ...); // counter is now 2
|
||||
|
||||
This is complicated:
|
||||
|
||||
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
||||
- Original papers don't allow mutating counters
|
||||
- Counter overflow is undefined [^1]
|
||||
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
||||
- Caveat: Cannot be re-used through all cases:
|
||||
- * chacha has (counter | nonce)
|
||||
- * xchacha has (nonce16 | counter | nonce16)
|
||||
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
||||
- Caveat: there are different counter sizes depending on an algorithm.
|
||||
- salsa & chacha also differ in structures of key & sigma:
|
||||
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
||||
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
||||
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
||||
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
||||
- Caveat: we can't re-use counter array
|
||||
|
||||
xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
||||
(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
|
||||
Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
|
||||
Current noble policy is strict non-wrap for the shared 32-bit counter path:
|
||||
exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
|
||||
wrap back to zero.
|
||||
See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
|
||||
|
||||
* @module
|
||||
*/
|
||||
import {
|
||||
type PRG,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
abool,
|
||||
abytes,
|
||||
anumber,
|
||||
checkOpts,
|
||||
clean,
|
||||
copyBytes,
|
||||
getOutput,
|
||||
isAligned32,
|
||||
isLE,
|
||||
randomBytes,
|
||||
swap32IfBE,
|
||||
u32,
|
||||
} from './utils.ts';
|
||||
|
||||
// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
|
||||
// Non-ASCII input would not match UTF-8 `TextEncoder` output.
|
||||
const encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
|
||||
// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
|
||||
// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
|
||||
// kept for legacy allowShortKeys Salsa/ChaCha variants.
|
||||
const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
|
||||
// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
|
||||
// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
|
||||
const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
|
||||
|
||||
/**
|
||||
* Rotates a 32-bit word left.
|
||||
* @param a - Input word.
|
||||
* @param b - Rotation count in bits.
|
||||
* @returns Rotated 32-bit word.
|
||||
* @example
|
||||
* Moves the top byte of `0x12345678` into the low byte position.
|
||||
* ```ts
|
||||
* rotl(0x12345678, 8);
|
||||
* ```
|
||||
*/
|
||||
export function rotl(a: number, b: number): number {
|
||||
return (a << b) | (a >>> (32 - b));
|
||||
}
|
||||
|
||||
/**
|
||||
* ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param nonce - Nonce and counter words prepared for the round function.
|
||||
* @param output - Output block written in place.
|
||||
* @param counter - Block counter value.
|
||||
* @param rounds - Optional round count override.
|
||||
*/
|
||||
export type CipherCoreFn = (
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
nonce: TArg<Uint32Array>,
|
||||
output: TArg<Uint32Array>,
|
||||
counter: number,
|
||||
rounds?: number
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Nonce-extension function used by XChaCha and XSalsa.
|
||||
* @param sigma - Sigma constants for the selected cipher layout.
|
||||
* @param key - Expanded key words.
|
||||
* @param input - Input nonce words used for subkey derivation.
|
||||
* @param output - Output buffer written with the derived nonce words.
|
||||
*/
|
||||
export type ExtendNonceFn = (
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
input: TArg<Uint32Array>,
|
||||
output: TArg<Uint32Array>
|
||||
) => void;
|
||||
|
||||
/** ARX cipher options.
|
||||
* * `allowShortKeys` for 16-byte keys
|
||||
* * `counterLength` in bytes
|
||||
* * `counterRight`: right: `nonce|counter`; left: `counter|nonce`
|
||||
* */
|
||||
export type CipherOpts = {
|
||||
/** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */
|
||||
allowShortKeys?: boolean;
|
||||
/** Optional nonce-expansion hook used by extended-nonce variants. */
|
||||
extendNonceFn?: ExtendNonceFn;
|
||||
/** Counter length in bytes inside the nonce/counter layout. */
|
||||
counterLength?: number;
|
||||
/** Whether the layout is `nonce|counter` instead of `counter|nonce`. */
|
||||
counterRight?: boolean;
|
||||
/** Number of core rounds to execute. */
|
||||
rounds?: number;
|
||||
};
|
||||
|
||||
// Salsa and Chacha block length is always 512-bit
|
||||
const BLOCK_LEN = 64;
|
||||
// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
|
||||
const BLOCK_LEN32 = 16;
|
||||
|
||||
// Counter policy for the shared public `counter` argument:
|
||||
// - RFC/IETF ChaCha20 uses a 32-bit counter.
|
||||
// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
|
||||
// counter state and carry into the next word.
|
||||
// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
|
||||
// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
|
||||
// boundary instead of carrying.
|
||||
// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
|
||||
// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
|
||||
// Noble intentionally throws instead of silently picking one wrap model for users. In the default
|
||||
// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
|
||||
// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
|
||||
// whatever wider carry / wrap policy they need on top.
|
||||
const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
|
||||
const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
|
||||
function runCipher(
|
||||
core: TArg<CipherCoreFn>,
|
||||
sigma: TArg<Uint32Array>,
|
||||
key: TArg<Uint32Array>,
|
||||
nonce: TArg<Uint32Array>,
|
||||
data: TArg<Uint8Array>,
|
||||
output: TArg<Uint8Array>,
|
||||
counter: number,
|
||||
rounds: number
|
||||
): void {
|
||||
const len = data.length;
|
||||
const block = new Uint8Array(BLOCK_LEN);
|
||||
const b32 = u32(block);
|
||||
// Make sure that buffers aligned to 4 bytes
|
||||
const isAligned = isLE && isAligned32(data) && isAligned32(output);
|
||||
const d32 = isAligned ? u32(data) : U32_EMPTY;
|
||||
const o32 = isAligned ? u32(output) : U32_EMPTY;
|
||||
// RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
|
||||
// truncating the final partial block instead of materializing the whole keystream.
|
||||
if (!isLE) {
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(
|
||||
sigma as TRet<Uint32Array>,
|
||||
key as TRet<Uint32Array>,
|
||||
nonce as TRet<Uint32Array>,
|
||||
b32,
|
||||
counter,
|
||||
rounds
|
||||
);
|
||||
// RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
|
||||
swap32IfBE(b32);
|
||||
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let pos = 0; pos < len; counter++) {
|
||||
core(
|
||||
sigma as TRet<Uint32Array>,
|
||||
key as TRet<Uint32Array>,
|
||||
nonce as TRet<Uint32Array>,
|
||||
b32,
|
||||
counter,
|
||||
rounds
|
||||
);
|
||||
// See MAX_COUNTER policy note above: never silently wrap the shared public counter.
|
||||
if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const take = Math.min(BLOCK_LEN, len - pos);
|
||||
// aligned to 4 bytes
|
||||
if (isAligned && take === BLOCK_LEN) {
|
||||
const pos32 = pos / 4;
|
||||
if (pos % 4 !== 0) throw new Error('arx: invalid block position');
|
||||
for (let j = 0, posj: number; j < BLOCK_LEN32; j++) {
|
||||
posj = pos32 + j;
|
||||
o32[posj] = d32[posj] ^ b32[j];
|
||||
}
|
||||
pos += BLOCK_LEN;
|
||||
continue;
|
||||
}
|
||||
for (let j = 0, posj; j < take; j++) {
|
||||
posj = pos + j;
|
||||
output[posj] = data[posj] ^ block[j];
|
||||
}
|
||||
pos += take;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ARX stream cipher from a 32-bit core permutation.
|
||||
* Used internally to build the exported Salsa and ChaCha stream ciphers.
|
||||
* @param core - Core function that fills one keystream block.
|
||||
* @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
|
||||
* @returns Stream cipher function over byte arrays.
|
||||
* @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
|
||||
*/
|
||||
export function createCipher(core: TArg<CipherCoreFn>, opts: TArg<CipherOpts>): TRet<XorStream> {
|
||||
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts(
|
||||
{ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 },
|
||||
opts
|
||||
);
|
||||
if (typeof core !== 'function') throw new Error('core must be a function');
|
||||
anumber(counterLength);
|
||||
anumber(rounds);
|
||||
abool(counterRight);
|
||||
abool(allowShortKeys);
|
||||
return (
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
data: TArg<Uint8Array>,
|
||||
output?: TArg<Uint8Array>,
|
||||
counter = 0
|
||||
): TRet<Uint8Array> => {
|
||||
abytes(key, undefined, 'key');
|
||||
abytes(nonce, undefined, 'nonce');
|
||||
abytes(data, undefined, 'data');
|
||||
const len = data.length;
|
||||
// Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
|
||||
// must match the logical result length exactly instead of returning an oversized workspace.
|
||||
output = getOutput(len, output, false);
|
||||
anumber(counter);
|
||||
// See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
|
||||
if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow');
|
||||
const toClean = [];
|
||||
|
||||
// Key & sigma
|
||||
// key=16 -> sigma16, k=key|key
|
||||
// key=32 -> sigma32, k=key
|
||||
let l = key.length;
|
||||
let k: Uint8Array;
|
||||
let sigma: Uint32Array;
|
||||
if (l === 32) {
|
||||
// Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
|
||||
// final clean(...) all mutate or wipe the temporary buffer in place.
|
||||
toClean.push((k = copyBytes(key)));
|
||||
sigma = sigma32_32;
|
||||
} else if (l === 16 && allowShortKeys) {
|
||||
k = new Uint8Array(32);
|
||||
k.set(key);
|
||||
k.set(key, 16);
|
||||
sigma = sigma16_32;
|
||||
toClean.push(k);
|
||||
} else {
|
||||
abytes(key, 32, 'arx key');
|
||||
throw new Error('invalid key size');
|
||||
// throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
|
||||
}
|
||||
|
||||
// Nonce
|
||||
// salsa20: 8 (8-byte counter)
|
||||
// chacha20orig: 8 (8-byte counter)
|
||||
// chacha20: 12 (4-byte counter)
|
||||
// xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
|
||||
// xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
|
||||
// Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
|
||||
// swap32IfBE(...) never mutates caller nonce bytes in place.
|
||||
if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce)));
|
||||
|
||||
let k32 = u32(k);
|
||||
// hsalsa & hchacha: handle extended nonce
|
||||
if (extendNonceFn) {
|
||||
if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);
|
||||
const n16 = nonce.subarray(0, 16);
|
||||
if (isLE) extendNonceFn(sigma as TRet<Uint32Array>, k32, u32(n16), k32);
|
||||
else {
|
||||
const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
|
||||
extendNonceFn(sigmaRaw, k32, u32(n16), k32);
|
||||
clean(sigmaRaw);
|
||||
swap32IfBE(k32);
|
||||
}
|
||||
nonce = nonce.subarray(16);
|
||||
} else if (!isLE) swap32IfBE(k32);
|
||||
|
||||
// Handle nonce counter
|
||||
const nonceNcLen = 16 - counterLength;
|
||||
if (nonceNcLen !== nonce.length)
|
||||
throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
||||
|
||||
// Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
|
||||
// counter bytes, while Salsa/XSalsa append them after the nonce words.
|
||||
if (nonceNcLen !== 12) {
|
||||
const nc = new Uint8Array(12);
|
||||
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
||||
nonce = nc;
|
||||
toClean.push(nonce);
|
||||
}
|
||||
const n32 = swap32IfBE(u32(nonce));
|
||||
// Ensure temporary key/nonce copies are wiped even if the remaining
|
||||
// runtime guard in runCipher(...) throws on counter overflow.
|
||||
try {
|
||||
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
||||
return output as TRet<Uint8Array>;
|
||||
} finally {
|
||||
clean(...toClean);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
|
||||
export class _XorStreamPRG implements PRG {
|
||||
readonly blockLen: number;
|
||||
readonly keyLen: number;
|
||||
readonly nonceLen: number;
|
||||
private state: TRet<Uint8Array>;
|
||||
private buf: TRet<Uint8Array>;
|
||||
private key: TRet<Uint8Array>;
|
||||
private nonce: TRet<Uint8Array>;
|
||||
private pos: number;
|
||||
private ctr: number;
|
||||
private cipher: TArg<XorStream>;
|
||||
constructor(
|
||||
cipher: TArg<XorStream>,
|
||||
blockLen: number,
|
||||
keyLen: number,
|
||||
nonceLen: number,
|
||||
seed: TArg<Uint8Array>
|
||||
) {
|
||||
this.cipher = cipher;
|
||||
this.blockLen = blockLen;
|
||||
this.keyLen = keyLen;
|
||||
this.nonceLen = nonceLen;
|
||||
this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet<Uint8Array>;
|
||||
this.reseed(seed);
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
this.buf = new Uint8Array(this.blockLen) as TRet<Uint8Array>;
|
||||
// Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
|
||||
// inputs in place through these subarray views.
|
||||
this.key = this.state.subarray(0, this.keyLen) as TRet<Uint8Array>;
|
||||
this.nonce = this.state.subarray(this.keyLen) as TRet<Uint8Array>;
|
||||
}
|
||||
private reseed(seed: TArg<Uint8Array>) {
|
||||
abytes(seed);
|
||||
if (!seed || seed.length === 0) throw new Error('entropy required');
|
||||
// Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
|
||||
// keystream so buffered leftovers from the previous state are never reused.
|
||||
for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i];
|
||||
this.ctr = 0;
|
||||
this.pos = this.blockLen;
|
||||
}
|
||||
addEntropy(seed: TArg<Uint8Array>): void {
|
||||
// Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
|
||||
abytes(seed);
|
||||
if (seed.length === 0) throw new Error('entropy required');
|
||||
// Re-key from the current stream first, then mix external entropy into the fresh key||nonce
|
||||
// state through reseed() so stale buffered bytes are discarded.
|
||||
this.state.set(this.randomBytes(this.state.length));
|
||||
this.reseed(seed);
|
||||
}
|
||||
randomBytes(len: number): TRet<Uint8Array> {
|
||||
anumber(len);
|
||||
if (len === 0) return new Uint8Array(0) as TRet<Uint8Array>;
|
||||
const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
|
||||
const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
|
||||
// Preflight overflow so failed reads don't partially consume keystream
|
||||
// and leave the PRG repeating blocks.
|
||||
if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow');
|
||||
const out = new Uint8Array(len);
|
||||
let outPos = 0;
|
||||
// `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
|
||||
// ciphers then emit raw keystream bytes directly into those buffers.
|
||||
// Serve buffered leftovers first so split reads stay identical to one larger read.
|
||||
if (this.pos < this.blockLen) {
|
||||
const take = Math.min(len, this.blockLen - this.pos);
|
||||
out.set(this.buf.subarray(this.pos, this.pos + take), 0);
|
||||
this.pos += take;
|
||||
outPos += take;
|
||||
if (outPos === len) return out as TRet<Uint8Array>; // fast path
|
||||
}
|
||||
// Full blocks directly to out
|
||||
const full = Math.floor((len - outPos) / this.blockLen);
|
||||
if (full > 0) {
|
||||
const blockBytes = full * this.blockLen;
|
||||
const b = out.subarray(outPos, outPos + blockBytes);
|
||||
this.cipher(this.key, this.nonce, b as TRet<Uint8Array>, b as TRet<Uint8Array>, this.ctr);
|
||||
this.ctr += full;
|
||||
outPos += blockBytes;
|
||||
}
|
||||
// Save leftovers
|
||||
const left = len - outPos;
|
||||
if (left > 0) {
|
||||
this.buf.fill(0);
|
||||
// NOTE: cipher will handle overflow
|
||||
this.cipher(
|
||||
this.key,
|
||||
this.nonce,
|
||||
this.buf as TRet<Uint8Array>,
|
||||
this.buf as TRet<Uint8Array>,
|
||||
this.ctr++
|
||||
);
|
||||
out.set(this.buf.subarray(0, left), outPos);
|
||||
this.pos = left;
|
||||
}
|
||||
return out as TRet<Uint8Array>;
|
||||
}
|
||||
// Clone seeds the new instance from this stream, so the source PRG advances too.
|
||||
clone(): _XorStreamPRG {
|
||||
return new _XorStreamPRG(
|
||||
this.cipher,
|
||||
this.blockLen,
|
||||
this.keyLen,
|
||||
this.nonceLen,
|
||||
this.randomBytes(this.state.length)
|
||||
);
|
||||
}
|
||||
// Zeroes the current state and leftover buffer, but does not make the instance unusable:
|
||||
// Later reads first drain zeros from the cleared buffer and then continue
|
||||
// from zero key||nonce state.
|
||||
clean(): void {
|
||||
this.pos = 0;
|
||||
this.ctr = 0;
|
||||
this.buf.fill(0);
|
||||
this.state.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PRG constructor backed by an ARX stream cipher.
|
||||
* @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32
|
||||
* random bytes are mixed in by default: larger states keep a zero tail, while smaller states
|
||||
* wrap those bytes through `reseed()`'s XOR schedule.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
*/
|
||||
export type XorPRG = (seed?: TArg<Uint8Array>) => TRet<_XorStreamPRG>;
|
||||
|
||||
/**
|
||||
* Creates a PRG constructor from a stream cipher.
|
||||
* @param cipher - Stream cipher used to fill output blocks.
|
||||
* @param blockLen - Keystream block length in bytes.
|
||||
* @param keyLen - Internal key length in bytes.
|
||||
* @param nonceLen - Internal nonce length in bytes.
|
||||
* @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
|
||||
* @example
|
||||
* Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { createPRG } from '@noble/ciphers/_arx.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const init = createPRG(xchacha20, 64, 32, 24);
|
||||
* const prg = init(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const createPRG = (
|
||||
cipher: TArg<XorStream>,
|
||||
blockLen: number,
|
||||
keyLen: number,
|
||||
nonceLen: number
|
||||
): TRet<XorPRG> => {
|
||||
return ((seed: TArg<Uint8Array> = randomBytes(32)): TRet<_XorStreamPRG> =>
|
||||
new _XorStreamPRG(
|
||||
cipher,
|
||||
blockLen,
|
||||
keyLen,
|
||||
nonceLen,
|
||||
seed
|
||||
) as TRet<_XorStreamPRG>) as TRet<XorPRG>;
|
||||
};
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
|
||||
* is a fast and parallel secret-key message-authentication code suitable for
|
||||
* a wide variety of applications. It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
|
||||
*
|
||||
* Polynomial MACs are not perfect for every situation:
|
||||
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
||||
* See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
|
||||
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
||||
* however, this would violate ciphertext indistinguishability:
|
||||
* an attacker would know which key was used - so `HKDF(key, i)`
|
||||
* could be used instead.
|
||||
*
|
||||
* Check out the {@link https://cr.yp.to/mac.html | original website}.
|
||||
* Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
|
||||
* @module
|
||||
*/
|
||||
// prettier-ignore
|
||||
import {
|
||||
abytes, aexists, aoutput, bytesToHex,
|
||||
clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE,
|
||||
wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet
|
||||
} from './utils.ts';
|
||||
|
||||
// Little-endian 2-byte load used by the Poly1305 limb decomposition.
|
||||
function u8to16(a: TArg<Uint8Array>, i: number) {
|
||||
return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
|
||||
}
|
||||
|
||||
function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {
|
||||
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
|
||||
/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
|
||||
function poly1305_small(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
abytes(msg);
|
||||
abytes(key, 32, 'key');
|
||||
const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
|
||||
const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
|
||||
const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
|
||||
const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
|
||||
const s = bytesToNumberLE(key.subarray(16));
|
||||
// Process by 16 byte chunks
|
||||
let acc = BigInt(0);
|
||||
for (let i = 0; i < msg.length; i += 16) {
|
||||
const m = msg.subarray(i, i + 16);
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
|
||||
const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
|
||||
acc = ((acc + n) * r) % POW_2_130_5;
|
||||
}
|
||||
const res = (acc + s) & POW_2_128_1;
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
|
||||
return numberToBytesBE(res, 16).reverse() as TRet<Uint8Array>; // LE
|
||||
}
|
||||
|
||||
// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
|
||||
// @ts-expect-error
|
||||
function poly1305_computeTag_small(
|
||||
authKey: TArg<Uint8Array>,
|
||||
// AEAD trailer must already be the 16-byte length block:
|
||||
// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
|
||||
lengths: TArg<Uint8Array>,
|
||||
ciphertext: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<Uint8Array> {
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
|
||||
// AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
|
||||
const res = [];
|
||||
const updatePadded2 = (msg: TArg<Uint8Array>) => {
|
||||
res.push(msg);
|
||||
const leftover = msg.length % 16;
|
||||
// RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
|
||||
// inputs, else 16-(len%16) zero bytes.
|
||||
if (leftover) res.push(new Uint8Array(16).slice(leftover));
|
||||
};
|
||||
if (AAD) updatePadded2(AAD);
|
||||
updatePadded2(ciphertext);
|
||||
res.push(lengths);
|
||||
return poly1305_small(concatBytes(...res), authKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental Poly1305 MAC state.
|
||||
* Prefer `poly1305()` for one-shot use.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @example
|
||||
* Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const mac = new Poly1305(key);
|
||||
* mac.update(new Uint8Array([1, 2, 3]));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Poly1305 implements IHash2 {
|
||||
readonly blockLen = 16;
|
||||
readonly outputLen = 16;
|
||||
private buffer = new Uint8Array(16);
|
||||
private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
|
||||
private h = new Uint16Array(10);
|
||||
private pad = new Uint16Array(8);
|
||||
private pos = 0;
|
||||
protected finished = false;
|
||||
protected destroyed = false;
|
||||
|
||||
// Can be speed-up using BigUint64Array, at the cost of complexity
|
||||
constructor(key: TArg<Uint8Array>) {
|
||||
key = copyBytes(abytes(key, 32, 'key'));
|
||||
const t0 = u8to16(key, 0);
|
||||
const t1 = u8to16(key, 2);
|
||||
const t2 = u8to16(key, 4);
|
||||
const t3 = u8to16(key, 6);
|
||||
const t4 = u8to16(key, 8);
|
||||
const t5 = u8to16(key, 10);
|
||||
const t6 = u8to16(key, 12);
|
||||
const t7 = u8to16(key, 14);
|
||||
|
||||
// RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
|
||||
// These masks unpack that clamped value into 13-bit limbs, while pad
|
||||
// keeps the raw s half for finalize().
|
||||
// {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
|
||||
this.r[0] = t0 & 0x1fff;
|
||||
this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
|
||||
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
|
||||
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
|
||||
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
|
||||
this.r[5] = (t4 >>> 1) & 0x1ffe;
|
||||
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
|
||||
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
|
||||
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
|
||||
this.r[9] = (t7 >>> 5) & 0x007f;
|
||||
for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);
|
||||
}
|
||||
|
||||
private process(data: TArg<Uint8Array>, offset: number, isLast = false) {
|
||||
// RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
|
||||
// bit to every full 16-byte block. The final partial block gets its
|
||||
// explicit `1` byte during digestInto(), so `hibit` stays zero there.
|
||||
const hibit = isLast ? 0 : 1 << 11;
|
||||
const { h, r } = this;
|
||||
const r0 = r[0];
|
||||
const r1 = r[1];
|
||||
const r2 = r[2];
|
||||
const r3 = r[3];
|
||||
const r4 = r[4];
|
||||
const r5 = r[5];
|
||||
const r6 = r[6];
|
||||
const r7 = r[7];
|
||||
const r8 = r[8];
|
||||
const r9 = r[9];
|
||||
|
||||
const t0 = u8to16(data, offset + 0);
|
||||
const t1 = u8to16(data, offset + 2);
|
||||
const t2 = u8to16(data, offset + 4);
|
||||
const t3 = u8to16(data, offset + 6);
|
||||
const t4 = u8to16(data, offset + 8);
|
||||
const t5 = u8to16(data, offset + 10);
|
||||
const t6 = u8to16(data, offset + 12);
|
||||
const t7 = u8to16(data, offset + 14);
|
||||
|
||||
let h0 = h[0] + (t0 & 0x1fff);
|
||||
let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
|
||||
let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
|
||||
let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
|
||||
let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
|
||||
let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
|
||||
let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
|
||||
let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
|
||||
let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
|
||||
let h9 = h[9] + ((t7 >>> 5) | hibit);
|
||||
|
||||
let c = 0;
|
||||
|
||||
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
||||
c = d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
||||
c += d0 >>> 13;
|
||||
d0 &= 0x1fff;
|
||||
|
||||
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
||||
c = d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
||||
c += d1 >>> 13;
|
||||
d1 &= 0x1fff;
|
||||
|
||||
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
||||
c = d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
||||
c += d2 >>> 13;
|
||||
d2 &= 0x1fff;
|
||||
|
||||
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
||||
c = d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
||||
c += d3 >>> 13;
|
||||
d3 &= 0x1fff;
|
||||
|
||||
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
||||
c = d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
||||
c += d4 >>> 13;
|
||||
d4 &= 0x1fff;
|
||||
|
||||
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
||||
c = d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
||||
c += d5 >>> 13;
|
||||
d5 &= 0x1fff;
|
||||
|
||||
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
||||
c = d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
||||
c += d6 >>> 13;
|
||||
d6 &= 0x1fff;
|
||||
|
||||
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
||||
c = d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
||||
c += d7 >>> 13;
|
||||
d7 &= 0x1fff;
|
||||
|
||||
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
||||
c = d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
||||
c += d8 >>> 13;
|
||||
d8 &= 0x1fff;
|
||||
|
||||
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
||||
c = d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
||||
c += d9 >>> 13;
|
||||
d9 &= 0x1fff;
|
||||
|
||||
c = ((c << 2) + c) | 0;
|
||||
c = (c + d0) | 0;
|
||||
d0 = c & 0x1fff;
|
||||
c = c >>> 13;
|
||||
d1 += c;
|
||||
|
||||
h[0] = d0;
|
||||
h[1] = d1;
|
||||
h[2] = d2;
|
||||
h[3] = d3;
|
||||
h[4] = d4;
|
||||
h[5] = d5;
|
||||
h[6] = d6;
|
||||
h[7] = d7;
|
||||
h[8] = d8;
|
||||
h[9] = d9;
|
||||
}
|
||||
|
||||
private finalize() {
|
||||
const { h, pad } = this;
|
||||
const g = new Uint16Array(10);
|
||||
let c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
for (let i = 2; i < 10; i++) {
|
||||
h[i] += c;
|
||||
c = h[i] >>> 13;
|
||||
h[i] &= 0x1fff;
|
||||
}
|
||||
h[0] += c * 5;
|
||||
c = h[0] >>> 13;
|
||||
h[0] &= 0x1fff;
|
||||
h[1] += c;
|
||||
c = h[1] >>> 13;
|
||||
h[1] &= 0x1fff;
|
||||
h[2] += c;
|
||||
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
|
||||
// to 16-bit words and adding the raw s half.
|
||||
g[0] = h[0] + 5;
|
||||
c = g[0] >>> 13;
|
||||
g[0] &= 0x1fff;
|
||||
for (let i = 1; i < 10; i++) {
|
||||
g[i] = h[i] + c;
|
||||
c = g[i] >>> 13;
|
||||
g[i] &= 0x1fff;
|
||||
}
|
||||
g[9] -= 1 << 13;
|
||||
|
||||
let mask = (c ^ 1) - 1;
|
||||
for (let i = 0; i < 10; i++) g[i] &= mask;
|
||||
mask = ~mask;
|
||||
for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i];
|
||||
h[0] = (h[0] | (h[1] << 13)) & 0xffff;
|
||||
h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
|
||||
h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
|
||||
h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
|
||||
h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
|
||||
h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
|
||||
h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
|
||||
h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
|
||||
|
||||
let f = h[0] + pad[0];
|
||||
h[0] = f & 0xffff;
|
||||
for (let i = 1; i < 8; i++) {
|
||||
f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
|
||||
h[i] = f & 0xffff;
|
||||
}
|
||||
clean(g);
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const { buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
|
||||
for (let pos = 0; pos < len; ) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path: we have at least one block in input
|
||||
if (take === blockLen) {
|
||||
for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.process(buffer, 0, false);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy(): void {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
clean(this.h, this.r, this.buffer, this.pad);
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
const { buffer, h } = this;
|
||||
let { pos } = this;
|
||||
if (pos) {
|
||||
// RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
|
||||
// single `0x01` byte and zero-fills the remaining bytes before the
|
||||
// last multiplication step.
|
||||
buffer[pos++] = 1;
|
||||
for (; pos < 16; pos++) buffer[pos] = 0;
|
||||
this.process(buffer, 0, true);
|
||||
}
|
||||
this.finalize();
|
||||
let opos = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
out[opos++] = h[i] >>> 0;
|
||||
out[opos++] = h[i] >>> 8;
|
||||
}
|
||||
}
|
||||
digest(): TRet<Uint8Array> {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Copy out before destroy() zeroes the internal buffer.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res as TRet<Uint8Array>;
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot keyed hash helper with `.create()`. */
|
||||
export type CHash = CMac<Poly1305>;
|
||||
|
||||
/**
|
||||
* Poly1305 MAC from RFC 8439.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 32-byte Poly1305 one-time key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates one message with a one-shot Poly1305 call and a fresh key.
|
||||
*
|
||||
* ```ts
|
||||
* import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* poly1305(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const poly1305: TRet<CHash> = /* @__PURE__ */ wrapMacConstructor(
|
||||
32,
|
||||
(key: TArg<Uint8Array>) => new Poly1305(key)
|
||||
);
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
/**
|
||||
* GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
|
||||
*
|
||||
* Implemented in terms of GHash with conversion function for keys
|
||||
* GCM GHASH from
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
|
||||
* SIV from
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
|
||||
*
|
||||
* GHASH modulo: x^128 + x^7 + x^2 + x + 1
|
||||
* POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import {
|
||||
abytes,
|
||||
aexists,
|
||||
aoutput,
|
||||
clean,
|
||||
copyBytes,
|
||||
createView,
|
||||
swap32IfBE,
|
||||
swap8IfBE,
|
||||
u32,
|
||||
wrapMacConstructor,
|
||||
type CMac,
|
||||
type IHash2,
|
||||
type TArg,
|
||||
type TRet,
|
||||
} from './utils.ts';
|
||||
|
||||
const BLOCK_SIZE = 16;
|
||||
// TODO: rewrite
|
||||
// temporary padding buffer
|
||||
// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
|
||||
// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
|
||||
// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
|
||||
const POLY = 0xe1;
|
||||
|
||||
// v = 2*v % POLY
|
||||
// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
|
||||
// Montgomery ladder can multiply any field element with this doubling step;
|
||||
// addition stays simple xor.
|
||||
const mul2 = (s0: number, s1: number, s2: number, s3: number) => {
|
||||
const hiBit = s3 & 1;
|
||||
return {
|
||||
s3: (s2 << 31) | (s3 >>> 1),
|
||||
s2: (s1 << 31) | (s2 >>> 1),
|
||||
s1: (s0 << 31) | (s1 >>> 1),
|
||||
// NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
|
||||
// 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
|
||||
s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
|
||||
};
|
||||
};
|
||||
|
||||
// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
|
||||
const swapLE = (n: number) =>
|
||||
(((n >>> 0) & 0xff) << 24) |
|
||||
(((n >>> 8) & 0xff) << 16) |
|
||||
(((n >>> 16) & 0xff) << 8) |
|
||||
((n >>> 24) & 0xff) |
|
||||
0;
|
||||
// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
|
||||
// host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
|
||||
const swap8IfLE = (n: number) => swap8IfBE(swapLE(n));
|
||||
|
||||
/**
|
||||
* `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
|
||||
* @param k mutated in place
|
||||
*/
|
||||
export function _toGHASHKey(k: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// The input is the original POLYVAL key H; reverse() materializes
|
||||
// RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
|
||||
k.reverse();
|
||||
const hiBit = k[15] & 1;
|
||||
// k >>= 1
|
||||
let carry = 0;
|
||||
for (let i = 0; i < k.length; i++) {
|
||||
const t = k[i];
|
||||
k[i] = (t >>> 1) | carry;
|
||||
carry = (t & 1) << 7;
|
||||
}
|
||||
k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
|
||||
return k as TRet<Uint8Array>;
|
||||
}
|
||||
|
||||
type Value = { s0: number; s1: number; s2: number; s3: number };
|
||||
|
||||
// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
|
||||
// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
|
||||
const estimateWindow = (bytes: number) => {
|
||||
if (bytes > 64 * 1024) return 8;
|
||||
if (bytes > 1024) return 4;
|
||||
return 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* Incremental GHASH state for AES-GCM.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
|
||||
* to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
|
||||
* use where AAD, payload, and length block are separate padded segments.
|
||||
* @example
|
||||
* Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { GHASH } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new GHASH(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class GHASH implements IHash2 {
|
||||
readonly blockLen: number = BLOCK_SIZE;
|
||||
readonly outputLen: number = BLOCK_SIZE;
|
||||
protected s0 = 0;
|
||||
protected s1 = 0;
|
||||
protected s2 = 0;
|
||||
protected s3 = 0;
|
||||
protected finished = false;
|
||||
protected destroyed = false;
|
||||
protected t: Value[];
|
||||
private W: number;
|
||||
private windowSize: number;
|
||||
// We select bits per window adaptively based on expectedLength
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
|
||||
abytes(key, 16, 'key');
|
||||
key = copyBytes(key);
|
||||
const kView = createView(key);
|
||||
let k0 = kView.getUint32(0, false);
|
||||
let k1 = kView.getUint32(4, false);
|
||||
let k2 = kView.getUint32(8, false);
|
||||
let k3 = kView.getUint32(12, false);
|
||||
// generate table of doubled keys (half of montgomery ladder)
|
||||
const doubles: Value[] = [];
|
||||
for (let i = 0; i < 128; i++) {
|
||||
doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
|
||||
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
|
||||
}
|
||||
const W = estimateWindow(expectedLength || 1024);
|
||||
if (![1, 2, 4, 8].includes(W))
|
||||
throw new Error('ghash: invalid window size, expected 2, 4 or 8');
|
||||
this.W = W;
|
||||
const bits = 128; // always 128 bits;
|
||||
const windows = bits / W;
|
||||
const windowSize = (this.windowSize = 2 ** W);
|
||||
const items: Value[] = [];
|
||||
// Create precompute table for window of W bits
|
||||
for (let w = 0; w < windows; w++) {
|
||||
// truth table: 00, 01, 10, 11
|
||||
for (let byte = 0; byte < windowSize; byte++) {
|
||||
// prettier-ignore
|
||||
let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
|
||||
for (let j = 0; j < W; j++) {
|
||||
const bit = (byte >>> (W - j - 1)) & 1;
|
||||
if (!bit) continue;
|
||||
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
|
||||
((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
|
||||
}
|
||||
items.push({ s0, s1, s2, s3 });
|
||||
}
|
||||
}
|
||||
this.t = items;
|
||||
}
|
||||
protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void {
|
||||
((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
|
||||
const { W, t, windowSize } = this;
|
||||
// prettier-ignore
|
||||
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
|
||||
const mask = (1 << W) - 1; // 2**W will kill performance.
|
||||
let w = 0;
|
||||
// NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
|
||||
// so the lookup walk consumes each word byte-by-byte from
|
||||
// least-significant to most-significant bits.
|
||||
for (const num of [s0, s1, s2, s3]) {
|
||||
for (let bytePos = 0; bytePos < 4; bytePos++) {
|
||||
const byte = (num >>> (8 * bytePos)) & 0xff;
|
||||
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
|
||||
const bit = (byte >>> (W * bitPos)) & mask;
|
||||
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
|
||||
((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
|
||||
w += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.s0 = o0;
|
||||
this.s1 = o1;
|
||||
this.s2 = o2;
|
||||
this.s3 = o3;
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
this._updateBlock(
|
||||
swap8IfBE(b32[i * 4 + 0]),
|
||||
swap8IfBE(b32[i * 4 + 1]),
|
||||
swap8IfBE(b32[i * 4 + 2]),
|
||||
swap8IfBE(b32[i * 4 + 3])
|
||||
);
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
// Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
|
||||
// normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
|
||||
this._updateBlock(
|
||||
swap8IfBE(ZEROS32[0]),
|
||||
swap8IfBE(ZEROS32[1]),
|
||||
swap8IfBE(ZEROS32[2]),
|
||||
swap8IfBE(ZEROS32[3])
|
||||
);
|
||||
clean(ZEROS32); // clean tmp buffer
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy(): void {
|
||||
// `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
|
||||
this.destroyed = true;
|
||||
const { t } = this;
|
||||
// Wipe the key-derived precompute table; scalar accumulator words remain,
|
||||
// but the destroyed guard blocks further use.
|
||||
// clean precompute table
|
||||
for (const elm of t) {
|
||||
((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
|
||||
}
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only
|
||||
// out[0..15] may be touched.
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(out);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
}
|
||||
digest(): TRet<Uint8Array> {
|
||||
const res = new Uint8Array(BLOCK_SIZE);
|
||||
this.digestInto(res);
|
||||
// `res` is independent of internal state, so it stays valid after destroy() wipes the table.
|
||||
this.destroy();
|
||||
return res as TRet<Uint8Array>;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Incremental POLYVAL state for AES-SIV.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @param expectedLength - Expected message length for table sizing.
|
||||
* Inherits GHASH's segment-padded `update()` behavior: each call is padded
|
||||
* independently to a 16-byte boundary before absorption.
|
||||
* @example
|
||||
* Feeds one block into an incremental POLYVAL state with a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { Polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const mac = new Polyval(key);
|
||||
* mac.update(new Uint8Array(16));
|
||||
* mac.digest();
|
||||
* ```
|
||||
*/
|
||||
export class Polyval extends GHASH {
|
||||
constructor(key: TArg<Uint8Array>, expectedLength?: number) {
|
||||
abytes(key);
|
||||
// RFC 8452 Appendix A converts the POLYVAL key with
|
||||
// `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
|
||||
// mutates in place.
|
||||
const ghKey = _toGHASHKey(copyBytes(key));
|
||||
super(ghKey, expectedLength);
|
||||
clean(ghKey);
|
||||
}
|
||||
update(data: TArg<Uint8Array>): this {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
data = copyBytes(data);
|
||||
const b32 = u32(data);
|
||||
const left = data.length % BLOCK_SIZE;
|
||||
const blocks = Math.floor(data.length / BLOCK_SIZE);
|
||||
for (let i = 0; i < blocks; i++) {
|
||||
// RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
|
||||
// reverses the 32-bit word order in addition to the per-word byte swap.
|
||||
this._updateBlock(
|
||||
swap8IfLE(b32[i * 4 + 3]),
|
||||
swap8IfLE(b32[i * 4 + 2]),
|
||||
swap8IfLE(b32[i * 4 + 1]),
|
||||
swap8IfLE(b32[i * 4 + 0])
|
||||
);
|
||||
}
|
||||
if (left) {
|
||||
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
|
||||
this._updateBlock(
|
||||
swap8IfLE(ZEROS32[3]),
|
||||
swap8IfLE(ZEROS32[2]),
|
||||
swap8IfLE(ZEROS32[1]),
|
||||
swap8IfLE(ZEROS32[0])
|
||||
);
|
||||
clean(ZEROS32);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out: TArg<Uint8Array>): void {
|
||||
aexists(this);
|
||||
// `digestInto(out)` is the no-allocation fast path, so callers must pass a
|
||||
// 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
|
||||
aoutput(out, this, true);
|
||||
this.finished = true;
|
||||
// RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
|
||||
// `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
|
||||
const view = out.subarray(0, this.outputLen);
|
||||
const { s0, s1, s2, s3 } = this;
|
||||
const o32 = u32(view);
|
||||
o32[0] = s0;
|
||||
o32[1] = s1;
|
||||
o32[2] = s2;
|
||||
o32[3] = s3;
|
||||
swap32IfBE(o32);
|
||||
view.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GHash MAC for AES-GCM.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte GHASH key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with GHASH and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { ghash } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* ghash(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const ghash: TRet<CMac<GHASH, [expectedLength?: number]>> =
|
||||
/* @__PURE__ */ wrapMacConstructor(
|
||||
16,
|
||||
(key: TArg<Uint8Array>, expectedLength?: number) => new GHASH(key, expectedLength),
|
||||
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
|
||||
);
|
||||
|
||||
/**
|
||||
* POLYVAL MAC for AES-SIV.
|
||||
* @param msg - Message bytes to authenticate.
|
||||
* @param key - 16-byte POLYVAL key.
|
||||
* @returns 16-byte authentication tag.
|
||||
* @example
|
||||
* Authenticates a short message with POLYVAL and a fresh hash key.
|
||||
*
|
||||
* ```ts
|
||||
* import { polyval } from '@noble/ciphers/_polyval.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* polyval(new Uint8Array(), key);
|
||||
* ```
|
||||
*/
|
||||
export const polyval: TRet<CMac<Polyval, [expectedLength?: number]>> =
|
||||
/* @__PURE__ */ wrapMacConstructor(
|
||||
16,
|
||||
(key: TArg<Uint8Array>, expectedLength?: number) => new Polyval(key, expectedLength),
|
||||
(msg: TArg<Uint8Array>): [expectedLength?: number] => [msg.length]
|
||||
);
|
||||
+2018
File diff suppressed because it is too large
Load Diff
+579
@@ -0,0 +1,579 @@
|
||||
/**
|
||||
* ChaCha stream cipher, released
|
||||
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
||||
* It was standardized in
|
||||
* {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and
|
||||
* is now used in TLS 1.3.
|
||||
*
|
||||
* {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20}
|
||||
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
||||
* randomly-generated nonces.
|
||||
*
|
||||
* Check out
|
||||
* {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF},
|
||||
* {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and
|
||||
* {@link https://cr.yp.to/chacha.html | website}.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts';
|
||||
import { poly1305 } from './_poly1305.ts';
|
||||
import {
|
||||
type ARXCipher,
|
||||
type CipherWithOutput,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
abytes,
|
||||
clean,
|
||||
equalBytes,
|
||||
getOutput,
|
||||
swap8IfBE,
|
||||
swap32IfBE,
|
||||
u64Lengths,
|
||||
wrapCipher,
|
||||
} from './utils.ts';
|
||||
|
||||
/**
|
||||
* ChaCha core function. It is implemented twice:
|
||||
* 1. Simple loop (chachaCore_small, hchacha_small)
|
||||
* 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
*/
|
||||
|
||||
/** RFC 8439 §2.1 quarter round on words a, b, c, d. */
|
||||
// prettier-ignore
|
||||
function chachaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
|
||||
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16);
|
||||
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12);
|
||||
x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8);
|
||||
x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7);
|
||||
}
|
||||
|
||||
/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */
|
||||
function chachaRound(x: TArg<Uint32Array>, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
// RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds.
|
||||
chachaQR(x, 0, 4, 8, 12);
|
||||
chachaQR(x, 1, 5, 9, 13);
|
||||
chachaQR(x, 2, 6, 10, 14);
|
||||
chachaQR(x, 3, 7, 11, 15);
|
||||
chachaQR(x, 0, 5, 10, 15);
|
||||
chachaQR(x, 1, 6, 11, 12);
|
||||
chachaQR(x, 2, 7, 8, 13);
|
||||
chachaQR(x, 3, 4, 9, 14);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared scratch for the auditability-only helper below; only the test-only
|
||||
// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant.
|
||||
const ctmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
|
||||
/** Small version of chacha without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function chacha(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
|
||||
isHChacha: boolean = true, rounds: number = 20
|
||||
): void {
|
||||
// `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block
|
||||
// function or the full 128-bit nonce prefix for the HChaCha subkey path.
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
k[0], k[1], k[2], k[3], // Key Key Key Key
|
||||
k[4], k[5], k[6], k[7], // Key Key Key Key
|
||||
i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce
|
||||
]);
|
||||
const x = ctmp;
|
||||
x.set(y);
|
||||
chachaRound(x, rounds);
|
||||
|
||||
// HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha
|
||||
// block path adds the original state word-by-word.
|
||||
if (isHChacha) {
|
||||
const xindexes = [0, 1, 2, 3, 12, 13, 14, 15];
|
||||
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
|
||||
} else {
|
||||
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */
|
||||
// @ts-ignore
|
||||
const chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) =>
|
||||
// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha().
|
||||
chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds);
|
||||
/** Identical to `hchacha`. Unused. */
|
||||
// @ts-ignore
|
||||
const hchacha_small: typeof hchacha = chacha;
|
||||
|
||||
/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */
|
||||
// prettier-ignore
|
||||
function chachaCore(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
|
||||
): void {
|
||||
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k"
|
||||
y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key
|
||||
y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key
|
||||
y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
|
||||
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
|
||||
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
|
||||
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
|
||||
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
|
||||
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
|
||||
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
|
||||
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
|
||||
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
|
||||
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
|
||||
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// RFC 8439 §2.3 / §2.3.1: add the original state words back in state order.
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
/**
|
||||
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
||||
* Algorithmically identical to `hchacha_small`, but this exported path
|
||||
* normalizes word order on big-endian hosts.
|
||||
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XChaCha subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hchacha(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hchacha(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
|
||||
): void {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]),
|
||||
x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]),
|
||||
x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]),
|
||||
x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12);
|
||||
x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8);
|
||||
x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7);
|
||||
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12);
|
||||
x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8);
|
||||
x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7);
|
||||
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12);
|
||||
x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8);
|
||||
x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7);
|
||||
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16);
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12);
|
||||
x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8)
|
||||
x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7);
|
||||
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12);
|
||||
x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8);
|
||||
x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7);
|
||||
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12);
|
||||
x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8);
|
||||
x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7);
|
||||
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12);
|
||||
x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8);
|
||||
x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7);
|
||||
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16)
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12);
|
||||
x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8);
|
||||
x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7);
|
||||
}
|
||||
// HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds.
|
||||
let oi = 0;
|
||||
out[oi++] = x00; out[oi++] = x01;
|
||||
out[oi++] = x02; out[oi++] = x03;
|
||||
out[oi++] = x12; out[oi++] = x13;
|
||||
out[oi++] = x14; out[oi++] = x15;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20orig } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* chacha20orig(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20orig: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
allowShortKeys: true,
|
||||
});
|
||||
/**
|
||||
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* The nonce/counter layout still reserves 8 counter bytes internally, but the shared public
|
||||
* `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts`
|
||||
* near `MAX_COUNTER` for the full counter-policy rationale.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte extended nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xchacha20(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 8,
|
||||
extendNonceFn: hchacha,
|
||||
allowShortKeys: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* Reduced 8-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha8(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha8: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 8,
|
||||
});
|
||||
|
||||
/**
|
||||
* Reduced 12-round chacha, described in original paper.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha12 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* chacha12(key, nonce, new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export const chacha12: TRet<XorStream> = /* @__PURE__ */ createCipher(chachaCore, {
|
||||
counterRight: false,
|
||||
counterLength: 4,
|
||||
rounds: 12,
|
||||
});
|
||||
|
||||
// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core.
|
||||
export const __TESTS: {
|
||||
chachaCore_small: typeof chachaCore_small;
|
||||
chachaCore: typeof chachaCore;
|
||||
} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore });
|
||||
|
||||
// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding.
|
||||
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
||||
// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes.
|
||||
const updatePadded = (h: ReturnType<typeof poly1305.create>, msg: TArg<Uint8Array>) => {
|
||||
h.update(msg);
|
||||
const leftover = msg.length % 16;
|
||||
if (leftover) h.update(ZEROS16.subarray(leftover));
|
||||
};
|
||||
|
||||
// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key
|
||||
// generation only needs 32 zero bytes.
|
||||
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
||||
function computeTag(
|
||||
fn: TArg<XorStream>,
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
ciphertext: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<Uint8Array> {
|
||||
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
|
||||
// RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0,
|
||||
// then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext).
|
||||
const authKey = fn(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
ZEROS32 as TRet<Uint8Array>
|
||||
);
|
||||
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
||||
|
||||
// Methods below can be replaced with
|
||||
// return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)
|
||||
const h = poly1305.create(authKey);
|
||||
if (AAD) updatePadded(h, AAD);
|
||||
updatePadded(h, ciphertext);
|
||||
h.update(lengths);
|
||||
const res = h.digest();
|
||||
clean(authKey, lengths);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* AEAD algorithm from RFC 8439.
|
||||
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
||||
* We could have composed them, but it's hard because of authKey:
|
||||
* In salsa20, authKey changes position in salsa stream.
|
||||
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
||||
*/
|
||||
export const _poly1305_aead =
|
||||
(xorStream: TArg<XorStream>) =>
|
||||
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>): CipherWithOutput => {
|
||||
// This borrows caller key/nonce/AAD buffers by reference; mutating them after construction
|
||||
// changes future encrypt/decrypt results.
|
||||
const tagLength = 16;
|
||||
return {
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
const plength = plaintext.length;
|
||||
output = getOutput(plength + tagLength, output, false);
|
||||
output.set(plaintext);
|
||||
const oPlain = output.subarray(0, -tagLength);
|
||||
// RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK.
|
||||
xorStream(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
oPlain as TRet<Uint8Array>,
|
||||
oPlain as TRet<Uint8Array>,
|
||||
1
|
||||
);
|
||||
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
||||
output.set(tag, plength); // append tag
|
||||
clean(tag);
|
||||
return output as TRet<Uint8Array>;
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
output = getOutput(ciphertext.length - tagLength, output, false);
|
||||
const data = ciphertext.subarray(0, -tagLength);
|
||||
const passedTag = ciphertext.subarray(-tagLength);
|
||||
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
||||
// RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with
|
||||
// the constant-time equalBytes() helper rather than decrypting speculative plaintext first.
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(tag);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
output.set(ciphertext.subarray(0, -tagLength));
|
||||
// Actual decryption
|
||||
xorStream(
|
||||
key as TRet<Uint8Array>,
|
||||
nonce as TRet<Uint8Array>,
|
||||
output as TRet<Uint8Array>,
|
||||
output as TRet<Uint8Array>,
|
||||
1
|
||||
); // start stream with i=1
|
||||
clean(tag);
|
||||
return output as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* ChaCha20-Poly1305 from RFC 8439.
|
||||
*
|
||||
* Unsafe to use random nonces under the same key, due to collision chance.
|
||||
* Prefer XChaCha instead.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 12-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { chacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = chacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const chacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 12, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(chacha20)
|
||||
);
|
||||
/**
|
||||
* XChaCha20-Poly1305 extended-nonce chacha.
|
||||
*
|
||||
* Can be safely used with random nonces (CSPRNG).
|
||||
* See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xchacha20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xchacha20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
/* @__PURE__ */ _poly1305_aead(xchacha20)
|
||||
);
|
||||
|
||||
/**
|
||||
* Chacha20 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 40-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the test-only ChaCha20 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha20 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha20(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha20: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8);
|
||||
/**
|
||||
* Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator).
|
||||
* It's best to limit usage to non-production, non-critical cases: for example, test-only.
|
||||
* Faster than `rngChacha20`.
|
||||
* @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted,
|
||||
* only 32 random bytes are mixed into the 44-byte state.
|
||||
* @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`.
|
||||
* @example
|
||||
* Seeds the faster test-only ChaCha8 DRBG from fresh entropy.
|
||||
*
|
||||
* ```ts
|
||||
* import { rngChacha8 } from '@noble/ciphers/chacha.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const seed = randomBytes(32);
|
||||
* const prg = rngChacha8(seed);
|
||||
* prg.randomBytes(8);
|
||||
* ```
|
||||
*/
|
||||
export const rngChacha8: TRet<XorPRG> = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12);
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* FPE-FF1 (Format-preserving encryption algorithm) specified in
|
||||
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
|
||||
* @module
|
||||
*/
|
||||
import { unsafe } from './aes.ts';
|
||||
import {
|
||||
abytes,
|
||||
anumber,
|
||||
bytesToNumberBE,
|
||||
clean,
|
||||
numberToBytesBE,
|
||||
type Cipher,
|
||||
type TArg,
|
||||
type TRet,
|
||||
} from './utils.ts';
|
||||
|
||||
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
|
||||
// reuses the reviewed AES key schedule and single-block encryption helpers.
|
||||
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
|
||||
const { expandKeyLE, encryptBlock } = unsafe;
|
||||
|
||||
// Format-preserving encryption algorithm (FPE-FF1) specified in
|
||||
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
|
||||
|
||||
const BLOCK_LEN = 16;
|
||||
|
||||
// FF1 step 6vi needs mathematical modulo in [0, b); JS `%` is remainder, so decrypt rounds must
|
||||
// map negative intermediate values back into that range.
|
||||
function mod(a: number, b: number): number;
|
||||
function mod(a: bigint, b: bigint): bigint;
|
||||
function mod(a: any, b: any): number | bigint {
|
||||
const result = a % b;
|
||||
return result >= 0 ? result : b + result;
|
||||
}
|
||||
|
||||
function NUMradix(radix: number, data: number[]): bigint {
|
||||
let res = BigInt(0);
|
||||
for (let i of data) res = res * BigInt(radix) + BigInt(i);
|
||||
return res;
|
||||
}
|
||||
|
||||
function getRound(radix: number, key: TArg<Uint8Array>, tweak: TArg<Uint8Array>, x: number[]) {
|
||||
if (radix > 2 ** 16 - 1) throw new Error('invalid radix ' + radix);
|
||||
// radix**minlen ≥ 100
|
||||
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
|
||||
const maxLen = 2 ** 32 - 1;
|
||||
// 2 ≤ minlen ≤ maxlen < 2**32
|
||||
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
|
||||
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
|
||||
if (!Array.isArray(x)) throw new Error('invalid X');
|
||||
if (x.length < minLen || x.length > maxLen) throw new Error('X is outside minLen..maxLen bounds');
|
||||
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
|
||||
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
|
||||
for (const i of x) {
|
||||
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
|
||||
throw new Error('invalid X: digit outside radix');
|
||||
}
|
||||
const u = Math.floor(x.length / 2);
|
||||
const v = x.length - u;
|
||||
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
|
||||
const d = 4 * Math.ceil(b / 4) + 4;
|
||||
const padding = mod(-tweak.length - b - 1, 16);
|
||||
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
|
||||
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
const view = new DataView(P.buffer);
|
||||
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
|
||||
// 0x00 || uint16_be(radix).
|
||||
view.setUint16(4, radix, false);
|
||||
view.setUint32(8, x.length, false);
|
||||
view.setUint32(12, tweak.length, false);
|
||||
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
|
||||
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
|
||||
PQ.set(P);
|
||||
clean(P);
|
||||
PQ.set(tweak, P.length);
|
||||
const xk = expandKeyLE(key);
|
||||
const round = (A: number[], B: number[], i: number, decrypt = false) => {
|
||||
// Q = ... || [i]1 || [NUMradix(B)]b.
|
||||
PQ[PQ.length - b - 1] = i;
|
||||
if (b) PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
|
||||
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
|
||||
let r = new Uint8Array(16);
|
||||
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
|
||||
for (let i = 0; i < BLOCK_LEN; i++) r[i] ^= PQ[j * BLOCK_LEN + i];
|
||||
encryptBlock(xk, r);
|
||||
}
|
||||
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
|
||||
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
|
||||
let s = Array.from(r);
|
||||
for (let j = 1; s.length < d; j++) {
|
||||
const block = numberToBytesBE(BigInt(j), 16);
|
||||
for (let k = 0; k < BLOCK_LEN; k++) block[k] ^= r[k];
|
||||
s.push(...Array.from(encryptBlock(xk, block)));
|
||||
}
|
||||
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
|
||||
s.fill(0);
|
||||
if (decrypt) y = -y;
|
||||
const m = i % 2 === 0 ? u : v;
|
||||
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
|
||||
// STR(radix, m, c)
|
||||
const C = Array(m).fill(0);
|
||||
for (let i = 0; i < m; i++, c /= BigInt(radix)) C[m - 1 - i] = Number(c % BigInt(radix));
|
||||
A.fill(0);
|
||||
A = B;
|
||||
B = C;
|
||||
return [A, B];
|
||||
};
|
||||
const destroy = () => {
|
||||
clean(xk, PQ);
|
||||
};
|
||||
return { u, round, destroy };
|
||||
}
|
||||
|
||||
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
|
||||
|
||||
/**
|
||||
* FPE-FF1 format-preserving encryption.
|
||||
* @param radix - Alphabet size for each input digit.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over digit arrays.
|
||||
* @example
|
||||
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { FF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = FF1(10, key);
|
||||
* ff1.encrypt([1, 2, 3]);
|
||||
* ```
|
||||
*/
|
||||
export function FF1(
|
||||
radix: number,
|
||||
key: TArg<Uint8Array>,
|
||||
tweak: TArg<Uint8Array> = EMPTY_BUF
|
||||
): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } {
|
||||
anumber(radix);
|
||||
abytes(key);
|
||||
abytes(tweak);
|
||||
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
|
||||
// after construction changes later encrypt/decrypt outputs.
|
||||
const PQ = getRound.bind(null, radix, key, tweak);
|
||||
return {
|
||||
encrypt(x: number[]): number[] {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
let [A, B] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 0; i < 10; i++) [A, B] = round(A, B, i);
|
||||
destroy();
|
||||
const res = A.concat(B);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
decrypt(x: number[]): number[] {
|
||||
const { u, round, destroy } = PQ(x);
|
||||
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
|
||||
// the differences are in Step 6, where:
|
||||
// 1) the order of the indices is reversed,
|
||||
// 2) the roles of A and B are swapped
|
||||
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
|
||||
let [B, A] = [x.slice(0, u), x.slice(u)];
|
||||
for (let i = 9; i >= 0; i--) [A, B] = round(A, B, i, true);
|
||||
destroy();
|
||||
const res = B.concat(A);
|
||||
A.fill(0);
|
||||
B.fill(0);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
|
||||
// in the first numeral slot for this library-defined byte-array surface.
|
||||
const binLE = {
|
||||
encode(bytes: TArg<Uint8Array>): number[] {
|
||||
const x = [];
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1);
|
||||
}
|
||||
return x;
|
||||
},
|
||||
decode(b: number[]): TRet<Uint8Array> {
|
||||
if (!Array.isArray(b) || b.length % 8) throw new Error('Invalid binary string');
|
||||
const res = new Uint8Array(b.length / 8);
|
||||
for (let i = 0, j = 0; i < res.length; i++) {
|
||||
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
|
||||
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
|
||||
}
|
||||
return res as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Binary FPE-FF1 wrapper over byte arrays.
|
||||
* @param key - AES key bytes.
|
||||
* @param tweak - Optional tweak bytes.
|
||||
* @returns Encrypt/decrypt helpers over byte arrays.
|
||||
* @example
|
||||
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
||||
*
|
||||
* ```ts
|
||||
* import { BinaryFF1 } from '@noble/ciphers/ff1.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const ff1 = BinaryFF1(key);
|
||||
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function BinaryFF1(
|
||||
key: TArg<Uint8Array>,
|
||||
tweak: TArg<Uint8Array> = EMPTY_BUF
|
||||
): TRet<Cipher> {
|
||||
const ff1 = FF1(2, key, tweak);
|
||||
return {
|
||||
encrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
|
||||
binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet<Uint8Array>,
|
||||
decrypt: (x: TArg<Uint8Array>): TRet<Uint8Array> =>
|
||||
binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet<Uint8Array>,
|
||||
} as TRet<Cipher>;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
|
||||
* @example
|
||||
```js
|
||||
import { gcm, aessiv } from '@noble/ciphers/aes.js';
|
||||
import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305
|
||||
import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// Unauthenticated encryption: make sure to use HMAC or similar
|
||||
import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js';
|
||||
import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js';
|
||||
|
||||
// KW
|
||||
import { aeskw, aeskwp } from '@noble/ciphers/aes.js';
|
||||
|
||||
// Utilities
|
||||
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js';
|
||||
import { poly1305 } from '@noble/ciphers/_poly1305.js';
|
||||
import { ghash, polyval } from '@noble/ciphers/_polyval.js';
|
||||
```
|
||||
* @module
|
||||
*/
|
||||
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
/**
|
||||
* Salsa20 stream cipher, released in 2005.
|
||||
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
||||
* which are hard to implement in a constant-time manner.
|
||||
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
||||
*
|
||||
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
|
||||
* extended-nonce
|
||||
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
|
||||
* and became safe to be picked at random.
|
||||
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
||||
* We provide the alias and corresponding seal / open methods.
|
||||
* "crypto_box" and "sealedbox" are available in package
|
||||
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
|
||||
* - Check out
|
||||
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
|
||||
* and {@link https://cr.yp.to/snuffle.html | website}.
|
||||
* @module
|
||||
*/
|
||||
import { createCipher, rotl } from './_arx.ts';
|
||||
import { poly1305 } from './_poly1305.ts';
|
||||
import {
|
||||
abytes,
|
||||
clean,
|
||||
equalBytes,
|
||||
getOutput,
|
||||
swap32IfBE,
|
||||
swap8IfBE,
|
||||
wrapCipher,
|
||||
type ARXCipher,
|
||||
type CipherWithOutput,
|
||||
type TArg,
|
||||
type TRet,
|
||||
type XorStream,
|
||||
} from './utils.ts';
|
||||
|
||||
/**
|
||||
* Salsa20 core function. It is implemented twice:
|
||||
* 1. Simple loop (salsaCore_small, hsalsa_small)
|
||||
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
|
||||
* The specific implementation is selected in `createCipher` below.
|
||||
* Performance numbers for 1MB inputs:
|
||||
* * default x 779 ops/sec @ 1ms/op
|
||||
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
|
||||
* * small x 132 ops/sec @ 7ms/op
|
||||
*/
|
||||
|
||||
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
|
||||
function salsaQR(x: TArg<Uint32Array>, a: number, b: number, c: number, d: number) {
|
||||
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
|
||||
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
|
||||
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
|
||||
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
|
||||
}
|
||||
|
||||
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
|
||||
function salsaRound(x: TArg<Uint32Array>, rounds = 20) {
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
salsaQR(x, 0, 4, 8, 12);
|
||||
salsaQR(x, 5, 9, 13, 1);
|
||||
salsaQR(x, 10, 14, 2, 6);
|
||||
salsaQR(x, 15, 3, 7, 11);
|
||||
salsaQR(x, 0, 1, 2, 3);
|
||||
salsaQR(x, 5, 6, 7, 4);
|
||||
salsaQR(x, 10, 11, 8, 9);
|
||||
salsaQR(x, 15, 12, 13, 14);
|
||||
}
|
||||
}
|
||||
|
||||
// Shared scratch for the unused auditability helper below; it would be
|
||||
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
|
||||
const stmp = /* @__PURE__ */ new Uint32Array(16);
|
||||
|
||||
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
|
||||
// prettier-ignore
|
||||
function salsa(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>,
|
||||
isHSalsa: boolean = true, rounds: number = 20
|
||||
): void {
|
||||
// Create initial array using common pattern
|
||||
const y = Uint32Array.from([
|
||||
s[0], k[0], k[1], k[2], // "expa" Key Key Key
|
||||
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
|
||||
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
|
||||
k[5], k[6], k[7], s[3], // Key Key Key "te k"
|
||||
]);
|
||||
const x = stmp;
|
||||
x.set(y);
|
||||
// const x = y.slice();
|
||||
salsaRound(x, rounds);
|
||||
|
||||
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
|
||||
if (isHSalsa) {
|
||||
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
|
||||
for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]];
|
||||
} else {
|
||||
for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0;
|
||||
}
|
||||
}
|
||||
/** Identical to `salsaCore`. Unused. */
|
||||
// @ts-ignore
|
||||
const salsaCore_small: typeof salsaCore = (s, k, n, out, cnt, rounds) =>
|
||||
salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
|
||||
/** Identical to `hsalsa`. Unused. */
|
||||
// @ts-ignore
|
||||
const hsalsa_small: typeof hsalsa = salsa;
|
||||
|
||||
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
|
||||
// prettier-ignore
|
||||
function salsaCore(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, n: TArg<Uint32Array>, out: TArg<Uint32Array>, cnt: number, rounds = 20
|
||||
): void {
|
||||
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
|
||||
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
|
||||
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
|
||||
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
|
||||
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
|
||||
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
|
||||
// Save state to temporary variables
|
||||
let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
|
||||
x04 = y04, x05 = y05, x06 = y06, x07 = y07,
|
||||
x08 = y08, x09 = y09, x10 = y10, x11 = y11,
|
||||
x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
||||
for (let r = 0; r < rounds; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
// Write output
|
||||
let oi = 0;
|
||||
out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
|
||||
out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
|
||||
out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
|
||||
out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
|
||||
out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
|
||||
out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
|
||||
out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
|
||||
out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
||||
* Identical to `hsalsa_small`.
|
||||
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
||||
* @param s - Sigma constants as 32-bit words.
|
||||
* @param k - Key words.
|
||||
* @param i - Nonce-prefix words.
|
||||
* @param out - Output buffer for the derived subkey.
|
||||
* @example
|
||||
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
||||
*
|
||||
* ```ts
|
||||
* const sigma = new Uint32Array(4);
|
||||
* const key = new Uint32Array(8);
|
||||
* const nonce = new Uint32Array(4);
|
||||
* const out = new Uint32Array(8);
|
||||
* hsalsa(sigma, key, nonce, out);
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function hsalsa(
|
||||
s: TArg<Uint32Array>, k: TArg<Uint32Array>, i: TArg<Uint32Array>, out: TArg<Uint32Array>
|
||||
): void {
|
||||
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]),
|
||||
x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]),
|
||||
x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]),
|
||||
x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
|
||||
for (let r = 0; r < 20; r += 2) {
|
||||
x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
|
||||
x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
|
||||
x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
|
||||
x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
|
||||
x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
|
||||
x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
|
||||
x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
|
||||
x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
|
||||
x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
|
||||
x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
|
||||
x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
|
||||
x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
|
||||
x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
|
||||
x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
|
||||
x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
|
||||
x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
|
||||
}
|
||||
let oi = 0;
|
||||
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
|
||||
out[oi++] = x00; out[oi++] = x05;
|
||||
out[oi++] = x10; out[oi++] = x15;
|
||||
out[oi++] = x06; out[oi++] = x07;
|
||||
out[oi++] = x08; out[oi++] = x09;
|
||||
swap32IfBE(out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Salsa20 from original paper. 8-byte nonce.
|
||||
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
||||
* @param key - 16-byte or 32-byte key.
|
||||
* @param nonce - 8-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
||||
* the high word stays zero and the implementation still caps the public
|
||||
* value to 32 bits.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
||||
*
|
||||
* ```ts
|
||||
* import { salsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(8);
|
||||
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const salsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
allowShortKeys: true,
|
||||
counterRight: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* XSalsa20 extended-nonce salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* @param key - 32-byte key.
|
||||
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Initial block counter.
|
||||
* @returns Encrypted or decrypted bytes.
|
||||
* @example
|
||||
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20: TRet<XorStream> = /* @__PURE__ */ createCipher(salsaCore, {
|
||||
counterRight: true,
|
||||
extendNonceFn: hsalsa,
|
||||
});
|
||||
|
||||
/**
|
||||
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
||||
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
||||
* Also known as `secretbox` from libsodium / nacl.
|
||||
* No AAD input is supported here. Caller-provided `output` buffers for
|
||||
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
||||
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
||||
* @returns AEAD cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const cipher = xsalsa20poly1305(key, nonce);
|
||||
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const xsalsa20poly1305: TRet<ARXCipher> = /* @__PURE__ */ wrapCipher(
|
||||
{ blockSize: 64, nonceLength: 24, tagLength: 16 },
|
||||
(key: TArg<Uint8Array>, nonce: TArg<Uint8Array>): TRet<CipherWithOutput> => {
|
||||
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
|
||||
// later encrypt/decrypt outputs.
|
||||
return {
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
|
||||
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
|
||||
// because 32 bytes is half-block of 64-byte salsa.
|
||||
// Need 32 extra bytes up front for the auth-key scratch area described above.
|
||||
output = getOutput(plaintext.length + 32, output, false);
|
||||
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
|
||||
const authKey = output.subarray(0, 32);
|
||||
const ciphPlaintext = output.subarray(32);
|
||||
output.set(plaintext, 32);
|
||||
// authKey is produced by xoring the first 32 bytes with zeros.
|
||||
clean(authKey);
|
||||
// output = stream ^ output; authKey = stream ^ zeros(32)
|
||||
xsalsa20(key, nonce, output, output);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
output.set(tag, 16);
|
||||
// Clean up auth-key remnants and the temporary tag copy.
|
||||
clean(output.subarray(0, 16), tag);
|
||||
// Return output[16..].
|
||||
return output.subarray(16) as TRet<Uint8Array>;
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array> {
|
||||
// tmp part passed tag ciphertext
|
||||
// [0..32] [32..48] [48..]
|
||||
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
|
||||
// buffer may already contain copied ciphertext and derived auth-key material.
|
||||
abytes(ciphertext);
|
||||
output = getOutput(ciphertext.length + 32, output, false);
|
||||
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
|
||||
// output[48..] is ciphertext then plaintext.
|
||||
const tmp = output.subarray(0, 32);
|
||||
const passedTag = output.subarray(32, 48);
|
||||
const ciphPlaintext = output.subarray(48);
|
||||
output.set(ciphertext, 32);
|
||||
// authKey is produced by xoring the scratch area with zeros.
|
||||
clean(tmp);
|
||||
const authKey = xsalsa20(key, nonce, tmp, tmp);
|
||||
const tag = poly1305(ciphPlaintext, authKey);
|
||||
if (!equalBytes(passedTag, tag)) {
|
||||
clean(output);
|
||||
throw new Error('invalid tag');
|
||||
}
|
||||
// output = stream ^ output[16..]
|
||||
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
|
||||
clean(tmp, passedTag, tag);
|
||||
// Return output[48..], skipping zeroized output[0..48].
|
||||
return ciphPlaintext as TRet<Uint8Array>;
|
||||
},
|
||||
} as TRet<CipherWithOutput>;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
||||
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
||||
* for `crypto_box`.
|
||||
* @param key - 32-byte key.
|
||||
* @param nonce - 24-byte nonce.
|
||||
* @returns Wrapper with `seal()` and `open()` helpers.
|
||||
* @example
|
||||
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
||||
*
|
||||
* ```ts
|
||||
* import { secretbox } from '@noble/ciphers/salsa.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(32);
|
||||
* const nonce = randomBytes(24);
|
||||
* const box = secretbox(key, nonce);
|
||||
* box.seal(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export function secretbox(
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>
|
||||
): TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}> {
|
||||
const xs = xsalsa20poly1305(key, nonce);
|
||||
return { seal: xs.encrypt, open: xs.decrypt } as TRet<{
|
||||
seal: (plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
open: (ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>) => TRet<Uint8Array>;
|
||||
}>;
|
||||
}
|
||||
+1191
File diff suppressed because it is too large
Load Diff
+226
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, anumber, type AsyncCipher, type TArg, type TRet } from './utils.ts';
|
||||
|
||||
function getWebcryptoSubtle(): any {
|
||||
const cr = typeof globalThis !== 'undefined' && (globalThis as any).crypto;
|
||||
if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle;
|
||||
throw new Error('crypto.subtle must be defined');
|
||||
}
|
||||
|
||||
type WebcryptoUtils = {
|
||||
encrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: unknown,
|
||||
cryptParams: unknown,
|
||||
plaintext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>>;
|
||||
decrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: unknown,
|
||||
cryptParams: unknown,
|
||||
ciphertext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export const utils: TRet<WebcryptoUtils> = {
|
||||
async encrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: any,
|
||||
cryptParams: any,
|
||||
plaintext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>> {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
|
||||
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
|
||||
return new Uint8Array(ciphertext) as TRet<Uint8Array>;
|
||||
},
|
||||
async decrypt(
|
||||
key: TArg<Uint8Array>,
|
||||
keyParams: any,
|
||||
cryptParams: any,
|
||||
ciphertext: TArg<Uint8Array>
|
||||
): Promise<TRet<Uint8Array>> {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
|
||||
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
|
||||
return new Uint8Array(plaintext) as TRet<Uint8Array>;
|
||||
},
|
||||
};
|
||||
|
||||
const mode = {
|
||||
CBC: 'AES-CBC',
|
||||
CTR: 'AES-CTR',
|
||||
GCM: 'AES-GCM',
|
||||
} as const;
|
||||
type BlockMode = (typeof mode)[keyof typeof mode];
|
||||
|
||||
function getCryptParams(algo: BlockMode, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) {
|
||||
if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };
|
||||
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
|
||||
if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 128 };
|
||||
if (algo === mode.GCM) {
|
||||
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
|
||||
if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD };
|
||||
else return { name: mode.GCM, iv: nonce };
|
||||
}
|
||||
|
||||
throw new Error('unknown aes block mode');
|
||||
}
|
||||
|
||||
function generate(
|
||||
algo: BlockMode,
|
||||
nonceLength: number
|
||||
): TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> {
|
||||
anumber(nonceLength);
|
||||
const res = (
|
||||
key: TArg<Uint8Array>,
|
||||
nonce: TArg<Uint8Array>,
|
||||
AAD?: TArg<Uint8Array>
|
||||
): TRet<AsyncCipher> => {
|
||||
abytes(key);
|
||||
abytes(nonce);
|
||||
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
|
||||
if (AAD !== undefined) abytes(AAD, undefined, 'AAD');
|
||||
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
|
||||
// delegated to the backend; locally we only require byte-array inputs here.
|
||||
// Keep caller key/nonce/AAD by reference; mutating them after
|
||||
// construction changes later operations.
|
||||
const keyParams = { name: algo, length: key.length * 8 };
|
||||
const cryptParams = getCryptParams(algo, nonce, AAD);
|
||||
let consumed = false;
|
||||
return {
|
||||
// keyLength,
|
||||
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
|
||||
abytes(plaintext);
|
||||
if (consumed) throw new Error('Cannot encrypt() twice with same key / nonce');
|
||||
consumed = true;
|
||||
return utils.encrypt(key, keyParams, cryptParams, plaintext);
|
||||
},
|
||||
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>> {
|
||||
abytes(ciphertext);
|
||||
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
|
||||
},
|
||||
} as TRet<AsyncCipher>;
|
||||
};
|
||||
res.nonceLength = nonceLength;
|
||||
res.blockSize = 16; // always for AES
|
||||
return res as TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export const cbc: TRet<
|
||||
((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const ctr: TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const gcm: TRet<
|
||||
((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}
|
||||
> = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
|
||||
|
||||
// // Type tests
|
||||
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
|
||||
// import { xsalsa20poly1305 } from '../salsa.ts';
|
||||
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
|
||||
|
||||
// const wsiv = managedNonce(siv);
|
||||
// const wgcm = managedNonce(gcm);
|
||||
// const wctr = managedNonce(ctr);
|
||||
// const wcbc = managedNonce(cbc);
|
||||
// const wsalsapoly = managedNonce(xsalsa20poly1305);
|
||||
// const wchacha = managedNonce(chacha20poly1305);
|
||||
// const wxchacha = managedNonce(xchacha20poly1305);
|
||||
|
||||
// // should fail
|
||||
// const wcbc2 = managedNonce(managedNonce(cbc));
|
||||
// const wctr = managedNonce(ctr);
|
||||
// import { gcm as gcmSync } from '../aes.ts';
|
||||
// const x1 = managedNonce(gcmSync);
|
||||
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
|
||||
// const x2 = managedNonce(gcm);
|
||||
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
|
||||
+717
@@ -0,0 +1,717 @@
|
||||
/**
|
||||
* Utilities for hex, bytes, CSPRNG.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||||
/**
|
||||
* Bytes API type helpers for old + new TypeScript.
|
||||
*
|
||||
* TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.
|
||||
* We can't use specific return type, because TS 5.6 will error.
|
||||
* We can't use generic return type, because most TS 5.9 software will expect specific type.
|
||||
*
|
||||
* Maps typed-array input leaves to broad forms.
|
||||
* These are compatibility adapters, not ownership guarantees.
|
||||
*
|
||||
* - `TArg` keeps byte inputs broad.
|
||||
* - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.
|
||||
*/
|
||||
export type TypedArg<T> = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never;
|
||||
/** Maps typed-array output leaves to narrow TS-compatible forms. */
|
||||
export type TypedRet<T> = T extends BigInt64Array ? ReturnType<typeof BigInt64Array.of> : T extends BigUint64Array ? ReturnType<typeof BigUint64Array.of> : T extends Float32Array ? ReturnType<typeof Float32Array.of> : T extends Float64Array ? ReturnType<typeof Float64Array.of> : T extends Int16Array ? ReturnType<typeof Int16Array.of> : T extends Int32Array ? ReturnType<typeof Int32Array.of> : T extends Int8Array ? ReturnType<typeof Int8Array.of> : T extends Uint16Array ? ReturnType<typeof Uint16Array.of> : T extends Uint32Array ? ReturnType<typeof Uint32Array.of> : T extends Uint8ClampedArray ? ReturnType<typeof Uint8ClampedArray.of> : T extends Uint8Array ? ReturnType<typeof Uint8Array.of> : never;
|
||||
/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */
|
||||
export type TArg<T> = T | ([TypedArg<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
|
||||
[K in keyof A]: TRet<A[K]>;
|
||||
}) => TArg<R>) & {
|
||||
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;
|
||||
} : T extends [infer A, ...infer R] ? [TArg<A>, ...{
|
||||
[K in keyof R]: TArg<R[K]>;
|
||||
}] : T extends readonly [infer A, ...infer R] ? readonly [TArg<A>, ...{
|
||||
[K in keyof R]: TArg<R[K]>;
|
||||
}] : T extends (infer A)[] ? TArg<A>[] : T extends readonly (infer A)[] ? readonly TArg<A>[] : T extends Promise<infer A> ? Promise<TArg<A>> : T extends object ? {
|
||||
[K in keyof T]: TArg<T[K]>;
|
||||
} : T : TypedArg<T>);
|
||||
/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */
|
||||
export type TRet<T> = T extends unknown ? T & ([TypedRet<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
|
||||
[K in keyof A]: TArg<A[K]>;
|
||||
}) => TRet<R>) & {
|
||||
[K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;
|
||||
} : T extends [infer A, ...infer R] ? [TRet<A>, ...{
|
||||
[K in keyof R]: TRet<R[K]>;
|
||||
}] : T extends readonly [infer A, ...infer R] ? readonly [TRet<A>, ...{
|
||||
[K in keyof R]: TRet<R[K]>;
|
||||
}] : T extends (infer A)[] ? TRet<A>[] : T extends readonly (infer A)[] ? readonly TRet<A>[] : T extends Promise<infer A> ? Promise<TRet<A>> : T extends object ? {
|
||||
[K in keyof T]: TRet<T[K]>;
|
||||
} : T : TypedRet<T>) : never;
|
||||
/**
|
||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
||||
* @param a - Value to inspect.
|
||||
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
|
||||
* @example
|
||||
* Guards a value before treating it as raw key material.
|
||||
*
|
||||
* ```ts
|
||||
* isBytes(new Uint8Array());
|
||||
* ```
|
||||
*/
|
||||
export declare function isBytes(a: unknown): a is Uint8Array;
|
||||
/**
|
||||
* Asserts something is boolean.
|
||||
* @param b - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Validates a boolean option before branching on it.
|
||||
*
|
||||
* ```ts
|
||||
* abool(true);
|
||||
* ```
|
||||
*/
|
||||
export declare function abool(b: boolean): void;
|
||||
/**
|
||||
* Asserts something is a non-negative safe integer.
|
||||
* @param n - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Validates a non-negative length or counter.
|
||||
*
|
||||
* ```ts
|
||||
* anumber(1);
|
||||
* ```
|
||||
*/
|
||||
export declare function anumber(n: number): void;
|
||||
/**
|
||||
* Asserts something is Uint8Array.
|
||||
* @param value - Value to validate.
|
||||
* @param length - Expected byte length.
|
||||
* @param title - Optional label used in error messages.
|
||||
* @returns The validated byte array.
|
||||
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument lengths. {@link RangeError}
|
||||
* @example
|
||||
* Validates a fixed-length nonce or key buffer.
|
||||
*
|
||||
* ```ts
|
||||
* abytes(new Uint8Array([1, 2]), 2);
|
||||
* ```
|
||||
*/
|
||||
export declare function abytes(value: TArg<Uint8Array>, length?: number, title?: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
|
||||
* @param instance - Stateful instance to validate.
|
||||
* @param checkFinished - Whether to reject finished instances.
|
||||
* When `false`, only `destroyed` is checked.
|
||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
||||
* @example
|
||||
* Guards against calling `update()` or `digest()` on a finished hash.
|
||||
*
|
||||
* ```ts
|
||||
* aexists({ destroyed: false, finished: false });
|
||||
* ```
|
||||
*/
|
||||
export declare function aexists(instance: any, checkFinished?: boolean): void;
|
||||
/**
|
||||
* Asserts output is a properly-sized byte array.
|
||||
* @param out - Output buffer to validate.
|
||||
* @param instance - Hash-like instance providing `outputLen`.
|
||||
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
|
||||
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
|
||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
||||
* @throws On wrong output buffer alignment. {@link Error}
|
||||
* @example
|
||||
* Verifies that a caller-provided output buffer is large enough.
|
||||
*
|
||||
* ```ts
|
||||
* aoutput(new Uint8Array(16), { outputLen: 16 });
|
||||
* ```
|
||||
*/
|
||||
export declare function aoutput(out: any, instance: any, onlyAligned?: boolean): void;
|
||||
/** One-shot hash helper with `.create()`. */
|
||||
export type IHash = {
|
||||
(data: string | TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/** Input block size in bytes. */
|
||||
blockLen: number;
|
||||
/** Digest size in bytes. */
|
||||
outputLen: number;
|
||||
/** Creates a fresh incremental hash instance of the same algorithm. */
|
||||
create: any;
|
||||
};
|
||||
/** One-shot MAC helper with `.create()`. */
|
||||
export type CMac<H extends IHash2 = IHash2, A extends any[] = []> = {
|
||||
(msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/** Input block size in bytes. */
|
||||
blockLen: number;
|
||||
/** Digest size in bytes. */
|
||||
outputLen: number;
|
||||
/**
|
||||
* Creates a fresh incremental MAC instance of the same algorithm.
|
||||
* @param key - MAC key bytes.
|
||||
* @param args - Additional constructor arguments, when the MAC wrapper needs them.
|
||||
* @returns Fresh incremental MAC instance.
|
||||
*/
|
||||
create(key: TArg<Uint8Array>, ...args: A): H;
|
||||
};
|
||||
/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */
|
||||
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
|
||||
/**
|
||||
* Casts a typed-array view to Uint8Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint8Array view over the same bytes.
|
||||
* @example
|
||||
* Views 32-bit words as raw bytes without copying.
|
||||
*
|
||||
* ```ts
|
||||
* u8(new Uint32Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export declare function u8(arr: TArg<TypedArray>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Casts a typed-array view to Uint32Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
|
||||
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
|
||||
* @example
|
||||
* Views a byte buffer as 32-bit words for block processing.
|
||||
*
|
||||
* ```ts
|
||||
* u32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function u32(arr: TArg<TypedArray>): TRet<Uint32Array>;
|
||||
/**
|
||||
* Zeroizes typed arrays in place.
|
||||
* Warning: JS provides no guarantees.
|
||||
* @param arrays - Arrays to wipe.
|
||||
* @example
|
||||
* Wipes a temporary key buffer after use.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([1]);
|
||||
* clean(bytes);
|
||||
* ```
|
||||
*/
|
||||
export declare function clean(...arrays: TArg<TypedArray[]>): void;
|
||||
/**
|
||||
* Creates a DataView for byte-level manipulation.
|
||||
* @param arr - Typed-array view to wrap.
|
||||
* @returns DataView over the same bytes.
|
||||
* @example
|
||||
* Creates an endian-aware view for length encoding.
|
||||
*
|
||||
* ```ts
|
||||
* createView(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function createView(arr: TArg<TypedArray>): DataView;
|
||||
/**
|
||||
* Whether the current platform is little-endian.
|
||||
* Most are; some IBM systems are not.
|
||||
*/
|
||||
export declare const isLE: boolean;
|
||||
/**
|
||||
* Reverses byte order of one 32-bit word.
|
||||
* @param word - Unsigned 32-bit word to swap.
|
||||
* @returns The same word with bytes reversed.
|
||||
* @example
|
||||
* Swaps a big-endian word into little-endian byte order.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export declare const byteSwap: (word: number) => number;
|
||||
/**
|
||||
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
|
||||
* @param n - Unsigned 32-bit word to normalize.
|
||||
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
|
||||
* @example
|
||||
* Normalizes a host-endian word before passing it into an ARX/AES core.
|
||||
*
|
||||
* ```ts
|
||||
* swap8IfBE(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export declare const swap8IfBE: (n: number) => number;
|
||||
/**
|
||||
* Byte-swaps every word of a Uint32Array in place.
|
||||
* @param arr - Uint32Array whose words should be swapped.
|
||||
* @returns The same array after in-place byte swapping.
|
||||
* @example
|
||||
* Swaps every 32-bit word in a word-view buffer.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap32(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export declare const byteSwap32: (arr: TArg<Uint32Array>) => TRet<Uint32Array>;
|
||||
/**
|
||||
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
|
||||
* @param u - Word view to normalize in place.
|
||||
* @returns Little-endian normalized word view.
|
||||
* @example
|
||||
* Normalizes a word-view buffer before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export declare const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array>;
|
||||
/**
|
||||
* Convert byte array to hex string. Uses built-in function, when available.
|
||||
* @param bytes - Bytes to encode.
|
||||
* @returns Lowercase hexadecimal string.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Formats ciphertext bytes for logs or test vectors.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToHex(bytes: TArg<Uint8Array>): string;
|
||||
/**
|
||||
* Convert hex string to byte array. Uses built-in function, when available.
|
||||
* @param hex - Hexadecimal string to decode.
|
||||
* @returns Decoded bytes.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On malformed hexadecimal input. {@link RangeError}
|
||||
* @example
|
||||
* Parses a hex test vector into bytes.
|
||||
*
|
||||
* ```ts
|
||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
||||
* ```
|
||||
*/
|
||||
export declare function hexToBytes(hex: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts a big-endian hex string into bigint.
|
||||
* @param hex - Hexadecimal string without `0x`.
|
||||
* @returns Parsed bigint value. The empty string is treated as `0n`.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Parses a big-endian field element or counter from hex.
|
||||
*
|
||||
* ```ts
|
||||
* hexToNumber('ff');
|
||||
* ```
|
||||
*/
|
||||
export declare function hexToNumber(hex: string): bigint;
|
||||
/**
|
||||
* Converts big-endian bytes into bigint.
|
||||
* @param bytes - Big-endian bytes.
|
||||
* @returns Parsed bigint value. Empty input is treated as `0n`.
|
||||
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
|
||||
* @example
|
||||
* Reads a big-endian integer from serialized bytes.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToNumberBE(new Uint8Array([1, 0]));
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint;
|
||||
/**
|
||||
* Converts a number into big-endian bytes of fixed length.
|
||||
* @param n - Number to encode.
|
||||
* @param len - Output length in bytes.
|
||||
* @returns Big-endian bytes padded to `len`.
|
||||
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
|
||||
* and values that do not fit surface through the downstream hex parser instead of a
|
||||
* dedicated range guard here.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
|
||||
* @example
|
||||
* Encodes a counter as fixed-width big-endian bytes.
|
||||
*
|
||||
* ```ts
|
||||
* numberToBytesBE(1, 2);
|
||||
* ```
|
||||
*/
|
||||
export declare function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts string to bytes using UTF8 encoding.
|
||||
* @param str - String to encode.
|
||||
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Encodes application text before encryption or MACing.
|
||||
*
|
||||
* ```ts
|
||||
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
|
||||
* ```
|
||||
*/
|
||||
export declare function utf8ToBytes(str: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @param bytes - UTF-8 bytes.
|
||||
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
|
||||
* UTF-8 is replacement-decoded instead of rejected.
|
||||
* @example
|
||||
* Decodes UTF-8 plaintext back into a string.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
|
||||
* ```
|
||||
*/
|
||||
export declare function bytesToUtf8(bytes: TArg<Uint8Array>): string;
|
||||
/**
|
||||
* Checks if two U8A use same underlying buffer and overlaps.
|
||||
* This is invalid and can corrupt data.
|
||||
* @param a - First byte view.
|
||||
* @param b - Second byte view.
|
||||
* @returns `true` when the views overlap in memory.
|
||||
* @example
|
||||
* Detects whether two slices alias the same backing buffer.
|
||||
*
|
||||
* ```ts
|
||||
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function overlapBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* If input and output overlap and input starts before output, we will overwrite end of input before
|
||||
* we start processing it, so this is not supported for most ciphers
|
||||
* (except chacha/salsa, which were designed for this)
|
||||
* @param input - Input bytes.
|
||||
* @param output - Output bytes.
|
||||
* @throws If the output view would overwrite unread input bytes. {@link Error}
|
||||
* @example
|
||||
* Rejects an in-place layout that would overwrite unread input bytes.
|
||||
*
|
||||
* ```ts
|
||||
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function complexOverlapBytes(input: TArg<Uint8Array>, output: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Copies several Uint8Arrays into one.
|
||||
* @param arrays - Byte arrays to concatenate.
|
||||
* @returns Combined byte array.
|
||||
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
|
||||
* @example
|
||||
* Builds a `nonce || ciphertext` style buffer.
|
||||
*
|
||||
* ```ts
|
||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
||||
* ```
|
||||
*/
|
||||
export declare function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array>;
|
||||
type EmptyObj = {};
|
||||
/**
|
||||
* Merges user options into defaults.
|
||||
* @param defaults - Default option values.
|
||||
* @param opts - User-provided overrides.
|
||||
* @returns Combined options object.
|
||||
* The merge mutates `defaults` in place and returns the same object.
|
||||
* @throws If options are missing or not an object. {@link Error}
|
||||
* @example
|
||||
* Applies user overrides to the default cipher options.
|
||||
*
|
||||
* ```ts
|
||||
* checkOpts({ rounds: 20 }, { rounds: 8 });
|
||||
* ```
|
||||
*/
|
||||
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
|
||||
/**
|
||||
* Compares two byte arrays in kinda constant time once lengths already match.
|
||||
* @param a - First byte array.
|
||||
* @param b - Second byte array.
|
||||
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
|
||||
* @example
|
||||
* Compares an expected authentication tag with the received one.
|
||||
*
|
||||
* ```ts
|
||||
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export declare function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
|
||||
/** Incremental hash interface used internally. */
|
||||
export interface IHash2 {
|
||||
/** Bytes processed per compression block. */
|
||||
blockLen: number;
|
||||
/** Bytes produced by the final digest. */
|
||||
outputLen: number;
|
||||
/**
|
||||
* Absorbs one more chunk into the hash state.
|
||||
* @param buf - Data chunk to hash.
|
||||
* @returns The same hash instance for chaining.
|
||||
*/
|
||||
update(buf: string | TArg<Uint8Array>): this;
|
||||
/**
|
||||
* Writes the final digest into a caller-provided buffer.
|
||||
* @param buf - Destination buffer for the digest bytes.
|
||||
* @returns Nothing. Implementations write into `buf` in place.
|
||||
*/
|
||||
digestInto(buf: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Finalizes the hash and returns a fresh digest buffer.
|
||||
* @returns Digest bytes.
|
||||
*/
|
||||
digest(): TRet<Uint8Array>;
|
||||
/**
|
||||
* Resets internal state. Makes Hash instance unusable.
|
||||
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
|
||||
* by user, they will need to manually call `destroy()` when zeroing is necessary.
|
||||
*/
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
|
||||
* @param keyLen - Valid probe-key length used to read static metadata once.
|
||||
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
|
||||
* can pass any representative size as long as those values stay fixed.
|
||||
* @param macCons - Keyed MAC constructor or factory.
|
||||
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
|
||||
* @returns Callable MAC helper with `.create()`.
|
||||
*/
|
||||
export declare function wrapMacConstructor<H extends IHash2, A extends any[] = []>(keyLen: number, macCons: TArg<(key: Uint8Array, ...args: A) => H>, fromMsg?: TArg<(msg: Uint8Array) => A>): TRet<CMac<H, A>>;
|
||||
/** Sync cipher: takes byte array and returns byte array. */
|
||||
export type Cipher = {
|
||||
/**
|
||||
* Encrypts plaintext bytes.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @returns Ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @returns Plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
};
|
||||
/** Async cipher e.g. from built-in WebCrypto. */
|
||||
export type AsyncCipher = {
|
||||
/**
|
||||
* Encrypts plaintext bytes.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @returns Promise resolving to ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @returns Promise resolving to plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/** Cipher with `output` argument which can optimize by doing 1 less allocation. */
|
||||
export type CipherWithOutput = Cipher & {
|
||||
/**
|
||||
* Encrypts plaintext bytes into an optional caller-provided buffer.
|
||||
* @param plaintext - Data to encrypt.
|
||||
* @param output - Optional destination buffer.
|
||||
* @returns Ciphertext bytes.
|
||||
*/
|
||||
encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Decrypts ciphertext bytes into an optional caller-provided buffer.
|
||||
* @param ciphertext - Data to decrypt.
|
||||
* @param output - Optional destination buffer.
|
||||
* @returns Plaintext bytes.
|
||||
*/
|
||||
decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
};
|
||||
/**
|
||||
* Params are outside of return type, so it is accessible before calling constructor.
|
||||
* If function support multiple nonceLength's, we return the best one.
|
||||
*/
|
||||
export type CipherParams = {
|
||||
/** Cipher block size in bytes. */
|
||||
blockSize: number;
|
||||
/** Nonce length in bytes when the cipher uses a fixed nonce size. */
|
||||
nonceLength?: number;
|
||||
/** Authentication-tag length in bytes for AEAD modes. */
|
||||
tagLength?: number;
|
||||
/** Whether nonce length is variable at runtime. */
|
||||
varSizeNonce?: boolean;
|
||||
};
|
||||
/**
|
||||
* ARX AEAD cipher, like salsa or chacha.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Optional associated data.
|
||||
* @returns Cipher instance with caller-managed output buffers.
|
||||
*/
|
||||
export type ARXCipher = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
tagLength: number;
|
||||
};
|
||||
/**
|
||||
* Cipher constructor signature.
|
||||
* @param key - Secret key bytes.
|
||||
* @param args - Additional constructor arguments, such as nonce or IV.
|
||||
* @returns Cipher instance.
|
||||
*/
|
||||
export type CipherCons<T extends any[]> = (key: TArg<Uint8Array>, ...args: T) => Cipher;
|
||||
/**
|
||||
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
||||
* Used internally by the exported cipher constructors.
|
||||
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
|
||||
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
|
||||
* `args[1]` for optional AAD.
|
||||
* @__NO_SIDE_EFFECTS__
|
||||
* @param params - Static cipher metadata. See {@link CipherParams}.
|
||||
* @param constructor - Cipher constructor.
|
||||
* @returns Wrapped constructor with validation.
|
||||
*/
|
||||
export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
|
||||
/**
|
||||
* Represents a Salsa or ChaCha xor stream.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param data - Input bytes to xor with the keystream.
|
||||
* @param output - Optional destination buffer.
|
||||
* @param counter - Optional starting block counter.
|
||||
* @returns Output bytes.
|
||||
*/
|
||||
export type XorStream = (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, data: TArg<Uint8Array>, output?: TArg<Uint8Array>, counter?: number) => TRet<Uint8Array>;
|
||||
/**
|
||||
* By default, returns u8a of length.
|
||||
* When out is available, it checks it for validity and uses it.
|
||||
* @param expectedLength - Required output length.
|
||||
* @param out - Optional destination buffer.
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned.
|
||||
* @returns Output buffer ready for writing.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
|
||||
* @example
|
||||
* Reuses a caller-provided output buffer when lengths match.
|
||||
*
|
||||
* ```ts
|
||||
* getOutput(16, new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export declare function getOutput(expectedLength: number, out?: TArg<Uint8Array>, onlyAligned?: boolean): TRet<Uint8Array>;
|
||||
/**
|
||||
* Encodes data and AAD bit lengths into a 16-byte buffer.
|
||||
* @param dataLength - Data length in bits.
|
||||
* @param aadLength - AAD length in bits.
|
||||
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
|
||||
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
|
||||
* @param isLE - Whether to encode lengths as little-endian.
|
||||
* @returns 16-byte length block.
|
||||
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Builds the length block appended by GCM and Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* u64Lengths(16, 8, true);
|
||||
* ```
|
||||
*/
|
||||
export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet<Uint8Array>;
|
||||
/**
|
||||
* Checks whether a byte array is aligned to a 4-byte offset.
|
||||
* @param bytes - Byte array to inspect.
|
||||
* @returns `true` when the view is 4-byte aligned.
|
||||
* @example
|
||||
* Checks whether a buffer can be safely viewed as Uint32Array.
|
||||
*
|
||||
* ```ts
|
||||
* isAligned32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export declare function isAligned32(bytes: TArg<Uint8Array>): boolean;
|
||||
/**
|
||||
* Copies bytes into a new Uint8Array.
|
||||
* @param bytes - Bytes to copy.
|
||||
* @returns Copied byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Copies input into an aligned Uint8Array before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* copyBytes(new Uint8Array([1, 2]));
|
||||
* ```
|
||||
*/
|
||||
export declare function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* Cryptographically secure PRNG.
|
||||
* Uses internal OS-level `crypto.getRandomValues`.
|
||||
* @param bytesLength - Number of bytes to produce.
|
||||
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
|
||||
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
|
||||
* @returns Random byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
|
||||
* @example
|
||||
* Generates a fresh nonce or key.
|
||||
*
|
||||
* ```ts
|
||||
* randomBytes(16);
|
||||
* ```
|
||||
*/
|
||||
export declare function randomBytes(bytesLength?: number): TRet<Uint8Array>;
|
||||
/**
|
||||
* The pseudorandom number generator doesn't wipe current state:
|
||||
* instead, it generates new one based on previous state + entropy.
|
||||
* Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,
|
||||
* which is in fact `reseed`, since it changes counter too.
|
||||
*/
|
||||
export interface PRG {
|
||||
/**
|
||||
* Mixes fresh entropy into the current generator state.
|
||||
* @param seed - Entropy bytes to absorb.
|
||||
*/
|
||||
addEntropy(seed: TArg<Uint8Array>): void;
|
||||
/**
|
||||
* Produces a requested number of pseudorandom bytes.
|
||||
* @param bytesLength - Number of bytes to generate.
|
||||
* @returns Random byte array.
|
||||
*/
|
||||
randomBytes(bytesLength: number): TRet<Uint8Array>;
|
||||
/** Destroys the generator state. */
|
||||
clean(): void;
|
||||
}
|
||||
/** Removes the nonce argument from a cipher constructor type. */
|
||||
export type RemoveNonce<T extends (...args: any) => any> = T extends (arg0: any, arg1: any, ...rest: infer R) => infer Ret ? (key: TArg<Uint8Array>, ...args: R) => Ret : never;
|
||||
/**
|
||||
* Cipher constructor that requires a nonce argument.
|
||||
* @param key - Secret key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param args - Additional cipher-specific arguments.
|
||||
* @returns Cipher instance.
|
||||
*/
|
||||
export type CipherWithNonce = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, ...args: any[]) => Cipher | AsyncCipher) & {
|
||||
nonceLength: number;
|
||||
};
|
||||
/**
|
||||
* Uses CSPRNG for nonce, nonce injected in ciphertext.
|
||||
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
||||
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
||||
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
|
||||
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
|
||||
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
|
||||
* to the wrapped cipher instead of being rejected here first.
|
||||
*
|
||||
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
||||
* should be limited to `2**23` (8M) messages to get a collision chance of
|
||||
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
|
||||
* `2**-33`, still negligible but creeping up.
|
||||
* @param fn - Cipher constructor that expects a nonce.
|
||||
* @param randomBytes_ - Random-byte source used for nonce generation.
|
||||
* @returns Cipher constructor that prepends the nonce to ciphertext.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
|
||||
* @example
|
||||
* Prepends a fresh random nonce to every ciphertext.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const wrapped = managedNonce(gcm);
|
||||
* const key = randomBytes(16);
|
||||
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
|
||||
* wrapped(key).decrypt(ciphertext);
|
||||
* ```
|
||||
*/
|
||||
export declare function managedNonce<T extends CipherWithNonce>(fn: T, randomBytes_?: typeof randomBytes): TRet<RemoveNonce<T>>;
|
||||
/** `Uint8Array.of()` return type helper for TS 5.9. */
|
||||
export type Uint8ArrayBuffer = TRet<Uint8Array>;
|
||||
export {};
|
||||
//# sourceMappingURL=utils.d.ts.map
|
||||
+1
File diff suppressed because one or more lines are too long
+807
@@ -0,0 +1,807 @@
|
||||
/**
|
||||
* Utilities for hex, bytes, CSPRNG.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
||||
/**
|
||||
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
||||
* @param a - Value to inspect.
|
||||
* @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
|
||||
* @example
|
||||
* Guards a value before treating it as raw key material.
|
||||
*
|
||||
* ```ts
|
||||
* isBytes(new Uint8Array());
|
||||
* ```
|
||||
*/
|
||||
export function isBytes(a) {
|
||||
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /
|
||||
// cross-realm cases. The fallback still requires a real ArrayBuffer view
|
||||
// so plain JSON-deserialized `{ constructor: ... }`
|
||||
// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
|
||||
return (a instanceof Uint8Array ||
|
||||
(ArrayBuffer.isView(a) &&
|
||||
a.constructor.name === 'Uint8Array' &&
|
||||
'BYTES_PER_ELEMENT' in a &&
|
||||
a.BYTES_PER_ELEMENT === 1));
|
||||
}
|
||||
/**
|
||||
* Asserts something is boolean.
|
||||
* @param b - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Validates a boolean option before branching on it.
|
||||
*
|
||||
* ```ts
|
||||
* abool(true);
|
||||
* ```
|
||||
*/
|
||||
export function abool(b) {
|
||||
if (typeof b !== 'boolean')
|
||||
throw new TypeError(`boolean expected, not ${b}`);
|
||||
}
|
||||
/**
|
||||
* Asserts something is a non-negative safe integer.
|
||||
* @param n - Value to validate.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Validates a non-negative length or counter.
|
||||
*
|
||||
* ```ts
|
||||
* anumber(1);
|
||||
* ```
|
||||
*/
|
||||
export function anumber(n) {
|
||||
if (typeof n !== 'number')
|
||||
throw new TypeError('number expected, got ' + typeof n);
|
||||
if (!Number.isSafeInteger(n) || n < 0)
|
||||
throw new RangeError('positive integer expected, got ' + n);
|
||||
}
|
||||
/**
|
||||
* Asserts something is Uint8Array.
|
||||
* @param value - Value to validate.
|
||||
* @param length - Expected byte length.
|
||||
* @param title - Optional label used in error messages.
|
||||
* @returns The validated byte array.
|
||||
* On Node, `Buffer` is accepted too because it is a Uint8Array view.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument lengths. {@link RangeError}
|
||||
* @example
|
||||
* Validates a fixed-length nonce or key buffer.
|
||||
*
|
||||
* ```ts
|
||||
* abytes(new Uint8Array([1, 2]), 2);
|
||||
* ```
|
||||
*/
|
||||
export function abytes(value, length, title = '') {
|
||||
const bytes = isBytes(value);
|
||||
const len = value?.length;
|
||||
const needsLen = length !== undefined;
|
||||
if (!bytes || (needsLen && len !== length)) {
|
||||
const prefix = title && `"${title}" `;
|
||||
const ofLen = needsLen ? ` of length ${length}` : '';
|
||||
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
||||
const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
|
||||
if (!bytes)
|
||||
throw new TypeError(message);
|
||||
throw new RangeError(message);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Asserts a hash- or MAC-like instance has not been destroyed or finished.
|
||||
* @param instance - Stateful instance to validate.
|
||||
* @param checkFinished - Whether to reject finished instances.
|
||||
* When `false`, only `destroyed` is checked.
|
||||
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
||||
* @example
|
||||
* Guards against calling `update()` or `digest()` on a finished hash.
|
||||
*
|
||||
* ```ts
|
||||
* aexists({ destroyed: false, finished: false });
|
||||
* ```
|
||||
*/
|
||||
export function aexists(instance, checkFinished = true) {
|
||||
if (instance.destroyed)
|
||||
throw new Error('Hash instance has been destroyed');
|
||||
if (checkFinished && instance.finished)
|
||||
throw new Error('Hash#digest() has already been called');
|
||||
}
|
||||
/**
|
||||
* Asserts output is a properly-sized byte array.
|
||||
* @param out - Output buffer to validate.
|
||||
* @param instance - Hash-like instance providing `outputLen`.
|
||||
* This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
|
||||
* unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
|
||||
* @throws On wrong output buffer lengths. {@link RangeError}
|
||||
* @throws On wrong output buffer alignment. {@link Error}
|
||||
* @example
|
||||
* Verifies that a caller-provided output buffer is large enough.
|
||||
*
|
||||
* ```ts
|
||||
* aoutput(new Uint8Array(16), { outputLen: 16 });
|
||||
* ```
|
||||
*/
|
||||
export function aoutput(out, instance, onlyAligned = false) {
|
||||
abytes(out, undefined, 'output');
|
||||
const min = instance.outputLen;
|
||||
if (out.length < min) {
|
||||
throw new RangeError('digestInto() expects output buffer of length at least ' + min);
|
||||
}
|
||||
if (onlyAligned && !isAligned32(out))
|
||||
throw new Error('invalid output, must be aligned');
|
||||
}
|
||||
/**
|
||||
* Casts a typed-array view to Uint8Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint8Array view over the same bytes.
|
||||
* @example
|
||||
* Views 32-bit words as raw bytes without copying.
|
||||
*
|
||||
* ```ts
|
||||
* u8(new Uint32Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export function u8(arr) {
|
||||
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
||||
}
|
||||
/**
|
||||
* Casts a typed-array view to Uint32Array.
|
||||
* @param arr - Typed-array view to reinterpret.
|
||||
* @returns Uint32Array view over the same bytes. Callers are expected to provide a
|
||||
* 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
|
||||
* @example
|
||||
* Views a byte buffer as 32-bit words for block processing.
|
||||
*
|
||||
* ```ts
|
||||
* u32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function u32(arr) {
|
||||
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
||||
}
|
||||
/**
|
||||
* Zeroizes typed arrays in place.
|
||||
* Warning: JS provides no guarantees.
|
||||
* @param arrays - Arrays to wipe.
|
||||
* @example
|
||||
* Wipes a temporary key buffer after use.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([1]);
|
||||
* clean(bytes);
|
||||
* ```
|
||||
*/
|
||||
export function clean(...arrays) {
|
||||
for (let i = 0; i < arrays.length; i++) {
|
||||
arrays[i].fill(0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a DataView for byte-level manipulation.
|
||||
* @param arr - Typed-array view to wrap.
|
||||
* @returns DataView over the same bytes.
|
||||
* @example
|
||||
* Creates an endian-aware view for length encoding.
|
||||
*
|
||||
* ```ts
|
||||
* createView(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function createView(arr) {
|
||||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
||||
}
|
||||
/**
|
||||
* Whether the current platform is little-endian.
|
||||
* Most are; some IBM systems are not.
|
||||
*/
|
||||
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
||||
/**
|
||||
* Reverses byte order of one 32-bit word.
|
||||
* @param word - Unsigned 32-bit word to swap.
|
||||
* @returns The same word with bytes reversed.
|
||||
* @example
|
||||
* Swaps a big-endian word into little-endian byte order.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export const byteSwap = (word) => ((word << 24) & 0xff000000) |
|
||||
((word << 8) & 0xff0000) |
|
||||
((word >>> 8) & 0xff00) |
|
||||
((word >>> 24) & 0xff);
|
||||
/**
|
||||
* Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
|
||||
* @param n - Unsigned 32-bit word to normalize.
|
||||
* @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
|
||||
* @example
|
||||
* Normalizes a host-endian word before passing it into an ARX/AES core.
|
||||
*
|
||||
* ```ts
|
||||
* swap8IfBE(0x11223344);
|
||||
* ```
|
||||
*/
|
||||
export const swap8IfBE = isLE
|
||||
? (n) => n
|
||||
: (n) => byteSwap(n) >>> 0;
|
||||
/**
|
||||
* Byte-swaps every word of a Uint32Array in place.
|
||||
* @param arr - Uint32Array whose words should be swapped.
|
||||
* @returns The same array after in-place byte swapping.
|
||||
* @example
|
||||
* Swaps every 32-bit word in a word-view buffer.
|
||||
*
|
||||
* ```ts
|
||||
* byteSwap32(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export const byteSwap32 = (arr) => {
|
||||
for (let i = 0; i < arr.length; i++)
|
||||
arr[i] = byteSwap(arr[i]);
|
||||
return arr;
|
||||
};
|
||||
/**
|
||||
* Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
|
||||
* @param u - Word view to normalize in place.
|
||||
* @returns Little-endian normalized word view.
|
||||
* @example
|
||||
* Normalizes a word-view buffer before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* swap32IfBE(new Uint32Array([0x11223344]));
|
||||
* ```
|
||||
*/
|
||||
export const swap32IfBE = isLE
|
||||
? (u) => u
|
||||
: byteSwap32;
|
||||
// Built-in hex conversion:
|
||||
// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}
|
||||
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
||||
// @ts-ignore
|
||||
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
||||
// Array where index 0xf0 (240) is mapped to string 'f0'
|
||||
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
||||
/**
|
||||
* Convert byte array to hex string. Uses built-in function, when available.
|
||||
* @param bytes - Bytes to encode.
|
||||
* @returns Lowercase hexadecimal string.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Formats ciphertext bytes for logs or test vectors.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
||||
* ```
|
||||
*/
|
||||
export function bytesToHex(bytes) {
|
||||
abytes(bytes);
|
||||
// @ts-ignore
|
||||
if (hasHexBuiltin)
|
||||
return bytes.toHex();
|
||||
// pre-caching improves the speed 6x
|
||||
let hex = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
hex += hexes[bytes[i]];
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
// We use optimized technique to convert hex string to byte array
|
||||
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
||||
function asciiToBase16(ch) {
|
||||
if (ch >= asciis._0 && ch <= asciis._9)
|
||||
return ch - asciis._0; // '2' => 50-48
|
||||
if (ch >= asciis.A && ch <= asciis.F)
|
||||
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
||||
if (ch >= asciis.a && ch <= asciis.f)
|
||||
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Convert hex string to byte array. Uses built-in function, when available.
|
||||
* @param hex - Hexadecimal string to decode.
|
||||
* @returns Decoded bytes.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On malformed hexadecimal input. {@link RangeError}
|
||||
* @example
|
||||
* Parses a hex test vector into bytes.
|
||||
*
|
||||
* ```ts
|
||||
* hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
||||
* ```
|
||||
*/
|
||||
export function hexToBytes(hex) {
|
||||
if (typeof hex !== 'string')
|
||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
||||
if (hasHexBuiltin) {
|
||||
try {
|
||||
return Uint8Array.fromHex(hex);
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof SyntaxError)
|
||||
throw new RangeError(error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const hl = hex.length;
|
||||
const al = hl / 2;
|
||||
if (hl % 2)
|
||||
throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
|
||||
const array = new Uint8Array(al);
|
||||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
||||
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
||||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
||||
if (n1 === undefined || n2 === undefined) {
|
||||
const char = hex[hi] + hex[hi + 1];
|
||||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
||||
}
|
||||
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
||||
}
|
||||
return array;
|
||||
}
|
||||
// Used in micro
|
||||
/**
|
||||
* Converts a big-endian hex string into bigint.
|
||||
* @param hex - Hexadecimal string without `0x`.
|
||||
* @returns Parsed bigint value. The empty string is treated as `0n`.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Parses a big-endian field element or counter from hex.
|
||||
*
|
||||
* ```ts
|
||||
* hexToNumber('ff');
|
||||
* ```
|
||||
*/
|
||||
export function hexToNumber(hex) {
|
||||
if (typeof hex !== 'string')
|
||||
throw new TypeError('hex string expected, got ' + typeof hex);
|
||||
return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
|
||||
}
|
||||
// Used in ff1
|
||||
// BE: Big Endian, LE: Little Endian
|
||||
/**
|
||||
* Converts big-endian bytes into bigint.
|
||||
* @param bytes - Big-endian bytes.
|
||||
* @returns Parsed bigint value. Empty input is treated as `0n`.
|
||||
* @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
|
||||
* @example
|
||||
* Reads a big-endian integer from serialized bytes.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToNumberBE(new Uint8Array([1, 0]));
|
||||
* ```
|
||||
*/
|
||||
export function bytesToNumberBE(bytes) {
|
||||
return hexToNumber(bytesToHex(bytes));
|
||||
}
|
||||
// Used in micro, ff1
|
||||
/**
|
||||
* Converts a number into big-endian bytes of fixed length.
|
||||
* @param n - Number to encode.
|
||||
* @param len - Output length in bytes.
|
||||
* @returns Big-endian bytes padded to `len`.
|
||||
* Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
|
||||
* and values that do not fit surface through the downstream hex parser instead of a
|
||||
* dedicated range guard here.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the requested output length cannot represent the encoded value. {@link RangeError}
|
||||
* @example
|
||||
* Encodes a counter as fixed-width big-endian bytes.
|
||||
*
|
||||
* ```ts
|
||||
* numberToBytesBE(1, 2);
|
||||
* ```
|
||||
*/
|
||||
export function numberToBytesBE(n, len) {
|
||||
// Reject coercible non-numeric inputs before string/hex conversion changes behavior.
|
||||
if (typeof n === 'number')
|
||||
anumber(n);
|
||||
else if (typeof n !== 'bigint')
|
||||
throw new TypeError(`number or bigint expected, got ${typeof n}`);
|
||||
anumber(len);
|
||||
return hexToBytes(n.toString(16).padStart(len * 2, '0'));
|
||||
}
|
||||
/**
|
||||
* Converts string to bytes using UTF8 encoding.
|
||||
* @param str - String to encode.
|
||||
* @returns UTF-8 bytes in a detached fresh Uint8Array copy.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Encodes application text before encryption or MACing.
|
||||
*
|
||||
* ```ts
|
||||
* utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
|
||||
* ```
|
||||
*/
|
||||
export function utf8ToBytes(str) {
|
||||
if (typeof str !== 'string')
|
||||
throw new TypeError('string expected');
|
||||
return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}
|
||||
}
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @param bytes - UTF-8 bytes.
|
||||
* @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
|
||||
* UTF-8 is replacement-decoded instead of rejected.
|
||||
* @example
|
||||
* Decodes UTF-8 plaintext back into a string.
|
||||
*
|
||||
* ```ts
|
||||
* bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
|
||||
* ```
|
||||
*/
|
||||
export function bytesToUtf8(bytes) {
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
/**
|
||||
* Checks if two U8A use same underlying buffer and overlaps.
|
||||
* This is invalid and can corrupt data.
|
||||
* @param a - First byte view.
|
||||
* @param b - Second byte view.
|
||||
* @returns `true` when the views overlap in memory.
|
||||
* @example
|
||||
* Detects whether two slices alias the same backing buffer.
|
||||
*
|
||||
* ```ts
|
||||
* overlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function overlapBytes(a, b) {
|
||||
// Zero-length views cannot overwrite anything, even if their offset sits inside another range.
|
||||
if (!a.byteLength || !b.byteLength)
|
||||
return false;
|
||||
return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
||||
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
||||
b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
|
||||
);
|
||||
}
|
||||
/**
|
||||
* If input and output overlap and input starts before output, we will overwrite end of input before
|
||||
* we start processing it, so this is not supported for most ciphers
|
||||
* (except chacha/salsa, which were designed for this)
|
||||
* @param input - Input bytes.
|
||||
* @param output - Output bytes.
|
||||
* @throws If the output view would overwrite unread input bytes. {@link Error}
|
||||
* @example
|
||||
* Rejects an in-place layout that would overwrite unread input bytes.
|
||||
*
|
||||
* ```ts
|
||||
* complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function complexOverlapBytes(input, output) {
|
||||
// This is very cursed. It works somehow, but I'm completely unsure,
|
||||
// reasoning about overlapping aligned windows is very hard.
|
||||
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
||||
throw new Error('complex overlap of input and output is not supported');
|
||||
}
|
||||
/**
|
||||
* Copies several Uint8Arrays into one.
|
||||
* @param arrays - Byte arrays to concatenate.
|
||||
* @returns Combined byte array.
|
||||
* @throws On wrong argument types inside the byte-array list. {@link TypeError}
|
||||
* @example
|
||||
* Builds a `nonce || ciphertext` style buffer.
|
||||
*
|
||||
* ```ts
|
||||
* concatBytes(new Uint8Array([1]), new Uint8Array([2]));
|
||||
* ```
|
||||
*/
|
||||
export function concatBytes(...arrays) {
|
||||
let sum = 0;
|
||||
for (let i = 0; i < arrays.length; i++) {
|
||||
const a = arrays[i];
|
||||
abytes(a);
|
||||
sum += a.length;
|
||||
}
|
||||
const res = new Uint8Array(sum);
|
||||
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
||||
const a = arrays[i];
|
||||
res.set(a, pad);
|
||||
pad += a.length;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Merges user options into defaults.
|
||||
* @param defaults - Default option values.
|
||||
* @param opts - User-provided overrides.
|
||||
* @returns Combined options object.
|
||||
* The merge mutates `defaults` in place and returns the same object.
|
||||
* @throws If options are missing or not an object. {@link Error}
|
||||
* @example
|
||||
* Applies user overrides to the default cipher options.
|
||||
*
|
||||
* ```ts
|
||||
* checkOpts({ rounds: 20 }, { rounds: 8 });
|
||||
* ```
|
||||
*/
|
||||
export function checkOpts(defaults, opts) {
|
||||
if (opts == null || typeof opts !== 'object')
|
||||
throw new Error('options must be defined');
|
||||
const merged = Object.assign(defaults, opts);
|
||||
return merged;
|
||||
}
|
||||
/**
|
||||
* Compares two byte arrays in kinda constant time once lengths already match.
|
||||
* @param a - First byte array.
|
||||
* @param b - Second byte array.
|
||||
* @returns `true` when the arrays contain the same bytes. Different lengths still return early.
|
||||
* @example
|
||||
* Compares an expected authentication tag with the received one.
|
||||
*
|
||||
* ```ts
|
||||
* equalBytes(new Uint8Array([1]), new Uint8Array([1]));
|
||||
* ```
|
||||
*/
|
||||
export function equalBytes(a, b) {
|
||||
if (a.length !== b.length)
|
||||
return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++)
|
||||
diff |= a[i] ^ b[i];
|
||||
return diff === 0;
|
||||
}
|
||||
/**
|
||||
* Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
|
||||
* @param keyLen - Valid probe-key length used to read static metadata once.
|
||||
* The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
|
||||
* can pass any representative size as long as those values stay fixed.
|
||||
* @param macCons - Keyed MAC constructor or factory.
|
||||
* @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
|
||||
* @returns Callable MAC helper with `.create()`.
|
||||
*/
|
||||
export function wrapMacConstructor(keyLen, macCons, fromMsg) {
|
||||
const mac = macCons;
|
||||
const getArgs = (fromMsg || (() => []));
|
||||
const macC = (msg, key) => mac(key, ...getArgs(msg))
|
||||
.update(msg)
|
||||
.digest();
|
||||
const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
|
||||
macC.outputLen = tmp.outputLen;
|
||||
macC.blockLen = tmp.blockLen;
|
||||
macC.create = (key, ...args) => mac(key, ...args);
|
||||
return macC;
|
||||
}
|
||||
/**
|
||||
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
||||
* Used internally by the exported cipher constructors.
|
||||
* Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
|
||||
* arity (`fn.length === 2`), and tag-bearing constructors are expected to use
|
||||
* `args[1]` for optional AAD.
|
||||
* @__NO_SIDE_EFFECTS__
|
||||
* @param params - Static cipher metadata. See {@link CipherParams}.
|
||||
* @param constructor - Cipher constructor.
|
||||
* @returns Wrapped constructor with validation.
|
||||
*/
|
||||
export const wrapCipher = (params, constructor) => {
|
||||
function wrappedCipher(key, ...args) {
|
||||
// Validate key
|
||||
abytes(key, undefined, 'key');
|
||||
// Validate nonce if nonceLength is present
|
||||
if (params.nonceLength !== undefined) {
|
||||
const nonce = args[0];
|
||||
abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
|
||||
}
|
||||
// Validate AAD if tagLength present
|
||||
const tagl = params.tagLength;
|
||||
if (tagl && args[1] !== undefined)
|
||||
abytes(args[1], undefined, 'AAD');
|
||||
const cipher = constructor(key, ...args);
|
||||
const checkOutput = (fnLength, output) => {
|
||||
if (output !== undefined) {
|
||||
if (fnLength !== 2)
|
||||
throw new Error('cipher output not supported');
|
||||
abytes(output, undefined, 'output');
|
||||
}
|
||||
};
|
||||
// Create wrapped cipher with validation and single-use encryption
|
||||
let called = false;
|
||||
const wrCipher = {
|
||||
encrypt(data, output) {
|
||||
if (called)
|
||||
throw new Error('cannot encrypt() twice with same key + nonce');
|
||||
called = true;
|
||||
abytes(data);
|
||||
checkOutput(cipher.encrypt.length, output);
|
||||
return cipher.encrypt(data, output);
|
||||
},
|
||||
decrypt(data, output) {
|
||||
abytes(data);
|
||||
if (tagl && data.length < tagl)
|
||||
throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
|
||||
checkOutput(cipher.decrypt.length, output);
|
||||
return cipher.decrypt(data, output);
|
||||
},
|
||||
};
|
||||
return wrCipher;
|
||||
}
|
||||
Object.assign(wrappedCipher, params);
|
||||
return wrappedCipher;
|
||||
};
|
||||
/**
|
||||
* By default, returns u8a of length.
|
||||
* When out is available, it checks it for validity and uses it.
|
||||
* @param expectedLength - Required output length.
|
||||
* @param out - Optional destination buffer.
|
||||
* @param onlyAligned - Whether `out` must be 4-byte aligned.
|
||||
* @returns Output buffer ready for writing.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws If the provided output buffer has the wrong size or alignment. {@link Error}
|
||||
* @example
|
||||
* Reuses a caller-provided output buffer when lengths match.
|
||||
*
|
||||
* ```ts
|
||||
* getOutput(16, new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export function getOutput(expectedLength, out, onlyAligned = true) {
|
||||
if (out === undefined)
|
||||
return new Uint8Array(expectedLength);
|
||||
// Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.
|
||||
abytes(out, undefined, 'output');
|
||||
if (out.length !== expectedLength)
|
||||
throw new Error('"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);
|
||||
if (onlyAligned && !isAligned32(out))
|
||||
throw new Error('invalid output, must be aligned');
|
||||
return out;
|
||||
}
|
||||
/**
|
||||
* Encodes data and AAD bit lengths into a 16-byte buffer.
|
||||
* @param dataLength - Data length in bits.
|
||||
* @param aadLength - AAD length in bits.
|
||||
* The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
|
||||
* conventions even though the helper parameter order is `(dataLength, aadLength)`.
|
||||
* @param isLE - Whether to encode lengths as little-endian.
|
||||
* @returns 16-byte length block.
|
||||
* @throws On wrong argument types passed to the endian validator. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @example
|
||||
* Builds the length block appended by GCM and Poly1305.
|
||||
*
|
||||
* ```ts
|
||||
* u64Lengths(16, 8, true);
|
||||
* ```
|
||||
*/
|
||||
export function u64Lengths(dataLength, aadLength, isLE) {
|
||||
// Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.
|
||||
anumber(dataLength);
|
||||
anumber(aadLength);
|
||||
abool(isLE);
|
||||
const num = new Uint8Array(16);
|
||||
const view = createView(num);
|
||||
view.setBigUint64(0, BigInt(aadLength), isLE);
|
||||
view.setBigUint64(8, BigInt(dataLength), isLE);
|
||||
return num;
|
||||
}
|
||||
/**
|
||||
* Checks whether a byte array is aligned to a 4-byte offset.
|
||||
* @param bytes - Byte array to inspect.
|
||||
* @returns `true` when the view is 4-byte aligned.
|
||||
* @example
|
||||
* Checks whether a buffer can be safely viewed as Uint32Array.
|
||||
*
|
||||
* ```ts
|
||||
* isAligned32(new Uint8Array(4));
|
||||
* ```
|
||||
*/
|
||||
export function isAligned32(bytes) {
|
||||
return bytes.byteOffset % 4 === 0;
|
||||
}
|
||||
/**
|
||||
* Copies bytes into a new Uint8Array.
|
||||
* @param bytes - Bytes to copy.
|
||||
* @returns Copied byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @example
|
||||
* Copies input into an aligned Uint8Array before block processing.
|
||||
*
|
||||
* ```ts
|
||||
* copyBytes(new Uint8Array([1, 2]));
|
||||
* ```
|
||||
*/
|
||||
export function copyBytes(bytes) {
|
||||
// `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
|
||||
// because callers use it at byte-validation boundaries before mutating the detached copy.
|
||||
return Uint8Array.from(abytes(bytes));
|
||||
}
|
||||
/**
|
||||
* Cryptographically secure PRNG.
|
||||
* Uses internal OS-level `crypto.getRandomValues`.
|
||||
* @param bytesLength - Number of bytes to produce.
|
||||
* Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
|
||||
* non-integers, negative lengths, and oversize requests surface backend/runtime errors.
|
||||
* @returns Random byte array.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On wrong argument ranges or values. {@link RangeError}
|
||||
* @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
|
||||
* @example
|
||||
* Generates a fresh nonce or key.
|
||||
*
|
||||
* ```ts
|
||||
* randomBytes(16);
|
||||
* ```
|
||||
*/
|
||||
export function randomBytes(bytesLength = 32) {
|
||||
// Validate upfront so fractional / coercible lengths do not silently
|
||||
// truncate through Uint8Array().
|
||||
anumber(bytesLength);
|
||||
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
|
||||
if (typeof cr?.getRandomValues !== 'function')
|
||||
throw new Error('crypto.getRandomValues must be defined');
|
||||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
||||
}
|
||||
/**
|
||||
* Uses CSPRNG for nonce, nonce injected in ciphertext.
|
||||
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
||||
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
||||
* are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
|
||||
* buffer on encrypt and intentionally does not support caller-provided destination buffers.
|
||||
* Too-short decrypt inputs are split into short/empty nonce views and then delegated
|
||||
* to the wrapped cipher instead of being rejected here first.
|
||||
*
|
||||
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
||||
* should be limited to `2**23` (8M) messages to get a collision chance of
|
||||
* `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
|
||||
* `2**-33`, still negligible but creeping up.
|
||||
* @param fn - Cipher constructor that expects a nonce.
|
||||
* @param randomBytes_ - Random-byte source used for nonce generation.
|
||||
* @returns Cipher constructor that prepends the nonce to ciphertext.
|
||||
* @throws On wrong argument types. {@link TypeError}
|
||||
* @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
|
||||
* @example
|
||||
* Prepends a fresh random nonce to every ciphertext.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/aes.js';
|
||||
* import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const wrapped = managedNonce(gcm);
|
||||
* const key = randomBytes(16);
|
||||
* const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
|
||||
* wrapped(key).decrypt(ciphertext);
|
||||
* ```
|
||||
*/
|
||||
export function managedNonce(fn, randomBytes_ = randomBytes) {
|
||||
const { nonceLength } = fn;
|
||||
anumber(nonceLength);
|
||||
const addNonce = (nonce, ciphertext, plaintext) => {
|
||||
const out = concatBytes(nonce, ciphertext);
|
||||
// Wrapped ciphers may alias caller plaintext on encrypt(); never zero
|
||||
// caller-owned buffers here.
|
||||
if (!overlapBytes(plaintext, ciphertext))
|
||||
ciphertext.fill(0);
|
||||
return out;
|
||||
};
|
||||
// NOTE: we cannot support DST here, it would be mistake:
|
||||
// - we don't know how much dst length cipher requires
|
||||
// - nonce may unalign dst and break everything
|
||||
// - we create new u8a anyway (concatBytes)
|
||||
// - previously we passed all args to cipher, but that was mistake!
|
||||
const res = ((key, ...args) => ({
|
||||
encrypt(plaintext) {
|
||||
abytes(plaintext);
|
||||
const nonce = randomBytes_(nonceLength);
|
||||
const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
|
||||
// @ts-ignore
|
||||
if (encrypted instanceof Promise)
|
||||
return encrypted.then((ct) => addNonce(nonce, ct, plaintext));
|
||||
return addNonce(nonce, encrypted, plaintext);
|
||||
},
|
||||
decrypt(ciphertext) {
|
||||
abytes(ciphertext);
|
||||
const nonce = ciphertext.subarray(0, nonceLength);
|
||||
const decrypted = ciphertext.subarray(nonceLength);
|
||||
return fn(key, nonce, ...args).decrypt(decrypted);
|
||||
},
|
||||
}));
|
||||
// Auto-nonce wrappers still preserve the wrapped payload geometry.
|
||||
if ('blockSize' in fn)
|
||||
res.blockSize = fn.blockSize;
|
||||
if ('tagLength' in fn)
|
||||
res.tagLength = fn.tagLength;
|
||||
return res;
|
||||
}
|
||||
//# sourceMappingURL=utils.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+89
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { type AsyncCipher, type TArg, type TRet } from './utils.ts';
|
||||
type WebcryptoUtils = {
|
||||
encrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
decrypt(key: TArg<Uint8Array>, keyParams: unknown, cryptParams: unknown, ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
|
||||
};
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export declare const utils: TRet<WebcryptoUtils>;
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => AsyncCipher) & {
|
||||
blockSize: number;
|
||||
nonceLength: number;
|
||||
}>;
|
||||
export {};
|
||||
//# sourceMappingURL=webcrypto.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAQrF,KAAK,cAAc,GAAG;IACpB,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,GAC1B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC7B,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;CAC9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,cAAc,CAuBtC,CAAC;AAwEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC1F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC"}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`.
|
||||
* We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, anumber } from "./utils.js";
|
||||
function getWebcryptoSubtle() {
|
||||
const cr = typeof globalThis !== 'undefined' && globalThis.crypto;
|
||||
if (cr && typeof cr.subtle === 'object' && cr.subtle != null)
|
||||
return cr.subtle;
|
||||
throw new Error('crypto.subtle must be defined');
|
||||
}
|
||||
/**
|
||||
* Internal webcrypto utils. Can be overridden if crypto.subtle is not present,
|
||||
* for example in React Native.
|
||||
* Raw keys are re-imported on every call; this wrapper intentionally does not
|
||||
* cache `CryptoKey` objects between operations.
|
||||
*/
|
||||
export const utils = {
|
||||
async encrypt(key, keyParams, cryptParams, plaintext) {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);
|
||||
const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);
|
||||
return new Uint8Array(ciphertext);
|
||||
},
|
||||
async decrypt(key, keyParams, cryptParams, ciphertext) {
|
||||
const cr = getWebcryptoSubtle();
|
||||
const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);
|
||||
const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);
|
||||
return new Uint8Array(plaintext);
|
||||
},
|
||||
};
|
||||
const mode = {
|
||||
CBC: 'AES-CBC',
|
||||
CTR: 'AES-CTR',
|
||||
GCM: 'AES-GCM',
|
||||
};
|
||||
function getCryptParams(algo, nonce, AAD) {
|
||||
if (algo === mode.CBC)
|
||||
return { name: mode.CBC, iv: nonce };
|
||||
// WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap.
|
||||
if (algo === mode.CTR)
|
||||
return { name: mode.CTR, counter: nonce, length: 128 };
|
||||
if (algo === mode.GCM) {
|
||||
// Rely on the backend default tag length (128 bits) instead of setting it explicitly.
|
||||
if (AAD)
|
||||
return { name: mode.GCM, iv: nonce, additionalData: AAD };
|
||||
else
|
||||
return { name: mode.GCM, iv: nonce };
|
||||
}
|
||||
throw new Error('unknown aes block mode');
|
||||
}
|
||||
function generate(algo, nonceLength) {
|
||||
anumber(nonceLength);
|
||||
const res = (key, nonce, AAD) => {
|
||||
abytes(key);
|
||||
abytes(nonce);
|
||||
// Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD".
|
||||
if (AAD !== undefined)
|
||||
abytes(AAD, undefined, 'AAD');
|
||||
// Exact nonce-length enforcement and WebCrypto-specific AAD normalization are
|
||||
// delegated to the backend; locally we only require byte-array inputs here.
|
||||
// Keep caller key/nonce/AAD by reference; mutating them after
|
||||
// construction changes later operations.
|
||||
const keyParams = { name: algo, length: key.length * 8 };
|
||||
const cryptParams = getCryptParams(algo, nonce, AAD);
|
||||
let consumed = false;
|
||||
return {
|
||||
// keyLength,
|
||||
encrypt(plaintext) {
|
||||
abytes(plaintext);
|
||||
if (consumed)
|
||||
throw new Error('Cannot encrypt() twice with same key / nonce');
|
||||
consumed = true;
|
||||
return utils.encrypt(key, keyParams, cryptParams, plaintext);
|
||||
},
|
||||
decrypt(ciphertext) {
|
||||
abytes(ciphertext);
|
||||
return utils.decrypt(key, keyParams, cryptParams, ciphertext);
|
||||
},
|
||||
};
|
||||
};
|
||||
res.nonceLength = nonceLength;
|
||||
res.blockSize = 16; // always for AES
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* AES-CBC implemented with WebCrypto.
|
||||
* Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are
|
||||
* delegated to the backend instead of local `abytes(..., 16)` validation.
|
||||
* @param key - AES key bytes.
|
||||
* @param iv - 16-byte initialization vector.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a block with the browser or Node WebCrypto backend.
|
||||
*
|
||||
* ```ts
|
||||
* import { cbc } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const iv = randomBytes(16);
|
||||
* const cipher = cbc(key, iv);
|
||||
* await cipher.encrypt(new Uint8Array(16));
|
||||
* ```
|
||||
*/
|
||||
export const cbc = /* @__PURE__ */ (() => generate(mode.CBC, 16))();
|
||||
/**
|
||||
* AES-CTR implemented with WebCrypto.
|
||||
* Uses WebCrypto's full 128-bit counter-length setting so the whole
|
||||
* 16-byte counter block is incremented, matching sync `aes.ts:ctr`.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - 16-byte counter block incremented as a full big-endian AES counter block.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts a short payload with WebCrypto AES-CTR.
|
||||
*
|
||||
* ```ts
|
||||
* import { ctr } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(16);
|
||||
* const cipher = ctr(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const ctr = /* @__PURE__ */ (() => generate(mode.CTR, 16))();
|
||||
/**
|
||||
* AES-GCM implemented with WebCrypto.
|
||||
* AAD type normalization and nonce-shape enforcement beyond raw bytes are left
|
||||
* to the backend WebCrypto implementation.
|
||||
* @param key - AES key bytes.
|
||||
* @param nonce - Nonce bytes.
|
||||
* @param AAD - Additional authenticated data.
|
||||
* @returns Async cipher instance.
|
||||
* @example
|
||||
* Encrypts and authenticates plaintext with WebCrypto AES-GCM.
|
||||
*
|
||||
* ```ts
|
||||
* import { gcm } from '@noble/ciphers/webcrypto.js';
|
||||
* import { randomBytes } from '@noble/ciphers/utils.js';
|
||||
* const key = randomBytes(16);
|
||||
* const nonce = randomBytes(12);
|
||||
* const cipher = gcm(key, nonce);
|
||||
* await cipher.encrypt(new Uint8Array([1, 2, 3]));
|
||||
* ```
|
||||
*/
|
||||
export const gcm = /* @__PURE__ */ (() => generate(mode.GCM, 12))();
|
||||
// // Type tests
|
||||
// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts';
|
||||
// import { xsalsa20poly1305 } from '../salsa.ts';
|
||||
// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts';
|
||||
// const wsiv = managedNonce(siv);
|
||||
// const wgcm = managedNonce(gcm);
|
||||
// const wctr = managedNonce(ctr);
|
||||
// const wcbc = managedNonce(cbc);
|
||||
// const wsalsapoly = managedNonce(xsalsa20poly1305);
|
||||
// const wchacha = managedNonce(chacha20poly1305);
|
||||
// const wxchacha = managedNonce(xchacha20poly1305);
|
||||
// // should fail
|
||||
// const wcbc2 = managedNonce(managedNonce(cbc));
|
||||
// const wctr = managedNonce(ctr);
|
||||
// import { gcm as gcmSync } from '../aes.ts';
|
||||
// const x1 = managedNonce(gcmSync);
|
||||
// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher
|
||||
// const x2 = managedNonce(gcm);
|
||||
// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher
|
||||
//# sourceMappingURL=webcrypto.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,OAAO,EAA0C,MAAM,YAAY,CAAC;AAErF,SAAS,kBAAkB;IACzB,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,WAAW,IAAK,UAAkB,CAAC,MAAM,CAAC;IAC3E,IAAI,EAAE,IAAI,OAAO,EAAE,CAAC,MAAM,KAAK,QAAQ,IAAI,EAAE,CAAC,MAAM,IAAI,IAAI;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC;IAC/E,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAgBD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,KAAK,GAAyB;IACzC,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,SAA2B;QAE3B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,UAAU,CAAqB,CAAC;IACxD,CAAC;IACD,KAAK,CAAC,OAAO,CACX,GAAqB,EACrB,SAAc,EACd,WAAgB,EAChB,UAA4B;QAE5B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;QAChC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;QAClE,OAAO,IAAI,UAAU,CAAC,SAAS,CAAqB,CAAC;IACvD,CAAC;CACF,CAAC;AAEF,MAAM,IAAI,GAAG;IACX,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;CACN,CAAC;AAGX,SAAS,cAAc,CAAC,IAAe,EAAE,KAAuB,EAAE,GAAsB;IACtF,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5D,gGAAgG;IAChG,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IAC9E,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC;QACtB,sFAAsF;QACtF,IAAI,GAAG;YAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC;;YAC9D,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC5C,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC5C,CAAC;AAED,SAAS,QAAQ,CACf,IAAe,EACf,WAAmB;IAOnB,OAAO,CAAC,WAAW,CAAC,CAAC;IACrB,MAAM,GAAG,GAAG,CACV,GAAqB,EACrB,KAAuB,EACvB,GAAsB,EACH,EAAE;QACrB,MAAM,CAAC,GAAG,CAAC,CAAC;QACZ,MAAM,CAAC,KAAK,CAAC,CAAC;QACd,yFAAyF;QACzF,IAAI,GAAG,KAAK,SAAS;YAAE,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QACrD,8EAA8E;QAC9E,4EAA4E;QAC5E,8DAA8D;QAC9D,yCAAyC;QACzC,MAAM,SAAS,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzD,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;QACrD,IAAI,QAAQ,GAAG,KAAK,CAAC;QACrB,OAAO;YACL,aAAa;YACb,OAAO,CAAC,SAA2B;gBACjC,MAAM,CAAC,SAAS,CAAC,CAAC;gBAClB,IAAI,QAAQ;oBAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAC9E,QAAQ,GAAG,IAAI,CAAC;gBAChB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;YAC/D,CAAC;YACD,OAAO,CAAC,UAA4B;gBAClC,MAAM,CAAC,UAAU,CAAC,CAAC;gBACnB,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;YAChE,CAAC;SACmB,CAAC;IACzB,CAAC,CAAC;IACF,GAAG,CAAC,WAAW,GAAG,WAAW,CAAC;IAC9B,GAAG,CAAC,SAAS,GAAG,EAAE,CAAC,CAAC,iBAAiB;IACrC,OAAO,GAKN,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,GAAG,GAKZ,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC;AAErD,gBAAgB;AAChB,uDAAuD;AACvD,kDAAkD;AAClD,sEAAsE;AAEtE,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,qDAAqD;AACrD,kDAAkD;AAClD,oDAAoD;AAEpD,iBAAiB;AACjB,iDAAiD;AACjD,kCAAkC;AAClC,8CAA8C;AAC9C,oCAAoC;AACpC,yEAAyE;AACzE,gCAAgC;AAChC,8EAA8E"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+563
@@ -0,0 +1,563 @@
|
||||
# noble-hashes
|
||||
|
||||
Audited & minimal JS implementation of hash functions, MACs and KDFs.
|
||||
|
||||
- 🔒 [**Audited**](#security) by an independent security firm
|
||||
- 🔻 Tree-shakeable: unused code is excluded from your builds
|
||||
- 🏎 Fast: hand-optimized for caveats of JS engines
|
||||
- 🔍 Reliable: chained / sliding window / DoS / ACVP tests and fuzzing
|
||||
- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x
|
||||
- 🦘 Includes SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt, Argon2
|
||||
- 🥈 Optional, friendly wrapper over native WebCrypto
|
||||
- 🪶 22KB (gzipped) for everything, 2.4KB for single-hash build
|
||||
|
||||
Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative.
|
||||
Check out [Upgrading](#upgrading) for information about upgrading from previous versions.
|
||||
Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support.
|
||||
|
||||
The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/).
|
||||
|
||||
### This library belongs to _noble_ cryptography
|
||||
|
||||
> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
|
||||
|
||||
- Zero or minimal dependencies
|
||||
- Highly readable TypeScript / JS code
|
||||
- PGP-signed releases and transparent NPM builds
|
||||
- All libraries:
|
||||
[ciphers](https://github.com/paulmillr/noble-ciphers),
|
||||
[curves](https://github.com/paulmillr/noble-curves),
|
||||
[hashes](https://github.com/paulmillr/noble-hashes),
|
||||
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
|
||||
5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
|
||||
[ed25519](https://github.com/paulmillr/noble-ed25519)
|
||||
- [Check out the homepage](https://paulmillr.com/noble/)
|
||||
for reading resources, documentation, and apps built with noble
|
||||
|
||||
## Usage
|
||||
|
||||
> `npm install @noble/hashes`
|
||||
|
||||
> `deno add jsr:@noble/hashes`
|
||||
|
||||
We support all major platforms and runtimes.
|
||||
For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values).
|
||||
A standalone file [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available.
|
||||
|
||||
```js
|
||||
// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size
|
||||
import { sha256 as noble_sha256 } from '@noble/hashes/sha2.js';
|
||||
const hash = noble_sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
|
||||
|
||||
// Available modules
|
||||
import { sha256, sha384, sha512, sha224, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
|
||||
import {
|
||||
sha3_256, sha3_512,
|
||||
keccak_256, keccak_512,
|
||||
shake128, shake256,
|
||||
} from '@noble/hashes/sha3.js';
|
||||
import {
|
||||
cshake256, turboshake256, kmac256, tuplehash256,
|
||||
kt128, kt256, keccakprg,
|
||||
} from '@noble/hashes/sha3-addons.js';
|
||||
import { blake3 } from '@noble/hashes/blake3.js';
|
||||
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
|
||||
import { blake256, blake512 } from '@noble/hashes/blake1.js';
|
||||
import { sha1, md5, ripemd160 } from '@noble/hashes/legacy.js';
|
||||
import { hmac } from '@noble/hashes/hmac.js';
|
||||
import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
|
||||
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
|
||||
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
|
||||
import * as webcrypto from '@noble/hashes/webcrypto.js';
|
||||
// const { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } = webcrypto;
|
||||
import * as utils from '@noble/hashes/utils.js';
|
||||
const { bytesToHex, concatBytes, equalBytes, hexToBytes } = utils;
|
||||
```
|
||||
|
||||
- [sha2: sha256, sha384, sha512](#sha2-sha256-sha384-sha512-and-others)
|
||||
- [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak)
|
||||
- [sha3-addons: cSHAKE, KMAC, KT128, TurboSHAKE](#sha3-addons-cshake-kmac-kt128-turboshake)
|
||||
- [blake1, blake2, blake3](#blake1-blake2-blake3)
|
||||
- [legacy: sha1, md5, ripemd160](#legacy-sha1-md5-ripemd160)
|
||||
- MACs: [hmac](#hmac) | [kmac](#sha3-addons-cshake-kmac-kt128-turboshake) | [blake3 key mode](#blake1-blake2-blake3)
|
||||
- KDFs: [hkdf](#hkdf) | [pbkdf2](#pbkdf2) | [scrypt](#scrypt) | [argon2](#argon2)
|
||||
- [webcrypto: friendly wrapper](#webcrypto-friendly-wrapper)
|
||||
- [utils](#utils)
|
||||
- [Security](#security) | [Speed](#speed) | [Contributing & testing](#contributing--testing) | [License](#license)
|
||||
|
||||
### Implementations
|
||||
|
||||
Hash functions:
|
||||
|
||||
- `sha256()`: receive & return `Uint8Array`
|
||||
- `sha256.create().update(a).update(b).digest()`: support partial updates
|
||||
- `blake3.create({ context: 'e', dkLen: 32 })`: can have options
|
||||
- support little-endian architecture; also experimentally big-endian
|
||||
- can hash up to 4GB per chunk, with any amount of chunks
|
||||
|
||||
#### sha2: sha256, sha384, sha512 and others
|
||||
|
||||
```typescript
|
||||
import { sha224, sha256, sha384, sha512, sha512_224, sha512_256 } from '@noble/hashes/sha2.js';
|
||||
const res = sha256(Uint8Array.from([0xbc])); // basic
|
||||
for (let hash of [sha256, sha384, sha512, sha224, sha512_224, sha512_256]) {
|
||||
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
|
||||
const a = hash(arr);
|
||||
const b = hash.create().update(arr).digest();
|
||||
}
|
||||
```
|
||||
|
||||
Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
|
||||
[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
|
||||
|
||||
#### sha3: FIPS, SHAKE, Keccak
|
||||
|
||||
```typescript
|
||||
import {
|
||||
sha3_224, sha3_256, sha3_384, sha3_512,
|
||||
keccak_224, keccak_256, keccak_384, keccak_512,
|
||||
shake128, shake256,
|
||||
} from '@noble/hashes/sha3.js';
|
||||
for (let hash of [
|
||||
sha3_224, sha3_256, sha3_384, sha3_512,
|
||||
keccak_224, keccak_256, keccak_384, keccak_512,
|
||||
]) {
|
||||
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
|
||||
const a = hash(arr);
|
||||
const b = hash.create().update(arr).digest();
|
||||
}
|
||||
const shka = shake128(Uint8Array.from([0x10]), { dkLen: 512 });
|
||||
const shkb = shake256(Uint8Array.from([0x30]), { dkLen: 512 });
|
||||
```
|
||||
|
||||
Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
|
||||
[Website](https://keccak.team/keccak.html).
|
||||
|
||||
Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub)
|
||||
|
||||
#### sha3-addons: cSHAKE, KMAC, K12, TurboSHAKE
|
||||
|
||||
```typescript
|
||||
import {
|
||||
cshake128, cshake256, kt128, kt256,
|
||||
keccakprg, kmac128, kmac256,
|
||||
parallelhash256, tuplehash256,
|
||||
turboshake128, turboshake256,
|
||||
} from '@noble/hashes/sha3-addons.js';
|
||||
const data = Uint8Array.from([0x10, 0x20, 0x30]);
|
||||
const personalization = new TextEncoder().encode('def');
|
||||
const ec1 = cshake128(data, { personalization });
|
||||
const ec2 = cshake256(data, { personalization });
|
||||
const et1 = turboshake128(data);
|
||||
const et2 = turboshake256(data, { D: 0x05 });
|
||||
// tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash([data])
|
||||
const et3 = tuplehash256([new TextEncoder().encode('ab'), new TextEncoder().encode('c')]);
|
||||
// Not parallel in JS (similar to blake3 / kt128), added for compat
|
||||
const ep1 = parallelhash256(data, { blockLen: 8 });
|
||||
const kk = Uint8Array.from([0xca]);
|
||||
const ek10 = kmac128(kk, data);
|
||||
const ek11 = kmac256(kk, data);
|
||||
const ek12 = kt128(data); // kangarootwelve 128-bit
|
||||
const ek13 = kt256(data); // kangarootwelve 256-bit
|
||||
// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength.
|
||||
// * with a capacity of 254 bits.
|
||||
const p = keccakprg(254);
|
||||
p.addEntropy(Uint8Array.from([1, 2, 3]));
|
||||
const rand1b = p.randomBytes(32);
|
||||
```
|
||||
|
||||
- cSHAKE, KMAC, TupleHash, ParallelHash + XOF are available, matching
|
||||
[NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf)
|
||||
- Reduced-round Keccak KT128 (KangarooTwelve 🦘, K12) and TurboSHAKE are available, matching
|
||||
[RFC 9861](https://datatracker.ietf.org/doc/rfc9861/).
|
||||
- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): pseudo-random generator based on Keccak
|
||||
|
||||
#### blake1, blake2, blake3
|
||||
|
||||
```typescript
|
||||
import { blake224, blake256, blake384, blake512 } from '@noble/hashes/blake1.js';
|
||||
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
|
||||
import { blake3 } from '@noble/hashes/blake3.js';
|
||||
|
||||
for (let hash of [blake224, blake256, blake384, blake512, blake2b, blake2s, blake3]) {
|
||||
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
|
||||
const a = hash(arr);
|
||||
const b = hash.create().update(arr).digest();
|
||||
}
|
||||
|
||||
// blake2 advanced usage
|
||||
const ab = Uint8Array.from([0x01]);
|
||||
const txt = new TextEncoder();
|
||||
blake2s(ab);
|
||||
blake2s(ab, { key: new Uint8Array(32) });
|
||||
blake2s(ab, { personalization: txt.encode('pers1234') });
|
||||
blake2s(ab, { salt: txt.encode('salt1234') });
|
||||
blake2b(ab);
|
||||
blake2b(ab, { key: new Uint8Array(64) });
|
||||
blake2b(ab, { personalization: txt.encode('pers1234pers1234') });
|
||||
blake2b(ab, { salt: txt.encode('salt1234salt1234') });
|
||||
|
||||
// blake3 advanced usage
|
||||
blake3(ab);
|
||||
blake3(ab, { dkLen: 256 });
|
||||
blake3(ab, { key: new Uint8Array(32) });
|
||||
blake3(ab, { context: txt.encode('application-name') });
|
||||
```
|
||||
|
||||
- Blake1 is legacy hash, one of SHA3 proposals. It is rarely used anywhere. See [pdf](https://www.aumasson.jp/blake/blake.pdf).
|
||||
- Blake2 is popular fast hash. blake2b focuses on 64-bit platforms while blake2s is for 8-bit to 32-bit ones. See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net)
|
||||
- Blake3 is faster, reduced-round blake2. See [Website & specs](https://blake3.io)
|
||||
|
||||
#### legacy: sha1, md5, ripemd160
|
||||
|
||||
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
|
||||
Don't use them in a new protocol. What "weak" means:
|
||||
|
||||
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
|
||||
- No practical pre-image attacks (only theoretical, 2^123.4)
|
||||
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
|
||||
|
||||
```typescript
|
||||
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js';
|
||||
for (let hash of [md5, ripemd160, sha1]) {
|
||||
const arr = Uint8Array.from([0x10, 0x20, 0x30]);
|
||||
const a = hash(arr);
|
||||
const b = hash.create().update(arr).digest();
|
||||
}
|
||||
```
|
||||
|
||||
#### hmac
|
||||
|
||||
```typescript
|
||||
import { hmac } from '@noble/hashes/hmac.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
const key = new Uint8Array(32).fill(1);
|
||||
const msg = new Uint8Array(32).fill(2);
|
||||
const mac1 = hmac(sha256, key, msg);
|
||||
const mac2 = hmac.create(sha256, key).update(msg).digest();
|
||||
```
|
||||
|
||||
Conforms to [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104).
|
||||
|
||||
#### hkdf
|
||||
|
||||
```typescript
|
||||
import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
import { randomBytes } from '@noble/hashes/utils.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
const inputKey = randomBytes(32);
|
||||
const salt = randomBytes(32);
|
||||
const info = new TextEncoder().encode('application-key');
|
||||
const hk1 = hkdf(sha256, inputKey, salt, info, 32);
|
||||
|
||||
// == same as
|
||||
import { extract, expand } from '@noble/hashes/hkdf.js';
|
||||
const prk = extract(sha256, inputKey, salt);
|
||||
const hk2 = expand(sha256, prk, info, 32);
|
||||
```
|
||||
|
||||
Conforms to [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869).
|
||||
|
||||
#### pbkdf2
|
||||
|
||||
```typescript
|
||||
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
|
||||
const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
|
||||
const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
|
||||
c: 524288,
|
||||
dkLen: 32,
|
||||
});
|
||||
```
|
||||
|
||||
Conforms to [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898).
|
||||
|
||||
#### scrypt
|
||||
|
||||
```typescript
|
||||
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
|
||||
const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
|
||||
const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 });
|
||||
const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), {
|
||||
N: 2 ** 17,
|
||||
r: 8,
|
||||
p: 1,
|
||||
dkLen: 32,
|
||||
onProgress(percentage) {
|
||||
console.log('progress', percentage);
|
||||
},
|
||||
maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p)
|
||||
});
|
||||
```
|
||||
|
||||
Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914),
|
||||
[Website](https://www.tarsnap.com/scrypt.html)
|
||||
|
||||
- `N, r, p` are work factors. It is common to only adjust N, while keeping `r: 8, p: 1`.
|
||||
See [the blog post](https://blog.filippo.io/the-scrypt-parameters/).
|
||||
JS doesn't support parallelization, making increasing `p` meaningless.
|
||||
- `dkLen` is the length of output bytes e.g. `32` or `64`
|
||||
- `onProgress` can be used with async version of the function to report progress to a user.
|
||||
- `maxmem` prevents DoS and is limited to `1GB + 1KB` (`2**30 + 2**10`), but can be adjusted using formula: `N * r * p * 128 + (128 * r * p)`
|
||||
|
||||
Time it takes to derive Scrypt key under different values of N (2\*\*N) on Apple M4 (mobile phones can be 1x-4x slower):
|
||||
|
||||
| N pow | Time | RAM |
|
||||
| ----- | ---- | ----- |
|
||||
| 16 | 0.1s | 64MB |
|
||||
| 17 | 0.2s | 128MB |
|
||||
| 18 | 0.4s | 256MB |
|
||||
| 19 | 0.8s | 512MB |
|
||||
| 20 | 1.5s | 1GB |
|
||||
| 21 | 3.1s | 2GB |
|
||||
| 22 | 6.2s | 4GB |
|
||||
| 23 | 13s | 8GB |
|
||||
| 24 | 27s | 16GB |
|
||||
|
||||
> [!NOTE]
|
||||
> We support N larger than `2**20` where available, however,
|
||||
> not all JS engines support >= 2GB ArrayBuffer-s.
|
||||
> When using such N, you'll need to manually adjust `maxmem`, using formula above.
|
||||
> Other JS implementations don't support large N-s.
|
||||
|
||||
#### argon2
|
||||
|
||||
```ts
|
||||
import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js';
|
||||
const arg1 = argon2id('password', 'saltsalt', { t: 2, m: 65536, p: 1, maxmem: 2 ** 32 - 1 });
|
||||
```
|
||||
|
||||
Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation.
|
||||
|
||||
> [!WARNING]
|
||||
> Argon2 can't be fast in JS, because there is no fast Uint64Array.
|
||||
> It is suggested to use [Scrypt](#scrypt) instead.
|
||||
> Being 5x slower than native code means brute-forcing attackers have bigger advantage.
|
||||
|
||||
#### webcrypto: friendly wrapper
|
||||
|
||||
```js
|
||||
import { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } from '@noble/hashes/webcrypto.js';
|
||||
import { randomBytes } from '@noble/hashes/utils.js';
|
||||
const whash = await sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23]));
|
||||
|
||||
const key = new Uint8Array(32).fill(1);
|
||||
const msg = new Uint8Array(32).fill(2);
|
||||
const wmac = await hmac(sha256, key, msg);
|
||||
|
||||
const inputKey = randomBytes(32);
|
||||
const salt = randomBytes(32);
|
||||
const info = new TextEncoder().encode('application-key');
|
||||
const hk1 = await hkdf(sha256, inputKey, salt, info, 32);
|
||||
|
||||
const pbkey1 = await pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 });
|
||||
```
|
||||
|
||||
Sometimes people want to use built-in `crypto.subtle` instead of pure JS implementation.
|
||||
However, it has terrible API.
|
||||
|
||||
We simplify access to built-ins with API which mirrors noble-hashes.
|
||||
The overhead is minimal - just 30+ lines of code, which verify input correctness.
|
||||
|
||||
> [!NOTE]
|
||||
> Webcrypto methods are always async.
|
||||
|
||||
#### utils
|
||||
|
||||
```typescript
|
||||
import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils.js';
|
||||
console.log(toHex(randomBytes(32)));
|
||||
```
|
||||
|
||||
- `bytesToHex` will convert `Uint8Array` to a hex string
|
||||
- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes`
|
||||
|
||||
## Security
|
||||
|
||||
The library has been audited:
|
||||
|
||||
- at version 2.2.0, in Apr 2026, by ourselves (self-audited)
|
||||
- Scope: everything
|
||||
- [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/2.2.0..main)
|
||||
- at version 1.0.0, in Jan 2022, independently, by [Cure53](https://cure53.de)
|
||||
- PDFs: [website](https://cure53.de/pentest-report_hashing-libs.pdf), [in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf)
|
||||
- Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited
|
||||
- The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io)
|
||||
|
||||
It is tested against property-based, cross-library and Wycheproof vectors,
|
||||
and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing).
|
||||
|
||||
If you see anything unusual: investigate and report.
|
||||
|
||||
### Constant-timeness
|
||||
|
||||
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
|
||||
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
|
||||
in a scripting language. Which means _any other JS library can't have
|
||||
constant-timeness_. Even statically typed Rust, a language without GC,
|
||||
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
|
||||
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
|
||||
Use low-level libraries & languages.
|
||||
|
||||
### Memory dumping
|
||||
|
||||
The library shares state buffers between hash
|
||||
function calls. The buffers are zeroed-out after each call. However, if an attacker
|
||||
can read application memory, you are doomed in any case:
|
||||
|
||||
- At some point, input will be a string and strings are immutable in JS:
|
||||
there is no way to overwrite them with zeros. For example: deriving
|
||||
key from `scrypt(password, salt)` where password and salt are strings
|
||||
- Input from a file will stay in file buffers
|
||||
- Input / output will be re-used multiple times in application which means it could stay in memory
|
||||
- `await anything()` will always write all internal variables (including numbers)
|
||||
to memory. With async functions / Promises there are no guarantees when the code
|
||||
chunk would be executed. Which means attacker can have plenty of time to read data from memory
|
||||
- There is no way to guarantee anything about zeroing sensitive data without
|
||||
complex tests-suite which will dump process memory and verify that there is
|
||||
no sensitive data left. For JS it means testing all browsers (incl. mobile),
|
||||
which is complex. And of course it will be useless without using the same
|
||||
test-suite in the actual application that consumes the library
|
||||
|
||||
### Supply chain security
|
||||
|
||||
- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures
|
||||
- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity.
|
||||
- **Rare releasing** is practiced to minimize the need for re-audits by end-users.
|
||||
- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk.
|
||||
- We use as few dependencies as possible.
|
||||
- Version ranges are locked, and changes are checked with npm-diff.
|
||||
- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps.
|
||||
|
||||
For this package, there are 0 dependencies; and a few dev dependencies:
|
||||
|
||||
- jsbt contains helpers for building, benchmarking & testing secure JS apps. It is developed by the same author
|
||||
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation
|
||||
|
||||
### Randomness
|
||||
|
||||
We rely on the built-in
|
||||
[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues),
|
||||
which is considered a cryptographically secure PRNG.
|
||||
|
||||
Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy.
|
||||
|
||||
### Quantum computers
|
||||
|
||||
Cryptographically relevant quantum computer, if built, will allow to
|
||||
utilize Grover's algorithm to break hashes in 2^n/2 operations, instead of 2^n.
|
||||
|
||||
This means SHA256 should be replaced with SHA512, SHA3-256 with SHA3-512, SHAKE128 with SHAKE256 etc.
|
||||
|
||||
Australian ASD prohibits SHA256 and similar hashes [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
|
||||
|
||||
## Upgrading
|
||||
|
||||
Supported node.js versions:
|
||||
|
||||
- v2: v20.19+ (ESM-only)
|
||||
- v1: v14.21+ (ESM & CJS)
|
||||
|
||||
v2.0 changelog:
|
||||
|
||||
- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+
|
||||
- `.js` extension must be used for all modules
|
||||
- Old: `@noble/hashes/sha3`
|
||||
- New: `@noble/hashes/sha3.js`
|
||||
- This simplifies working in browsers natively without transpilers
|
||||
- Only allow Uint8Array as hash inputs, prohibit `string`
|
||||
- Strict validation checks improve security
|
||||
- To replicate previous behavior, use `utils.utf8ToBytes`
|
||||
- Rename / remove some modules for consistency. Previously, sha384 resided in sha512, which was weird
|
||||
- `sha256`, `sha512` => `sha2.js` (consistent with `sha3.js`)
|
||||
- `blake2b`, `blake2s` => `blake2.js` (consistent with `blake3.js`, `blake1.js`)
|
||||
- `ripemd160`, `sha1`, `md5` => `legacy.js` (all low-security hashes are there)
|
||||
- `_assert` => `utils.js`
|
||||
- `crypto` internal module got removed: use built-in WebCrypto instead
|
||||
- Improve typescript types & option autocomplete
|
||||
- Bump compilation target from es2020 to es2022
|
||||
|
||||
## Contributing & testing
|
||||
|
||||
`test/misc` directory contains implementations of loop unrolling and md5.
|
||||
|
||||
- `npm install && npm run build && npm test` will build the code and run tests.
|
||||
- `npm run lint` / `npm run format` will run linter / fix linter issues.
|
||||
- `npm run bench` will run benchmarks
|
||||
- `npm run build:release` will build single file
|
||||
- There is **additional** 20-min DoS test `npm run test:dos` and 2-hour multicore test `npm run test:slow`.
|
||||
See [our approach to testing](./test/README.md)
|
||||
|
||||
Some hashes are outside of scope of the library:
|
||||
- [Pedersen in micro-zk-proofs](https://github.com/paulmillr/micro-zk-proofs/blob/1ed5ce1253583b2e540eef7f3477fb52bf5344ff/src/pedersen.ts)
|
||||
- [Poseidon in noble-curves](https://github.com/paulmillr/noble-curves/blob/3d124dd3ecec8b6634cc0b2ba1c183aded5304f9/src/abstract/poseidon.ts)
|
||||
- [Poly1305 & GHash in noble-ciphers](https://github.com/paulmillr/noble-ciphers)
|
||||
|
||||
See [paulmillr.com/noble](https://paulmillr.com/noble/) for useful resources, articles, documentation and demos related to the library.
|
||||
|
||||
## Speed
|
||||
|
||||
```sh
|
||||
npm run bench
|
||||
```
|
||||
|
||||
Benchmarks measured on Apple M4. If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble).
|
||||
|
||||
```
|
||||
# 32B
|
||||
sha256 x 2,016,129 ops/sec @ 496ns/op
|
||||
sha512 x 740,740 ops/sec @ 1μs/op
|
||||
sha3_256 x 287,686 ops/sec @ 3μs/op
|
||||
sha3_512 x 288,267 ops/sec @ 3μs/op
|
||||
k12 x 476,190 ops/sec @ 2μs/op
|
||||
blake2b x 410,340 ops/sec @ 2μs/op
|
||||
blake2s x 942,507 ops/sec @ 1μs/op
|
||||
blake3 x 1,006,036 ops/sec @ 994ns/op
|
||||
ripemd160 x 1,410,437 ops/sec @ 709ns/op
|
||||
md5 x 1,663,893 ops/sec @ 601ns/op
|
||||
sha1 x 1,589,825 ops/sec @ 629ns/op
|
||||
|
||||
# 1MB
|
||||
sha256 x 331 ops/sec @ 3ms/op
|
||||
sha512 x 128 ops/sec @ 7ms/op
|
||||
sha3_256 x 39 ops/sec @ 25ms/op
|
||||
sha3_512 x 21 ops/sec @ 46ms/op
|
||||
kt128 x 91 ops/sec @ 10ms/op
|
||||
kt256 x 75 ops/sec @ 13ms/op
|
||||
turboshake128 x 93 ops/sec @ 10ms/op
|
||||
blake256 x 57 ops/sec @ 17ms/op
|
||||
blake2b x 61 ops/sec @ 16ms/op
|
||||
blake2s x 78 ops/sec @ 12ms/op
|
||||
blake3 x 95 ops/sec @ 10ms/op
|
||||
ripemd160 x 177 ops/sec @ 5ms/op
|
||||
md5 x 250 ops/sec @ 3ms/op
|
||||
sha1 x 416 ops/sec @ 2ms/op
|
||||
|
||||
# MAC
|
||||
hmac(sha256) x 599,880 ops/sec @ 1μs/op
|
||||
hmac(sha512) x 197,122 ops/sec @ 5μs/op
|
||||
kmac256 x 87,981 ops/sec @ 11μs/op
|
||||
blake3(key) x 796,812 ops/sec @ 1μs/op
|
||||
|
||||
# KDF
|
||||
hkdf(sha256) x 259,942 ops/sec @ 3μs/op
|
||||
blake3(context) x 424,808 ops/sec @ 2μs/op
|
||||
pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op
|
||||
pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op
|
||||
scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 400ms/op
|
||||
argon2id(t: 1, m: 256MB) 2881ms
|
||||
```
|
||||
|
||||
The library could be 3x faster by utilizing loop unrolling. It isn't used because
|
||||
unrolling a) would increase bundle size b) make lib un-readable c) current perf is "fast enough"
|
||||
for most use-cases.
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
|
||||
|
||||
See LICENSE file.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Internal helpers for blake hash.
|
||||
* @module
|
||||
*/
|
||||
import { type TRet } from './utils.ts';
|
||||
/**
|
||||
* Internal blake permutation table.
|
||||
* Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also
|
||||
* reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows
|
||||
* `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.
|
||||
*/
|
||||
export declare const BSIGMA: TRet<Uint8Array>;
|
||||
export type Num4 = {
|
||||
a: number;
|
||||
b: number;
|
||||
c: number;
|
||||
d: number;
|
||||
};
|
||||
export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4;
|
||||
export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4;
|
||||
//# sourceMappingURL=_blake.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_blake.d.ts","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAQ,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AAEH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,UAAU,CAkBlC,CAAC;AAGH,MAAM,MAAM,IAAI,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;CAAE,CAAC;AAKnE,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E;AAKD,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E"}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Internal helpers for blake hash.
|
||||
* @module
|
||||
*/
|
||||
import { rotr } from "./utils.js";
|
||||
/**
|
||||
* Internal blake permutation table.
|
||||
* Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also
|
||||
* reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows
|
||||
* `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants.
|
||||
*/
|
||||
// prettier-ignore
|
||||
export const BSIGMA = /* @__PURE__ */ Uint8Array.from([
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
||||
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
|
||||
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
|
||||
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
|
||||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
||||
// Blake1, unused in others
|
||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
||||
]);
|
||||
// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair.
|
||||
// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed
|
||||
// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path.
|
||||
export function G1s(a, b, c, d, x) {
|
||||
a = (a + b + x) | 0;
|
||||
d = rotr(d ^ a, 16);
|
||||
c = (c + d) | 0;
|
||||
b = rotr(b ^ c, 12);
|
||||
return { a, b, c, d };
|
||||
}
|
||||
// 32-bit / BLAKE2s second half of G.
|
||||
// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed
|
||||
// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path.
|
||||
export function G2s(a, b, c, d, x) {
|
||||
a = (a + b + x) | 0;
|
||||
d = rotr(d ^ a, 8);
|
||||
c = (c + d) | 0;
|
||||
b = rotr(b ^ c, 7);
|
||||
return { a, b, c, d };
|
||||
}
|
||||
//# sourceMappingURL=_blake.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_blake.js","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAa,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AACH,kBAAkB;AAClB,MAAM,CAAC,MAAM,MAAM,GAAqB,eAAe,CAAC,UAAU,CAAC,IAAI,CAAC;IACtE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,2BAA2B;IAC3B,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE;IACpD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;CACrD,CAAC,CAAC;AAKH,6EAA6E;AAC7E,+EAA+E;AAC/E,mEAAmE;AACnE,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC;AAED,qCAAqC;AACrC,sFAAsF;AACtF,qEAAqE;AACrE,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS,EAAE,CAAS;IACvE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACpB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC"}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Internal Merkle-Damgard hash utils.
|
||||
* @module
|
||||
*/
|
||||
import { type Hash, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
||||
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
||||
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
||||
* set the same bit.
|
||||
* @param a - selector word
|
||||
* @param b - word chosen when selector bit is set
|
||||
* @param c - word chosen when selector bit is clear
|
||||
* @returns Mixed 32-bit word.
|
||||
* @example
|
||||
* Combine three words with the shared 32-bit choice primitive.
|
||||
* ```ts
|
||||
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
||||
* ```
|
||||
*/
|
||||
export declare function Chi(a: number, b: number, c: number): number;
|
||||
/**
|
||||
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
||||
* Returns bits shared by at least two inputs.
|
||||
* @param a - first input word
|
||||
* @param b - second input word
|
||||
* @param c - third input word
|
||||
* @returns Mixed 32-bit word.
|
||||
* @example
|
||||
* Combine three words with the shared 32-bit majority primitive.
|
||||
* ```ts
|
||||
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
||||
* ```
|
||||
*/
|
||||
export declare function Maj(a: number, b: number, c: number): number;
|
||||
/**
|
||||
* Merkle-Damgard hash construction base class.
|
||||
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
||||
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
||||
* strings with partial-byte tails.
|
||||
* @param blockLen - internal block size in bytes
|
||||
* @param outputLen - digest size in bytes
|
||||
* @param padOffset - trailing length field size in bytes
|
||||
* @param isLE - whether length and state words are encoded in little-endian
|
||||
* @example
|
||||
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
||||
* ```ts
|
||||
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
||||
* const hash = new _SHA1();
|
||||
* hash.update(new Uint8Array([97, 98, 99]));
|
||||
* hash.digest();
|
||||
* ```
|
||||
*/
|
||||
export declare abstract class HashMD<T extends HashMD<T>> implements Hash<T> {
|
||||
protected abstract process(buf: DataView, offset: number): void;
|
||||
protected abstract get(): number[];
|
||||
protected abstract set(...args: number[]): void;
|
||||
abstract destroy(): void;
|
||||
protected abstract roundClean(): void;
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
readonly canXOF = false;
|
||||
readonly padOffset: number;
|
||||
readonly isLE: boolean;
|
||||
protected buffer: Uint8Array;
|
||||
protected view: DataView;
|
||||
protected finished: boolean;
|
||||
protected length: number;
|
||||
protected pos: number;
|
||||
protected destroyed: boolean;
|
||||
constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean);
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
_cloneInto(to?: T): T;
|
||||
clone(): T;
|
||||
}
|
||||
/**
|
||||
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
||||
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
||||
*/
|
||||
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
||||
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
||||
* it as read-only because constructors copy words from it by index. */
|
||||
export declare const SHA256_IV: TRet<Uint32Array>;
|
||||
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
|
||||
* treat it as read-only because constructors copy words from it by index. */
|
||||
export declare const SHA224_IV: TRet<Uint32Array>;
|
||||
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
|
||||
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
|
||||
* because constructors copy halves from it by index. */
|
||||
export declare const SHA384_IV: TRet<Uint32Array>;
|
||||
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
|
||||
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
|
||||
* constructors copy halves from it by index. */
|
||||
export declare const SHA512_IV: TRet<Uint32Array>;
|
||||
//# sourceMappingURL=_md.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_md.d.ts","sourceRoot":"","sources":["src/_md.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAML,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,8BAAsB,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IAGlE,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAC/D,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,QAAQ,CAAC,UAAU,IAAI,IAAI;IAErC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,SAAS;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAGvB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAEhB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO;IAQjF,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA0BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAkCvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;IAS1B,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAarB,KAAK,IAAI,CAAC;CAGX;AAED;;;GAGG;AAEH;;uEAEuE;AACvE,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;6EAC6E;AAC7E,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;;;wDAGwD;AACxD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC;AAEH;;;gDAGgD;AAChD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC"}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Internal Merkle-Damgard hash utils.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, aexists, aoutput, clean, createView, } from "./utils.js";
|
||||
/**
|
||||
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
||||
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
||||
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
||||
* set the same bit.
|
||||
* @param a - selector word
|
||||
* @param b - word chosen when selector bit is set
|
||||
* @param c - word chosen when selector bit is clear
|
||||
* @returns Mixed 32-bit word.
|
||||
* @example
|
||||
* Combine three words with the shared 32-bit choice primitive.
|
||||
* ```ts
|
||||
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
||||
* ```
|
||||
*/
|
||||
export function Chi(a, b, c) {
|
||||
return (a & b) ^ (~a & c);
|
||||
}
|
||||
/**
|
||||
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
||||
* Returns bits shared by at least two inputs.
|
||||
* @param a - first input word
|
||||
* @param b - second input word
|
||||
* @param c - third input word
|
||||
* @returns Mixed 32-bit word.
|
||||
* @example
|
||||
* Combine three words with the shared 32-bit majority primitive.
|
||||
* ```ts
|
||||
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
||||
* ```
|
||||
*/
|
||||
export function Maj(a, b, c) {
|
||||
return (a & b) ^ (a & c) ^ (b & c);
|
||||
}
|
||||
/**
|
||||
* Merkle-Damgard hash construction base class.
|
||||
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
||||
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
||||
* strings with partial-byte tails.
|
||||
* @param blockLen - internal block size in bytes
|
||||
* @param outputLen - digest size in bytes
|
||||
* @param padOffset - trailing length field size in bytes
|
||||
* @param isLE - whether length and state words are encoded in little-endian
|
||||
* @example
|
||||
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
||||
* ```ts
|
||||
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
||||
* const hash = new _SHA1();
|
||||
* hash.update(new Uint8Array([97, 98, 99]));
|
||||
* hash.digest();
|
||||
* ```
|
||||
*/
|
||||
export class HashMD {
|
||||
blockLen;
|
||||
outputLen;
|
||||
canXOF = false;
|
||||
padOffset;
|
||||
isLE;
|
||||
// For partial updates less than block size
|
||||
buffer;
|
||||
view;
|
||||
finished = false;
|
||||
length = 0;
|
||||
pos = 0;
|
||||
destroyed = false;
|
||||
constructor(blockLen, outputLen, padOffset, isLE) {
|
||||
this.blockLen = blockLen;
|
||||
this.outputLen = outputLen;
|
||||
this.padOffset = padOffset;
|
||||
this.isLE = isLE;
|
||||
this.buffer = new Uint8Array(blockLen);
|
||||
this.view = createView(this.buffer);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
const { view, buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
for (let pos = 0; pos < len;) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path only when there is no buffered partial block: `take === blockLen` implies
|
||||
// `this.pos === 0`, so we can process full blocks directly from the input view.
|
||||
if (take === blockLen) {
|
||||
const dataView = createView(data);
|
||||
for (; blockLen <= len - pos; pos += blockLen)
|
||||
this.process(dataView, pos);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.process(view, 0);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
this.length += data.length;
|
||||
this.roundClean();
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
// Padding
|
||||
// We can avoid allocation of buffer for padding completely if it
|
||||
// was previously not allocated here. But it won't change performance.
|
||||
const { buffer, view, blockLen, isLE } = this;
|
||||
let { pos } = this;
|
||||
// append the bit '1' to the message
|
||||
buffer[pos++] = 0b10000000;
|
||||
clean(this.buffer.subarray(pos));
|
||||
// we have less than padOffset left in buffer, so we cannot put length in
|
||||
// current block, need process it and pad again
|
||||
if (this.padOffset > blockLen - pos) {
|
||||
this.process(view, 0);
|
||||
pos = 0;
|
||||
}
|
||||
// Pad until full block byte with zeros
|
||||
for (let i = pos; i < blockLen; i++)
|
||||
buffer[i] = 0;
|
||||
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
|
||||
// the padding fill above, and JS will overflow before user input can make that half non-zero.
|
||||
// So we only need to write the low 64 bits here.
|
||||
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
||||
this.process(view, 0);
|
||||
const oview = createView(out);
|
||||
const len = this.outputLen;
|
||||
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
|
||||
if (len % 4)
|
||||
throw new Error('_sha2: outputLen must be aligned to 32bit');
|
||||
const outLen = len / 4;
|
||||
const state = this.get();
|
||||
if (outLen > state.length)
|
||||
throw new Error('_sha2: outputLen bigger than state');
|
||||
for (let i = 0; i < outLen; i++)
|
||||
oview.setUint32(4 * i, state[i], isLE);
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
|
||||
// fresh bytes to the caller.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
_cloneInto(to) {
|
||||
to ||= new this.constructor();
|
||||
to.set(...this.get());
|
||||
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
||||
to.destroyed = destroyed;
|
||||
to.finished = finished;
|
||||
to.length = length;
|
||||
to.pos = pos;
|
||||
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
|
||||
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
|
||||
if (length % blockLen)
|
||||
to.buffer.set(buffer);
|
||||
return to;
|
||||
}
|
||||
clone() {
|
||||
return this._cloneInto();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
||||
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
||||
*/
|
||||
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
||||
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
||||
* it as read-only because constructors copy words from it by index. */
|
||||
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
||||
]);
|
||||
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
|
||||
* treat it as read-only because constructors copy words from it by index. */
|
||||
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
|
||||
]);
|
||||
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
|
||||
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
|
||||
* because constructors copy halves from it by index. */
|
||||
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
|
||||
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
|
||||
]);
|
||||
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
|
||||
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
|
||||
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
|
||||
* constructors copy halves from it by index. */
|
||||
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
|
||||
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
|
||||
]);
|
||||
//# sourceMappingURL=_md.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Internal helpers for u64.
|
||||
* BigUint64Array is too slow as per 2026, so we implement it using
|
||||
* Uint32Array.
|
||||
* @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}
|
||||
* @module
|
||||
*/
|
||||
import type { TRet } from './utils.ts';
|
||||
declare function fromBig(n: bigint, le?: boolean): {
|
||||
h: number;
|
||||
l: number;
|
||||
};
|
||||
declare function split(lst: bigint[], le?: boolean): TRet<Uint32Array[]>;
|
||||
declare const toBig: (h: number, l: number) => bigint;
|
||||
declare const shrSH: (h: number, _l: number, s: number) => number;
|
||||
declare const shrSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotrSH: (h: number, l: number, s: number) => number;
|
||||
declare const rotrSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotrBH: (h: number, l: number, s: number) => number;
|
||||
declare const rotrBL: (h: number, l: number, s: number) => number;
|
||||
declare const rotr32H: (_h: number, l: number) => number;
|
||||
declare const rotr32L: (h: number, _l: number) => number;
|
||||
declare const rotlSH: (h: number, l: number, s: number) => number;
|
||||
declare const rotlSL: (h: number, l: number, s: number) => number;
|
||||
declare const rotlBH: (h: number, l: number, s: number) => number;
|
||||
declare const rotlBL: (h: number, l: number, s: number) => number;
|
||||
declare function add(Ah: number, Al: number, Bh: number, Bl: number): {
|
||||
h: number;
|
||||
l: number;
|
||||
};
|
||||
declare const add3L: (Al: number, Bl: number, Cl: number) => number;
|
||||
declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
|
||||
declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
|
||||
declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
|
||||
declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
|
||||
declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
|
||||
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
|
||||
declare const u64: {
|
||||
fromBig: typeof fromBig;
|
||||
split: typeof split;
|
||||
toBig: (h: number, l: number) => bigint;
|
||||
shrSH: (h: number, _l: number, s: number) => number;
|
||||
shrSL: (h: number, l: number, s: number) => number;
|
||||
rotrSH: (h: number, l: number, s: number) => number;
|
||||
rotrSL: (h: number, l: number, s: number) => number;
|
||||
rotrBH: (h: number, l: number, s: number) => number;
|
||||
rotrBL: (h: number, l: number, s: number) => number;
|
||||
rotr32H: (_h: number, l: number) => number;
|
||||
rotr32L: (h: number, _l: number) => number;
|
||||
rotlSH: (h: number, l: number, s: number) => number;
|
||||
rotlSL: (h: number, l: number, s: number) => number;
|
||||
rotlBH: (h: number, l: number, s: number) => number;
|
||||
rotlBL: (h: number, l: number, s: number) => number;
|
||||
add: typeof add;
|
||||
add3L: (Al: number, Bl: number, Cl: number) => number;
|
||||
add3H: (low: number, Ah: number, Bh: number, Ch: number) => number;
|
||||
add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number;
|
||||
add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number;
|
||||
add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number;
|
||||
add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number;
|
||||
};
|
||||
export default u64;
|
||||
//# sourceMappingURL=_u64.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"_u64.d.ts","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAOvC,iBAAS,OAAO,CACd,CAAC,EAAE,MAAM,EACT,EAAE,UAAQ,GACT;IACD,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX,CAGA;AAID,iBAAS,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,UAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,CAS7D;AAID,QAAA,MAAM,KAAK,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqD,CAAC;AAE5F,QAAA,MAAM,KAAK,GAAI,GAAG,MAAM,EAAE,IAAI,MAAM,EAAE,GAAG,MAAM,KAAG,MAAiB,CAAC;AAEpE,QAAA,MAAM,KAAK,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqC,CAAC;AAEvF,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqC,CAAC;AAExF,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqC,CAAC;AAExF,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAA4C,CAAC;AAE/F,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAA4C,CAAC;AAE/F,QAAA,MAAM,OAAO,GAAI,IAAI,MAAM,EAAE,GAAG,MAAM,KAAG,MAAW,CAAC;AAErD,QAAA,MAAM,OAAO,GAAI,GAAG,MAAM,EAAE,IAAI,MAAM,KAAG,MAAW,CAAC;AAErD,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqC,CAAC;AAExF,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAAqC,CAAC;AAExF,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAA4C,CAAC;AAE/F,QAAA,MAAM,MAAM,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAA4C,CAAC;AAK/F,iBAAS,GAAG,CACV,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,MAAM,GACT;IACD,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX,CAGA;AAGD,QAAA,MAAM,KAAK,GAAI,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MAA8C,CAAC;AAEnG,QAAA,MAAM,KAAK,GAAI,KAAK,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MACrB,CAAC;AAE7C,QAAA,MAAM,KAAK,GAAI,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MACb,CAAC;AAEpD,QAAA,MAAM,KAAK,GAAI,KAAK,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MAC5B,CAAC;AAElD,QAAA,MAAM,KAAK,GAAI,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MACZ,CAAC;AAEjE,QAAA,MAAM,KAAK,GAAI,KAAK,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,KAAG,MACnC,CAAC;AAGvD,OAAO,EACL,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EACrK,CAAC;AAIF,QAAA,MAAM,GAAG,EAAE;IAAE,OAAO,EAAE,OAAO,OAAO,CAAC;IAAC,KAAK,EAAE,OAAO,KAAK,CAAC;IAAC,KAAK,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,OAAO,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,GAAG,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;CAOrpC,CAAC;AAEF,eAAe,GAAG,CAAC"}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
||||
const _32n = /* @__PURE__ */ BigInt(32);
|
||||
// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
|
||||
// }` to match little-endian word order rather than the property names.
|
||||
function fromBig(n, le = false) {
|
||||
if (le)
|
||||
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
|
||||
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
||||
}
|
||||
// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
|
||||
// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
|
||||
function split(lst, le = false) {
|
||||
const len = lst.length;
|
||||
let Ah = new Uint32Array(len);
|
||||
let Al = new Uint32Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
const { h, l } = fromBig(lst[i], le);
|
||||
[Ah[i], Al[i]] = [h, l];
|
||||
}
|
||||
return [Ah, Al];
|
||||
}
|
||||
// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS
|
||||
// bitwise results back to uint32 first, and little-endian callers must swap.
|
||||
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
|
||||
// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
|
||||
const shrSH = (h, _l, s) => h >>> s;
|
||||
// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
|
||||
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
||||
// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
|
||||
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
|
||||
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
|
||||
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
||||
// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
||||
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
|
||||
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
||||
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
|
||||
// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
|
||||
const rotr32H = (_h, l) => l;
|
||||
// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
|
||||
const rotr32L = (h, _l) => h;
|
||||
// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
|
||||
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
|
||||
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
|
||||
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
|
||||
// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
||||
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
|
||||
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
|
||||
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
|
||||
// Add two split 64-bit words and return the split `{ h, l }` sum.
|
||||
// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
|
||||
// of the low sum and instead use division.
|
||||
function add(Ah, Al, Bh, Bl) {
|
||||
const l = (Al >>> 0) + (Bl >>> 0);
|
||||
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
|
||||
}
|
||||
// Addition with more than 2 elements
|
||||
// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
|
||||
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
||||
// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
|
||||
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
|
||||
// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
|
||||
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
||||
// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
|
||||
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
|
||||
// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
|
||||
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
||||
// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
|
||||
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
|
||||
// prettier-ignore
|
||||
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
|
||||
// Canonical grouped namespace for callers that prefer one object.
|
||||
// Named exports stay for direct imports.
|
||||
// prettier-ignore
|
||||
const u64 = {
|
||||
fromBig, split, toBig,
|
||||
shrSH, shrSL,
|
||||
rotrSH, rotrSL, rotrBH, rotrBL,
|
||||
rotr32H, rotr32L,
|
||||
rotlSH, rotlSL, rotlBH, rotlBL,
|
||||
add, add3L, add3H, add4L, add4H, add5H, add5L,
|
||||
};
|
||||
// Default export mirrors named `u64` for compatibility with object-style imports.
|
||||
export default u64;
|
||||
//# sourceMappingURL=_u64.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+112
@@ -0,0 +1,112 @@
|
||||
import { type KDFInput, type TArg, type TRet } from './utils.ts';
|
||||
/** Argon2 cost, output, and optional secret/personalization inputs. */
|
||||
export type ArgonOpts = {
|
||||
/** Time cost measured in iterations. */
|
||||
t: number;
|
||||
/** Memory cost in kibibytes. */
|
||||
m: number;
|
||||
/** Parallelization parameter. */
|
||||
p: number;
|
||||
/** Argon2 version number. Defaults to `0x13`. */
|
||||
version?: number;
|
||||
/** Optional secret key mixed into initialization. */
|
||||
key?: KDFInput;
|
||||
/** Optional personalization string or bytes. */
|
||||
personalization?: KDFInput;
|
||||
/** Desired output length in bytes. RFC 9106 §3.1 requires `T` in the 4..(2^32 - 1) range. */
|
||||
dkLen?: number;
|
||||
/** Max scheduler block time in milliseconds for the async variants. */
|
||||
asyncTick?: number;
|
||||
/** Maximum temporary memory budget in bytes. */
|
||||
maxmem?: number;
|
||||
/**
|
||||
* Optional progress callback invoked during long-running derivations.
|
||||
* param progress - completion fraction in the `0..1` range
|
||||
*/
|
||||
onProgress?: (progress: number) => void;
|
||||
};
|
||||
/**
|
||||
* Argon2d GPU-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2d.
|
||||
* ```ts
|
||||
* argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2d: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Argon2i side-channel-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2i.
|
||||
* ```ts
|
||||
* argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2i: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Argon2id, combining i+d, the most popular version from RFC 9106.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2id.
|
||||
* ```ts
|
||||
* argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2id: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => TRet<Uint8Array>;
|
||||
/**
|
||||
* Argon2d async GPU-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2d asynchronously.
|
||||
* ```ts
|
||||
* await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2dAsync: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => Promise<TRet<Uint8Array>>;
|
||||
/**
|
||||
* Argon2i async side-channel-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2i asynchronously.
|
||||
* ```ts
|
||||
* await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2iAsync: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => Promise<TRet<Uint8Array>>;
|
||||
/**
|
||||
* Argon2id async, combining i+d, the most popular version from RFC 9106.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2id asynchronously.
|
||||
* ```ts
|
||||
* await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export declare const argon2idAsync: (password: TArg<KDFInput>, salt: TArg<KDFInput>, opts: TArg<ArgonOpts>) => Promise<TRet<Uint8Array>>;
|
||||
//# sourceMappingURL=argon2.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":"AAYA,OAAO,EASL,KAAK,QAAQ,EACb,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAuLpB,uEAAuE;AACvE,MAAM,MAAM,SAAS,GAAG;IACtB,wCAAwC;IACxC,CAAC,EAAE,MAAM,CAAC;IACV,gCAAgC;IAChC,CAAC,EAAE,MAAM,CAAC;IACV,iCAAiC;IACjC,CAAC,EAAE,MAAM,CAAC;IACV,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qDAAqD;IACrD,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,gDAAgD;IAChD,eAAe,CAAC,EAAE,QAAQ,CAAC;IAC3B,6FAA6F;IAC7F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,uEAAuE;IACvE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AA6PF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,GAClB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,IAAI,CAAC,UAAU,CAA8C,CAAC;AACjE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,GAClB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,IAAI,CAAC,UAAU,CAA6C,CAAC;AAChE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,QAAQ,GACnB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,IAAI,CAAC,UAAU,CAA8C,CAAC;AA2EjE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAmD,CAAC;AAC/E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAkD,CAAC;AAC9E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,aAAa,GACxB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAmD,CAAC"}
|
||||
+517
@@ -0,0 +1,517 @@
|
||||
/**
|
||||
* Argon2 KDF from RFC 9106. Can be used to create a key from password and salt.
|
||||
* We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness:
|
||||
* * argon uses uint64, but JS doesn't have fast uint64array
|
||||
* * uint64 multiplication is 1/3 of time
|
||||
* * `P` function would be very nice with u64, because most of value will be in registers,
|
||||
* hovewer with u32 it will require 32 registers, which is too much.
|
||||
* * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down
|
||||
* @module
|
||||
*/
|
||||
import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from "./_u64.js";
|
||||
import { blake2b } from "./blake2.js";
|
||||
import { anumber, clean, kdfInputToBytes, nextTick, swap32IfBE, swap8IfBE, u32, u8, } from "./utils.js";
|
||||
// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the
|
||||
// spec-bound part here; the object keys are internal labels.
|
||||
const AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 };
|
||||
// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob.
|
||||
const ARGON2_SYNC_POINTS = 4;
|
||||
// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted
|
||||
// optional fields by emitting empty bytes.
|
||||
const abytesOrZero = (buf, errorTitle = '') => {
|
||||
if (buf === undefined)
|
||||
return Uint8Array.of();
|
||||
return kdfInputToBytes(buf, errorTitle);
|
||||
};
|
||||
// Unsigned `u32 * u32 = { h, l }`, returned as split 64-bit halves.
|
||||
function mul(a, b) {
|
||||
// Split into 16-bit limbs so each partial product stays exact under `Math.imul`.
|
||||
const aL = a & 0xffff;
|
||||
const aH = a >>> 16;
|
||||
const bL = b & 0xffff;
|
||||
const bH = b >>> 16;
|
||||
const ll = Math.imul(aL, bL);
|
||||
const hl = Math.imul(aH, bL);
|
||||
const lh = Math.imul(aL, bH);
|
||||
const hh = Math.imul(aH, bH);
|
||||
const carry = (ll >>> 16) + (hl & 0xffff) + lh;
|
||||
const high = (hh + (hl >>> 16) + (carry >>> 16)) | 0;
|
||||
const low = (carry << 16) | (ll & 0xffff);
|
||||
return { h: high, l: low };
|
||||
}
|
||||
function mul2(a, b) {
|
||||
// Double the split 64-bit product; carry from `l` is folded back into `h` via `l >>> 31`.
|
||||
const { h, l } = mul(a, b);
|
||||
return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff };
|
||||
}
|
||||
// BlaMka permutation for Argon2
|
||||
// `A + B + 2 * trunc(A) * trunc(B)`, where `trunc(...)` means the low 32-bit halves.
|
||||
function blamka(Ah, Al, Bh, Bl) {
|
||||
const { h: Ch, l: Cl } = mul2(Al, Bl);
|
||||
// A + B + (2 * A * B)
|
||||
const Rll = add3L(Al, Bl, Cl);
|
||||
return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 };
|
||||
}
|
||||
// Temporary block buffer.
|
||||
// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's
|
||||
// 8x8 matrix of 16-byte registers.
|
||||
const A2_BUF = new Uint32Array(256);
|
||||
// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s.
|
||||
function G(a, b, c, d) {
|
||||
let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore
|
||||
let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore
|
||||
let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore
|
||||
let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore
|
||||
// RFC 9106 Figure 19 GB rotates by 32, 24, 16, and 63 bits after each XOR step.
|
||||
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
|
||||
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
|
||||
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
|
||||
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
|
||||
((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah));
|
||||
((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh));
|
||||
((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch));
|
||||
((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh));
|
||||
}
|
||||
// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves.
|
||||
// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word
|
||||
// indices inside eight 16-byte inputs, not copied word values.
|
||||
// prettier-ignore
|
||||
function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) {
|
||||
// RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix.
|
||||
G(v00, v04, v08, v12);
|
||||
G(v01, v05, v09, v13);
|
||||
G(v02, v06, v10, v14);
|
||||
G(v03, v07, v11, v15);
|
||||
G(v00, v05, v10, v15);
|
||||
G(v01, v06, v11, v12);
|
||||
G(v02, v07, v08, v13);
|
||||
G(v03, v04, v09, v14);
|
||||
}
|
||||
function block(x, xPos, yPos, outPos, needXor) {
|
||||
for (let i = 0; i < 256; i++)
|
||||
A2_BUF[i] = x[xPos + i] ^ x[yPos + i];
|
||||
// rows (8 consecutive 16-register groups)
|
||||
for (let i = 0; i < 128; i += 16) {
|
||||
// prettier-ignore
|
||||
P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15);
|
||||
}
|
||||
// columns (8 strided 16-register groups)
|
||||
for (let i = 0; i < 16; i += 2) {
|
||||
// prettier-ignore
|
||||
P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113);
|
||||
}
|
||||
// RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y).
|
||||
if (needXor)
|
||||
for (let i = 0; i < 256; i++)
|
||||
x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
|
||||
else
|
||||
for (let i = 0; i < 256; i++)
|
||||
x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
|
||||
clean(A2_BUF);
|
||||
}
|
||||
// Variable-Length Hash Function H'
|
||||
// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`.
|
||||
function Hp(A, dkLen) {
|
||||
const A8 = u8(A);
|
||||
const T = new Uint32Array(1);
|
||||
const T8 = u8(T);
|
||||
// Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x.
|
||||
T[0] = swap8IfBE(dkLen);
|
||||
// Fast path
|
||||
if (dkLen <= 64)
|
||||
return blake2b.create({ dkLen }).update(T8).update(A8).digest();
|
||||
const out = new Uint8Array(dkLen);
|
||||
let V = blake2b.create({}).update(T8).update(A8).digest();
|
||||
let pos = 0;
|
||||
// RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only
|
||||
// `V_{r+1}` is emitted in full at the remaining length.
|
||||
out.set(V.subarray(0, 32));
|
||||
pos += 32;
|
||||
// Rest blocks
|
||||
for (; dkLen - pos > 64; pos += 32) {
|
||||
const Vh = blake2b.create({}).update(V);
|
||||
Vh.digestInto(V);
|
||||
Vh.destroy();
|
||||
out.set(V.subarray(0, 32), pos);
|
||||
}
|
||||
// Last block
|
||||
out.set(blake2b(V, { dkLen: dkLen - pos }), pos);
|
||||
clean(V, T);
|
||||
// H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes.
|
||||
return out;
|
||||
}
|
||||
// Used only inside process block!
|
||||
function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) {
|
||||
// RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`.
|
||||
let area;
|
||||
if (r === 0) {
|
||||
if (s === 0)
|
||||
area = index - 1;
|
||||
else if (sameLane)
|
||||
area = s * segmentLen + index - 1;
|
||||
else
|
||||
area = s * segmentLen + (index == 0 ? -1 : 0);
|
||||
}
|
||||
else if (sameLane)
|
||||
area = laneLen - segmentLen + index - 1;
|
||||
else
|
||||
area = laneLen - segmentLen + (index == 0 ? -1 : 0);
|
||||
const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
|
||||
// RFC 9106 Figure 13: `mul(randL, randL).h` is `floor(J_1^2 / 2^32)`, and the outer high-half
|
||||
// multiply computes `floor(|W| * x / 2^32)` without floating-point math.
|
||||
const rel = area - 1 - mul(area, mul(randL, randL).h).h;
|
||||
return (startPos + rel) % laneLen;
|
||||
}
|
||||
// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value.
|
||||
const maxUint32 = Math.pow(2, 32);
|
||||
// Validate safe JS integers in `[0, 2^32 - 1]`.
|
||||
function isU32(num) {
|
||||
return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;
|
||||
}
|
||||
function argon2Opts(opts) {
|
||||
const merged = {
|
||||
version: 0x13,
|
||||
dkLen: 32,
|
||||
maxmem: maxUint32 - 1,
|
||||
asyncTick: 10,
|
||||
};
|
||||
// Unknown keys are copied through unchanged here and later ignored unless
|
||||
// destructuring consumes them.
|
||||
for (let [k, v] of Object.entries(opts))
|
||||
if (v !== undefined)
|
||||
merged[k] = v;
|
||||
const { dkLen, p, m, t, version, onProgress, asyncTick } = merged;
|
||||
// RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1.
|
||||
if (!isU32(dkLen) || dkLen < 4)
|
||||
throw new Error('"dkLen" must be 4..');
|
||||
if (!isU32(p) || p < 1 || p >= Math.pow(2, 24))
|
||||
throw new Error('"p" must be 1..2^24');
|
||||
if (!isU32(m))
|
||||
throw new Error('"m" must be 0..2^32');
|
||||
if (!isU32(t) || t < 1)
|
||||
throw new Error('"t" (iterations) must be 1..2^32');
|
||||
if (onProgress !== undefined && typeof onProgress !== 'function')
|
||||
throw new Error('"progressCb" must be a function');
|
||||
anumber(asyncTick, 'asyncTick');
|
||||
/*
|
||||
Memory size m MUST be an integer number of kibibytes from 8*p
|
||||
to 2^(32)-1. The actual number of blocks is m', which is m
|
||||
rounded down to the nearest multiple of 4*p.
|
||||
*/
|
||||
if (!isU32(m) || m < 8 * p)
|
||||
throw new Error('"m" (memory) must be at least 8*p bytes');
|
||||
// Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`.
|
||||
if (version !== 0x10 && version !== 0x13)
|
||||
throw new Error('"version" must be 0x10 or 0x13, got ' + version);
|
||||
return merged;
|
||||
}
|
||||
function argon2Init(password, salt, type, opts) {
|
||||
password = kdfInputToBytes(password, 'password');
|
||||
salt = kdfInputToBytes(salt, 'salt');
|
||||
if (!isU32(password.length))
|
||||
throw new Error('"password" must be less of length 1..4Gb');
|
||||
// RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password
|
||||
// hashing; this library intentionally takes the stricter common >=8-byte salt path.
|
||||
if (!isU32(salt.length) || salt.length < 8)
|
||||
throw new Error('"salt" must be of length 8..4Gb');
|
||||
if (!Object.values(AT).includes(type))
|
||||
throw new Error('"type" was invalid');
|
||||
let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts);
|
||||
// Validation
|
||||
key = abytesOrZero(key, 'key');
|
||||
personalization = abytesOrZero(personalization, 'personalization');
|
||||
// H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) ||
|
||||
// LE32(v) || LE32(y) || LE32(length(P)) || P ||
|
||||
// LE32(length(S)) || S || LE32(length(K)) || K ||
|
||||
// LE32(length(X)) || X)
|
||||
const h = blake2b.create();
|
||||
const BUF = new Uint32Array(1);
|
||||
const BUF8 = u8(BUF);
|
||||
for (let item of [p, dkLen, m, t, version, type]) {
|
||||
// RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before exposing bytes.
|
||||
BUF[0] = swap8IfBE(item);
|
||||
h.update(BUF8);
|
||||
}
|
||||
for (let i of [password, salt, key, personalization]) {
|
||||
BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes
|
||||
h.update(BUF8).update(i);
|
||||
}
|
||||
// Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append
|
||||
// `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks.
|
||||
const H0 = new Uint32Array(18);
|
||||
const H0_8 = u8(H0);
|
||||
h.digestInto(H0_8);
|
||||
// 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing
|
||||
// Params
|
||||
const lanes = p;
|
||||
// m' = 4 * p * floor (m / 4p)
|
||||
const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
|
||||
//q = m' / p columns
|
||||
const laneLen = Math.floor(mP / p);
|
||||
const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
|
||||
// `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation.
|
||||
const memUsed = mP * 1024;
|
||||
if (!isU32(maxmem))
|
||||
throw new Error('"maxmem" expected <2**32, got ' + maxmem);
|
||||
if (memUsed > maxmem)
|
||||
throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem);
|
||||
const B = new Uint32Array(memUsed / 4);
|
||||
// Fill first blocks
|
||||
for (let l = 0; l < p; l++) {
|
||||
const i = 256 * laneLen * l;
|
||||
// B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))
|
||||
H0[17] = swap8IfBE(l);
|
||||
H0[16] = swap8IfBE(0);
|
||||
B.set(swap32IfBE(u32(Hp(H0, 1024))), i);
|
||||
// B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))
|
||||
H0[16] = swap8IfBE(1);
|
||||
B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256);
|
||||
}
|
||||
let perBlock = () => { };
|
||||
if (onProgress) {
|
||||
// The first segment of the first pass skips two preinitialized blocks per lane.
|
||||
const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p;
|
||||
// Invoke callback if progress changes from 10.01 to 10.02
|
||||
// Allows to draw smooth progress bar on up to 8K screen
|
||||
const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1);
|
||||
let blockCnt = 0;
|
||||
perBlock = () => {
|
||||
blockCnt++;
|
||||
if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
|
||||
onProgress(blockCnt / totalBlock);
|
||||
};
|
||||
}
|
||||
clean(BUF, H0);
|
||||
return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
|
||||
}
|
||||
function argon2Output(B, p, laneLen, dkLen) {
|
||||
const B_final = new Uint32Array(256);
|
||||
for (let l = 0; l < p; l++)
|
||||
for (let j = 0; j < 256; j++)
|
||||
B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
|
||||
// RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words
|
||||
// back to spec byte order before `Hp(...)` reinterprets them as bytes.
|
||||
const res = Hp(swap32IfBE(B_final), dkLen);
|
||||
// Wipe both the xor scratch and the full working matrix once final digest bytes exist.
|
||||
// JS cleanup is still only best-effort, but this local buffer is no longer needed here.
|
||||
clean(B, B_final);
|
||||
return res;
|
||||
}
|
||||
function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) {
|
||||
if (offset % laneLen)
|
||||
prev = offset - 1;
|
||||
let randL, randH;
|
||||
if (dataIndependent) {
|
||||
let i128 = index % 128;
|
||||
// RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so regenerate
|
||||
// it whenever the segment index crosses a multiple of 128.
|
||||
if (i128 === 0) {
|
||||
address[256 + 12]++;
|
||||
block(address, 256, 2 * 256, 0, false);
|
||||
block(address, 0, 2 * 256, 0, false);
|
||||
}
|
||||
randL = address[2 * i128];
|
||||
randH = address[2 * i128 + 1];
|
||||
}
|
||||
else {
|
||||
const T = 256 * prev;
|
||||
randL = B[T];
|
||||
randH = B[T + 1];
|
||||
}
|
||||
// Address-block path selects `J1` / `J2`, then maps them to the reference
|
||||
// lane/block per RFC 9106 §3.4.
|
||||
const refLane = r === 0 && s === 0 ? l : randH % lanes;
|
||||
const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
|
||||
const refBlock = laneLen * refLane + refPos;
|
||||
// B[i][j] = G(B[i][j-1], B[l][z])
|
||||
block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
|
||||
}
|
||||
function argon2(type, password, salt, opts) {
|
||||
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(password, salt, type, opts);
|
||||
// Pre-loop setup
|
||||
// [address, input, zero_block] format so we can pass single U32 to block function
|
||||
const address = new Uint32Array(3 * 256);
|
||||
address[256 + 6] = mP;
|
||||
address[256 + 8] = t;
|
||||
address[256 + 10] = type;
|
||||
for (let r = 0; r < t; r++) {
|
||||
// RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy
|
||||
// `0x10` keeps the older overwrite behavior used by the v16 test vectors.
|
||||
const needXor = r !== 0 && version === 0x13;
|
||||
address[256 + 0] = r;
|
||||
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
|
||||
address[256 + 4] = s;
|
||||
// RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only
|
||||
// in pass 0, slices 0 and 1; Argon2i uses it in every segment.
|
||||
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
|
||||
for (let l = 0; l < p; l++) {
|
||||
address[256 + 2] = l;
|
||||
address[256 + 12] = 0;
|
||||
let startPos = 0;
|
||||
if (r === 0 && s === 0) {
|
||||
startPos = 2;
|
||||
if (dataIndependent) {
|
||||
address[256 + 12]++;
|
||||
block(address, 256, 2 * 256, 0, false);
|
||||
block(address, 0, 2 * 256, 0, false);
|
||||
}
|
||||
}
|
||||
// current block postion
|
||||
let offset = l * laneLen + s * segmentLen + startPos;
|
||||
// previous block position
|
||||
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
|
||||
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
|
||||
perBlock();
|
||||
processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
clean(address);
|
||||
return argon2Output(B, p, laneLen, dkLen);
|
||||
}
|
||||
/**
|
||||
* Argon2d GPU-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2d.
|
||||
* ```ts
|
||||
* argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2d = (password, salt, opts) => argon2(AT.Argond2d, password, salt, opts);
|
||||
/**
|
||||
* Argon2i side-channel-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2i.
|
||||
* ```ts
|
||||
* argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2i = (password, salt, opts) => argon2(AT.Argon2i, password, salt, opts);
|
||||
/**
|
||||
* Argon2id, combining i+d, the most popular version from RFC 9106.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2id.
|
||||
* ```ts
|
||||
* argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2id = (password, salt, opts) => argon2(AT.Argon2id, password, salt, opts);
|
||||
async function argon2Async(type, password, salt, opts) {
|
||||
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } = argon2Init(password, salt, type, opts);
|
||||
// Pre-loop setup
|
||||
// [address, input, zero_block] format so we can pass single U32 to block function
|
||||
const address = new Uint32Array(3 * 256);
|
||||
address[256 + 6] = mP;
|
||||
address[256 + 8] = t;
|
||||
address[256 + 10] = type;
|
||||
let ts = Date.now();
|
||||
for (let r = 0; r < t; r++) {
|
||||
// RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy
|
||||
// `0x10` keeps the older overwrite behavior used by the v16 test vectors.
|
||||
const needXor = r !== 0 && version === 0x13;
|
||||
address[256 + 0] = r;
|
||||
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
|
||||
address[256 + 4] = s;
|
||||
// RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only
|
||||
// in pass 0, slices 0 and 1; Argon2i uses it in every segment.
|
||||
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
|
||||
for (let l = 0; l < p; l++) {
|
||||
address[256 + 2] = l;
|
||||
address[256 + 12] = 0;
|
||||
let startPos = 0;
|
||||
if (r === 0 && s === 0) {
|
||||
startPos = 2;
|
||||
if (dataIndependent) {
|
||||
address[256 + 12]++;
|
||||
block(address, 256, 2 * 256, 0, false);
|
||||
block(address, 0, 2 * 256, 0, false);
|
||||
}
|
||||
}
|
||||
// current block postion
|
||||
let offset = l * laneLen + s * segmentLen + startPos;
|
||||
// previous block position
|
||||
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
|
||||
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
|
||||
perBlock();
|
||||
processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor);
|
||||
// Date.now() is not monotonic. If the clock goes backwards,
|
||||
// still yield control.
|
||||
const diff = Date.now() - ts;
|
||||
if (!(diff >= 0 && diff < asyncTick)) {
|
||||
await nextTick();
|
||||
ts += diff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
clean(address);
|
||||
return argon2Output(B, p, laneLen, dkLen);
|
||||
}
|
||||
/**
|
||||
* Argon2d async GPU-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2d asynchronously.
|
||||
* ```ts
|
||||
* await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2dAsync = (password, salt, opts) => argon2Async(AT.Argond2d, password, salt, opts);
|
||||
/**
|
||||
* Argon2i async side-channel-resistant version.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2i asynchronously.
|
||||
* ```ts
|
||||
* await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2iAsync = (password, salt, opts) => argon2Async(AT.Argon2i, password, salt, opts);
|
||||
/**
|
||||
* Argon2id async, combining i+d, the most popular version from RFC 9106.
|
||||
* @param password - password or input key material
|
||||
* @param salt - unique salt value
|
||||
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
|
||||
* @returns Promise resolving to derived key bytes.
|
||||
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
|
||||
* @example
|
||||
* Derive a key with Argon2id asynchronously.
|
||||
* ```ts
|
||||
* await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
|
||||
* ```
|
||||
*/
|
||||
export const argon2idAsync = (password, salt, opts) => argon2Async(AT.Argon2id, password, salt, opts);
|
||||
//# sourceMappingURL=argon2.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+156
@@ -0,0 +1,156 @@
|
||||
import { type CHash, type Hash, type TArg, type TRet } from './utils.ts';
|
||||
/** Blake1 options. Basically just `salt`. */
|
||||
export type BlakeOpts = {
|
||||
/** Optional salt mixed into initialization. */
|
||||
salt?: Uint8Array;
|
||||
};
|
||||
declare abstract class BLAKE1<T extends BLAKE1<T>> implements Hash<T> {
|
||||
readonly canXOF = false;
|
||||
protected finished: boolean;
|
||||
protected length: number;
|
||||
protected pos: number;
|
||||
protected destroyed: boolean;
|
||||
protected buffer: Uint8Array;
|
||||
protected view: DataView;
|
||||
protected salt: Uint32Array;
|
||||
abstract compress(view: DataView, offset: number, withLength?: boolean): void;
|
||||
protected abstract get(): number[];
|
||||
protected abstract set(...args: number[]): void;
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
private lengthFlag;
|
||||
private counterLen;
|
||||
protected constants: Uint32Array;
|
||||
constructor(blockLen: number, outputLen: number, lengthFlag: number, counterLen: number, saltLen: number, constants: Uint32Array, opts?: BlakeOpts);
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
destroy(): void;
|
||||
_cloneInto(to?: T): T;
|
||||
clone(): T;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
declare class BLAKE1_32B extends BLAKE1<BLAKE1_32B> {
|
||||
private v0;
|
||||
private v1;
|
||||
private v2;
|
||||
private v3;
|
||||
private v4;
|
||||
private v5;
|
||||
private v6;
|
||||
private v7;
|
||||
constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts);
|
||||
protected get(): [number, number, number, number, number, number, number, number];
|
||||
protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void;
|
||||
destroy(): void;
|
||||
compress(view: DataView, offset: number, withLength?: boolean): void;
|
||||
}
|
||||
declare class BLAKE1_64B extends BLAKE1<BLAKE1_64B> {
|
||||
private v0l;
|
||||
private v0h;
|
||||
private v1l;
|
||||
private v1h;
|
||||
private v2l;
|
||||
private v2h;
|
||||
private v3l;
|
||||
private v3h;
|
||||
private v4l;
|
||||
private v4h;
|
||||
private v5l;
|
||||
private v5h;
|
||||
private v6l;
|
||||
private v6h;
|
||||
private v7l;
|
||||
private v7h;
|
||||
constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts);
|
||||
protected get(): [
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number
|
||||
];
|
||||
protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void;
|
||||
destroy(): void;
|
||||
compress(view: DataView, offset: number, withLength?: boolean): void;
|
||||
}
|
||||
/** Internal blake1-224 hash class. */
|
||||
export declare class _BLAKE224 extends BLAKE1_32B {
|
||||
constructor(opts?: BlakeOpts);
|
||||
}
|
||||
/** Internal blake1-256 hash class. */
|
||||
export declare class _BLAKE256 extends BLAKE1_32B {
|
||||
constructor(opts?: BlakeOpts);
|
||||
}
|
||||
/** Internal blake1-384 hash class. */
|
||||
export declare class _BLAKE384 extends BLAKE1_64B {
|
||||
constructor(opts?: BlakeOpts);
|
||||
}
|
||||
/** Internal blake1-512 hash class. */
|
||||
export declare class _BLAKE512 extends BLAKE1_64B {
|
||||
constructor(opts?: BlakeOpts);
|
||||
}
|
||||
/**
|
||||
* Blake1-224 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 16 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-224.
|
||||
* ```ts
|
||||
* blake224(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake224: TRet<CHash<_BLAKE224, BlakeOpts>>;
|
||||
/**
|
||||
* Blake1-256 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 16 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-256.
|
||||
* ```ts
|
||||
* blake256(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake256: TRet<CHash<_BLAKE256, BlakeOpts>>;
|
||||
/**
|
||||
* Blake1-384 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 32 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-384.
|
||||
* ```ts
|
||||
* blake384(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake384: TRet<CHash<_BLAKE384, BlakeOpts>>;
|
||||
/**
|
||||
* Blake1-512 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 32 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-512.
|
||||
* ```ts
|
||||
* blake512(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake512: TRet<CHash<_BLAKE512, BlakeOpts>>;
|
||||
export {};
|
||||
//# sourceMappingURL=blake1.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"blake1.d.ts","sourceRoot":"","sources":["src/blake1.ts"],"names":[],"mappings":"AA4BA,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB,6CAA6C;AAC7C,MAAM,MAAM,SAAS,GAAG;IACtB,+CAA+C;IAC/C,IAAI,CAAC,EAAE,UAAU,CAAC;CACnB,CAAC;AAOF,uBAAe,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IAC3D,QAAQ,CAAC,MAAM,SAAS;IACxB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;IAE5B,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,IAAI,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,IAAI;IAC7E,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAE/C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,SAAS,CAAC,SAAS,EAAE,WAAW,CAAC;gBAG/B,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,WAAW,EACtB,IAAI,GAAE,SAAc;IAyBtB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA8BpC,OAAO,IAAI,IAAI;IAMf,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAcrB,KAAK,IAAI,CAAC;IAGV,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA8BvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAQ3B;AA0CD,cAAM,UAAW,SAAQ,MAAM,CAAC,UAAU,CAAC;IACzC,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;IACnB,OAAO,CAAC,EAAE,CAAS;gBACP,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAWxF,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAC7F,IAAI;IAUP,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,UAAO,GAAG,IAAI;CAoDlE;AA8ED,cAAM,UAAW,SAAQ,MAAM,CAAC,UAAU,CAAC;IACzC,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;IACpB,OAAO,CAAC,GAAG,CAAS;gBACR,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc;IAoBxF,SAAS,CAAC,GAAG,IAAI;QACf,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAC9D,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;KAC/D;IAKD,SAAS,CAAC,GAAG,CACX,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GACjD,IAAI;IAkBP,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,UAAO,GAAG,IAAI;CAmDlE;AAED,sCAAsC;AACtC,qBAAa,SAAU,SAAQ,UAAU;gBAC3B,IAAI,GAAE,SAAc;CAGjC;AACD,sCAAsC;AACtC,qBAAa,SAAU,SAAQ,UAAU;gBAC3B,IAAI,GAAE,SAAc;CAGjC;AACD,sCAAsC;AACtC,qBAAa,SAAU,SAAQ,UAAU;gBAC3B,IAAI,GAAE,SAAc;CAGjC;AACD,sCAAsC;AACtC,qBAAa,SAAU,SAAQ,UAAU;gBAC3B,IAAI,GAAE,SAAc;CAGjC;AACD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC;AACF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC;AACF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC;AACF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC"}
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
/**
|
||||
* Blake1 legacy hash function, one of SHA3 proposals.
|
||||
* Rarely used. Check out blake2 or blake3 instead.
|
||||
* {@link https://www.aumasson.jp/blake/blake.pdf}
|
||||
*
|
||||
* In the best case, there are 0 allocations.
|
||||
*
|
||||
* Differences from blake2:
|
||||
*
|
||||
* - BE instead of LE
|
||||
* - Paddings, similar to MD5, RIPEMD, SHA1, SHA2, but:
|
||||
* - length flag is located before actual length
|
||||
* - padding block is compressed differently (no lengths)
|
||||
* Instead of msg[sigma[k]], we have `msg[sigma[k]] ^ constants[sigma[k-1]]`
|
||||
* (-1 for g1, g2 without -1)
|
||||
* - Salt is XOR-ed into constants instead of state
|
||||
* - Salt is XOR-ed with output in `compress`
|
||||
* - Additional rows (+64 bytes) in SIGMA for new rounds
|
||||
* - Different round count:
|
||||
* - 14 / 10 rounds in blake256 / blake2s
|
||||
* - 16 / 12 rounds in blake512 / blake2b
|
||||
* - blake512: G1b: rotr 24 -> 25, G2b: rotr 63 -> 11
|
||||
* @module
|
||||
*/
|
||||
import { BSIGMA, G1s, G2s } from "./_blake.js";
|
||||
import { SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
|
||||
import * as u64 from "./_u64.js";
|
||||
// prettier-ignore
|
||||
import { abytes, aexists, aoutput, clean, createHasher, createView } from "./utils.js";
|
||||
// Shared unsalted sentinel, sized for the 64-bit path and reused by the 32-bit path via prefix.
|
||||
const EMPTY_SALT = /* @__PURE__ */ new Uint32Array(8);
|
||||
// Base destroy logic only clears salt-derived state; the partial message buffer and length/position
|
||||
// bookkeeping remain until the instance or backing buffer is reused.
|
||||
class BLAKE1 {
|
||||
canXOF = false;
|
||||
finished = false;
|
||||
length = 0;
|
||||
pos = 0;
|
||||
destroyed = false;
|
||||
// For partial updates less than block size
|
||||
buffer;
|
||||
view;
|
||||
salt;
|
||||
blockLen;
|
||||
outputLen;
|
||||
lengthFlag;
|
||||
counterLen;
|
||||
constants;
|
||||
constructor(blockLen, outputLen, lengthFlag, counterLen, saltLen, constants, opts = {}) {
|
||||
const { salt } = opts;
|
||||
this.blockLen = blockLen;
|
||||
this.outputLen = outputLen;
|
||||
this.lengthFlag = lengthFlag;
|
||||
this.counterLen = counterLen;
|
||||
this.buffer = new Uint8Array(blockLen);
|
||||
this.view = createView(this.buffer);
|
||||
if (salt !== undefined) {
|
||||
let slt = salt;
|
||||
abytes(slt, 4 * saltLen, 'salt');
|
||||
// if (slt.length !== 4 * saltLen) throw new Error('wrong salt length');
|
||||
const salt32 = (this.salt = new Uint32Array(saltLen));
|
||||
const sv = createView(slt);
|
||||
this.constants = constants.slice();
|
||||
for (let i = 0, offset = 0; i < salt32.length; i++, offset += 4) {
|
||||
salt32[i] = sv.getUint32(offset, false);
|
||||
this.constants[i] ^= salt32[i];
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.salt = EMPTY_SALT;
|
||||
this.constants = constants;
|
||||
}
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
// From _md, but update length before each compress
|
||||
const { view, buffer, blockLen } = this;
|
||||
const len = data.length;
|
||||
let dataView;
|
||||
for (let pos = 0; pos < len;) {
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
// Fast path only when there is no buffered partial block: `take === blockLen` implies
|
||||
// `this.pos === 0`, so we can process full blocks directly from the input view.
|
||||
if (take === blockLen) {
|
||||
if (!dataView)
|
||||
dataView = createView(data);
|
||||
for (; blockLen <= len - pos; pos += blockLen) {
|
||||
this.length += blockLen;
|
||||
this.compress(dataView, pos);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
pos += take;
|
||||
if (this.pos === blockLen) {
|
||||
this.length += blockLen;
|
||||
this.compress(view, 0, true);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
if (this.salt !== EMPTY_SALT) {
|
||||
clean(this.salt, this.constants);
|
||||
}
|
||||
}
|
||||
_cloneInto(to) {
|
||||
to ||= new this.constructor();
|
||||
to.set(...this.get());
|
||||
const { buffer, length, finished, destroyed, constants, salt, pos } = this;
|
||||
to.buffer.set(buffer);
|
||||
// Clone salt-derived arrays by value so destroying the clone cannot wipe the source instance.
|
||||
to.constants = constants.slice();
|
||||
to.destroyed = destroyed;
|
||||
to.finished = finished;
|
||||
to.length = length;
|
||||
to.pos = pos;
|
||||
to.salt = salt.slice();
|
||||
return to;
|
||||
}
|
||||
clone() {
|
||||
return this._cloneInto();
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
// Padding
|
||||
const { buffer, blockLen, counterLen, lengthFlag, view } = this;
|
||||
clean(buffer.subarray(this.pos)); // clean buf
|
||||
const counter = BigInt((this.length + this.pos) * 8);
|
||||
const counterPos = blockLen - counterLen - 1;
|
||||
buffer[this.pos] |= 0b1000_0000; // End block flag
|
||||
this.length += this.pos; // add unwritten length
|
||||
// Not enough in buffer for length: write what we have.
|
||||
if (this.pos > counterPos) {
|
||||
this.compress(view, 0);
|
||||
clean(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
// Difference with md: here we have lengthFlag!
|
||||
buffer[counterPos] |= lengthFlag; // Length flag
|
||||
// We always set 8 byte length flag. Because length will overflow significantly sooner.
|
||||
view.setBigUint64(blockLen - 8, counter, false);
|
||||
// Blake1 omits the counter from the extra all-padding block; only the block that still carries
|
||||
// message bytes mixes in the final bit length.
|
||||
this.compress(view, 0, this.pos !== 0);
|
||||
// Write output
|
||||
clean(buffer);
|
||||
const v = createView(out);
|
||||
const state = this.get();
|
||||
for (let i = 0; i < this.outputLen / 4; ++i)
|
||||
v.setUint32(i * 4, state[i]);
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Return a copy so callers do not alias the instance scratch buffer used during finalization.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
// Blake1-512 / Blake1-384 constant table `C512`.
|
||||
// Stored as sixteen 64-bit constants split into `[high32, low32]` halves so
|
||||
// the Blake1-64 path can reuse one layout for both `v8..v15` initialization
|
||||
// and the permuted constant lookups.
|
||||
const B64C = /* @__PURE__ */ Uint32Array.from([
|
||||
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
|
||||
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
|
||||
0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
|
||||
0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69,
|
||||
]);
|
||||
// Blake1-256 / Blake1-224 constant table `C256`, derived as the first half of `C512`.
|
||||
const B32C = /* @__PURE__ */ B64C.slice(0, 16);
|
||||
// Blake1-256 IV cloned from SHA-256.
|
||||
const B256_IV = /* @__PURE__ */ SHA256_IV.slice();
|
||||
// Blake1-224 IV cloned from SHA-224.
|
||||
const B224_IV = /* @__PURE__ */ SHA224_IV.slice();
|
||||
// Blake1-384 IV cloned from the SHA-384 high-then-low 32-bit halves.
|
||||
const B384_IV = /* @__PURE__ */ SHA384_IV.slice();
|
||||
// Blake1-512 IV cloned from the SHA-512 high-then-low 32-bit halves.
|
||||
const B512_IV = /* @__PURE__ */ SHA512_IV.slice();
|
||||
// Precompute the odd/even companion constants used by all 14 Blake1-32 rounds.
|
||||
// Each pair stores `u[sigma[2i + 1]]` then `u[sigma[2i]]`, matching the `G1s` / `G2s` xor order.
|
||||
function generateTBL256() {
|
||||
const TBL = [];
|
||||
for (let i = 0, j = 0; i < 14; i++, j += 16) {
|
||||
for (let offset = 1; offset < 16; offset += 2) {
|
||||
TBL.push(B32C[BSIGMA[j + offset]]);
|
||||
TBL.push(B32C[BSIGMA[j + offset - 1]]);
|
||||
}
|
||||
}
|
||||
return new Uint32Array(TBL);
|
||||
}
|
||||
// Full 14-round companion-constant table for Blake1-32.
|
||||
const TBL256 = /* @__PURE__ */ generateTBL256();
|
||||
// Shared synchronous message-word scratch for the 32-bit Blake1 path.
|
||||
const BLAKE256_W = /* @__PURE__ */ new Uint32Array(16);
|
||||
class BLAKE1_32B extends BLAKE1 {
|
||||
v0;
|
||||
v1;
|
||||
v2;
|
||||
v3;
|
||||
v4;
|
||||
v5;
|
||||
v6;
|
||||
v7;
|
||||
constructor(outputLen, IV, lengthFlag, opts = {}) {
|
||||
super(64, outputLen, lengthFlag, 8, 4, B32C, opts);
|
||||
this.v0 = IV[0] | 0;
|
||||
this.v1 = IV[1] | 0;
|
||||
this.v2 = IV[2] | 0;
|
||||
this.v3 = IV[3] | 0;
|
||||
this.v4 = IV[4] | 0;
|
||||
this.v5 = IV[5] | 0;
|
||||
this.v6 = IV[6] | 0;
|
||||
this.v7 = IV[7] | 0;
|
||||
}
|
||||
get() {
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
|
||||
return [v0, v1, v2, v3, v4, v5, v6, v7];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0, v1, v2, v3, v4, v5, v6, v7) {
|
||||
this.v0 = v0 | 0;
|
||||
this.v1 = v1 | 0;
|
||||
this.v2 = v2 | 0;
|
||||
this.v3 = v3 | 0;
|
||||
this.v4 = v4 | 0;
|
||||
this.v5 = v5 | 0;
|
||||
this.v6 = v6 | 0;
|
||||
this.v7 = v7 | 0;
|
||||
}
|
||||
destroy() {
|
||||
super.destroy();
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
compress(view, offset, withLength = true) {
|
||||
for (let i = 0; i < 16; i++, offset += 4)
|
||||
BLAKE256_W[i] = view.getUint32(offset, false);
|
||||
// Cannot reuse blake2s compress: Blake1 mixes each message word with the companion constants
|
||||
// precomputed in `TBL256`, rather than using the raw schedule words directly.
|
||||
let v00 = this.v0 | 0;
|
||||
let v01 = this.v1 | 0;
|
||||
let v02 = this.v2 | 0;
|
||||
let v03 = this.v3 | 0;
|
||||
let v04 = this.v4 | 0;
|
||||
let v05 = this.v5 | 0;
|
||||
let v06 = this.v6 | 0;
|
||||
let v07 = this.v7 | 0;
|
||||
let v08 = this.constants[0] | 0;
|
||||
let v09 = this.constants[1] | 0;
|
||||
let v10 = this.constants[2] | 0;
|
||||
let v11 = this.constants[3] | 0;
|
||||
// Blake1-32 injects the 64-bit bit counter as `[t0, t0, t1, t1]` across `v12..v15`; the
|
||||
// final all-padding block passes `withLength = false`, leaving these lanes as raw constants.
|
||||
const { h, l } = u64.fromBig(BigInt(withLength ? this.length * 8 : 0));
|
||||
let v12 = (this.constants[4] ^ l) >>> 0;
|
||||
let v13 = (this.constants[5] ^ l) >>> 0;
|
||||
let v14 = (this.constants[6] ^ h) >>> 0;
|
||||
let v15 = (this.constants[7] ^ h) >>> 0;
|
||||
// prettier-ignore
|
||||
for (let i = 0, k = 0, j = 0; i < 14; i++) {
|
||||
({ a: v00, b: v04, c: v08, d: v12 } = G1s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v00, b: v04, c: v08, d: v12 } = G2s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v01, b: v05, c: v09, d: v13 } = G1s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v01, b: v05, c: v09, d: v13 } = G2s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v02, b: v06, c: v10, d: v14 } = G1s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v02, b: v06, c: v10, d: v14 } = G2s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v03, b: v07, c: v11, d: v15 } = G1s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v03, b: v07, c: v11, d: v15 } = G2s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v00, b: v05, c: v10, d: v15 } = G1s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v00, b: v05, c: v10, d: v15 } = G2s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v01, b: v06, c: v11, d: v12 } = G1s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v01, b: v06, c: v11, d: v12 } = G2s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v02, b: v07, c: v08, d: v13 } = G1s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v02, b: v07, c: v08, d: v13 } = G2s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v03, b: v04, c: v09, d: v14 } = G1s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
({ a: v03, b: v04, c: v09, d: v14 } = G2s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++]));
|
||||
}
|
||||
this.v0 = (this.v0 ^ v00 ^ v08 ^ this.salt[0]) >>> 0;
|
||||
this.v1 = (this.v1 ^ v01 ^ v09 ^ this.salt[1]) >>> 0;
|
||||
this.v2 = (this.v2 ^ v02 ^ v10 ^ this.salt[2]) >>> 0;
|
||||
this.v3 = (this.v3 ^ v03 ^ v11 ^ this.salt[3]) >>> 0;
|
||||
this.v4 = (this.v4 ^ v04 ^ v12 ^ this.salt[0]) >>> 0;
|
||||
this.v5 = (this.v5 ^ v05 ^ v13 ^ this.salt[1]) >>> 0;
|
||||
this.v6 = (this.v6 ^ v06 ^ v14 ^ this.salt[2]) >>> 0;
|
||||
this.v7 = (this.v7 ^ v07 ^ v15 ^ this.salt[3]) >>> 0;
|
||||
clean(BLAKE256_W);
|
||||
}
|
||||
}
|
||||
// Shared Blake1-64 work vector storing 16 working words as adjacent high/low 32-bit halves.
|
||||
const BBUF = /* @__PURE__ */ new Uint32Array(32);
|
||||
// Shared synchronous message-word scratch for the 64-bit Blake1 path.
|
||||
const BLAKE512_W = /* @__PURE__ */ new Uint32Array(32);
|
||||
// Precompute the high/low companion constants used by all 16 Blake1-64 rounds.
|
||||
// Each quartet stores `u[sigma[2i + 1]]` high/low halves, then `u[sigma[2i]]` high/low halves.
|
||||
function generateTBL512() {
|
||||
const TBL = [];
|
||||
for (let r = 0, k = 0; r < 16; r++, k += 16) {
|
||||
for (let offset = 1; offset < 16; offset += 2) {
|
||||
TBL.push(B64C[BSIGMA[k + offset] * 2 + 0]);
|
||||
TBL.push(B64C[BSIGMA[k + offset] * 2 + 1]);
|
||||
TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 0]);
|
||||
TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 1]);
|
||||
}
|
||||
}
|
||||
return new Uint32Array(TBL);
|
||||
}
|
||||
// Full 16-round companion-constant table as high/low halves.
|
||||
const TBL512 = /* @__PURE__ */ generateTBL512();
|
||||
// Blake1-64 first half-round with rotations `32` and `25`; `k` is the half-call schedule index.
|
||||
function G1b(a, b, c, d, msg, k) {
|
||||
const Xpos = 2 * BSIGMA[k];
|
||||
const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore
|
||||
let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh) >>> 0;
|
||||
Al = (ll | 0) >>> 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 32)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 25)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 25), Bl: u64.rotrSL(Bh, Bl, 25) });
|
||||
((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah));
|
||||
((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh));
|
||||
((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch));
|
||||
((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh));
|
||||
}
|
||||
// Blake1-64 second half-round with rotations `16` and `11`; `k` is the half-call schedule index.
|
||||
function G2b(a, b, c, d, msg, k) {
|
||||
const Xpos = 2 * BSIGMA[k];
|
||||
const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore
|
||||
let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
||||
Al = ll | 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 16)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 11)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 11), Bl: u64.rotrSL(Bh, Bl, 11) });
|
||||
((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah));
|
||||
((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh));
|
||||
((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch));
|
||||
((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh));
|
||||
}
|
||||
// Legacy field names keep the local `l/h` spelling, but array/state order stays `[high, low]` to
|
||||
// match the IV tables and `BBUF` layout.
|
||||
class BLAKE1_64B extends BLAKE1 {
|
||||
v0l;
|
||||
v0h;
|
||||
v1l;
|
||||
v1h;
|
||||
v2l;
|
||||
v2h;
|
||||
v3l;
|
||||
v3h;
|
||||
v4l;
|
||||
v4h;
|
||||
v5l;
|
||||
v5h;
|
||||
v6l;
|
||||
v6h;
|
||||
v7l;
|
||||
v7h;
|
||||
constructor(outputLen, IV, lengthFlag, opts = {}) {
|
||||
super(128, outputLen, lengthFlag, 16, 8, B64C, opts);
|
||||
this.v0l = IV[0] | 0;
|
||||
this.v0h = IV[1] | 0;
|
||||
this.v1l = IV[2] | 0;
|
||||
this.v1h = IV[3] | 0;
|
||||
this.v2l = IV[4] | 0;
|
||||
this.v2h = IV[5] | 0;
|
||||
this.v3l = IV[6] | 0;
|
||||
this.v3h = IV[7] | 0;
|
||||
this.v4l = IV[8] | 0;
|
||||
this.v4h = IV[9] | 0;
|
||||
this.v5l = IV[10] | 0;
|
||||
this.v5h = IV[11] | 0;
|
||||
this.v6l = IV[12] | 0;
|
||||
this.v6h = IV[13] | 0;
|
||||
this.v7l = IV[14] | 0;
|
||||
this.v7h = IV[15] | 0;
|
||||
}
|
||||
// prettier-ignore
|
||||
get() {
|
||||
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
|
||||
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
|
||||
this.v0l = v0l | 0;
|
||||
this.v0h = v0h | 0;
|
||||
this.v1l = v1l | 0;
|
||||
this.v1h = v1h | 0;
|
||||
this.v2l = v2l | 0;
|
||||
this.v2h = v2h | 0;
|
||||
this.v3l = v3l | 0;
|
||||
this.v3h = v3h | 0;
|
||||
this.v4l = v4l | 0;
|
||||
this.v4h = v4h | 0;
|
||||
this.v5l = v5l | 0;
|
||||
this.v5h = v5h | 0;
|
||||
this.v6l = v6l | 0;
|
||||
this.v6h = v6h | 0;
|
||||
this.v7l = v7l | 0;
|
||||
this.v7h = v7h | 0;
|
||||
}
|
||||
destroy() {
|
||||
super.destroy();
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
compress(view, offset, withLength = true) {
|
||||
for (let i = 0; i < 32; i++, offset += 4)
|
||||
BLAKE512_W[i] = view.getUint32(offset, false);
|
||||
this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
|
||||
BBUF.set(this.constants.subarray(0, 16), 16);
|
||||
if (withLength) {
|
||||
// Blake1-64 injects the 64-bit bit counter into `v12` and `v13`; the final all-padding
|
||||
// block passes `withLength = false`, leaving the trailing constant lanes untouched.
|
||||
const { h, l } = u64.fromBig(BigInt(this.length * 8));
|
||||
BBUF[24] = (BBUF[24] ^ h) >>> 0;
|
||||
BBUF[25] = (BBUF[25] ^ l) >>> 0;
|
||||
BBUF[26] = (BBUF[26] ^ h) >>> 0;
|
||||
BBUF[27] = (BBUF[27] ^ l) >>> 0;
|
||||
}
|
||||
for (let i = 0, k = 0; i < 16; i++) {
|
||||
G1b(0, 4, 8, 12, BLAKE512_W, k++);
|
||||
G2b(0, 4, 8, 12, BLAKE512_W, k++);
|
||||
G1b(1, 5, 9, 13, BLAKE512_W, k++);
|
||||
G2b(1, 5, 9, 13, BLAKE512_W, k++);
|
||||
G1b(2, 6, 10, 14, BLAKE512_W, k++);
|
||||
G2b(2, 6, 10, 14, BLAKE512_W, k++);
|
||||
G1b(3, 7, 11, 15, BLAKE512_W, k++);
|
||||
G2b(3, 7, 11, 15, BLAKE512_W, k++);
|
||||
G1b(0, 5, 10, 15, BLAKE512_W, k++);
|
||||
G2b(0, 5, 10, 15, BLAKE512_W, k++);
|
||||
G1b(1, 6, 11, 12, BLAKE512_W, k++);
|
||||
G2b(1, 6, 11, 12, BLAKE512_W, k++);
|
||||
G1b(2, 7, 8, 13, BLAKE512_W, k++);
|
||||
G2b(2, 7, 8, 13, BLAKE512_W, k++);
|
||||
G1b(3, 4, 9, 14, BLAKE512_W, k++);
|
||||
G2b(3, 4, 9, 14, BLAKE512_W, k++);
|
||||
}
|
||||
this.v0l ^= BBUF[0] ^ BBUF[16] ^ this.salt[0];
|
||||
this.v0h ^= BBUF[1] ^ BBUF[17] ^ this.salt[1];
|
||||
this.v1l ^= BBUF[2] ^ BBUF[18] ^ this.salt[2];
|
||||
this.v1h ^= BBUF[3] ^ BBUF[19] ^ this.salt[3];
|
||||
this.v2l ^= BBUF[4] ^ BBUF[20] ^ this.salt[4];
|
||||
this.v2h ^= BBUF[5] ^ BBUF[21] ^ this.salt[5];
|
||||
this.v3l ^= BBUF[6] ^ BBUF[22] ^ this.salt[6];
|
||||
this.v3h ^= BBUF[7] ^ BBUF[23] ^ this.salt[7];
|
||||
this.v4l ^= BBUF[8] ^ BBUF[24] ^ this.salt[0];
|
||||
this.v4h ^= BBUF[9] ^ BBUF[25] ^ this.salt[1];
|
||||
this.v5l ^= BBUF[10] ^ BBUF[26] ^ this.salt[2];
|
||||
this.v5h ^= BBUF[11] ^ BBUF[27] ^ this.salt[3];
|
||||
this.v6l ^= BBUF[12] ^ BBUF[28] ^ this.salt[4];
|
||||
this.v6h ^= BBUF[13] ^ BBUF[29] ^ this.salt[5];
|
||||
this.v7l ^= BBUF[14] ^ BBUF[30] ^ this.salt[6];
|
||||
this.v7h ^= BBUF[15] ^ BBUF[31] ^ this.salt[7];
|
||||
clean(BBUF, BLAKE512_W);
|
||||
}
|
||||
}
|
||||
/** Internal blake1-224 hash class. */
|
||||
export class _BLAKE224 extends BLAKE1_32B {
|
||||
constructor(opts = {}) {
|
||||
super(28, B224_IV, 0b0000_0000, opts);
|
||||
}
|
||||
}
|
||||
/** Internal blake1-256 hash class. */
|
||||
export class _BLAKE256 extends BLAKE1_32B {
|
||||
constructor(opts = {}) {
|
||||
super(32, B256_IV, 0b0000_0001, opts);
|
||||
}
|
||||
}
|
||||
/** Internal blake1-384 hash class. */
|
||||
export class _BLAKE384 extends BLAKE1_64B {
|
||||
constructor(opts = {}) {
|
||||
super(48, B384_IV, 0b0000_0000, opts);
|
||||
}
|
||||
}
|
||||
/** Internal blake1-512 hash class. */
|
||||
export class _BLAKE512 extends BLAKE1_64B {
|
||||
constructor(opts = {}) {
|
||||
super(64, B512_IV, 0b0000_0001, opts);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Blake1-224 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 16 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-224.
|
||||
* ```ts
|
||||
* blake224(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake224 = /* @__PURE__ */ createHasher((opts) => new _BLAKE224(opts));
|
||||
/**
|
||||
* Blake1-256 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 16 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-256.
|
||||
* ```ts
|
||||
* blake256(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake256 = /* @__PURE__ */ createHasher((opts) => new _BLAKE256(opts));
|
||||
/**
|
||||
* Blake1-384 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 32 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-384.
|
||||
* ```ts
|
||||
* blake384(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake384 = /* @__PURE__ */ createHasher((opts) => new _BLAKE384(opts));
|
||||
/**
|
||||
* Blake1-512 hash function.
|
||||
* @param msg - message bytes to hash
|
||||
* @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set,
|
||||
* `opts.salt` must be exactly 32 bytes.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake1-512.
|
||||
* ```ts
|
||||
* blake512(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake512 = /* @__PURE__ */ createHasher((opts) => new _BLAKE512(opts));
|
||||
//# sourceMappingURL=blake1.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+184
@@ -0,0 +1,184 @@
|
||||
import { type CHash, type Hash, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Blake hash options.
|
||||
* `dkLen` is output length. `key` is used in MAC mode. `salt` is used in
|
||||
* KDF mode.
|
||||
*/
|
||||
export type Blake2Opts = {
|
||||
/** Desired digest length in bytes. RFC 7693 uses 1..64 for blake2b and 1..32 for blake2s. */
|
||||
dkLen?: number;
|
||||
/** Optional MAC key. */
|
||||
key?: Uint8Array;
|
||||
/** Optional salt mixed into initialization. */
|
||||
salt?: Uint8Array;
|
||||
/** Optional personalization bytes. */
|
||||
personalization?: Uint8Array;
|
||||
};
|
||||
/** Internal base class for BLAKE2. */
|
||||
export declare abstract class _BLAKE2<T extends _BLAKE2<T>> implements Hash<T> {
|
||||
protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void;
|
||||
protected abstract get(): number[];
|
||||
protected abstract set(...args: number[]): void;
|
||||
abstract destroy(): void;
|
||||
protected buffer: Uint8Array;
|
||||
protected buffer32: Uint32Array;
|
||||
protected finished: boolean;
|
||||
protected destroyed: boolean;
|
||||
protected length: number;
|
||||
protected pos: number;
|
||||
readonly blockLen: number;
|
||||
readonly outputLen: number;
|
||||
readonly canXOF: boolean;
|
||||
constructor(blockLen: number, outputLen: number);
|
||||
update(data: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
_cloneInto(to?: T): T;
|
||||
clone(): T;
|
||||
}
|
||||
/** Internal blake2b hash class with state stored as LE u32 low/high halves. */
|
||||
export declare class _BLAKE2b extends _BLAKE2<_BLAKE2b> {
|
||||
private v0l;
|
||||
private v0h;
|
||||
private v1l;
|
||||
private v1h;
|
||||
private v2l;
|
||||
private v2h;
|
||||
private v3l;
|
||||
private v3h;
|
||||
private v4l;
|
||||
private v4h;
|
||||
private v5l;
|
||||
private v5h;
|
||||
private v6l;
|
||||
private v6h;
|
||||
private v7l;
|
||||
private v7h;
|
||||
constructor(opts?: Blake2Opts);
|
||||
protected get(): [
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number,
|
||||
number
|
||||
];
|
||||
protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void;
|
||||
protected compress(msg: Uint32Array, offset: number, isLast: boolean): void;
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
||||
* `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present,
|
||||
* must be 16 bytes each. See {@link Blake2Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake2b.
|
||||
* ```ts
|
||||
* blake2b(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake2b: TRet<CHash<_BLAKE2b, Blake2Opts>>;
|
||||
/** Internal type, 16 numbers. */
|
||||
export type _Num16 = {
|
||||
v0: number;
|
||||
v1: number;
|
||||
v2: number;
|
||||
v3: number;
|
||||
v4: number;
|
||||
v5: number;
|
||||
v6: number;
|
||||
v7: number;
|
||||
v8: number;
|
||||
v9: number;
|
||||
v10: number;
|
||||
v11: number;
|
||||
v12: number;
|
||||
v13: number;
|
||||
v14: number;
|
||||
v15: number;
|
||||
};
|
||||
/**
|
||||
* BLAKE2-compress core method.
|
||||
* Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15`
|
||||
* and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves.
|
||||
* @param s - flattened sigma schedule bytes
|
||||
* @param offset - starting word offset inside `msg`, not a byte offset
|
||||
* @param msg - message words
|
||||
* @param rounds - round count to execute
|
||||
* @param v0 - state word 0
|
||||
* @param v1 - state word 1
|
||||
* @param v2 - state word 2
|
||||
* @param v3 - state word 3
|
||||
* @param v4 - state word 4
|
||||
* @param v5 - state word 5
|
||||
* @param v6 - state word 6
|
||||
* @param v7 - state word 7
|
||||
* @param v8 - state word 8
|
||||
* @param v9 - state word 9
|
||||
* @param v10 - state word 10
|
||||
* @param v11 - state word 11
|
||||
* @param v12 - state word 12
|
||||
* @param v13 - state word 13
|
||||
* @param v14 - state word 14
|
||||
* @param v15 - state word 15
|
||||
* @returns Updated compression state words.
|
||||
* @example
|
||||
* Run the BLAKE2 compression core on zeroed state and message words.
|
||||
* ```ts
|
||||
* import { compress } from '@noble/hashes/blake2.js';
|
||||
* const state = compress(
|
||||
* new Uint8Array(16),
|
||||
* 0,
|
||||
* new Uint32Array(16),
|
||||
* 1,
|
||||
* 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
* 0, 0, 0, 0, 0, 0, 0, 0
|
||||
* );
|
||||
* state.v0;
|
||||
* ```
|
||||
*/
|
||||
export declare function compress(s: TArg<Uint8Array>, offset: number, msg: TArg<Uint32Array>, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): _Num16;
|
||||
/** Internal blake2s hash class. */
|
||||
export declare class _BLAKE2s extends _BLAKE2<_BLAKE2s> {
|
||||
private v0;
|
||||
private v1;
|
||||
private v2;
|
||||
private v3;
|
||||
private v4;
|
||||
private v5;
|
||||
private v6;
|
||||
private v7;
|
||||
constructor(opts?: Blake2Opts);
|
||||
protected get(): [number, number, number, number, number, number, number, number];
|
||||
protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void;
|
||||
protected compress(msg: Uint32Array, offset: number, isLast: boolean): void;
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
||||
* `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present,
|
||||
* must be 8 bytes each. See {@link Blake2Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake2s.
|
||||
* ```ts
|
||||
* blake2s(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export declare const blake2s: TRet<CHash<_BLAKE2s, Blake2Opts>>;
|
||||
//# sourceMappingURL=blake2.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"blake2.d.ts","sourceRoot":"","sources":["src/blake2.ts"],"names":[],"mappings":"AASA,OAAO,EAKL,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,6FAA6F;IAC7F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wBAAwB;IACxB,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,+CAA+C;IAC/C,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,sCAAsC;IACtC,eAAe,CAAC,EAAE,UAAU,CAAC;CAC9B,CAAC;AAiFF,sCAAsC;AACtC,8BAAsB,OAAO,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IACpE,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IACpF,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI;IAC/C,QAAQ,CAAC,OAAO,IAAI,IAAI;IACxB,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,QAAQ,EAAE,WAAW,CAAC;IAChC,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;IAC5B,SAAS,CAAC,MAAM,EAAE,MAAM,CAAK;IAC7B,SAAS,CAAC,GAAG,EAAE,MAAM,CAAK;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAS;gBAErB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;IAQ/C,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAuCpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAyBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;IAQ1B,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAcrB,KAAK,IAAI,CAAC;CAGX;AAED,+EAA+E;AAC/E,qBAAa,QAAS,SAAQ,OAAO,CAAC,QAAQ,CAAC;IAE7C,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAiB;IAC5B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,GAAG,CAAkB;gBAEjB,IAAI,GAAE,UAAe;IAqCjC,SAAS,CAAC,GAAG,IAAI;QACf,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAC9D,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;QAAE,MAAM;KAC/D;IAKD,SAAS,CAAC,GAAG,CACX,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAClD,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GACjD,IAAI;IAkBP,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAoD3E,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAErD,CAAC;AAMF,iCAAiC;AAEjC,MAAM,MAAM,MAAM,GAAG;IACnB,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAC/C,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAC/C,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IACjD,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;CACpD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,MAAM,EAClG,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAC9F,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GACnG,MAAM,CAsBR;AAKD,mCAAmC;AACnC,qBAAa,QAAS,SAAQ,OAAO,CAAC,QAAQ,CAAC;IAE7C,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;gBAEf,IAAI,GAAE,UAAe;IAgCjC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAC7F,IAAI;IAUP,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAoB3E,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAErD,CAAC"}
|
||||
+501
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.
|
||||
* b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.
|
||||
* @module
|
||||
*/
|
||||
import { BSIGMA, G1s, G2s } from "./_blake.js";
|
||||
import { SHA256_IV } from "./_md.js";
|
||||
import * as u64 from "./_u64.js";
|
||||
// prettier-ignore
|
||||
import { abytes, aexists, anumber, aoutput, clean, createHasher, swap32IfBE, swap8IfBE, u32 } from "./utils.js";
|
||||
// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves
|
||||
// for the BLAKE2b u64 helpers below.
|
||||
const B2B_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
|
||||
0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
|
||||
]);
|
||||
// Shared synchronous BLAKE2b work vector as LE u32 low/high halves.
|
||||
const BBUF = /* @__PURE__ */ new Uint32Array(32);
|
||||
// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs.
|
||||
function G1b(a, b, c, d, msg, x) {
|
||||
// NOTE: V is LE here
|
||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
||||
Al = ll | 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 32)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 24)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });
|
||||
((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah));
|
||||
((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh));
|
||||
((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch));
|
||||
((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh));
|
||||
}
|
||||
// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset.
|
||||
function G2b(a, b, c, d, msg, x) {
|
||||
// NOTE: V is LE here
|
||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
||||
Al = ll | 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 16)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 63)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });
|
||||
((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah));
|
||||
((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh));
|
||||
((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch));
|
||||
((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh));
|
||||
}
|
||||
function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
|
||||
anumber(keyLen);
|
||||
// RFC 7693 §2.1 requires digest length nn in 1..keyLen.
|
||||
if (outputLen <= 0 || outputLen > keyLen)
|
||||
throw new Error('outputLen bigger than keyLen');
|
||||
const { key, salt, personalization } = opts;
|
||||
// This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty.
|
||||
if (key !== undefined && (key.length < 1 || key.length > keyLen))
|
||||
throw new Error('"key" expected to be undefined or of length=1..' + keyLen);
|
||||
if (salt !== undefined)
|
||||
abytes(salt, saltLen, 'salt');
|
||||
if (personalization !== undefined)
|
||||
abytes(personalization, persLen, 'personalization');
|
||||
}
|
||||
/** Internal base class for BLAKE2. */
|
||||
export class _BLAKE2 {
|
||||
buffer;
|
||||
buffer32;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
length = 0;
|
||||
pos = 0;
|
||||
blockLen;
|
||||
outputLen;
|
||||
canXOF = false;
|
||||
constructor(blockLen, outputLen) {
|
||||
anumber(blockLen);
|
||||
anumber(outputLen);
|
||||
this.blockLen = blockLen;
|
||||
this.outputLen = outputLen;
|
||||
this.buffer = new Uint8Array(blockLen);
|
||||
this.buffer32 = u32(this.buffer);
|
||||
}
|
||||
update(data) {
|
||||
aexists(this);
|
||||
abytes(data);
|
||||
// Main difference with other hashes: there is flag for last block,
|
||||
// so we cannot process current block before we know that there
|
||||
// is the next one. This significantly complicates logic and reduces ability
|
||||
// to do zero-copy processing
|
||||
const { blockLen, buffer, buffer32 } = this;
|
||||
const len = data.length;
|
||||
const offset = data.byteOffset;
|
||||
const buf = data.buffer;
|
||||
for (let pos = 0; pos < len;) {
|
||||
// If buffer is full and we still have input (don't process last block, same as blake2s)
|
||||
if (this.pos === blockLen) {
|
||||
swap32IfBE(buffer32);
|
||||
this.compress(buffer32, 0, false);
|
||||
swap32IfBE(buffer32);
|
||||
this.pos = 0;
|
||||
}
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
const dataOffset = offset + pos;
|
||||
// Zero-copy only for full, 4-byte-aligned, non-final blocks.
|
||||
if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
|
||||
const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
|
||||
swap32IfBE(data32);
|
||||
for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
|
||||
this.length += blockLen;
|
||||
this.compress(data32, pos32, false);
|
||||
}
|
||||
swap32IfBE(data32);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
this.length += take;
|
||||
pos += take;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
const { pos, buffer32 } = this;
|
||||
this.finished = true;
|
||||
// Padding
|
||||
clean(this.buffer.subarray(pos));
|
||||
swap32IfBE(buffer32);
|
||||
this.compress(buffer32, 0, true);
|
||||
swap32IfBE(buffer32);
|
||||
// Reject unaligned views explicitly instead of hiding them behind a full scratch copy.
|
||||
if (out.byteOffset & 3)
|
||||
throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
|
||||
const state = this.get();
|
||||
const out32 = u32(out);
|
||||
const full = Math.floor(this.outputLen / 4);
|
||||
for (let i = 0; i < full; i++)
|
||||
out32[i] = swap8IfBE(state[i]);
|
||||
const tail = this.outputLen % 4;
|
||||
if (!tail)
|
||||
return;
|
||||
const off = full * 4;
|
||||
const word = state[full];
|
||||
for (let i = 0; i < tail; i++)
|
||||
out[off + i] = word >>> (8 * i);
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
// Return a copy so callers do not alias the instance scratch buffer used during finalization.
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
_cloneInto(to) {
|
||||
const { buffer, length, finished, destroyed, outputLen, pos } = this;
|
||||
// Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state.
|
||||
to ||= new this.constructor({ dkLen: outputLen });
|
||||
to.set(...this.get());
|
||||
to.buffer.set(buffer);
|
||||
to.destroyed = destroyed;
|
||||
to.finished = finished;
|
||||
to.length = length;
|
||||
to.pos = pos;
|
||||
// @ts-ignore
|
||||
to.outputLen = outputLen;
|
||||
return to;
|
||||
}
|
||||
clone() {
|
||||
return this._cloneInto();
|
||||
}
|
||||
}
|
||||
/** Internal blake2b hash class with state stored as LE u32 low/high halves. */
|
||||
export class _BLAKE2b extends _BLAKE2 {
|
||||
// Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves.
|
||||
v0l = B2B_IV[0] | 0;
|
||||
v0h = B2B_IV[1] | 0;
|
||||
v1l = B2B_IV[2] | 0;
|
||||
v1h = B2B_IV[3] | 0;
|
||||
v2l = B2B_IV[4] | 0;
|
||||
v2h = B2B_IV[5] | 0;
|
||||
v3l = B2B_IV[6] | 0;
|
||||
v3h = B2B_IV[7] | 0;
|
||||
v4l = B2B_IV[8] | 0;
|
||||
v4h = B2B_IV[9] | 0;
|
||||
v5l = B2B_IV[10] | 0;
|
||||
v5h = B2B_IV[11] | 0;
|
||||
v6l = B2B_IV[12] | 0;
|
||||
v6h = B2B_IV[13] | 0;
|
||||
v7l = B2B_IV[14] | 0;
|
||||
v7h = B2B_IV[15] | 0;
|
||||
constructor(opts = {}) {
|
||||
const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
|
||||
super(128, olen);
|
||||
checkBlake2Opts(olen, opts, 64, 16, 16);
|
||||
let { key, personalization, salt } = opts;
|
||||
let keyLength = 0;
|
||||
if (key !== undefined) {
|
||||
abytes(key, undefined, 'key');
|
||||
keyLength = key.length;
|
||||
}
|
||||
// RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`;
|
||||
// the high 32 bits stay at `IV[0]`.
|
||||
this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
||||
if (salt !== undefined) {
|
||||
abytes(salt, undefined, 'salt');
|
||||
const slt = u32(salt);
|
||||
this.v4l ^= swap8IfBE(slt[0]);
|
||||
this.v4h ^= swap8IfBE(slt[1]);
|
||||
this.v5l ^= swap8IfBE(slt[2]);
|
||||
this.v5h ^= swap8IfBE(slt[3]);
|
||||
}
|
||||
if (personalization !== undefined) {
|
||||
abytes(personalization, undefined, 'personalization');
|
||||
const pers = u32(personalization);
|
||||
this.v6l ^= swap8IfBE(pers[0]);
|
||||
this.v6h ^= swap8IfBE(pers[1]);
|
||||
this.v7l ^= swap8IfBE(pers[2]);
|
||||
this.v7h ^= swap8IfBE(pers[3]);
|
||||
}
|
||||
if (key !== undefined) {
|
||||
// Pad to blockLen and update
|
||||
const tmp = new Uint8Array(this.blockLen);
|
||||
tmp.set(key);
|
||||
this.update(tmp);
|
||||
}
|
||||
}
|
||||
// prettier-ignore
|
||||
get() {
|
||||
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
|
||||
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
|
||||
this.v0l = v0l | 0;
|
||||
this.v0h = v0h | 0;
|
||||
this.v1l = v1l | 0;
|
||||
this.v1h = v1h | 0;
|
||||
this.v2l = v2l | 0;
|
||||
this.v2h = v2h | 0;
|
||||
this.v3l = v3l | 0;
|
||||
this.v3h = v3h | 0;
|
||||
this.v4l = v4l | 0;
|
||||
this.v4h = v4h | 0;
|
||||
this.v5l = v5l | 0;
|
||||
this.v5h = v5h | 0;
|
||||
this.v6l = v6l | 0;
|
||||
this.v6h = v6h | 0;
|
||||
this.v7l = v7l | 0;
|
||||
this.v7h = v7h | 0;
|
||||
}
|
||||
compress(msg, offset, isLast) {
|
||||
this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
|
||||
BBUF.set(B2B_IV, 16); // Second half from IV.
|
||||
let { h, l } = u64.fromBig(BigInt(this.length));
|
||||
BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.
|
||||
BBUF[25] = B2B_IV[9] ^ h; // High word.
|
||||
// Invert all bits for last block
|
||||
if (isLast) {
|
||||
BBUF[28] = ~BBUF[28];
|
||||
BBUF[29] = ~BBUF[29];
|
||||
}
|
||||
let j = 0;
|
||||
const s = BSIGMA;
|
||||
// SIGMA selects 64-bit message words; multiply by 2 because `msg` stores
|
||||
// each word as [low32, high32].
|
||||
for (let i = 0; i < 12; i++) {
|
||||
G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
||||
G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
||||
G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
||||
G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
||||
G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
||||
G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
||||
G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
||||
G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
||||
G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
||||
G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
||||
G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
||||
G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
||||
G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
||||
G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
||||
G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
||||
G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
||||
}
|
||||
this.v0l ^= BBUF[0] ^ BBUF[16];
|
||||
this.v0h ^= BBUF[1] ^ BBUF[17];
|
||||
this.v1l ^= BBUF[2] ^ BBUF[18];
|
||||
this.v1h ^= BBUF[3] ^ BBUF[19];
|
||||
this.v2l ^= BBUF[4] ^ BBUF[20];
|
||||
this.v2h ^= BBUF[5] ^ BBUF[21];
|
||||
this.v3l ^= BBUF[6] ^ BBUF[22];
|
||||
this.v3h ^= BBUF[7] ^ BBUF[23];
|
||||
this.v4l ^= BBUF[8] ^ BBUF[24];
|
||||
this.v4h ^= BBUF[9] ^ BBUF[25];
|
||||
this.v5l ^= BBUF[10] ^ BBUF[26];
|
||||
this.v5h ^= BBUF[11] ^ BBUF[27];
|
||||
this.v6l ^= BBUF[12] ^ BBUF[28];
|
||||
this.v6h ^= BBUF[13] ^ BBUF[29];
|
||||
this.v7l ^= BBUF[14] ^ BBUF[30];
|
||||
this.v7h ^= BBUF[15] ^ BBUF[31];
|
||||
clean(BBUF);
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clean(this.buffer32);
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
||||
* `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present,
|
||||
* must be 16 bytes each. See {@link Blake2Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake2b.
|
||||
* ```ts
|
||||
* blake2b(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts));
|
||||
/**
|
||||
* BLAKE2-compress core method.
|
||||
* Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15`
|
||||
* and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves.
|
||||
* @param s - flattened sigma schedule bytes
|
||||
* @param offset - starting word offset inside `msg`, not a byte offset
|
||||
* @param msg - message words
|
||||
* @param rounds - round count to execute
|
||||
* @param v0 - state word 0
|
||||
* @param v1 - state word 1
|
||||
* @param v2 - state word 2
|
||||
* @param v3 - state word 3
|
||||
* @param v4 - state word 4
|
||||
* @param v5 - state word 5
|
||||
* @param v6 - state word 6
|
||||
* @param v7 - state word 7
|
||||
* @param v8 - state word 8
|
||||
* @param v9 - state word 9
|
||||
* @param v10 - state word 10
|
||||
* @param v11 - state word 11
|
||||
* @param v12 - state word 12
|
||||
* @param v13 - state word 13
|
||||
* @param v14 - state word 14
|
||||
* @param v15 - state word 15
|
||||
* @returns Updated compression state words.
|
||||
* @example
|
||||
* Run the BLAKE2 compression core on zeroed state and message words.
|
||||
* ```ts
|
||||
* import { compress } from '@noble/hashes/blake2.js';
|
||||
* const state = compress(
|
||||
* new Uint8Array(16),
|
||||
* 0,
|
||||
* new Uint32Array(16),
|
||||
* 1,
|
||||
* 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
* 0, 0, 0, 0, 0, 0, 0, 0
|
||||
* );
|
||||
* state.v0;
|
||||
* ```
|
||||
*/
|
||||
// prettier-ignore
|
||||
export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
|
||||
let j = 0;
|
||||
for (let i = 0; i < rounds; i++) {
|
||||
({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
|
||||
}
|
||||
return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
|
||||
}
|
||||
// Blake2s reuses the SHA-256 IV words as-is.
|
||||
const B2S_IV = /* @__PURE__ */ SHA256_IV.slice();
|
||||
/** Internal blake2s hash class. */
|
||||
export class _BLAKE2s extends _BLAKE2 {
|
||||
// Internal state, same as SHA-256
|
||||
v0 = B2S_IV[0] | 0;
|
||||
v1 = B2S_IV[1] | 0;
|
||||
v2 = B2S_IV[2] | 0;
|
||||
v3 = B2S_IV[3] | 0;
|
||||
v4 = B2S_IV[4] | 0;
|
||||
v5 = B2S_IV[5] | 0;
|
||||
v6 = B2S_IV[6] | 0;
|
||||
v7 = B2S_IV[7] | 0;
|
||||
constructor(opts = {}) {
|
||||
const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
|
||||
super(64, olen);
|
||||
checkBlake2Opts(olen, opts, 32, 8, 8);
|
||||
let { key, personalization, salt } = opts;
|
||||
let keyLength = 0;
|
||||
if (key !== undefined) {
|
||||
abytes(key, undefined, 'key');
|
||||
keyLength = key.length;
|
||||
}
|
||||
// RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since
|
||||
// BLAKE2s stores each state word as one `u32`.
|
||||
this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
||||
if (salt !== undefined) {
|
||||
abytes(salt, undefined, 'salt');
|
||||
const slt = u32(salt);
|
||||
this.v4 ^= swap8IfBE(slt[0]);
|
||||
this.v5 ^= swap8IfBE(slt[1]);
|
||||
}
|
||||
if (personalization !== undefined) {
|
||||
abytes(personalization, undefined, 'personalization');
|
||||
const pers = u32(personalization);
|
||||
this.v6 ^= swap8IfBE(pers[0]);
|
||||
this.v7 ^= swap8IfBE(pers[1]);
|
||||
}
|
||||
if (key !== undefined) {
|
||||
// Pad to blockLen and update
|
||||
const tmp = new Uint8Array(this.blockLen);
|
||||
tmp.set(key);
|
||||
this.update(tmp);
|
||||
}
|
||||
}
|
||||
get() {
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
|
||||
return [v0, v1, v2, v3, v4, v5, v6, v7];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0, v1, v2, v3, v4, v5, v6, v7) {
|
||||
this.v0 = v0 | 0;
|
||||
this.v1 = v1 | 0;
|
||||
this.v2 = v2 | 0;
|
||||
this.v3 = v3 | 0;
|
||||
this.v4 = v4 | 0;
|
||||
this.v5 = v5 | 0;
|
||||
this.v6 = v6 | 0;
|
||||
this.v7 = v7 | 0;
|
||||
}
|
||||
compress(msg, offset, isLast) {
|
||||
const { h, l } = u64.fromBig(BigInt(this.length));
|
||||
// Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into
|
||||
// v12/v13, and invert v14 on the final block.
|
||||
// prettier-ignore
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
|
||||
this.v0 ^= v0 ^ v8;
|
||||
this.v1 ^= v1 ^ v9;
|
||||
this.v2 ^= v2 ^ v10;
|
||||
this.v3 ^= v3 ^ v11;
|
||||
this.v4 ^= v4 ^ v12;
|
||||
this.v5 ^= v5 ^ v13;
|
||||
this.v6 ^= v6 ^ v14;
|
||||
this.v7 ^= v7 ^ v15;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clean(this.buffer32);
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, salt, and personalization settings.
|
||||
* `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present,
|
||||
* must be 8 bytes each. See {@link Blake2Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash a message with Blake2s.
|
||||
* ```ts
|
||||
* blake2s(new Uint8Array([97, 98, 99]));
|
||||
* ```
|
||||
*/
|
||||
export const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts));
|
||||
//# sourceMappingURL=blake2.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+68
@@ -0,0 +1,68 @@
|
||||
import { _BLAKE2 } from './blake2.ts';
|
||||
import { type CHashXOF, type HashXOF, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Ensure to use EITHER `key` OR `context`, not both.
|
||||
*
|
||||
* * `key`: 32-byte MAC key.
|
||||
* * `context`: caller-encoded KDF context bytes. If your protocol defines a
|
||||
* string context, encode it before passing it here.
|
||||
* A good default format for the original context string is
|
||||
* "[application] [commit timestamp] [purpose]".
|
||||
*/
|
||||
export type Blake3Opts = {
|
||||
/** Desired digest length in bytes. The BLAKE3 spec allows 0..2^64-1 bytes of output. */
|
||||
dkLen?: number;
|
||||
/** Optional 32-byte MAC key. */
|
||||
key?: Uint8Array;
|
||||
/** Optional KDF context bytes. */
|
||||
context?: Uint8Array;
|
||||
};
|
||||
/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */
|
||||
export declare class _BLAKE3 extends _BLAKE2<_BLAKE3> implements HashXOF<_BLAKE3> {
|
||||
readonly canXOF = true;
|
||||
private chunkPos;
|
||||
private chunksDone;
|
||||
private flags;
|
||||
private IV;
|
||||
private state;
|
||||
private stack;
|
||||
private posOut;
|
||||
private bufferOut32;
|
||||
private bufferOut;
|
||||
private chunkOut;
|
||||
private enableXOF;
|
||||
constructor(opts?: Blake3Opts, flags?: number);
|
||||
protected get(): [];
|
||||
protected set(): void;
|
||||
private b2Compress;
|
||||
protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void;
|
||||
_cloneInto(to?: _BLAKE3): _BLAKE3;
|
||||
destroy(): void;
|
||||
private b2CompressOut;
|
||||
protected finish(): void;
|
||||
private writeInto;
|
||||
xofInto(out: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
xof(bytes: number): TRet<Uint8Array>;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
}
|
||||
/**
|
||||
* BLAKE3 hash function. Can be used as MAC and KDF.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, or KDF configuration. `key` must be
|
||||
* exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be
|
||||
* 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash, MAC, or derive key material with BLAKE3.
|
||||
* ```ts
|
||||
* import { blake3 } from '@noble/hashes/blake3.js';
|
||||
* import { utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
* const data = new Uint8Array(32);
|
||||
* const hash = blake3(data);
|
||||
* const mac = blake3(data, { key: new Uint8Array(32) });
|
||||
* const kdf = blake3(data, { context: utf8ToBytes('application name') });
|
||||
* ```
|
||||
*/
|
||||
export declare const blake3: TRet<CHashXOF<_BLAKE3, Blake3Opts>>;
|
||||
//# sourceMappingURL=blake3.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,OAAO,EAAY,MAAM,aAAa,CAAC;AAEhD,OAAO,EAML,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AA4BpB;;;;;;;;GAQG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,wFAAwF;IACxF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gCAAgC;IAChC,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,kCAAkC;IAClC,OAAO,CAAC,EAAE,UAAU,CAAC;CACtB,CAAC;AAEF,iFAAiF;AACjF,qBAAa,OAAQ,SAAQ,OAAO,CAAC,OAAO,CAAE,YAAW,OAAO,CAAC,OAAO,CAAC;IACvE,QAAQ,CAAC,MAAM,QAAQ;IACvB,OAAO,CAAC,QAAQ,CAAK;IAGrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,EAAE,CAAc;IACxB,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAElC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,SAAS,CAAa;IAG9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAQ;gBAEb,IAAI,GAAE,UAAe,EAAE,KAAK,SAAI;IA6B5C,SAAS,CAAC,GAAG,IAAI,EAAE;IAGnB,SAAS,CAAC,GAAG,IAAI,IAAI;IAGrB,OAAO,CAAC,UAAU;IAmBlB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,GAAE,MAAU,EAAE,MAAM,GAAE,OAAe,GAAG,IAAI;IAkCvF,UAAU,CAAC,EAAE,CAAC,EAAE,OAAO,GAAG,OAAO;IAiBjC,OAAO,IAAI,IAAI;IAQf,OAAO,CAAC,aAAa;IA+BrB,SAAS,CAAC,MAAM,IAAI,IAAI;IAsBxB,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC;IAIhD,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IAIpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAQvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAK3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC,CAEtD,CAAC"}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.
|
||||
*
|
||||
* It is advertised as "the fastest cryptographic hash". However, it isn't true in JS.
|
||||
* Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%:
|
||||
*
|
||||
* * There is only 30% reduction in number of rounds from blake2s
|
||||
* * Speed-up comes from tree structure, which is parallelized using SIMD & threading.
|
||||
* These features are not present in JS, so we only get overhead from trees.
|
||||
* * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.
|
||||
* * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm
|
||||
* @module
|
||||
*/
|
||||
import { SHA256_IV } from "./_md.js";
|
||||
import { fromBig } from "./_u64.js";
|
||||
import { _BLAKE2, compress } from "./blake2.js";
|
||||
// prettier-ignore
|
||||
import { abytes, aexists, anumber, aoutput, clean, copyBytes, createHasher, swap32IfBE, u32, u8 } from "./utils.js";
|
||||
// Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree
|
||||
// flags (`CHUNK_*`, `PARENT`, `ROOT`).
|
||||
const B3_Flags = {
|
||||
CHUNK_START: 0b1,
|
||||
CHUNK_END: 0b10,
|
||||
PARENT: 0b100,
|
||||
ROOT: 0b1000,
|
||||
KEYED_HASH: 0b10000,
|
||||
DERIVE_KEY_CONTEXT: 0b100000,
|
||||
DERIVE_KEY_MATERIAL: 0b1000000,
|
||||
};
|
||||
// Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis.
|
||||
const B3_IV = /* @__PURE__ */ SHA256_IV.slice();
|
||||
// Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly
|
||||
// permuting the identity row.
|
||||
const B3_SIGMA = /* @__PURE__ */ (() => {
|
||||
const Id = Array.from({ length: 16 }, (_, i) => i);
|
||||
const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
|
||||
const res = [];
|
||||
for (let i = 0, v = Id; i < 7; i++, v = permute(v))
|
||||
res.push(...v);
|
||||
return Uint8Array.from(res);
|
||||
})();
|
||||
/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */
|
||||
export class _BLAKE3 extends _BLAKE2 {
|
||||
canXOF = true;
|
||||
chunkPos = 0; // Position of current block in chunk
|
||||
// How many chunks we already have; exact while this stays within
|
||||
// JS's safe-integer range.
|
||||
chunksDone = 0;
|
||||
flags = 0 | 0;
|
||||
IV;
|
||||
state;
|
||||
stack = [];
|
||||
// Output
|
||||
posOut = 0;
|
||||
bufferOut32 = new Uint32Array(16);
|
||||
bufferOut;
|
||||
// Index of output chunk; exact while this stays within JS's
|
||||
// safe-integer range.
|
||||
chunkOut = 0;
|
||||
enableXOF = true;
|
||||
constructor(opts = {}, flags = 0) {
|
||||
super(64, opts.dkLen === undefined ? 32 : opts.dkLen);
|
||||
const { key, context } = opts;
|
||||
const hasContext = context !== undefined;
|
||||
if (key !== undefined) {
|
||||
if (hasContext)
|
||||
throw new Error('Only "key" or "context" can be specified at same time');
|
||||
abytes(key, 32, 'key');
|
||||
const k = copyBytes(key);
|
||||
this.IV = u32(k);
|
||||
swap32IfBE(this.IV);
|
||||
this.flags = flags | B3_Flags.KEYED_HASH;
|
||||
}
|
||||
else if (hasContext) {
|
||||
abytes(context, undefined, 'context');
|
||||
const ctx = context;
|
||||
const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)
|
||||
.update(ctx)
|
||||
.digest();
|
||||
this.IV = u32(contextKey);
|
||||
swap32IfBE(this.IV);
|
||||
this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
|
||||
}
|
||||
else {
|
||||
this.IV = B3_IV.slice();
|
||||
this.flags = flags;
|
||||
}
|
||||
this.state = this.IV.slice();
|
||||
this.bufferOut = u8(this.bufferOut32);
|
||||
}
|
||||
// _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and
|
||||
// copies it directly in _cloneInto().
|
||||
get() {
|
||||
return [];
|
||||
}
|
||||
set() { }
|
||||
// Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1,
|
||||
// block length, and flags, then keep only the first 8 output words.
|
||||
b2Compress(counter, flags, buf, bufPos = 0) {
|
||||
const { state: s, pos } = this;
|
||||
const { h, l } = fromBig(BigInt(counter), true);
|
||||
// prettier-ignore
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
|
||||
s[0] = v0 ^ v8;
|
||||
s[1] = v1 ^ v9;
|
||||
s[2] = v2 ^ v10;
|
||||
s[3] = v3 ^ v11;
|
||||
s[4] = v4 ^ v12;
|
||||
s[5] = v5 ^ v13;
|
||||
s[6] = v6 ^ v14;
|
||||
s[7] = v7 ^ v15;
|
||||
}
|
||||
compress(buf, bufPos = 0, isLast = false) {
|
||||
// Compress last block
|
||||
let flags = this.flags;
|
||||
if (!this.chunkPos)
|
||||
flags |= B3_Flags.CHUNK_START;
|
||||
if (this.chunkPos === 15 || isLast)
|
||||
flags |= B3_Flags.CHUNK_END;
|
||||
if (!isLast)
|
||||
this.pos = this.blockLen;
|
||||
this.b2Compress(this.chunksDone, flags, buf, bufPos);
|
||||
this.chunkPos += 1;
|
||||
// If current block is last in chunk (16 blocks), then compress chunks
|
||||
if (this.chunkPos === 16 || isLast) {
|
||||
let chunk = this.state;
|
||||
this.state = this.IV.slice();
|
||||
// If not the last one, compress only when there are trailing zeros in chunk counter
|
||||
// Chunks are used as a binary tree where the current stack is the path.
|
||||
// Zero means the current leaf is finished and can be compressed.
|
||||
// 1 (001) - leaf not finished (just push current chunk to stack)
|
||||
// 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
|
||||
// 3 (011) - last leaf not finished
|
||||
// 4 (100) - leafs finished at depth=1 and depth=2
|
||||
for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
|
||||
if (!(last = this.stack.pop()))
|
||||
break;
|
||||
this.buffer32.set(last, 0);
|
||||
this.buffer32.set(chunk, 8);
|
||||
this.pos = this.blockLen;
|
||||
this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
|
||||
chunk = this.state;
|
||||
this.state = this.IV.slice();
|
||||
}
|
||||
this.chunksDone++;
|
||||
this.chunkPos = 0;
|
||||
this.stack.push(chunk);
|
||||
}
|
||||
this.pos = 0;
|
||||
}
|
||||
_cloneInto(to) {
|
||||
to = super._cloneInto(to);
|
||||
const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
|
||||
to.state.set(state.slice());
|
||||
// Clone each CV stack entry by value so extending or destroying the clone
|
||||
// cannot alias the source tree state.
|
||||
to.stack = stack.map((i) => Uint32Array.from(i));
|
||||
to.IV.set(IV);
|
||||
to.flags = flags;
|
||||
to.chunkPos = chunkPos;
|
||||
to.chunksDone = chunksDone;
|
||||
to.posOut = posOut;
|
||||
to.chunkOut = chunkOut;
|
||||
to.enableXOF = this.enableXOF;
|
||||
to.bufferOut32.set(this.bufferOut32);
|
||||
return to;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clean(this.state, this.buffer32, this.IV, this.bufferOut32);
|
||||
clean(...this.stack);
|
||||
}
|
||||
// Root/XOF compression: rerun the same ROOT inputs with incrementing output
|
||||
// counter `t` and materialize all 16 output words.
|
||||
// Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
|
||||
b2CompressOut() {
|
||||
const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
|
||||
const { h, l } = fromBig(BigInt(this.chunkOut++));
|
||||
swap32IfBE(buffer32);
|
||||
// prettier-ignore
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
|
||||
out32[0] = v0 ^ v8;
|
||||
out32[1] = v1 ^ v9;
|
||||
out32[2] = v2 ^ v10;
|
||||
out32[3] = v3 ^ v11;
|
||||
out32[4] = v4 ^ v12;
|
||||
out32[5] = v5 ^ v13;
|
||||
out32[6] = v6 ^ v14;
|
||||
out32[7] = v7 ^ v15;
|
||||
out32[8] = s[0] ^ v8;
|
||||
out32[9] = s[1] ^ v9;
|
||||
out32[10] = s[2] ^ v10;
|
||||
out32[11] = s[3] ^ v11;
|
||||
out32[12] = s[4] ^ v12;
|
||||
out32[13] = s[5] ^ v13;
|
||||
out32[14] = s[6] ^ v14;
|
||||
out32[15] = s[7] ^ v15;
|
||||
swap32IfBE(buffer32);
|
||||
swap32IfBE(out32);
|
||||
this.posOut = 0;
|
||||
}
|
||||
finish() {
|
||||
if (this.finished)
|
||||
return;
|
||||
this.finished = true;
|
||||
// Padding
|
||||
clean(this.buffer.subarray(this.pos));
|
||||
// Process last chunk
|
||||
let flags = this.flags | B3_Flags.ROOT;
|
||||
if (this.stack.length) {
|
||||
// Finalize the current chunk first, then rerun the last parent
|
||||
// compression as ROOT with t = 0 and b = 64.
|
||||
flags |= B3_Flags.PARENT;
|
||||
swap32IfBE(this.buffer32);
|
||||
this.compress(this.buffer32, 0, true);
|
||||
swap32IfBE(this.buffer32);
|
||||
this.chunksDone = 0;
|
||||
this.pos = this.blockLen;
|
||||
}
|
||||
else {
|
||||
flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
|
||||
}
|
||||
this.flags = flags;
|
||||
this.b2CompressOut();
|
||||
}
|
||||
writeInto(out) {
|
||||
aexists(this, false);
|
||||
abytes(out);
|
||||
this.finish();
|
||||
const { blockLen, bufferOut } = this;
|
||||
for (let pos = 0, len = out.length; pos < len;) {
|
||||
if (this.posOut >= blockLen)
|
||||
this.b2CompressOut();
|
||||
const take = Math.min(blockLen - this.posOut, len - pos);
|
||||
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
||||
this.posOut += take;
|
||||
pos += take;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
xofInto(out) {
|
||||
if (!this.enableXOF)
|
||||
throw new Error('XOF is not possible after digest call');
|
||||
return this.writeInto(out);
|
||||
}
|
||||
xof(bytes) {
|
||||
anumber(bytes);
|
||||
return this.xofInto(new Uint8Array(bytes));
|
||||
}
|
||||
digestInto(out) {
|
||||
aoutput(out, this);
|
||||
if (this.finished)
|
||||
throw new Error('digest() was already called');
|
||||
this.enableXOF = false;
|
||||
// `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest.
|
||||
this.writeInto(out.subarray(0, this.outputLen));
|
||||
this.destroy();
|
||||
}
|
||||
digest() {
|
||||
const out = new Uint8Array(this.outputLen);
|
||||
this.digestInto(out);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* BLAKE3 hash function. Can be used as MAC and KDF.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - Optional output, MAC, or KDF configuration. `key` must be
|
||||
* exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be
|
||||
* 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}.
|
||||
* @returns Digest bytes.
|
||||
* @example
|
||||
* Hash, MAC, or derive key material with BLAKE3.
|
||||
* ```ts
|
||||
* import { blake3 } from '@noble/hashes/blake3.js';
|
||||
* import { utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
* const data = new Uint8Array(32);
|
||||
* const hash = blake3(data);
|
||||
* const mac = blake3(data, { key: new Uint8Array(32) });
|
||||
* const kdf = blake3(data, { context: utf8ToBytes('application name') });
|
||||
* ```
|
||||
*/
|
||||
export const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts));
|
||||
//# sourceMappingURL=blake3.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+92
@@ -0,0 +1,92 @@
|
||||
import { type TRet } from './utils.ts';
|
||||
/**
|
||||
* Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`.
|
||||
* @param password - user password string, UTF-8 encoded before entering RFC 7914
|
||||
* @param salt - unique salt string, UTF-8 encoded before entering RFC 7914
|
||||
* @returns Derived 32-byte key.
|
||||
* @example
|
||||
* Derive the 32-byte scrypt key used by ESKDF.
|
||||
* ```ts
|
||||
* scrypt('password123', 'user@example.com');
|
||||
* ```
|
||||
*/
|
||||
export declare function scrypt(password: string, salt: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`.
|
||||
* @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
|
||||
* @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
|
||||
* @returns Derived 32-byte key.
|
||||
* @example
|
||||
* Derive the 32-byte PBKDF2 key used by ESKDF.
|
||||
* ```ts
|
||||
* pbkdf2('password123', 'user@example.com');
|
||||
* ```
|
||||
*/
|
||||
export declare function pbkdf2(password: string, salt: string): TRet<Uint8Array>;
|
||||
/**
|
||||
* Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)`
|
||||
* flow unless you specifically need the raw main seed.
|
||||
* Derives the main seed by xor'ing two branches:
|
||||
* the scrypt branch uses a `0x01` separator byte on username/password,
|
||||
* and the PBKDF2 branch uses `0x02`.
|
||||
* Username and password strings are encoded by the underlying KDFs after the
|
||||
* local separator bytes are appended.
|
||||
* @param username - account identifier used as public salt
|
||||
* @param password - user password string
|
||||
* @returns Main 32-byte seed for the account.
|
||||
* @throws If the username or password length is invalid. {@link Error}
|
||||
* @example
|
||||
* Derive the main ESKDF seed from username and password.
|
||||
* ```ts
|
||||
* deriveMainSeed('example-user', 'example-password');
|
||||
* ```
|
||||
*/
|
||||
export declare function deriveMainSeed(username: string, password: string): TRet<Uint8Array>;
|
||||
type AccountID = number | string;
|
||||
type OptsLength = {
|
||||
keyLength: number;
|
||||
};
|
||||
type OptsMod = {
|
||||
modulus: bigint;
|
||||
};
|
||||
type KeyOpts = undefined | OptsLength | OptsMod;
|
||||
/** Not using classes because constructor cannot be async. */
|
||||
export interface ESKDF {
|
||||
/**
|
||||
* Derives a child key. Child key will not be associated with any
|
||||
* other child key because of properties of underlying KDF.
|
||||
*
|
||||
* @param protocol - 3-15 character protocol name
|
||||
* @param accountId - numeric account identifier, or a string id for
|
||||
* `password\d{0,3}`, `ssh`, `tor`, or `file`
|
||||
* @param options - Optional child-key shaping parameters. See {@link KeyOpts}.
|
||||
* @returns Derived child key bytes.
|
||||
*/
|
||||
deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => TRet<Uint8Array>;
|
||||
/** Deletes the main seed from the ESKDF instance. */
|
||||
expire: () => void;
|
||||
/**
|
||||
* Human-readable fingerprint: first 6 bytes of
|
||||
* `deriveChildKey('fingerprint', 0)`, formatted as uppercase
|
||||
* colon-separated hex.
|
||||
*/
|
||||
fingerprint: string;
|
||||
}
|
||||
/**
|
||||
* ESKDF
|
||||
* @param username - username, email, or identifier, min: 8 characters, should have enough entropy
|
||||
* @param password - password, min: 8 characters, should have enough entropy
|
||||
* @returns Frozen API that derives child keys and exposes the account fingerprint.
|
||||
* @throws If the username or password length is invalid. {@link Error}
|
||||
* @example
|
||||
* Derive account-specific child keys from the main ESKDF seed.
|
||||
* ```ts
|
||||
* const kdf = await eskdf('example-university', 'beginning-new-example');
|
||||
* const key = kdf.deriveChildKey('aes', 0);
|
||||
* const fingerprint = kdf.fingerprint;
|
||||
* kdf.expire();
|
||||
* ```
|
||||
*/
|
||||
export declare function eskdf(username: string, password: string): Promise<TRet<ESKDF>>;
|
||||
export {};
|
||||
//# sourceMappingURL=eskdf.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"eskdf.d.ts","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":"AAQA,OAAO,EAQL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAYpB;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAEvE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAEvE;AAkBD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAanF;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAkCjC,KAAK,UAAU,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AACxC,KAAK,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AACnC,KAAK,OAAO,GAAG,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC;AA6ChD,6DAA6D;AAC7D,MAAM,WAAW,KAAK;IACpB;;;;;;;;;OASG;IACH,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAChG,qDAAqD;IACrD,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CA+BpF"}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* Experimental KDF for AES.
|
||||
* @module
|
||||
*/
|
||||
import { hkdf } from "./hkdf.js";
|
||||
import { pbkdf2 as _pbkdf2 } from "./pbkdf2.js";
|
||||
import { scrypt as _scrypt } from "./scrypt.js";
|
||||
import { sha256 } from "./sha2.js";
|
||||
import { abytes, bytesToHex, clean, createView, hexToBytes, kdfInputToBytes, } from "./utils.js";
|
||||
// A tiny KDF for various applications like AES key-gen.
|
||||
// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure".
|
||||
// Which is good enough: assume sha2-256 retained preimage resistance.
|
||||
// Fixed ESKDF scrypt work factor: interactive-latency target with about 512 MiB RAM per derivation.
|
||||
const SCRYPT_FACTOR = /* @__PURE__ */ (() => 2 ** 19)();
|
||||
// Fixed ESKDF PBKDF2 work factor: CPU-only companion branch in the same rough
|
||||
// interactive-latency range.
|
||||
const PBKDF2_FACTOR = /* @__PURE__ */ (() => 2 ** 17)();
|
||||
/**
|
||||
* Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`.
|
||||
* @param password - user password string, UTF-8 encoded before entering RFC 7914
|
||||
* @param salt - unique salt string, UTF-8 encoded before entering RFC 7914
|
||||
* @returns Derived 32-byte key.
|
||||
* @example
|
||||
* Derive the 32-byte scrypt key used by ESKDF.
|
||||
* ```ts
|
||||
* scrypt('password123', 'user@example.com');
|
||||
* ```
|
||||
*/
|
||||
export function scrypt(password, salt) {
|
||||
return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 });
|
||||
}
|
||||
/**
|
||||
* PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`.
|
||||
* @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
|
||||
* @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
|
||||
* @returns Derived 32-byte key.
|
||||
* @example
|
||||
* Derive the 32-byte PBKDF2 key used by ESKDF.
|
||||
* ```ts
|
||||
* pbkdf2('password123', 'user@example.com');
|
||||
* ```
|
||||
*/
|
||||
export function pbkdf2(password, salt) {
|
||||
return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 });
|
||||
}
|
||||
// Combines two 32-byte byte arrays into a fresh 32-byte result without aliasing either input.
|
||||
function xor32(a, b) {
|
||||
abytes(a, 32);
|
||||
abytes(b, 32);
|
||||
const arr = new Uint8Array(32);
|
||||
for (let i = 0; i < 32; i++) {
|
||||
arr[i] = a[i] ^ b[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
// All local string length checks are in JS UTF-16 code units, not UTF-8 bytes.
|
||||
function strHasLength(str, min, max) {
|
||||
return typeof str === 'string' && str.length >= min && str.length <= max;
|
||||
}
|
||||
/**
|
||||
* Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)`
|
||||
* flow unless you specifically need the raw main seed.
|
||||
* Derives the main seed by xor'ing two branches:
|
||||
* the scrypt branch uses a `0x01` separator byte on username/password,
|
||||
* and the PBKDF2 branch uses `0x02`.
|
||||
* Username and password strings are encoded by the underlying KDFs after the
|
||||
* local separator bytes are appended.
|
||||
* @param username - account identifier used as public salt
|
||||
* @param password - user password string
|
||||
* @returns Main 32-byte seed for the account.
|
||||
* @throws If the username or password length is invalid. {@link Error}
|
||||
* @example
|
||||
* Derive the main ESKDF seed from username and password.
|
||||
* ```ts
|
||||
* deriveMainSeed('example-user', 'example-password');
|
||||
* ```
|
||||
*/
|
||||
export function deriveMainSeed(username, password) {
|
||||
if (!strHasLength(username, 8, 255))
|
||||
throw new Error('invalid username');
|
||||
if (!strHasLength(password, 8, 255))
|
||||
throw new Error('invalid password');
|
||||
// Keep the protocol separators as the literal bytes 0x01 / 0x02 even after minification.
|
||||
// Embedding them as non-printable characters directly can be awkward across
|
||||
// JS tooling and environments.
|
||||
const codes = { _1: 1, _2: 2 };
|
||||
const sep = { s: String.fromCharCode(codes._1), p: String.fromCharCode(codes._2) };
|
||||
const scr = scrypt(password + sep.s, username + sep.s);
|
||||
const pbk = pbkdf2(password + sep.p, username + sep.p);
|
||||
const res = xor32(scr, pbk);
|
||||
clean(scr, pbk);
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Converts protocol & accountId pair to HKDF params:
|
||||
* `info` is UTF-8 protocol bytes, numeric ids become 4-byte BE `salt`,
|
||||
* and string ids become UTF-8 `salt` bytes.
|
||||
*/
|
||||
function getSaltInfo(protocol, accountId = 0) {
|
||||
// Note that length here also repeats two lines below
|
||||
// We do an additional length check here to reduce the scope of DoS attacks
|
||||
if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) {
|
||||
throw new Error('invalid protocol');
|
||||
}
|
||||
// Exact-match only: substring matches like `assh` / `mentor` must not widen the public whitelist.
|
||||
const allowsStr = /^(password\d{0,3}|ssh|tor|file)$/.test(protocol);
|
||||
let salt; // Assigned below: either 4-byte BE account bytes or UTF-8 account bytes.
|
||||
if (typeof accountId === 'string') {
|
||||
if (!allowsStr)
|
||||
throw new Error('accountId must be a number');
|
||||
if (!strHasLength(accountId, 1, 255))
|
||||
throw new Error('accountId must be string of length 1..255');
|
||||
salt = kdfInputToBytes(accountId);
|
||||
}
|
||||
else if (Number.isSafeInteger(accountId)) {
|
||||
if (accountId < 0 || accountId > Math.pow(2, 32) - 1)
|
||||
throw new Error('invalid accountId');
|
||||
// Convert to Big Endian Uint32
|
||||
salt = new Uint8Array(4);
|
||||
createView(salt).setUint32(0, accountId, false);
|
||||
}
|
||||
else {
|
||||
throw new Error('accountId must be a number' + (allowsStr ? ' or string' : ''));
|
||||
}
|
||||
const info = kdfInputToBytes(protocol);
|
||||
return { salt, info };
|
||||
}
|
||||
// Local modulus-size helper, not a general bigint-byte-length primitive:
|
||||
// `<= 128n` is rejected by ESKDF policy.
|
||||
function countBytes(num) {
|
||||
if (typeof num !== 'bigint' || num <= BigInt(128))
|
||||
throw new Error('invalid number');
|
||||
return Math.ceil(num.toString(2).length / 8);
|
||||
}
|
||||
/**
|
||||
* Parses keyLength and modulus options to extract length of result key.
|
||||
* If modulus is used, adds 64 bits to it per the FIPS 186-5 Appendix A.3.1 /
|
||||
* A.4.1 extra-bits guidance.
|
||||
*/
|
||||
function getKeyLength(options) {
|
||||
if (!options || typeof options !== 'object')
|
||||
return 32;
|
||||
const hasLen = 'keyLength' in options;
|
||||
const hasMod = 'modulus' in options;
|
||||
if (hasLen && hasMod)
|
||||
throw new Error('cannot combine keyLength and modulus options');
|
||||
if (!hasLen && !hasMod)
|
||||
throw new Error('must have either keyLength or modulus option');
|
||||
// FIPS 186-5 Appendix A.3.1 / A.4.1 calls for at least 64 extra bits.
|
||||
const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength;
|
||||
if (!(typeof l === 'number' && l >= 16 && l <= 8192))
|
||||
throw new Error('invalid keyLength');
|
||||
return l;
|
||||
}
|
||||
/**
|
||||
* Converts key to bigint and divides it by modulus. Big Endian.
|
||||
* Adapts FIPS 186-5 Appendix A.4.1: `getKeyLength()` already requested the
|
||||
* extra 64-bit margin, and this step maps the result into `1..modulus-1`.
|
||||
*/
|
||||
function modReduceKey(key, modulus) {
|
||||
const _1 = BigInt(1);
|
||||
const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber()
|
||||
const res = (num % (modulus - _1)) + _1; // Remove 0 from output
|
||||
if (res < _1)
|
||||
throw new Error('expected positive number'); // Guard against bad values
|
||||
// Strip the extra 64-bit margin that `getKeyLength()` requested
|
||||
// for bias reduction.
|
||||
const len = key.length - 8;
|
||||
const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex()
|
||||
const bytes = hexToBytes(hex);
|
||||
if (bytes.length !== len)
|
||||
throw new Error('invalid length of result key');
|
||||
return bytes;
|
||||
}
|
||||
/**
|
||||
* ESKDF
|
||||
* @param username - username, email, or identifier, min: 8 characters, should have enough entropy
|
||||
* @param password - password, min: 8 characters, should have enough entropy
|
||||
* @returns Frozen API that derives child keys and exposes the account fingerprint.
|
||||
* @throws If the username or password length is invalid. {@link Error}
|
||||
* @example
|
||||
* Derive account-specific child keys from the main ESKDF seed.
|
||||
* ```ts
|
||||
* const kdf = await eskdf('example-university', 'beginning-new-example');
|
||||
* const key = kdf.deriveChildKey('aes', 0);
|
||||
* const fingerprint = kdf.fingerprint;
|
||||
* kdf.expire();
|
||||
* ```
|
||||
*/
|
||||
export async function eskdf(username, password) {
|
||||
// We are using closure + object instead of class because
|
||||
// we want to make `seed` non-accessible for any external function.
|
||||
let seed = deriveMainSeed(username, password);
|
||||
function deriveCK(protocol, accountId = 0, options) {
|
||||
// Reject expired instances before deriving any HKDF inputs from the closure-held seed.
|
||||
abytes(seed, 32);
|
||||
const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId
|
||||
// Validate option shape and coarse length bounds;
|
||||
// `hkdf()` still rejects non-integer lengths.
|
||||
const keyLength = getKeyLength(options);
|
||||
const key = hkdf(sha256, seed, salt, info, keyLength);
|
||||
// Modulus has already been validated
|
||||
return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key;
|
||||
}
|
||||
function expire() {
|
||||
// Overwrite the closure-held seed before dropping the reference.
|
||||
if (seed)
|
||||
seed.fill(1);
|
||||
seed = undefined;
|
||||
}
|
||||
// prettier-ignore
|
||||
const fingerprint = Array.from(deriveCK('fingerprint', 0))
|
||||
.slice(0, 6)
|
||||
.map((char) => char.toString(16).padStart(2, '0').toUpperCase())
|
||||
.join(':');
|
||||
return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint });
|
||||
}
|
||||
//# sourceMappingURL=eskdf.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+64
@@ -0,0 +1,64 @@
|
||||
import { type CHash, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
|
||||
* Arguments position differs from spec (IKM is first one, since it is not optional)
|
||||
* Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
* @returns Pseudorandom key derived from input keying material.
|
||||
* @example
|
||||
* Run the HKDF extract step.
|
||||
* ```ts
|
||||
* import { extract } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
|
||||
* ```
|
||||
*/
|
||||
export declare function extract(hash: TArg<CHash>, ikm: TArg<Uint8Array>, salt?: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
/**
|
||||
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param prk - a pseudorandom key of at least HashLen octets
|
||||
* (usually, the output from the extract step)
|
||||
* @param info - optional context and application specific information (can be a zero-length string)
|
||||
* @param length - length of output keying material in bytes.
|
||||
* RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
|
||||
* @returns Output keying material with the requested length.
|
||||
* @throws If the requested output length exceeds the HKDF limit
|
||||
* for the selected hash. {@link Error}
|
||||
* @example
|
||||
* Run the HKDF expand step.
|
||||
* ```ts
|
||||
* import { expand } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
|
||||
* ```
|
||||
*/
|
||||
export declare function expand(hash: TArg<CHash>, prk: TArg<Uint8Array>, info?: TArg<Uint8Array>, length?: number): TRet<Uint8Array>;
|
||||
/**
|
||||
* HKDF (RFC 5869): derive keys from an initial input.
|
||||
* Combines hkdf_extract + hkdf_expand in one step
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
* @param info - optional context and application specific information bytes
|
||||
* @param length - length of output keying material in bytes.
|
||||
* RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
|
||||
* @returns Output keying material derived from the input key.
|
||||
* @throws If the requested output length exceeds the HKDF limit
|
||||
* for the selected hash. {@link Error}
|
||||
* @example
|
||||
* HKDF (RFC 5869): derive keys from an initial input.
|
||||
* ```ts
|
||||
* import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
* const inputKey = randomBytes(32);
|
||||
* const salt = randomBytes(32);
|
||||
* const info = utf8ToBytes('application-key');
|
||||
* const okm = hkdf(sha256, inputKey, salt, info, 32);
|
||||
* ```
|
||||
*/
|
||||
export declare const hkdf: (hash: TArg<CHash>, ikm: TArg<Uint8Array>, salt: TArg<Uint8Array | undefined>, info: TArg<Uint8Array | undefined>, length: number) => TRet<Uint8Array>;
|
||||
//# sourceMappingURL=hkdf.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hkdf.d.ts","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":"AAMA,OAAO,EAA0B,KAAK,KAAK,EAAS,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7F;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,OAAO,CACrB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC,UAAU,CAAC,CAOlB;AAQD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,MAAM,CACpB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,EACvB,MAAM,GAAE,MAAW,GAClB,IAAI,CAAC,UAAU,CAAC,CAiClB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,IAAI,GACf,MAAM,IAAI,CAAC,KAAK,CAAC,EACjB,KAAK,IAAI,CAAC,UAAU,CAAC,EACrB,MAAM,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,MAAM,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,QAAQ,MAAM,KACb,IAAI,CAAC,UAAU,CAAyD,CAAC"}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* HKDF (RFC 5869): extract + expand in one step.
|
||||
* See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.
|
||||
* @module
|
||||
*/
|
||||
import { hmac } from "./hmac.js";
|
||||
import { abytes, ahash, anumber, clean } from "./utils.js";
|
||||
/**
|
||||
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
|
||||
* Arguments position differs from spec (IKM is first one, since it is not optional)
|
||||
* Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
* @returns Pseudorandom key derived from input keying material.
|
||||
* @example
|
||||
* Run the HKDF extract step.
|
||||
* ```ts
|
||||
* import { extract } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
|
||||
* ```
|
||||
*/
|
||||
export function extract(hash, ikm, salt) {
|
||||
ahash(hash);
|
||||
// NOTE: some libraries treat zero-length array as 'not provided';
|
||||
// we don't, since we have undefined as 'not provided'
|
||||
// https://github.com/RustCrypto/KDFs/issues/15
|
||||
if (salt === undefined)
|
||||
salt = new Uint8Array(hash.outputLen);
|
||||
return hmac(hash, salt, ikm);
|
||||
}
|
||||
// Shared mutable scratch byte for the RFC 5869 block counter `N`.
|
||||
// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.
|
||||
const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
|
||||
// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.
|
||||
const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
|
||||
/**
|
||||
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param prk - a pseudorandom key of at least HashLen octets
|
||||
* (usually, the output from the extract step)
|
||||
* @param info - optional context and application specific information (can be a zero-length string)
|
||||
* @param length - length of output keying material in bytes.
|
||||
* RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
|
||||
* @returns Output keying material with the requested length.
|
||||
* @throws If the requested output length exceeds the HKDF limit
|
||||
* for the selected hash. {@link Error}
|
||||
* @example
|
||||
* Run the HKDF expand step.
|
||||
* ```ts
|
||||
* import { expand } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
|
||||
* ```
|
||||
*/
|
||||
export function expand(hash, prk, info, length = 32) {
|
||||
ahash(hash);
|
||||
anumber(length, 'length');
|
||||
abytes(prk, undefined, 'prk');
|
||||
const olen = hash.outputLen;
|
||||
// RFC 5869 §2.3: PRK is "a pseudorandom key of at least HashLen octets".
|
||||
if (prk.length < olen)
|
||||
throw new Error('"prk" must be at least HashLen octets');
|
||||
// RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.
|
||||
if (length > 255 * olen)
|
||||
throw new Error('Length must be <= 255*HashLen');
|
||||
const blocks = Math.ceil(length / olen);
|
||||
if (info === undefined)
|
||||
info = EMPTY_BUFFER;
|
||||
else
|
||||
abytes(info, undefined, 'info');
|
||||
// first L(ength) octets of T
|
||||
const okm = new Uint8Array(blocks * olen);
|
||||
// Re-use HMAC instance between blocks
|
||||
const HMAC = hmac.create(hash, prk);
|
||||
const HMACTmp = HMAC._cloneInto();
|
||||
const T = new Uint8Array(HMAC.outputLen);
|
||||
for (let counter = 0; counter < blocks; counter++) {
|
||||
HKDF_COUNTER[0] = counter + 1;
|
||||
// T(0) = empty string (zero length)
|
||||
// T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
|
||||
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
|
||||
.update(info)
|
||||
.update(HKDF_COUNTER)
|
||||
.digestInto(T);
|
||||
okm.set(T, olen * counter);
|
||||
HMAC._cloneInto(HMACTmp);
|
||||
}
|
||||
HMAC.destroy();
|
||||
HMACTmp.destroy();
|
||||
clean(T, HKDF_COUNTER);
|
||||
return okm.slice(0, length);
|
||||
}
|
||||
/**
|
||||
* HKDF (RFC 5869): derive keys from an initial input.
|
||||
* Combines hkdf_extract + hkdf_expand in one step
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
* @param info - optional context and application specific information bytes
|
||||
* @param length - length of output keying material in bytes.
|
||||
* RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
|
||||
* @returns Output keying material derived from the input key.
|
||||
* @throws If the requested output length exceeds the HKDF limit
|
||||
* for the selected hash. {@link Error}
|
||||
* @example
|
||||
* HKDF (RFC 5869): derive keys from an initial input.
|
||||
* ```ts
|
||||
* import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
* const inputKey = randomBytes(32);
|
||||
* const salt = randomBytes(32);
|
||||
* const info = utf8ToBytes('application-key');
|
||||
* const okm = hkdf(sha256, inputKey, salt, info, 32);
|
||||
* ```
|
||||
*/
|
||||
export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
|
||||
//# sourceMappingURL=hkdf.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAc,KAAK,EAAwB,MAAM,YAAY,CAAC;AAE7F;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,OAAO,CACrB,IAAiB,EACjB,GAAqB,EACrB,IAAuB;IAEvB,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,kEAAkE;IAClE,sDAAsD;IACtD,+CAA+C;IAC/C,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC9D,OAAO,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,kEAAkE;AAClE,oGAAoG;AACpG,MAAM,YAAY,GAAG,eAAe,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACtD,+FAA+F;AAC/F,MAAM,YAAY,GAAG,eAAe,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC;AAErD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,MAAM,CACpB,IAAiB,EACjB,GAAqB,EACrB,IAAuB,EACvB,SAAiB,EAAE;IAEnB,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC1B,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;IAC5B,yEAAyE;IACzE,IAAI,GAAG,CAAC,MAAM,GAAG,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAChF,0FAA0F;IAC1F,IAAI,MAAM,GAAG,GAAG,GAAG,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC1E,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACxC,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,GAAG,YAAY,CAAC;;QACvC,MAAM,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IACrC,6BAA6B;IAC7B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC1C,sCAAsC;IACtC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACpC,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;IAClC,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACzC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC;QAClD,YAAY,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,CAAC,CAAC;QAC9B,oCAAoC;QACpC,2CAA2C;QAC3C,OAAO,CAAC,MAAM,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;aAC7C,MAAM,CAAC,IAAI,CAAC;aACZ,MAAM,CAAC,YAAY,CAAC;aACpB,UAAU,CAAC,CAAC,CAAC,CAAC;QACjB,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;IACf,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;IACvB,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAqB,CAAC;AAClD,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAClB,IAAiB,EACjB,GAAqB,EACrB,IAAkC,EAClC,IAAkC,EAClC,MAAc,EACI,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* HMAC: RFC2104 message authentication code.
|
||||
* @module
|
||||
*/
|
||||
import { type CHash, type Hash, type TArg, type TRet } from './utils.ts';
|
||||
/**
|
||||
* Internal class for HMAC.
|
||||
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
|
||||
* `HashLen` bytes long.
|
||||
*/
|
||||
export declare class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {
|
||||
oHash: T;
|
||||
iHash: T;
|
||||
blockLen: number;
|
||||
outputLen: number;
|
||||
canXOF: boolean;
|
||||
private finished;
|
||||
private destroyed;
|
||||
constructor(hash: TArg<CHash>, key: TArg<Uint8Array>);
|
||||
update(buf: TArg<Uint8Array>): this;
|
||||
digestInto(out: TArg<Uint8Array>): void;
|
||||
digest(): TRet<Uint8Array>;
|
||||
_cloneInto(to?: _HMAC<T>): _HMAC<T>;
|
||||
clone(): _HMAC<T>;
|
||||
destroy(): void;
|
||||
}
|
||||
/**
|
||||
* HMAC: RFC2104 message authentication code.
|
||||
* @param hash - function that would be used e.g. sha256
|
||||
* @param key - authentication key bytes
|
||||
* @param message - message bytes to authenticate
|
||||
* @returns Authentication tag bytes.
|
||||
* @example
|
||||
* Compute an RFC 2104 HMAC.
|
||||
* ```ts
|
||||
* import { hmac } from '@noble/hashes/hmac.js';
|
||||
* import { sha256 } from '@noble/hashes/sha2.js';
|
||||
* const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
|
||||
* ```
|
||||
*/
|
||||
type HmacFn = {
|
||||
(hash: TArg<CHash>, key: TArg<Uint8Array>, message: TArg<Uint8Array>): TRet<Uint8Array>;
|
||||
create(hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>>;
|
||||
};
|
||||
export declare const hmac: TRet<HmacFn>;
|
||||
export {};
|
||||
//# sourceMappingURL=hmac.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hmac.d.ts","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAML,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,qBAAa,KAAK,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC7D,KAAK,EAAE,CAAC,CAAC;IACT,KAAK,EAAE,CAAC,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,UAAS;IACf,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;gBAEd,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC;IAsBpD,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAKnC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAYvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;IAK1B,UAAU,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;IAcnC,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC;IAGjB,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;;;;;GAaG;AACH,KAAK,MAAM,GAAG;IACZ,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IACxF,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;CACpE,CAAC;AACF,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,MAAM,CAS1B,CAAC"}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* HMAC: RFC2104 message authentication code.
|
||||
* @module
|
||||
*/
|
||||
import { abytes, aexists, ahash, aoutput, clean, } from "./utils.js";
|
||||
/**
|
||||
* Internal class for HMAC.
|
||||
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
|
||||
* `HashLen` bytes long.
|
||||
*/
|
||||
export class _HMAC {
|
||||
oHash;
|
||||
iHash;
|
||||
blockLen;
|
||||
outputLen;
|
||||
canXOF = false;
|
||||
finished = false;
|
||||
destroyed = false;
|
||||
constructor(hash, key) {
|
||||
ahash(hash);
|
||||
abytes(key, undefined, 'key');
|
||||
this.iHash = hash.create();
|
||||
if (typeof this.iHash.update !== 'function')
|
||||
throw new Error('Expected instance of class which extends utils.Hash');
|
||||
this.blockLen = this.iHash.blockLen;
|
||||
this.outputLen = this.iHash.outputLen;
|
||||
const blockLen = this.blockLen;
|
||||
const pad = new Uint8Array(blockLen);
|
||||
// blockLen can be bigger than outputLen
|
||||
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
||||
for (let i = 0; i < pad.length; i++)
|
||||
pad[i] ^= 0x36;
|
||||
this.iHash.update(pad);
|
||||
// By doing update (processing of the first block) of the outer hash here,
|
||||
// we can re-use it between multiple calls via clone.
|
||||
this.oHash = hash.create();
|
||||
// Undo internal XOR && apply outer XOR
|
||||
for (let i = 0; i < pad.length; i++)
|
||||
pad[i] ^= 0x36 ^ 0x5c;
|
||||
this.oHash.update(pad);
|
||||
clean(pad);
|
||||
}
|
||||
update(buf) {
|
||||
aexists(this);
|
||||
this.iHash.update(buf);
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
aexists(this);
|
||||
aoutput(out, this);
|
||||
this.finished = true;
|
||||
const buf = out.subarray(0, this.outputLen);
|
||||
// Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
|
||||
// overwriting that same prefix with the final tag, leaving any oversized tail untouched.
|
||||
this.iHash.digestInto(buf);
|
||||
this.oHash.update(buf);
|
||||
this.oHash.digestInto(buf);
|
||||
this.destroy();
|
||||
}
|
||||
digest() {
|
||||
const out = new Uint8Array(this.oHash.outputLen);
|
||||
this.digestInto(out);
|
||||
return out;
|
||||
}
|
||||
_cloneInto(to) {
|
||||
// Create new instance without calling constructor since the key
|
||||
// is already in state and we don't know it.
|
||||
to ||= Object.create(Object.getPrototypeOf(this), {});
|
||||
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
||||
to = to;
|
||||
to.finished = finished;
|
||||
to.destroyed = destroyed;
|
||||
to.blockLen = blockLen;
|
||||
to.outputLen = outputLen;
|
||||
to.oHash = oHash._cloneInto(to.oHash);
|
||||
to.iHash = iHash._cloneInto(to.iHash);
|
||||
return to;
|
||||
}
|
||||
clone() {
|
||||
return this._cloneInto();
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
this.oHash.destroy();
|
||||
this.iHash.destroy();
|
||||
}
|
||||
}
|
||||
export const hmac = /* @__PURE__ */ (() => {
|
||||
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
||||
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
||||
return hmac_;
|
||||
})();
|
||||
//# sourceMappingURL=hmac.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,MAAM,EACN,OAAO,EACP,KAAK,EACL,OAAO,EACP,KAAK,GAKN,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,MAAM,OAAO,KAAK;IAChB,KAAK,CAAI;IACT,KAAK,CAAI;IACT,QAAQ,CAAS;IACjB,SAAS,CAAS;IAClB,MAAM,GAAG,KAAK,CAAC;IACP,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,GAAG,KAAK,CAAC;IAE1B,YAAY,IAAiB,EAAE,GAAqB;QAClD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,UAAU;YACzC,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;QACzE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC;QACrC,wCAAwC;QACxC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QAC1E,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;QACpD,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,0EAA0E;QAC1E,qDAAqD;QACrD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,uCAAuC;QACvC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,GAAG,IAAI,CAAC;QAC3D,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,KAAK,CAAC,GAAG,CAAC,CAAC;IACb,CAAC;IACD,MAAM,CAAC,GAAqB;QAC1B,OAAO,CAAC,IAAI,CAAC,CAAC;QACd,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,UAAU,CAAC,GAAqB;QAC9B,OAAO,CAAC,IAAI,CAAC,CAAC;QACd,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QAC5C,4FAA4F;QAC5F,yFAAyF;QACzF,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IACD,MAAM;QACJ,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QACrB,OAAO,GAAuB,CAAC;IACjC,CAAC;IACD,UAAU,CAAC,EAAa;QACtB,gEAAgE;QAChE,4CAA4C;QAC5C,EAAE,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;QACtD,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACxE,EAAE,GAAG,EAAU,CAAC;QAChB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACvB,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;QACzB,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAoBD,MAAM,CAAC,MAAM,IAAI,GAAiB,eAAe,CAAC,CAAC,GAAG,EAAE;IACtD,MAAM,KAAK,GAAG,CAAC,CACb,IAAiB,EACjB,GAAqB,EACrB,OAAyB,EACP,EAAE,CAAC,IAAI,KAAK,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAiB,CAAC;IAC3F,KAAK,CAAC,MAAM,GAAG,CAAC,IAAiB,EAAE,GAAqB,EAAoB,EAAE,CAC5E,IAAI,KAAK,CAAM,IAAI,EAAE,GAAG,CAAqB,CAAC;IAChD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC,EAAE,CAAC"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export {};
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Audited & minimal JS implementation of hash functions, MACs, and KDFs.
|
||||
* Check out individual modules.
|
||||
* @module
|
||||
* @example
|
||||
```js
|
||||
import {
|
||||
sha256, sha384, sha512, sha224, sha512_224, sha512_256
|
||||
} from '@noble/hashes/sha2.js';
|
||||
import {
|
||||
sha3_224, sha3_256, sha3_384, sha3_512,
|
||||
keccak_224, keccak_256, keccak_384, keccak_512,
|
||||
shake128, shake256
|
||||
} from '@noble/hashes/sha3.js';
|
||||
import {
|
||||
cshake128, cshake256,
|
||||
turboshake128, turboshake256,
|
||||
kt128, kt256,
|
||||
kmac128, kmac256,
|
||||
tuplehash256, parallelhash256,
|
||||
keccakprg
|
||||
} from '@noble/hashes/sha3-addons.js';
|
||||
import { blake3 } from '@noble/hashes/blake3.js';
|
||||
import { blake2b, blake2s } from '@noble/hashes/blake2.js';
|
||||
import { hmac } from '@noble/hashes/hmac.js';
|
||||
import { hkdf } from '@noble/hashes/hkdf.js';
|
||||
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';
|
||||
import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js';
|
||||
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js';
|
||||
import * as utils from '@noble/hashes/utils.js';
|
||||
```
|
||||
*/
|
||||
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
||||
export {};
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user