mirror of
https://github.com/UneBaguette/blake3.wasm.git
synced 2026-08-08 00:00:30 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99980eff38
|
||
|
|
7fec54a9b5
|
||
|
|
5c4c776268
|
||
|
|
9911c9309f
|
||
|
|
230976664c
|
||
|
|
4570d6826f
|
||
|
|
878508fbd3
|
||
|
|
35dbf0f97e
|
||
|
|
08e01269bc
|
||
|
|
a0e262bf02
|
||
|
|
55db5a6575
|
@@ -1,2 +0,0 @@
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
@@ -30,4 +30,4 @@ jobs:
|
||||
run: cargo test
|
||||
|
||||
- name: WASM tests (Node)
|
||||
run: wasm-pack test --node
|
||||
run: wasm-pack test --node --features wasm,talc
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: [ "v*" ]
|
||||
release:
|
||||
types: [ published ]
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -12,6 +16,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
@@ -35,15 +40,15 @@ jobs:
|
||||
run: cargo test
|
||||
|
||||
- name: WASM tests (Node)
|
||||
run: wasm-pack test --node
|
||||
run: wasm-pack test --node --features wasm,talc
|
||||
|
||||
- name: Build package
|
||||
run: make
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > pkg/.npmrc
|
||||
echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > ~/.npmrc
|
||||
cd pkg
|
||||
npm publish --access public
|
||||
npm publish --access public --provenance
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
Generated
+1
-1
@@ -53,7 +53,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "blake3-wasm-rs"
|
||||
version = "0.1.4"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"hex",
|
||||
|
||||
+8
-6
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "blake3-wasm-rs"
|
||||
version = "0.1.4"
|
||||
version = "0.6.1"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
authors = ["UneBaguette <[email protected]>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
authors = ["Thomas <[email protected]>"]
|
||||
publish = false
|
||||
repository = "https://github.com/UneBaguette/blake3.wasm"
|
||||
description = "Simple blake3 to wasm project"
|
||||
description = "BLAKE3 hashing with optional WASM bindings"
|
||||
keywords = ["blake3", "wasm", "hash", "cryptography", "wasm-bindgen"]
|
||||
categories = ["cryptography", "wasm"]
|
||||
|
||||
@@ -14,11 +14,13 @@ categories = ["cryptography", "wasm"]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
wasm = ["dep:wasm-bindgen"]
|
||||
talc = ["dep:talc"]
|
||||
|
||||
[dependencies]
|
||||
blake3 = { version = "1.8", features = ["wasm32_simd"] }
|
||||
wasm-bindgen = "=0.2.118"
|
||||
blake3 = { version = "1", features = ["wasm32_simd"] }
|
||||
wasm-bindgen = { version = "=0.2.118", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 UneBaguette
|
||||
Copyright (c) 2026 Thomas <tom@unebaguette.fr>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -19,4 +19,3 @@ 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.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
ROOT := pkg
|
||||
CRATE := blake3_wasm_rs
|
||||
VERSION := 0.4.0
|
||||
VERSION := $(shell grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)"/\1/')
|
||||
|
||||
CARGO := cargo
|
||||
WASM_BINDGEN := wasm-bindgen
|
||||
WASM_OPT := wasm-opt
|
||||
WASM_OPT_FLAGS := --enable-bulk-memory --enable-nontrapping-float-to-int -O
|
||||
WASM_OPT_FLAGS := --enable-bulk-memory --enable-nontrapping-float-to-int -O3
|
||||
WASM_TARGET := wasm32-unknown-unknown
|
||||
TARGET_DIR := target/$(WASM_TARGET)/release
|
||||
|
||||
@@ -20,7 +20,7 @@ build: build-all node-esm
|
||||
|
||||
build-all:
|
||||
@echo "Building all target..."
|
||||
RUSTFLAGS='-C opt-level=s' $(CARGO) build --target $(WASM_TARGET) --release --features talc
|
||||
RUSTFLAGS='-C opt-level=3 -C target-feature=+simd128' $(CARGO) build --target $(WASM_TARGET) --release --features wasm,talc
|
||||
@mkdir -p $(ROOT)/bundler $(ROOT)/web $(ROOT)/node
|
||||
$(WASM_BINDGEN) --target bundler --out-dir $(ROOT)/bundler $(TARGET_DIR)/$(CRATE).wasm
|
||||
$(WASM_BINDGEN) --target web --out-dir $(ROOT)/web $(TARGET_DIR)/$(CRATE).wasm
|
||||
@@ -34,9 +34,10 @@ build-all:
|
||||
@echo '{"type":"commonjs"}' > $(ROOT)/node/package.json
|
||||
@cp scripts/tpl/index.js.template $(ROOT)/index.js
|
||||
@cp scripts/tpl/index.d.ts $(ROOT)/index.d.ts
|
||||
@cp scripts/tpl/README.md $(ROOT)/README.md
|
||||
@cp LICENSE $(ROOT)/LICENSE
|
||||
@sed -i 's|// @ts-nocheck|// Types|' $(ROOT)/index.d.ts
|
||||
@cp README.md $(ROOT)/README.md
|
||||
@cp LICENSE-MIT $(ROOT)/LICENSE-MIT
|
||||
@cp LICENSE-APACHE $(ROOT)/LICENSE-APACHE
|
||||
@sed -i 's|// @ts-nocheck||' $(ROOT)/index.d.ts
|
||||
@node -e "\
|
||||
const pkg = {\
|
||||
name: 'blake3-wasm-rs',\
|
||||
@@ -48,11 +49,12 @@ build-all:
|
||||
main: 'index.js',\
|
||||
types: 'index.d.ts',\
|
||||
exports: { '.': {\
|
||||
types: './index.d.ts',\
|
||||
node: { require: './node/$(CRATE).js', import: './node-esm/index.mjs' },\
|
||||
import: './bundler/$(CRATE).js',\
|
||||
default: './web/$(CRATE).js'\
|
||||
}},\
|
||||
files: ['bundler/', 'web/', 'node/', 'node-esm/', '$(CRATE)_bg.wasm', 'README.md', 'LICENSE'],\
|
||||
files: ['bundler/', 'web/', 'node/', 'node-esm/', 'index.js', 'index.d.ts', '$(CRATE)_bg.wasm', 'README.md', 'LICENSE'],\
|
||||
keywords: ['blake3', 'wasm', 'hash', 'cryptography', 'wasm-bindgen']\
|
||||
};\
|
||||
require('fs').writeFileSync('./$(ROOT)/package.json', JSON.stringify(pkg, null, 2) + '\n');"
|
||||
|
||||
@@ -12,18 +12,11 @@
|
||||
```sh
|
||||
# lets build it!
|
||||
|
||||
# For NodeJS
|
||||
wasm-pack build --target nodejs --release
|
||||
# normal
|
||||
make build
|
||||
|
||||
# For the web!
|
||||
wasm-pack build --target web --release
|
||||
```
|
||||
|
||||
SIMD is enabled via `wasm32_simd` feature in `Cargo.toml` and requires:
|
||||
```toml
|
||||
# .cargo/config.toml
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
# clean
|
||||
make
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -171,11 +164,11 @@ Tested on **Ryzen 7 5800X**, Node.js v24.
|
||||
|
||||
| Size | @noble/hashes | awasm-noble | awasm-noble (threads) | blake3-wasm |
|
||||
|-------|---------------|-------------|-----------------------|-------------|
|
||||
| 32 B | 11 MB/s | 34 MB/s | 45 MB/s | 70 MB/s |
|
||||
| 1 KB | 56 MB/s | 499 MB/s | 526 MB/s | 885 MB/s |
|
||||
| 64 KB | 52 MB/s | 1,729 MB/s | 1,684 MB/s | 2,037 MB/s |
|
||||
| 1 MB | 51 MB/s | 1,550 MB/s | 4,036 MB/s | 1,829 MB/s |
|
||||
| 10 MB | 50 MB/s | 1,497 MB/s | 4,946 MB/s | 1,877 MB/s |
|
||||
| 32 B | 11 MB/s | 34 MB/s | 45 MB/s | 86 MB/s |
|
||||
| 1 KB | 56 MB/s | 499 MB/s | 526 MB/s | 919 MB/s |
|
||||
| 64 KB | 52 MB/s | 1,729 MB/s | 1,684 MB/s | 2,067 MB/s |
|
||||
| 1 MB | 51 MB/s | 1,550 MB/s | 4,036 MB/s | 1,848 MB/s |
|
||||
| 10 MB | 50 MB/s | 1,497 MB/s | 4,946 MB/s | 1,776 MB/s |
|
||||
|
||||
## Security
|
||||
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
# blake3-wasm-rs
|
||||
|
||||
[](https://www.npmjs.com/package/blake3-wasm-rs)
|
||||
[](https://github.com/UneBaguette/blake3.wasm/actions/workflows/ci.yml)
|
||||
[](https://github.com/UneBaguette/blake3.wasm/blob/master/LICENSE)
|
||||
[](https://www.npmjs.com/package/blake3-wasm-rs)
|
||||
|
||||
**blake3-wasm-rs** is a WebAssembly port of the BLAKE3 cryptographic hash function written in **Rust**. It enables fast and secure hashing right inside **browsers** and **Node.js**.
|
||||
|
||||
## build
|
||||
|
||||
```sh
|
||||
# lets build it!
|
||||
|
||||
# For NodeJS
|
||||
wasm-pack build --target nodejs --release
|
||||
|
||||
# For the web!
|
||||
wasm-pack build --target web --release
|
||||
```
|
||||
|
||||
SIMD is enabled via `wasm32_simd` feature in `Cargo.toml` and requires:
|
||||
```toml
|
||||
# .cargo/config.toml
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import * as blake3 from 'blake3-wasm-rs';
|
||||
|
||||
const data = new TextEncoder().encode('hello world');
|
||||
const key = new Uint8Array(32).fill(1);
|
||||
|
||||
// One-shot hashing
|
||||
blake3.hash(data);
|
||||
blake3.hashXof(data, 64); // variable output length
|
||||
blake3.keyedHash(data, key); // key must be exactly 32 bytes
|
||||
blake3.deriveKey('my context', key);
|
||||
|
||||
// Conctruct for Streaming
|
||||
{
|
||||
using h = new blake3.Hasher();
|
||||
h.update(data.slice(0, 5));
|
||||
h.update(data.slice(5));
|
||||
h.finalize();
|
||||
h.finalizeXof(64);
|
||||
h.reset();
|
||||
}
|
||||
|
||||
// Streaming
|
||||
// Keyed (MAC mode)
|
||||
{
|
||||
using mac = blake3.Hasher.newKeyed(key);
|
||||
mac.update(data);
|
||||
mac.finalize();
|
||||
}
|
||||
|
||||
// Streaming
|
||||
// Key derivation mode
|
||||
{
|
||||
using kdf = blake3.Hasher.newDeriveKey('my app v1 :: subkey');
|
||||
kdf.update(key);
|
||||
kdf.finalize();
|
||||
}
|
||||
|
||||
// Batch hashing without re-allocating
|
||||
{
|
||||
using h = new blake3.Hasher();
|
||||
h.update(chunk1);
|
||||
const first = h.finalizeAndReset();
|
||||
h.update(chunk2);
|
||||
const second = h.finalizeAndReset();
|
||||
}
|
||||
```
|
||||
|
||||
#### Named imports
|
||||
|
||||
```ts
|
||||
import { hash, hashXof, keyedHash, deriveKey, Hasher } from 'blake3-wasm-rs';
|
||||
|
||||
const data = new TextEncoder().encode('hello world');
|
||||
const key = new Uint8Array(32).fill(1);
|
||||
|
||||
// One-shot hashing
|
||||
hash(data);
|
||||
hashXof(data, 64); // variable output length
|
||||
keyedHash(data, key); // key must be exactly 32 bytes
|
||||
deriveKey('my context', key);
|
||||
|
||||
// Streaming
|
||||
{
|
||||
using h = new Hasher();
|
||||
h.update(data.slice(0, 5));
|
||||
h.update(data.slice(5));
|
||||
h.finalize();
|
||||
h.finalizeXof(64);
|
||||
h.reset();
|
||||
}
|
||||
|
||||
// Keyed (MAC mode)
|
||||
{
|
||||
using mac = Hasher.newKeyed(key);
|
||||
mac.update(data);
|
||||
mac.finalize();
|
||||
}
|
||||
|
||||
// Key derivation mode
|
||||
{
|
||||
using kdf = Hasher.newDeriveKey('my app v1 :: subkey');
|
||||
kdf.update(key);
|
||||
kdf.finalize();
|
||||
}
|
||||
|
||||
// Batch hashing without re-allocating
|
||||
{
|
||||
using h = new Hasher();
|
||||
h.update(chunk1);
|
||||
const first = h.finalizeAndReset();
|
||||
h.update(chunk2);
|
||||
const second = h.finalizeAndReset();
|
||||
}
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### Functions
|
||||
|
||||
| Function | Returns | Description |
|
||||
|-----------------------------------|--------------|-------------------------------------------------|
|
||||
| `hash(data)` | `Uint8Array` | One-shot 32-byte BLAKE3 digest |
|
||||
| `hashXof(data, outLen)` | `Uint8Array` | Variable-length digest (XOF mode) |
|
||||
| `keyedHash(data, key)` | `Uint8Array` | Keyed hash / MAC (key must be exactly 32 bytes) |
|
||||
| `deriveKey(context, keyMaterial)` | `Uint8Array` | Derive a 32-byte subkey |
|
||||
|
||||
### Hasher class
|
||||
|
||||
| Method | Returns | Description |
|
||||
|--------------------------------|--------------|-----------------------------------------------------------|
|
||||
| `new Hasher()` | `Hasher` | Streaming hasher, unkeyed |
|
||||
| `Hasher.newKeyed(key)` | `Hasher` | Streaming hasher, MAC mode (key must be exactly 32 bytes) |
|
||||
| `Hasher.newDeriveKey(context)` | `Hasher` | Streaming hasher, KDF mode |
|
||||
| `.update(data)` | `void` | Feed data, can be called multiple times |
|
||||
| `.finalize()` | `Uint8Array` | 32-byte digest, non-destructive |
|
||||
| `.finalizeXof(outLen)` | `Uint8Array` | Variable-length digest, non-destructive |
|
||||
| `.finalizeAndReset()` | `Uint8Array` | Finalize then reset (useful for batch hashing) |
|
||||
| `.reset()` | `void` | Reset to initial state, preserves mode |
|
||||
| `.free()` | `void` | Release WASM memory manually (prefer `using` instead) |
|
||||
|
||||
> **Memory management:** In all modern browsers (and wasm-bindgen ≥ 0.2.91), WASM memory is freed automatically via the TC39 weak references proposal when the JS object goes out of scope.
|
||||
>
|
||||
> In practice, you often don't need to think about this. For deterministic cleanup or environments without weak reference support (older browsers, some Node.js setups), use `using` (TypeScript 5.2+ / ES2026) or call `.free()` manually.
|
||||
>
|
||||
> Never call `.free()` on a `using`-managed instance otherwise it will double-free.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Tested on **Apple M4**, Node.js v24.
|
||||
|
||||
| Size | @noble/hashes | awasm-noble | awasm-noble (threads) | blake3-wasm |
|
||||
|-------|---------------|-------------|-----------------------|-------------|
|
||||
| 32 B | 28 MB/s | 105 MB/s | 94 MB/s | 129 MB/s |
|
||||
| 1 KB | 105 MB/s | 843 MB/s | 819 MB/s | 568 MB/s |
|
||||
| 64 KB | 102 MB/s | 1,898 MB/s | 1,855 MB/s | 2,004 MB/s |
|
||||
| 1 MB | 101 MB/s | 1,943 MB/s | 4,711 MB/s | 1,893 MB/s |
|
||||
| 10 MB | 101 MB/s | 1,911 MB/s | 6,456 MB/s | 2,185 MB/s |
|
||||
|
||||
Tested on **Ryzen 7 5800X**, Node.js v24.
|
||||
|
||||
| Size | @noble/hashes | awasm-noble | awasm-noble (threads) | blake3-wasm |
|
||||
|-------|---------------|-------------|-----------------------|-------------|
|
||||
| 32 B | 11 MB/s | 34 MB/s | 45 MB/s | 70 MB/s |
|
||||
| 1 KB | 56 MB/s | 499 MB/s | 526 MB/s | 885 MB/s |
|
||||
| 64 KB | 52 MB/s | 1,729 MB/s | 1,684 MB/s | 2,037 MB/s |
|
||||
| 1 MB | 51 MB/s | 1,550 MB/s | 4,036 MB/s | 1,829 MB/s |
|
||||
| 10 MB | 50 MB/s | 1,497 MB/s | 4,946 MB/s | 1,877 MB/s |
|
||||
|
||||
## Security
|
||||
|
||||
The underlying `blake3` Rust crate targets algorithmic constant time. However, the JavaScript boundary (via napi-rs or WASM) introduces non-determinism from the V8 runtime that is outside our control. For absolute security, use the `blake3` Rust crate directly in a Rust program.
|
||||
|
||||
## See also
|
||||
|
||||
- [@noble/hashes](https://github.com/paulmillr/noble-hashes) | pure JS implementation
|
||||
- [awasm-noble](https://github.com/paulmillr/awasm-noble) | auditable WASM implementation
|
||||
- [blake3-napi](https://github.com/UneBaguette/blake3-napi) | native Node.js addon, faster for large inputs
|
||||
Vendored
+2
@@ -1,3 +1,5 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// Copyright 2026 Thomas <[email protected]>
|
||||
// @ts-nocheck
|
||||
|
||||
export { Hasher, deriveKey, hash, hashXof, keyedHash } from './bundler/blake3_wasm_rs';
|
||||
@@ -1,3 +1,6 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// Copyright 2026 Thomas <[email protected]>
|
||||
//
|
||||
// blake3-wasm-rs. Auto-generated entry point
|
||||
// Do not edit directly!
|
||||
|
||||
|
||||
+238
-62
@@ -1,4 +1,5 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
// Copyright 2026 Thomas <[email protected]>
|
||||
|
||||
#[cfg(all(
|
||||
not(target_feature = "atomics"),
|
||||
@@ -8,68 +9,79 @@ use wasm_bindgen::prelude::*;
|
||||
#[global_allocator]
|
||||
static TALC: talc::wasm::WasmDynamicTalc = talc::wasm::new_wasm_dynamic_allocator();
|
||||
|
||||
const MAX_XOF_LEN: usize = 1 << 16; // 65_536
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Blake3Error(pub String);
|
||||
|
||||
impl core::fmt::Display for Blake3Error {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Blake3Error {}
|
||||
|
||||
fn err(msg: &str) -> Blake3Error {
|
||||
Blake3Error(msg.to_string())
|
||||
}
|
||||
|
||||
fn checked_xof_len(out_len: usize) -> Result<usize, Blake3Error> {
|
||||
if out_len == 0 || out_len > MAX_XOF_LEN {
|
||||
return Err(err("out_len must be between 1 and 65536"));
|
||||
}
|
||||
|
||||
Ok(out_len)
|
||||
}
|
||||
|
||||
/// Hash data and return a 32-byte BLAKE3 digest.
|
||||
#[wasm_bindgen]
|
||||
pub fn hash(value: &[u8]) -> Vec<u8> {
|
||||
blake3::hash(value).as_bytes().to_vec()
|
||||
pub fn hash(value: &[u8]) -> [u8; 32] {
|
||||
*blake3::hash(value).as_bytes()
|
||||
}
|
||||
|
||||
/// Hash data with variable-length output (XOF mode).
|
||||
/// Returns `out_len` bytes of BLAKE3 extended output.
|
||||
#[wasm_bindgen(js_name = "hashXof")]
|
||||
pub fn hash_xof(data: &[u8], out_len: usize) -> Vec<u8> {
|
||||
pub fn hash_xof(data: &[u8], out_len: usize) -> Result<Vec<u8>, Blake3Error> {
|
||||
let out_len = checked_xof_len(out_len)?;
|
||||
let mut out = vec![0u8; out_len];
|
||||
let mut reader = blake3::Hasher::new().update(data).finalize_xof();
|
||||
|
||||
reader.fill(&mut out);
|
||||
blake3::Hasher::new()
|
||||
.update(data)
|
||||
.finalize_xof()
|
||||
.fill(&mut out);
|
||||
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Compute a keyed BLAKE3 hash (MAC). Key must be exactly 32 bytes.
|
||||
/// Throws if the key length is wrong.
|
||||
#[wasm_bindgen(js_name = "keyedHash")]
|
||||
pub fn keyed_hash(data: &[u8], key: &[u8]) -> Result<Vec<u8>, JsError> {
|
||||
pub fn keyed_hash(data: &[u8], key: &[u8]) -> Result<[u8; 32], Blake3Error> {
|
||||
let key: &[u8; 32] = key
|
||||
.try_into()
|
||||
.map_err(|_| JsError::new("key must be exactly 32 bytes"))?;
|
||||
.map_err(|_| err("key must be exactly 32 bytes"))?;
|
||||
|
||||
Ok(blake3::keyed_hash(key, data).as_bytes().to_vec())
|
||||
Ok(*blake3::keyed_hash(key, data).as_bytes())
|
||||
}
|
||||
|
||||
/// Derive a 32-byte key from a context string and key material.
|
||||
/// Context should be a hardcoded, globally unique, application-specific string.
|
||||
#[wasm_bindgen(js_name = "deriveKey")]
|
||||
pub fn derive_key(context: &str, key_material: &[u8]) -> Vec<u8> {
|
||||
blake3::derive_key(context, key_material).to_vec()
|
||||
pub fn derive_key(context: &str, key_material: &[u8]) -> [u8; 32] {
|
||||
blake3::derive_key(context, key_material)
|
||||
}
|
||||
|
||||
/// Incremental BLAKE3 hasher for streaming data.
|
||||
///
|
||||
/// ```js
|
||||
/// const hasher = new Hasher();
|
||||
/// hasher.update(chunk1);
|
||||
/// hasher.update(chunk2);
|
||||
/// const digest = hasher.finalize(); // 32 bytes
|
||||
/// ```
|
||||
#[wasm_bindgen]
|
||||
pub struct Hasher(blake3::Hasher);
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Hasher {
|
||||
/// Create a new hasher for unkeyed hashing.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Hasher(blake3::Hasher::new())
|
||||
}
|
||||
|
||||
/// Create a keyed hasher (MAC mode). Key must be exactly 32 bytes.
|
||||
/// Throws if the key length is wrong.
|
||||
#[wasm_bindgen(js_name = "newKeyed")]
|
||||
pub fn new_keyed(key: &[u8]) -> Result<Hasher, JsError> {
|
||||
pub fn new_keyed(key: &[u8]) -> Result<Hasher, Blake3Error> {
|
||||
let key: &[u8; 32] = key
|
||||
.try_into()
|
||||
.map_err(|_| JsError::new("key must be exactly 32 bytes"))?;
|
||||
.map_err(|_| err("key must be exactly 32 bytes"))?;
|
||||
|
||||
Ok(Hasher(blake3::Hasher::new_keyed(key)))
|
||||
}
|
||||
@@ -77,8 +89,7 @@ impl Hasher {
|
||||
/// Create a hasher in derive-key mode.
|
||||
/// Context should be a hardcoded, globally unique, application-specific string.
|
||||
/// Feed key material via `update()`, then call `finalize()`.
|
||||
#[wasm_bindgen(js_name = "newDeriveKey")]
|
||||
pub fn new_derive_key(context: &str) -> Hasher {
|
||||
pub fn new_derive_key(context: &str) -> Self {
|
||||
Hasher(blake3::Hasher::new_derive_key(context))
|
||||
}
|
||||
|
||||
@@ -88,24 +99,25 @@ impl Hasher {
|
||||
}
|
||||
|
||||
/// Return the 32-byte hash digest. Non-destructive. Can be called multiple times.
|
||||
pub fn finalize(&self) -> Vec<u8> {
|
||||
self.0.finalize().as_bytes().to_vec()
|
||||
pub fn finalize(&self) -> [u8; 32] {
|
||||
*self.0.finalize().as_bytes()
|
||||
}
|
||||
|
||||
/// Return `out_len` bytes of extended output (XOF mode). Non-destructive.
|
||||
#[wasm_bindgen(js_name = "finalizeXof")]
|
||||
pub fn finalize_xof(&self, out_len: usize) -> Vec<u8> {
|
||||
pub fn finalize_xof(&self, out_len: usize) -> Result<Vec<u8>, Blake3Error> {
|
||||
let out_len = checked_xof_len(out_len)?;
|
||||
let mut out = vec![0u8; out_len];
|
||||
|
||||
self.0.finalize_xof().fill(&mut out);
|
||||
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Finalize the hash and reset the hasher in one call.
|
||||
/// Useful for hashing multiple inputs sequentially without creating new instances.
|
||||
#[wasm_bindgen(js_name = "finalizeAndReset")]
|
||||
pub fn finalize_and_reset(&mut self) -> Vec<u8> {
|
||||
let out = self.0.finalize().as_bytes().to_vec();
|
||||
pub fn finalize_and_reset(&mut self) -> [u8; 32] {
|
||||
let out = *self.0.finalize().as_bytes();
|
||||
|
||||
self.0.reset();
|
||||
|
||||
out
|
||||
@@ -117,17 +129,123 @@ impl Hasher {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Hasher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wasm")]
|
||||
mod wasm {
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn hash(value: &[u8]) -> Vec<u8> {
|
||||
super::hash(value).to_vec()
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "hashXof")]
|
||||
pub fn hash_xof(data: &[u8], out_len: usize) -> Result<Vec<u8>, JsError> {
|
||||
super::hash_xof(data, out_len).map_err(|e| JsError::new(&e.0))
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "keyedHash")]
|
||||
pub fn keyed_hash(data: &[u8], key: &[u8]) -> Result<Vec<u8>, JsError> {
|
||||
super::keyed_hash(data, key)
|
||||
.map(|h| h.to_vec())
|
||||
.map_err(|e| JsError::new(&e.0))
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = "deriveKey")]
|
||||
pub fn derive_key(context: &str, key_material: &[u8]) -> Vec<u8> {
|
||||
super::derive_key(context, key_material).to_vec()
|
||||
}
|
||||
|
||||
/// Incremental BLAKE3 hasher for streaming data.
|
||||
///
|
||||
/// ```js
|
||||
/// const hasher = new Hasher();
|
||||
/// hasher.update(chunk1);
|
||||
/// hasher.update(chunk2);
|
||||
/// const digest = hasher.finalize(); // 32 bytes
|
||||
/// ```
|
||||
#[wasm_bindgen]
|
||||
pub struct Hasher(blake3::Hasher);
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Hasher {
|
||||
/// Create a new hasher for unkeyed hashing.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Hasher(blake3::Hasher::new())
|
||||
}
|
||||
|
||||
/// Create a keyed hasher (MAC mode). Key must be exactly 32 bytes.
|
||||
/// Throws if the key length is wrong.
|
||||
#[wasm_bindgen(js_name = "newKeyed")]
|
||||
pub fn new_keyed(key: &[u8]) -> Result<Self, JsError> {
|
||||
let key: &[u8; 32] = key
|
||||
.try_into()
|
||||
.map_err(|_| JsError::new("key must be exactly 32 bytes"))?;
|
||||
|
||||
Ok(Hasher(blake3::Hasher::new_keyed(key)))
|
||||
}
|
||||
|
||||
/// Create a hasher in derive-key mode.
|
||||
/// Context should be a hardcoded, globally unique, application-specific string.
|
||||
/// Feed key material via `update()`, then call `finalize()`.
|
||||
#[wasm_bindgen(js_name = "newDeriveKey")]
|
||||
pub fn new_derive_key(context: &str) -> Self {
|
||||
Hasher(blake3::Hasher::new_derive_key(context))
|
||||
}
|
||||
|
||||
/// Feed data into the hasher. Can be called multiple times for streaming.
|
||||
pub fn update(&mut self, data: &[u8]) {
|
||||
self.0.update(data);
|
||||
}
|
||||
|
||||
/// Return the 32-byte hash digest. Non-destructive. Can be called multiple times.
|
||||
pub fn finalize(&self) -> Vec<u8> {
|
||||
self.0.finalize().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
/// Return `out_len` bytes of extended output (XOF mode). Non-destructive.
|
||||
#[wasm_bindgen(js_name = "finalizeXof")]
|
||||
pub fn finalize_xof(&self, out_len: usize) -> Result<Vec<u8>, JsError> {
|
||||
let len = super::checked_xof_len(out_len).map_err(|e| JsError::new(&e.0))?;
|
||||
let mut out = vec![0u8; len];
|
||||
|
||||
self.0.finalize_xof().fill(&mut out);
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Finalize the hash and reset the hasher in one call.
|
||||
/// Useful for hashing multiple inputs sequentially without creating new instances.
|
||||
#[wasm_bindgen(js_name = "finalizeAndReset")]
|
||||
pub fn finalize_and_reset(&mut self) -> Vec<u8> {
|
||||
let out = self.0.finalize().as_bytes().to_vec();
|
||||
|
||||
self.0.reset();
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Reset the hasher to its initial state. Preserves the mode (keyed/derive-key).
|
||||
pub fn reset(&mut self) {
|
||||
self.0.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_hash_deterministic() {
|
||||
let a = hash(b"hello");
|
||||
let b = hash(b"hello");
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(hash(b"hello"), hash(b"hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_length() {
|
||||
assert_eq!(hash(b"hello").len(), 32);
|
||||
@@ -135,8 +253,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_hash_xof_length() {
|
||||
assert_eq!(hash_xof(b"hello", 64).len(), 64);
|
||||
assert_eq!(hash_xof(b"hello", 16).len(), 16);
|
||||
assert_eq!(hash_xof(b"hello", 64).unwrap().len(), 64);
|
||||
assert_eq!(hash_xof(b"hello", 16).unwrap().len(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -145,6 +263,11 @@ mod tests {
|
||||
assert!(keyed_hash(b"hello", &key).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_keyed_hash_bad_key() {
|
||||
assert!(keyed_hash(b"hello", &[0u8; 16]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_key() {
|
||||
let a = derive_key("ctx", b"material");
|
||||
@@ -162,6 +285,7 @@ mod tests {
|
||||
let mut h = Hasher::new();
|
||||
h.update(b"hello");
|
||||
h.update(b"world");
|
||||
|
||||
assert_eq!(h.finalize(), oneshot);
|
||||
}
|
||||
|
||||
@@ -170,6 +294,7 @@ mod tests {
|
||||
let oneshot = derive_key("my-ctx", b"material");
|
||||
let mut h = Hasher::new_derive_key("my-ctx");
|
||||
h.update(b"material");
|
||||
|
||||
assert_eq!(h.finalize(), oneshot);
|
||||
}
|
||||
|
||||
@@ -194,22 +319,25 @@ mod tests {
|
||||
let mut h = Hasher::new_keyed(&key).unwrap();
|
||||
h.update(b"hello ");
|
||||
h.update(b"world");
|
||||
|
||||
assert_eq!(h.finalize(), oneshot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hasher_finalize_xof() {
|
||||
let oneshot = hash_xof(b"hello", 64);
|
||||
let oneshot = hash_xof(b"hello", 64).unwrap();
|
||||
let mut h = Hasher::new();
|
||||
h.update(b"hello");
|
||||
assert_eq!(h.finalize_xof(64), oneshot);
|
||||
|
||||
assert_eq!(h.finalize_xof(64).unwrap(), oneshot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hasher_finalize_xof_prefix_matches_hash() {
|
||||
// First 32 bytes of XOF output should equal the standard hash
|
||||
let standard = hash(b"test data");
|
||||
let xof = hash_xof(b"test data", 64);
|
||||
let xof = hash_xof(b"test data", 64).unwrap();
|
||||
|
||||
assert_eq!(&xof[..32], standard.as_slice());
|
||||
}
|
||||
|
||||
@@ -219,13 +347,30 @@ mod tests {
|
||||
h.update(b"junk");
|
||||
h.reset();
|
||||
h.update(b"hello");
|
||||
|
||||
assert_eq!(h.finalize(), hash(b"hello"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hasher_keyed_bad_key() {
|
||||
assert!(Hasher::new_keyed(&[0u8; 10]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_xof_zero_len() {
|
||||
assert!(hash_xof(b"hello", 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_xof_over_max() {
|
||||
assert!(hash_xof(b"hello", 65_537).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hasher_keyed() {
|
||||
let key = [1u8; 32];
|
||||
let h = Hasher::new_keyed(&key).unwrap();
|
||||
|
||||
assert_ne!(h.finalize(), hash(b"").as_slice());
|
||||
}
|
||||
|
||||
@@ -239,49 +384,58 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_vector_empty() {
|
||||
let out = hash(&[]);
|
||||
let expected =
|
||||
hex::decode("af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262")
|
||||
.unwrap();
|
||||
assert_eq!(out, expected);
|
||||
}
|
||||
|
||||
assert_eq!(hash(&[]).as_slice(), expected.as_slice());
|
||||
}
|
||||
#[test]
|
||||
fn test_vector_1_byte() {
|
||||
let input = test_input(1);
|
||||
let out = hash(&input);
|
||||
let expected =
|
||||
hex::decode("2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213")
|
||||
.unwrap();
|
||||
assert_eq!(out, expected);
|
||||
|
||||
assert_eq!(hash(&test_input(1)).as_slice(), expected.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vector_1025_bytes() {
|
||||
let input = test_input(1025);
|
||||
let out = hash(&input);
|
||||
let expected =
|
||||
hex::decode("d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444")
|
||||
.unwrap();
|
||||
assert_eq!(out, expected);
|
||||
|
||||
assert_eq!(hash(&test_input(1025)).as_slice(), expected.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_vector_keyed_empty() {
|
||||
let key = b"whats the Elvish word for friend";
|
||||
let out = keyed_hash(&[], key).unwrap();
|
||||
let expected =
|
||||
hex::decode("92b2b75604ed3c761f9d6f62392c8a9227ad0ea3f09573e783f1498a4ed60d26")
|
||||
.unwrap();
|
||||
assert_eq!(out, expected);
|
||||
|
||||
assert_eq!(
|
||||
keyed_hash(&[], key).unwrap().as_slice(),
|
||||
expected.as_slice()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", test))]
|
||||
mod wasm_tests {
|
||||
use super::*;
|
||||
use super::wasm::*;
|
||||
use wasm_bindgen_test::*;
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_hash_roundtrip() {
|
||||
let a = hash(b"hello");
|
||||
let b = hash(b"hello");
|
||||
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.len(), 32);
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_keyed_hash_bad_key() {
|
||||
assert!(keyed_hash(b"hello", &[0u8; 16]).is_err());
|
||||
@@ -291,4 +445,26 @@ mod wasm_tests {
|
||||
fn test_hasher_keyed_bad_key() {
|
||||
assert!(Hasher::new_keyed(&[0u8; 10]).is_err());
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_hash_xof_zero_len() {
|
||||
assert!(hash_xof(b"hello", 0).is_err());
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_hash_xof_over_max() {
|
||||
assert!(hash_xof(b"hello", 65_537).is_err());
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_hasher_finalize_xof_zero_len() {
|
||||
let h = Hasher::new();
|
||||
assert!(h.finalize_xof(0).is_err());
|
||||
}
|
||||
|
||||
#[wasm_bindgen_test]
|
||||
fn test_hasher_finalize_xof_over_max() {
|
||||
let h = Hasher::new();
|
||||
assert!(h.finalize_xof(65_537).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user