Start LibreLedger: an encrypted money ledger that stores only ciphertext

LibreLedger is a single-person money ledger. The browser encrypts
everything (PBKDF2-HMAC-SHA256 with 250k iterations, then AES-256-GCM),
and a small standard-library Python server stores only the resulting
{v, salt, iv, ct} blob. Ledger files from the earlier Money Ledger version
open unchanged.

- On plain http to a LAN or VPN address, where browsers hide Web Crypto,
  the app switches to vendored @noble/hashes and @noble/ciphers 2.2.0 and
  says so on the lock screen. tests/crypto-interop.test.mjs shows both
  paths read each other's files.
- The server hands out only the app's own files, sends a self-only CSP,
  nosniff, frame denial and no-referrer, checks the shape of each blob,
  refuses cross-site writes and writes atomically. It keeps the last 10
  backups plus one per day for 30 days.
- The container runs that server from a digest-pinned python alpine
  image, as an unprivileged user, with its data in /data and a health
  check on /api/health.

Assisted-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
LibrePortal
2026-09-17 01:17:16 +01:00
commit 2cffc3ab07
45 changed files with 11114 additions and 0 deletions
+77
View File
@@ -0,0 +1,77 @@
# Vendored crypto
LibreLedger encrypts in the browser. Where the page is a secure context
(HTTPS, `http://localhost`) it uses the browser's Web Crypto API. Where it is
not (plain `http://` to a LAN or VPN address), browsers hide `crypto.subtle`,
and `crypto-fallback.js` runs the same PBKDF2-HMAC-SHA256 and AES-256-GCM from
these files instead. They are loaded only in that case, and the server serves
only the files listed in `server.py` (`VENDOR_FILES`).
| Package | Version | Released | Licence | npm tarball integrity |
| --- | --- | --- | --- | --- |
| [@noble/hashes](https://github.com/paulmillr/noble-hashes) | 2.2.0 | 2026-04-11 | MIT | `sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==` |
| [@noble/ciphers](https://github.com/paulmillr/noble-ciphers) | 2.2.0 | 2026-04-11 | MIT | `sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==` |
Both are zero-dependency libraries by Paul Miller. Audit history, from their
READMEs: independent Cure53 audits of @noble/hashes 1.0.0 (Jan 2022) and
@noble/ciphers 1.0.0 (Sep 2024), and a self-audit of exactly 2.2.0 for both
(Apr 2026), which is why 2.2.0 is the version pinned here. The files below are **unmodified**
copies of the compiled ES modules from those tarballs, with each package's
`LICENSE`. Only the modules needed for PBKDF2-SHA256 and AES-GCM are kept.
The tarballs were checked against the integrity values above before
extracting.
## File hashes
`sha256sum`:
```
d079978bb7dac51e88586dd881ea3d7be010624b876d332f395f4a2b934f5fbc noble-ciphers-2.2.0/aes.js
f36671a5487c9c5050efacb58011c37c24c55a889803cb036cf9d9a6347c1e2d noble-ciphers-2.2.0/LICENSE
87a6cdf9cad2cec61229404cc7f8da1214952a76114b8a6342a3e771f1127cd1 noble-ciphers-2.2.0/_polyval.js
cfb9806b3339c79544a48a7026ee3c868cd1f0a1555c5eef4854b7eec43ccb63 noble-ciphers-2.2.0/utils.js
137ed94227806b351a55b09801287a4dba72d2a35d3838730becf641271bc3dd noble-hashes-2.2.0/hmac.js
4f221aee6e072336700c408c68ab3b96a3fc09f6aebe6f48f1bd99e5ef13faec noble-hashes-2.2.0/LICENSE
8227b9b5cabf078a9d7f7317f7a1ace6e46627539aa9364667aec724e1636f14 noble-hashes-2.2.0/_md.js
d61f870b99cf8e67b6df0ae5f582c74177445844d6a92ea51e8060032d05b555 noble-hashes-2.2.0/pbkdf2.js
0fb8e3c3f2c73a890be2524ac5d2542aaed4decff69e561231a86131203b3973 noble-hashes-2.2.0/sha2.js
766b91a693a798f9d3cde97b25db4a6d0cef66b2ca21153d3d42424d37878870 noble-hashes-2.2.0/_u64.js
e2adfc13c846487feff0410bd5508a1d66f5ebadc3188f3a40a6b55449981e2f noble-hashes-2.2.0/utils.js
```
Subresource-integrity form (`sha384`):
```
sha384-0YHayko0KfpRNxkCNkZTuDkZIofvvDbgY4URpQALCIVKUglJYgnGQ4qGfXFFzXe8 noble-ciphers-2.2.0/aes.js
sha384-RCB3oUufLSfqmAfe/Csz1PRWhjGYjVj48y1X4s/XpyPQk1Bcd2Pa54pZCBo+u7O1 noble-ciphers-2.2.0/LICENSE
sha384-IHfhTh3OeAiHoY7cB8F9YUBJ9rn6RieetfuNQZY75cIgd5UcjVqOCh6ssn0gIGed noble-ciphers-2.2.0/_polyval.js
sha384-VZAiMxOScRfdOr1e2+N5h6GRH5I1mBeWGL1BSjmYLB9VuR/ODNHxvqbMzPIvwwXV noble-ciphers-2.2.0/utils.js
sha384-jjTbQ/7iXpfi7CA4vLI8VW2ljCxeMnfWE6FYpgMrpYgpT+IKKDJLplkP3KlaqLXp noble-hashes-2.2.0/hmac.js
sha384-a19tauEwIs1iP+2eFZxRsChHXNFBtRprDPX8zuYyn/tuG+DeZzAzH1Fv/gHlGrk7 noble-hashes-2.2.0/LICENSE
sha384-cQrKviUiqTLrOSU3x5KyKb6vIptltNRJQbJGyyXy0+QCUUpOHRwOLM0JuIE//YJB noble-hashes-2.2.0/_md.js
sha384-z3+NFrFNV0hs4V5jqy3EAGPvJQAi902QeBkbt5se8GRLG02Vbdz12785sBD3H/mx noble-hashes-2.2.0/pbkdf2.js
sha384-lVYA2l9kQw+NU1uh5QaTLMkTJaFpmFJuIohWWtXdZ5Ri+AdJ+gG7dWCnv0VpvBYt noble-hashes-2.2.0/sha2.js
sha384-j/S9oLRxzt1W++wUX4Lid0ZXyDVraPlN3I5Olt/q+FBuApzg+Tk6GAjTioMmzu0G noble-hashes-2.2.0/_u64.js
sha384-eVOwgoKAAt0Ur0m4yWkKHg9hlMn4HGGrUW0PlHqEzo7hYCelwnnIejIRYCoUIbbf noble-hashes-2.2.0/utils.js
```
## Checking them yourself
```bash
for p in hashes ciphers; do
curl -sSfO "https://registry.npmjs.org/@noble/$p/-/$p-2.2.0.tgz"
echo "$p sha512-$(openssl dgst -sha512 -binary $p-2.2.0.tgz | base64 -w0)" # compare with the table
mkdir -p "$p" && tar xzf "$p-2.2.0.tgz" -C "$p"
done
for f in noble-hashes-2.2.0/*; do cmp "$f" "hashes/package/${f#*/}"; done
for f in noble-ciphers-2.2.0/*; do cmp "$f" "ciphers/package/${f#*/}"; done
```
## Updating
Pick a release that has been out for a while, verify its tarball integrity
against the npm registry, copy the same files into a new versioned folder,
update the imports in `crypto-fallback.js`, `VENDOR_FILES` in `server.py` and
this file, then run `tests/crypto-interop.test.mjs`. The modules still carry
their `//# sourceMappingURL` comments; the maps are not shipped, so a browser's
developer tools may note a missing map, which is harmless.
+22
View File
@@ -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.
+330
View File
@@ -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
+1765
View File
File diff suppressed because it is too large Load Diff
+807
View File
@@ -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
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+202
View File
@@ -0,0 +1,202 @@
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
import { abytes, aexists, aoutput, clean, createView, } from "./utils.js";
/**
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
* Returns bits from `b` when `a` is set, otherwise from `c`.
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
* set the same bit.
* @param a - selector word
* @param b - word chosen when selector bit is set
* @param c - word chosen when selector bit is clear
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit choice primitive.
* ```ts
* Chi(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Chi(a, b, c) {
return (a & b) ^ (~a & c);
}
/**
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
* Returns bits shared by at least two inputs.
* @param a - first input word
* @param b - second input word
* @param c - third input word
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit majority primitive.
* ```ts
* Maj(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Maj(a, b, c) {
return (a & b) ^ (a & c) ^ (b & c);
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
* strings with partial-byte tails.
* @param blockLen - internal block size in bytes
* @param outputLen - digest size in bytes
* @param padOffset - trailing length field size in bytes
* @param isLE - whether length and state words are encoded in little-endian
* @example
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
* ```ts
* import { _SHA1 } from '@noble/hashes/legacy.js';
* const hash = new _SHA1();
* hash.update(new Uint8Array([97, 98, 99]));
* hash.digest();
* ```
*/
export class HashMD {
blockLen;
outputLen;
canXOF = false;
padOffset;
isLE;
// For partial updates less than block size
buffer;
view;
finished = false;
length = 0;
pos = 0;
destroyed = false;
constructor(blockLen, outputLen, padOffset, isLE) {
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
aexists(this);
abytes(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path only when there is no buffered partial block: `take === blockLen` implies
// `this.pos === 0`, so we can process full blocks directly from the input view.
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
clean(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
// the padding fill above, and JS will overflow before user input can make that half non-zero.
// So we only need to write the low 64 bits here.
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
if (len % 4)
throw new Error('_sha2: outputLen must be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
// fresh bytes to the caller.
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to ||= new this.constructor();
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
}
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
* it as read-only because constructors copy words from it by index. */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
* treat it as read-only because constructors copy words from it by index. */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
* because constructors copy halves from it by index. */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
* constructors copy halves from it by index. */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map
+84
View File
@@ -0,0 +1,84 @@
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
// }` to match little-endian word order rather than the property names.
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS
// bitwise results back to uint32 first, and little-endian callers must swap.
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
const shrSH = (h, _l, s) => h >>> s;
// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
const rotr32H = (_h, l) => l;
// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
const rotr32L = (h, _l) => h;
// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// Add two split 64-bit words and return the split `{ h, l }` sum.
// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
// of the low sum and instead use division.
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// Canonical grouped namespace for callers that prefer one object.
// Named exports stay for direct imports.
// prettier-ignore
const u64 = {
fromBig, split, toBig,
shrSH, shrSL,
rotrSH, rotrSL, rotrBH, rotrBL,
rotr32H, rotr32L,
rotlSH, rotlSL, rotlBH, rotlBL,
add, add3L, add3H, add4L, add4H, add5H, add5L,
};
// Default export mirrors named `u64` for compatibility with object-style imports.
export default u64;
//# sourceMappingURL=_u64.js.map
+93
View File
@@ -0,0 +1,93 @@
/**
* HMAC: RFC2104 message authentication code.
* @module
*/
import { abytes, aexists, ahash, aoutput, clean, } from "./utils.js";
/**
* Internal class for HMAC.
* Accepts any byte key, although RFC 2104 §3 recommends keys at least
* `HashLen` bytes long.
*/
export class _HMAC {
oHash;
iHash;
blockLen;
outputLen;
canXOF = false;
finished = false;
destroyed = false;
constructor(hash, key) {
ahash(hash);
abytes(key, undefined, 'key');
this.iHash = hash.create();
if (typeof this.iHash.update !== 'function')
throw new Error('Expected instance of class which extends utils.Hash');
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
// blockLen can be bigger than outputLen
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36;
this.iHash.update(pad);
// By doing update (processing of the first block) of the outer hash here,
// we can re-use it between multiple calls via clone.
this.oHash = hash.create();
// Undo internal XOR && apply outer XOR
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36 ^ 0x5c;
this.oHash.update(pad);
clean(pad);
}
update(buf) {
aexists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const buf = out.subarray(0, this.outputLen);
// Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
// overwriting that same prefix with the final tag, leaving any oversized tail untouched.
this.iHash.digestInto(buf);
this.oHash.update(buf);
this.oHash.digestInto(buf);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
// Create new instance without calling constructor since the key
// is already in state and we don't know it.
to ||= Object.create(Object.getPrototypeOf(this), {});
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
clone() {
return this._cloneInto();
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
export const hmac = /* @__PURE__ */ (() => {
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
hmac_.create = (hash, key) => new _HMAC(hash, key);
return hmac_;
})();
//# sourceMappingURL=hmac.js.map
+135
View File
@@ -0,0 +1,135 @@
/**
* PBKDF (RFC 2898). Can be used to create a key from password and salt.
* @module
*/
import { hmac } from "./hmac.js";
// prettier-ignore
import { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from "./utils.js";
// Common start and end for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
ahash(hash);
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
const { c, dkLen, asyncTick } = opts;
anumber(c, 'c');
anumber(dkLen, 'dkLen');
anumber(asyncTick, 'asyncTick');
if (c < 1)
throw new Error('iterations (c) must be >= 1');
// RFC 8018 §5.2 defines `dkLen` as "a positive integer".
if (dkLen < 1)
throw new Error('"dkLen" must be >= 1');
// RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen`
// before allocating the destination buffer.
if (dkLen > (2 ** 32 - 1) * hash.outputLen)
throw new Error('derived key too long');
const password = kdfInputToBytes(_password, 'password');
const salt = kdfInputToBytes(_salt, 'salt');
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
const DK = new Uint8Array(dkLen);
// U1 = PRF(Password, Salt + INT_32_BE(i))
const PRF = hmac.create(hash, password);
// Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).
const PRFSalt = PRF._cloneInto().update(salt);
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
// Shared sync/async cleanup point: wipe transient PRF state
// while preserving the derived key buffer.
PRF.destroy();
PRFSalt.destroy();
if (prfW)
prfW.destroy();
clean(u);
return DK;
}
/**
* PBKDF2-HMAC: RFC 8018 key derivation function.
* @param hash - hash function that would be used e.g. sha256
* @param password - password from which a derived key is generated;
* JS string inputs are UTF-8 encoded first
* @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
* @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
* must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.
* @returns Derived key bytes.
* @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
* @example
* PBKDF2-HMAC: RFC 2898 key derivation function.
* ```ts
* import { pbkdf2 } from '@noble/hashes/pbkdf2.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
* ```
*/
export function pbkdf2(hash, password, salt, opts) {
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
let prfW; // Working copy
const arr = new Uint8Array(4);
const view = createView(arr);
const u = new Uint8Array(PRF.outputLen);
// DK = T1 + T2 + ⋯ + Tdklen/hlen
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
// Ti = F(Password, Salt, c, i)
// The last Ti view can be shorter than hLen, which applies
// RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
// U1 = PRF(Password, Salt + INT_32_BE(i))
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
for (let ui = 1; ui < c; ui++) {
// Uc = PRF(Password, Uc1)
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
}
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
/**
* PBKDF2-HMAC: RFC 8018 key derivation function. Async version.
* @param hash - hash function that would be used e.g. sha256
* @param password - password from which a derived key is generated;
* JS string inputs are UTF-8 encoded first
* @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
* @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
* must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local
* scheduler-yield knob for this JS wrapper, not part of RFC 8018.
* See {@link Pbkdf2Opt}.
* @returns Promise resolving to derived key bytes.
* @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
* @example
* PBKDF2-HMAC: RFC 2898 key derivation function.
* ```ts
* import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
* ```
*/
export async function pbkdf2Async(hash, password, salt, opts) {
const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
let prfW; // Working copy
const arr = new Uint8Array(4);
const view = createView(arr);
const u = new Uint8Array(PRF.outputLen);
// DK = T1 + T2 + ⋯ + Tdklen/hlen
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
// Ti = F(Password, Salt, c, i)
// The last Ti view can be shorter than hLen, which applies
// RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
// U1 = PRF(Password, Salt + INT_32_BE(i))
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
await asyncLoop(c - 1, asyncTick, () => {
// Uc = PRF(Password, Uc1)
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
});
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//# sourceMappingURL=pbkdf2.js.map
+458
View File
@@ -0,0 +1,458 @@
/**
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
* @module
*/
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, oidNist, rotr } from "./utils.js";
/**
* SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
* of the cube roots of the first 64 primes (2..311).
*/
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
class SHA2_32B extends HashMD {
constructor(outputLen) {
super(64, outputLen, 8, false);
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
}
// Compression function main loop, 64 rounds
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
const T2 = (sigma0 + Maj(A, B, C)) | 0;
H = G;
G = F;
F = E;
E = (D + T1) | 0;
D = C;
C = B;
B = A;
A = (T1 + T2) | 0;
}
// Add the compressed chunk to the current hash value
A = (A + this.A) | 0;
B = (B + this.B) | 0;
C = (C + this.C) | 0;
D = (D + this.D) | 0;
E = (E + this.E) | 0;
F = (F + this.F) | 0;
G = (G + this.G) | 0;
H = (H + this.H) | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
clean(SHA256_W);
}
destroy() {
// HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
// update()/digest() callable on reused instances.
this.destroyed = true;
this.set(0, 0, 0, 0, 0, 0, 0, 0);
clean(this.buffer);
}
}
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
export class _SHA256 extends SHA2_32B {
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
A = SHA256_IV[0] | 0;
B = SHA256_IV[1] | 0;
C = SHA256_IV[2] | 0;
D = SHA256_IV[3] | 0;
E = SHA256_IV[4] | 0;
F = SHA256_IV[5] | 0;
G = SHA256_IV[6] | 0;
H = SHA256_IV[7] | 0;
constructor() {
super(32);
}
}
/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */
export class _SHA224 extends SHA2_32B {
A = SHA224_IV[0] | 0;
B = SHA224_IV[1] | 0;
C = SHA224_IV[2] | 0;
D = SHA224_IV[3] | 0;
E = SHA224_IV[4] | 0;
F = SHA224_IV[5] | 0;
G = SHA224_IV[6] | 0;
H = SHA224_IV[7] | 0;
constructor() {
super(28);
}
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:
// 80 full 64-bit words split into high/low halves.
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
'0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
'0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
'0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
'0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
'0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
'0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
'0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
'0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
'0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
'0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
'0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
'0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
'0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
'0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
'0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
'0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
'0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
'0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
'0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
'0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
class SHA2_64B extends HashMD {
constructor(outputLen) {
super(128, outputLen, 16, false);
}
// prettier-ignore
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
// Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32((offset += 4));
}
for (let i = 16; i < 80; i++) {
// s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
// s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
// SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];
const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
// Compression function main loop, 80 rounds
for (let i = 0; i < 80; i++) {
// S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
//const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
const CHIh = (Eh & Fh) ^ (~Eh & Gh);
const CHIl = (El & Fl) ^ (~El & Gl);
// T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
// prettier-ignore
const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
// S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = u64.add3L(T1l, sigma0l, MAJl);
Ah = u64.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
// Add the compressed chunk to the current hash value
({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
clean(SHA512_W_H, SHA512_W_L);
}
destroy() {
// HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
// update()/digest() callable on reused instances.
this.destroyed = true;
clean(this.buffer);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
export class _SHA512 extends SHA2_64B {
Ah = SHA512_IV[0] | 0;
Al = SHA512_IV[1] | 0;
Bh = SHA512_IV[2] | 0;
Bl = SHA512_IV[3] | 0;
Ch = SHA512_IV[4] | 0;
Cl = SHA512_IV[5] | 0;
Dh = SHA512_IV[6] | 0;
Dl = SHA512_IV[7] | 0;
Eh = SHA512_IV[8] | 0;
El = SHA512_IV[9] | 0;
Fh = SHA512_IV[10] | 0;
Fl = SHA512_IV[11] | 0;
Gh = SHA512_IV[12] | 0;
Gl = SHA512_IV[13] | 0;
Hh = SHA512_IV[14] | 0;
Hl = SHA512_IV[15] | 0;
constructor() {
super(64);
}
}
/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */
export class _SHA384 extends SHA2_64B {
Ah = SHA384_IV[0] | 0;
Al = SHA384_IV[1] | 0;
Bh = SHA384_IV[2] | 0;
Bl = SHA384_IV[3] | 0;
Ch = SHA384_IV[4] | 0;
Cl = SHA384_IV[5] | 0;
Dh = SHA384_IV[6] | 0;
Dl = SHA384_IV[7] | 0;
Eh = SHA384_IV[8] | 0;
El = SHA384_IV[9] | 0;
Fh = SHA384_IV[10] | 0;
Fl = SHA384_IV[11] | 0;
Gh = SHA384_IV[12] | 0;
Gl = SHA384_IV[13] | 0;
Hh = SHA384_IV[14] | 0;
Hl = SHA384_IV[15] | 0;
constructor() {
super(48);
}
}
/**
* Truncated SHA512/256 and SHA512/224.
* SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
* Then t hashes string to produce result IV.
* See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.
* These IV literals are checked against that script rather than a dedicated
* local RFC section.
*/
/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and
* stored as sixteen big-endian 32-bit halves. */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and
* stored as sixteen big-endian 32-bit halves. */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared
* RFC 6234 §6.4 compression engine. */
export class _SHA512_224 extends SHA2_64B {
Ah = T224_IV[0] | 0;
Al = T224_IV[1] | 0;
Bh = T224_IV[2] | 0;
Bl = T224_IV[3] | 0;
Ch = T224_IV[4] | 0;
Cl = T224_IV[5] | 0;
Dh = T224_IV[6] | 0;
Dl = T224_IV[7] | 0;
Eh = T224_IV[8] | 0;
El = T224_IV[9] | 0;
Fh = T224_IV[10] | 0;
Fl = T224_IV[11] | 0;
Gh = T224_IV[12] | 0;
Gl = T224_IV[13] | 0;
Hh = T224_IV[14] | 0;
Hl = T224_IV[15] | 0;
constructor() {
super(28);
}
}
/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared
* RFC 6234 §6.4 compression engine. */
export class _SHA512_256 extends SHA2_64B {
Ah = T256_IV[0] | 0;
Al = T256_IV[1] | 0;
Bh = T256_IV[2] | 0;
Bl = T256_IV[3] | 0;
Ch = T256_IV[4] | 0;
Cl = T256_IV[5] | 0;
Dh = T256_IV[6] | 0;
Dl = T256_IV[7] | 0;
Eh = T256_IV[8] | 0;
El = T256_IV[9] | 0;
Fh = T256_IV[10] | 0;
Fl = T256_IV[11] | 0;
Gh = T256_IV[12] | 0;
Gl = T256_IV[13] | 0;
Hh = T256_IV[14] | 0;
Hl = T256_IV[15] | 0;
constructor() {
super(32);
}
}
/**
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
*
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
* - Each sha256 hash is executing 2^18 bit operations.
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-256.
* ```ts
* sha256(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
/* @__PURE__ */ oidNist(0x01));
/**
* SHA2-224 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-224.
* ```ts
* sha224(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(),
/* @__PURE__ */ oidNist(0x04));
/**
* SHA2-512 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512.
* ```ts
* sha512(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(),
/* @__PURE__ */ oidNist(0x03));
/**
* SHA2-384 hash function from RFC 4634.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-384.
* ```ts
* sha384(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(),
/* @__PURE__ */ oidNist(0x02));
/**
* SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512/256.
* ```ts
* sha512_256(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(),
/* @__PURE__ */ oidNist(0x06));
/**
* SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
* @param msg - message bytes to hash
* @returns Digest bytes.
* @example
* Hash a message with SHA2-512/224.
* ```ts
* sha512_224(new Uint8Array([97, 98, 99]));
* ```
*/
export const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(),
/* @__PURE__ */ oidNist(0x05));
//# sourceMappingURL=sha2.js.map
+578
View File
@@ -0,0 +1,578 @@
/**
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
* @param a - value to test
* @returns `true` when the value is a Uint8Array-compatible view.
* @example
* Check whether a value is a Uint8Array-compatible view.
* ```ts
* isBytes(new Uint8Array([1, 2, 3]));
* ```
*/
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 a non-negative integer.
* @param n - number to validate
* @param title - label included in thrown errors
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Validate a non-negative integer option.
* ```ts
* anumber(32, 'length');
* ```
*/
export function anumber(n, title = '') {
if (typeof n !== 'number') {
const prefix = title && `"${title}" `;
throw new TypeError(`${prefix}expected number, got ${typeof n}`);
}
if (!Number.isSafeInteger(n) || n < 0) {
const prefix = title && `"${title}" `;
throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
}
}
/**
* Asserts something is Uint8Array.
* @param value - value to validate
* @param length - optional exact length constraint
* @param title - label included in thrown errors
* @returns The validated byte array.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Validate that a value is a byte array.
* ```ts
* abytes(new Uint8Array([1, 2, 3]));
* ```
*/
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;
}
/**
* Copies bytes into a fresh Uint8Array.
* Buffer-style slices can alias the same backing store, so callers that need ownership should copy.
* @param bytes - source bytes to clone
* @returns Freshly allocated copy of `bytes`.
* @throws On wrong argument types. {@link TypeError}
* @example
* Clone a byte array before mutating it.
* ```ts
* const copy = copyBytes(new Uint8Array([1, 2, 3]));
* ```
*/
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));
}
/**
* Asserts something is a wrapped hash constructor.
* @param h - hash constructor to validate
* @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
* @throws On invalid hash metadata ranges or values. {@link RangeError}
* @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
* @example
* Validate a callable hash wrapper.
* ```ts
* import { ahash } from '@noble/hashes/utils.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* ahash(sha256);
* ```
*/
export function ahash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new TypeError('Hash must wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
// HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
// validation and can produce empty outputs instead of failing fast.
if (h.outputLen < 1)
throw new Error('"outputLen" must be >= 1');
if (h.blockLen < 1)
throw new Error('"blockLen" must be >= 1');
}
/**
* Asserts a hash instance has not been destroyed or finished.
* @param instance - hash instance to validate
* @param checkFinished - whether to reject finalized instances
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
* @example
* Validate that a hash instance is still usable.
* ```ts
* import { aexists } from '@noble/hashes/utils.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* const hash = sha256.create();
* aexists(hash);
* ```
*/
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 sufficiently-sized byte array.
* @param out - destination buffer
* @param instance - hash instance providing output length
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @example
* Validate a caller-provided digest buffer.
* ```ts
* import { aoutput } from '@noble/hashes/utils.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* const hash = sha256.create();
* aoutput(new Uint8Array(hash.outputLen), hash);
* ```
*/
export function aoutput(out, instance) {
abytes(out, undefined, 'digestInto() output');
const min = instance.outputLen;
if (out.length < min) {
throw new RangeError('"digestInto() output" expected to be of length >=' + min);
}
}
/**
* Casts a typed array view to Uint8Array.
* @param arr - source typed array
* @returns Uint8Array view over the same buffer.
* @example
* Reinterpret a typed array as bytes.
* ```ts
* u8(new Uint32Array([1, 2]));
* ```
*/
export function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/**
* Casts a typed array view to Uint32Array.
* `arr.byteOffset` must already be 4-byte aligned or the platform
* Uint32Array constructor will throw.
* @param arr - source typed array
* @returns Uint32Array view over the same buffer.
* @example
* Reinterpret a byte array as 32-bit words.
* ```ts
* u32(new Uint8Array(8));
* ```
*/
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 overwrite with zeros
* @example
* Zeroize sensitive buffers in place.
* ```ts
* clean(new Uint8Array([1, 2, 3]));
* ```
*/
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 - source typed array
* @returns DataView over the same buffer region.
* @example
* Create a DataView over an existing buffer.
* ```ts
* createView(new Uint8Array(4));
* ```
*/
export function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/**
* Rotate-right operation for uint32 values.
* @param word - source word
* @param shift - shift amount in bits
* @returns Rotated word.
* @example
* Rotate a 32-bit word to the right.
* ```ts
* rotr(0x12345678, 8);
* ```
*/
export function rotr(word, shift) {
return (word << (32 - shift)) | (word >>> shift);
}
/**
* Rotate-left operation for uint32 values.
* @param word - source word
* @param shift - shift amount in bits
* @returns Rotated word.
* @example
* Rotate a 32-bit word to the left.
* ```ts
* rotl(0x12345678, 8);
* ```
*/
export function rotl(word, shift) {
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Whether the current platform is little-endian. */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/**
* Byte-swap operation for uint32 values.
* @param word - source word
* @returns Word with reversed byte order.
* @example
* Reverse the byte order of a 32-bit word.
* ```ts
* byteSwap(0x11223344);
* ```
*/
export function byteSwap(word) {
return (((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff));
}
/**
* Conditionally byte-swaps one 32-bit word on big-endian platforms.
* @param n - source word
* @returns Original or byte-swapped word depending on platform endianness.
* @example
* Normalize a 32-bit word for host endianness.
* ```ts
* swap8IfBE(0x11223344);
* ```
*/
export const swap8IfBE = isLE
? (n) => n
: (n) => byteSwap(n) >>> 0;
/**
* Byte-swaps every word of a Uint32Array in place.
* @param arr - array to mutate
* @returns The same array after mutation; callers pass live state arrays here.
* @example
* Reverse the byte order of every word in place.
* ```ts
* byteSwap32(new Uint32Array([0x11223344]));
* ```
*/
export function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap(arr[i]);
}
return arr;
}
/**
* Conditionally byte-swaps a Uint32Array on big-endian platforms.
* @param u - array to normalize for host endianness
* @returns Original or byte-swapped array depending on platform endianness.
* On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
* @example
* Normalize a word array for host endianness.
* ```ts
* swap32IfBE(new Uint32Array([0x11223344]));
* ```
*/
export const swap32IfBE = isLE
? (u) => u
: byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
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 the built-in function when available and assumes it matches the tested
* fallback semantics.
* @param bytes - bytes to encode
* @returns Lowercase hexadecimal string.
* @throws On wrong argument types. {@link TypeError}
* @example
* Convert bytes to lowercase hexadecimal.
* ```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 wrong argument ranges or values. {@link RangeError}
* @example
* Decode lowercase hexadecimal 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;
}
/**
* There is no setImmediate in browser and setTimeout is slow.
* This yields to the Promise/microtask scheduler queue, not to timers or the
* full macrotask event loop.
* @example
* Yield to the next scheduler tick.
* ```ts
* await nextTick();
* ```
*/
export const nextTick = async () => { };
/**
* Returns control to the Promise/microtask scheduler every `tick`
* milliseconds to avoid blocking long loops.
* @param iters - number of loop iterations to run
* @param tick - maximum time slice in milliseconds
* @param cb - callback executed on each iteration
* @example
* Run a loop that periodically yields back to the event loop.
* ```ts
* await asyncLoop(2, 0, () => {});
* ```
*/
export async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await nextTick();
ts += diff;
}
}
/**
* Converts string to bytes using UTF8 encoding.
* Built-in doesn't validate input to be string: we do the check.
* Non-ASCII details are delegated to the platform `TextEncoder`.
* @param str - string to encode
* @returns UTF-8 encoded bytes.
* @throws On wrong argument types. {@link TypeError}
* @example
* Encode a string as UTF-8 bytes.
* ```ts
* utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
* ```
*/
export function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new TypeError('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Helper for KDFs: consumes Uint8Array or string.
* String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
* @param data - user-provided KDF input
* @param errorTitle - label included in thrown errors
* @returns Byte representation of the input.
* @throws On wrong argument types. {@link TypeError}
* @example
* Normalize KDF input to bytes.
* ```ts
* kdfInputToBytes('password');
* ```
*/
export function kdfInputToBytes(data, errorTitle = '') {
if (typeof data === 'string')
return utf8ToBytes(data);
return abytes(data, undefined, errorTitle);
}
/**
* Copies several Uint8Arrays into one.
* @param arrays - arrays to concatenate
* @returns Concatenated byte array.
* @throws On wrong argument types. {@link TypeError}
* @example
* Concatenate multiple byte arrays.
* ```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 default options and passed options.
* @param defaults - base option object
* @param opts - user overrides
* @returns Merged option object. The merge mutates `defaults` in place.
* @throws On wrong argument types. {@link TypeError}
* @example
* Merge user overrides onto default options.
* ```ts
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
* ```
*/
export function checkOpts(defaults, opts) {
if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
throw new TypeError('options must be object or undefined');
const merged = Object.assign(defaults, opts);
return merged;
}
/**
* Creates a callable hash function from a stateful class constructor.
* @param hashCons - hash constructor or factory
* @param info - optional metadata such as DER OID
* @returns Frozen callable hash wrapper with `.create()`.
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
* `outputLen` / `blockLen`, so constructor side effects happen at module
* init time.
* @example
* Wrap a stateful hash constructor into a callable helper.
* ```ts
* import { createHasher } from '@noble/hashes/utils.js';
* import { sha256 } from '@noble/hashes/sha2.js';
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
* wrapped(new Uint8Array([1]));
* ```
*/
export function createHasher(hashCons, info = {}) {
const hashC = (msg, opts) => hashCons(opts)
.update(msg)
.digest();
const tmp = hashCons(undefined);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.canXOF = tmp.canXOF;
hashC.create = (opts) => hashCons(opts);
Object.assign(hashC, info);
return Object.freeze(hashC);
}
/**
* Cryptographically secure PRNG backed by `crypto.getRandomValues`.
* @param bytesLength - number of random bytes to generate
* @returns Random bytes.
* The platform `getRandomValues()` implementation still defines any
* single-call length cap, and this helper rejects oversize requests
* with a stable library `RangeError` instead of host-specific errors.
* @throws On wrong argument types. {@link TypeError}
* @throws On wrong argument ranges or values. {@link RangeError}
* @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
* @example
* Generate a fresh random key or nonce.
* ```ts
* const key = randomBytes(16);
* ```
*/
export function randomBytes(bytesLength = 32) {
// Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
anumber(bytesLength, 'bytesLength');
const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
if (typeof cr?.getRandomValues !== 'function')
throw new Error('crypto.getRandomValues must be defined');
// Web Cryptography API Level 2 §10.1.1:
// if `byteLength > 65536`, throw `QuotaExceededError`.
// Keep the guard explicit so callers can see the quota in code
// instead of discovering it by reading the spec or host errors.
// This wrapper surfaces the same quota as a stable library RangeError.
if (bytesLength > 65536)
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
return cr.getRandomValues(new Uint8Array(bytesLength));
}
/**
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
* @param suffix - final OID byte for the selected hash.
* The helper accepts any byte even though only the documented NIST hash
* suffixes are meaningful downstream.
* @returns Object containing the DER-encoded OID.
* @example
* Build OID metadata for a NIST hash.
* ```ts
* oidNist(0x01);
* ```
*/
export const oidNist = (suffix) => ({
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
// Larger suffix values would need base-128 OID encoding and a different length byte.
oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
});
//# sourceMappingURL=utils.js.map