first commit
This commit is contained in:
+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"}
|
||||
Reference in New Issue
Block a user