31 Commits
Author SHA1 Message Date
breakingbread a841ee1313 fix: export init only 2026-06-14 05:48:19 +02:00
breakingbread ac63099741 feat: add webpack export condition and init type declaration
bump to 0.6.5
2026-06-14 05:30:25 +02:00
breakingbread 2de1b09087 fix(build): add missing bindgen in files 2026-06-14 00:38:16 +02:00
breakingbread 112db2e0fe chore(ci): update and put SHA and variables 2026-06-14 00:27:34 +02:00
breakingbread 90e9a905b0 chore(bump): update wasm-bindgen and add bindgen file in root 2026-06-14 00:18:25 +02:00
breakingbread 7e7ee43bad fix: added missing apache license in package.json file 2026-05-08 20:50:24 +02:00
breakingbread d3871afb58 ci: fix OIDC publishing with Node 24 and registry-url 2026-05-04 13:26:40 +02:00
breakingbread 7fca25291c ci: use OIDC trusted publisher, drop npm token 2026-05-04 13:06:54 +02:00
breakingbread 4476a5bcc4 chore: bump to v0.6.2 2026-05-04 12:59:53 +02:00
breakingbread edc8284936 feat: add zeroize feature to wipe blake3 internal key material on drop 2026-05-04 12:56:18 +02:00
breakingbreadandGitHub c9a6d8f39b ci: add permissions for contents in CI workflow 2026-04-30 20:31:39 +02:00
breakingbreadandGitHub ccb2d39c16 ci: update binaryen download URL in publish workflow 2026-04-30 20:26:02 +02:00
breakingbread 85b27b140d chore: fix indentation and update README.md
- Make readme clearer
2026-04-29 18:03:03 +02:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
7f8fb67345 chore(deps): bump blake3 from 1.8.4 to 1.8.5 (#2)
Bumps [blake3](https://github.com/BLAKE3-team/BLAKE3) from 1.8.4 to 1.8.5.
- [Release notes](https://github.com/BLAKE3-team/BLAKE3/releases)
- [Commits](https://github.com/BLAKE3-team/BLAKE3/compare/1.8.4...1.8.5)

---
updated-dependencies:
- dependency-name: blake3
  dependency-version: 1.8.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-29 02:07:06 +02:00
breakingbread 99980eff38 chore: bump to v0.6.1 2026-04-28 06:32:43 +02:00
breakingbread 7fec54a9b5 fix: add id-token permission to publish job 2026-04-28 06:27:18 +02:00
breakingbread 5c4c776268 ci: switch to release publish 2026-04-28 06:16:48 +02:00
breakingbread 9911c9309f fix: add NPM_TOKEN auth to publish workflow 2026-04-28 06:14:10 +02:00
breakingbread 230976664c feat!: native-first API refactor, WASM behind feature flag
BREAKING: native functions return [u8; 32] instead of Vec<u8>.
BREAKING: WASM bindings require `wasm` feature flag.
New Blake3Error type replaces JsError for native consumers.
2026-04-28 06:05:57 +02:00
breakingbread 4570d6826f chore: added apache license, added types to export 2026-04-27 19:28:10 +02:00
breakingbread 878508fbd3 ci: switch npm publish to OIDC provenance 2026-04-25 19:36:18 +02:00
breakingbread 35dbf0f97e fix: include index.d.ts in published package 2026-04-25 19:28:44 +02:00
breakingbread 08e01269bc chore: bump version to 0.5.0
BREAKING: hashXof/finalizeXof now throw on invalid out_len
2026-04-25 19:19:59 +02:00
breakingbread a0e262bf02 fix: enable SIMD in build and cap XOF output length
- Merge target-feature=+simd128 into Makefile RUSTFLAGS (was being
  overridden by the explicit RUSTFLAGS env var)
- Cap hash_xof/finalize_xof to 64KB to prevent unbounded WASM
  linear memory growth
- Add boundary tests for XOF length validation
- Update benchmarks with SIMD-enabled build
2026-04-25 19:16:44 +02:00
breakingbread 55db5a6575 chore: optimize build, removed duplicate README 2026-04-25 18:52:41 +02:00
breakingbread 4397fa0beb ci: pin wasm-pack and wasm-bindgen-cli versions 2026-04-25 16:21:51 +02:00
breakingbread 9441c3a7cd fix: add wasm-bindgen-test-runner 2026-04-25 16:20:22 +02:00
breakingbread ed3a4d5fbc ci: use prebuilt binaries for wasm-pack, wasm-bindgen, wasm-opt 2026-04-25 16:13:43 +02:00
breakingbread 1f9d01b073 fix: pin wasm-bindgen to 0.2.118, update CI 2026-04-25 16:10:48 +02:00
breakingbread 84b2e75967 feat: camelCase JS exports, node-esm, index entry point 2026-04-25 15:56:36 +02:00
breakingbread 70a1423cb8 feat: add new_derive_key, finalize_and_reset, doc comments, official test vectors, Makefile 2026-04-24 02:15:51 +02:00
13 changed files with 848 additions and 228 deletions
-2
View File
@@ -1,2 +0,0 @@
[target.wasm32-unknown-unknown]
rustflags = ["-C", "target-feature=+simd128"]
+14 -5
View File
@@ -2,9 +2,9 @@ name: CI
on:
push:
branches: [master]
branches: [ master ]
pull_request:
branches: [master]
branches: [ master ]
env:
CARGO_TERM_COLOR: always
@@ -12,14 +12,23 @@ env:
jobs:
test:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- name: Install wasm-pack
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
run: |
curl -L https://github.com/wasm-bindgen/wasm-pack/releases/download/v${{ vars.WASM_PACK_VERSION }}/wasm-pack-v${{ vars.WASM_PACK_VERSION }}-x86_64-unknown-linux-musl.tar.gz | tar xz
sudo mv wasm-pack-*/wasm-pack /usr/local/bin/
- name: Install wasm-bindgen-cli
run: |
curl -L https://github.com/wasm-bindgen/wasm-bindgen/releases/download/${{ vars.WASM_BINDGEN_VERSION }}/wasm-bindgen-${{ vars.WASM_BINDGEN_VERSION }}-x86_64-unknown-linux-musl.tar.gz | tar xz
sudo mv wasm-bindgen-*/wasm-bindgen-test-runner /usr/local/bin/
- name: Rust tests
run: cargo test
- name: WASM tests (Node)
run: wasm-pack test --node
run: wasm-pack test --node --features wasm,talc
+27 -10
View File
@@ -1,8 +1,8 @@
name: Publish
on:
push:
tags: ["v*"]
release:
types: [ published ]
env:
CARGO_TERM_COLOR: always
@@ -12,25 +12,42 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- name: Setup Node
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4
with:
node-version: '24.16.0'
registry-url: 'https://registry.npmjs.org'
- name: Install wasm-pack
run: cargo install wasm-pack
run: |
curl -L https://github.com/wasm-bindgen/wasm-pack/releases/download/v${{ vars.WASM_PACK_VERSION }}/wasm-pack-v${{ vars.WASM_PACK_VERSION }}-x86_64-unknown-linux-musl.tar.gz | tar xz
sudo mv wasm-pack-*/wasm-pack /usr/local/bin/
- name: Install wasm-bindgen-cli
run: |
curl -L https://github.com/wasm-bindgen/wasm-bindgen/releases/download/${{ vars.WASM_BINDGEN_VERSION }}/wasm-bindgen-${{ vars.WASM_BINDGEN_VERSION }}-x86_64-unknown-linux-musl.tar.gz | tar xz
sudo mv wasm-bindgen-*/wasm-bindgen /usr/local/bin/
sudo mv wasm-bindgen-*/wasm-bindgen-test-runner /usr/local/bin/
- name: Install wasm-opt
run: |
curl -L https://github.com/WebAssembly/binaryen/releases/download/version_${{ vars.WASM_OPT_VERSION }}/binaryen-version_${{ vars.WASM_OPT_VERSION }}-x86_64-linux.tar.gz | tar xz
sudo mv binaryen-*/bin/wasm-opt /usr/local/bin/
- name: Rust tests
run: cargo test
- name: WASM tests (Node)
run: wasm-pack test --node
run: wasm-pack test --node --features wasm,talc
- name: Build package
run: bash build.sh
run: make
- name: Publish to npm
run: |
echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > pkg/.npmrc
cd pkg
npm publish --access public
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
npm publish
Generated
+70 -22
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "allocator-api2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
[[package]]
name = "arrayref"
version = "0.3.9"
@@ -13,6 +19,9 @@ name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
dependencies = [
"zeroize",
]
[[package]]
name = "async-trait"
@@ -33,9 +42,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "blake3"
version = "1.8.4"
version = "1.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d2d5991425dfd0785aed03aedcf0b321d61975c9b5b3689c774a2610ae0b51e"
checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce"
dependencies = [
"arrayref",
"arrayvec",
@@ -43,13 +52,16 @@ dependencies = [
"cfg-if",
"constant_time_eq",
"cpufeatures",
"zeroize",
]
[[package]]
name = "blake3-wasm-rs"
version = "0.1.2"
version = "0.6.5"
dependencies = [
"blake3",
"hex",
"talc",
"wasm-bindgen",
"wasm-bindgen-test",
]
@@ -127,6 +139,12 @@ dependencies = [
"slab",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "itoa"
version = "1.0.18"
@@ -135,13 +153,12 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.95"
version = "0.3.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
checksum = "f2025f20d7a4fa7785846e7b63d10a76d3f1cee98ee5cb79ea59703f95e42162"
dependencies = [
"cfg-if",
"futures-util",
"once_cell",
"wasm-bindgen",
]
@@ -157,6 +174,15 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "memchr"
version = "2.8.0"
@@ -243,6 +269,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.228"
@@ -309,6 +341,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "talc"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3081e3f3ad542dc4cd0ae720f752598f8880fd364dc2d031132e3509f673aa23"
dependencies = [
"allocator-api2",
"lock_api",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -327,9 +369,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
version = "0.2.118"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
checksum = "a254a4b10c19a76f09a27640e7ffbf9bc30bf67e16a3bf28aaefa4920fe81563"
dependencies = [
"cfg-if",
"once_cell",
@@ -340,9 +382,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.68"
version = "0.4.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
checksum = "54568702fabf5d4849ce2b90fadfa64168a097eaf4b351ce9df8b687a0086aaf"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -350,9 +392,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.118"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
checksum = "24a40fc75b0ec6f3746ceb10d36f53a93dcd68a93b11b6445983945d79eba0dc"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -360,9 +402,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.118"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
checksum = "908f34bd9b9ce3d4caf07b72dfab63d61504d156856c6bd3cd87fa350cf3985b"
dependencies = [
"bumpalo",
"proc-macro2",
@@ -373,18 +415,18 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.118"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
checksum = "7acbf7616c27b194bbb550bf77ed0c2c3e5b7fd1260a93082b95fb7f47959b92"
dependencies = [
"unicode-ident",
]
[[package]]
name = "wasm-bindgen-test"
version = "0.3.68"
version = "0.3.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb55e2540ad1c56eec35fd63e2aea15f83b11ce487fd2de9ad11578dfc047ea"
checksum = "e28a0782b173cf2e98f62aacb487c5c021b7c5925df46098675f28e1fa85e159"
dependencies = [
"async-trait",
"cast",
@@ -404,9 +446,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.68"
version = "0.3.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf0ca1bd612b988616bac1ab34c4e4290ef18f7148a1d8b7f31c150080e9295"
checksum = "ee997551ce1ad5adda03f7ce37ec34b4140fe9f547fd07b46d55901d1ba1a06b"
dependencies = [
"proc-macro2",
"quote",
@@ -415,9 +457,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-test-shared"
version = "0.2.118"
version = "0.2.123"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23cda5ecc67248c48d3e705d3e03e00af905769b78b9d2a1678b663b8b9d4472"
checksum = "ae0f005eb61f765eff31a79ef71df7e21819731268a868df41192c1e41d6d3e5"
[[package]]
name = "winapi-util"
@@ -443,6 +485,12 @@ dependencies = [
"windows-link",
]
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]]
name = "zmij"
version = "1.0.21"
+17 -7
View File
@@ -1,21 +1,31 @@
[package]
name = "blake3-wasm-rs"
version = "0.1.2"
version = "0.6.5"
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"]
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = []
wasm = ["dep:wasm-bindgen"]
talc = ["dep:talc"]
zeroize = ["blake3/zeroize"]
[dependencies]
blake3 = { version = "1.8", features = ["wasm32_simd"] }
wasm-bindgen = "0.2"
blake3 = { version = "1", features = ["wasm32_simd"] }
wasm-bindgen = { version = "=0.2.123", optional = true }
[dev-dependencies]
wasm-bindgen-test = "0.3"
wasm-bindgen-test = "0.3"
hex = "0.4"
[target.'cfg(target_family = "wasm")'.dependencies]
talc = { version = "5", optional = true }
+177
View File
@@ -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 -2
View File
@@ -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.
+94
View File
@@ -0,0 +1,94 @@
ROOT := pkg
CRATE := blake3_wasm_rs
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 -O3
WASM_TARGET := wasm32-unknown-unknown
TARGET_DIR := target/$(WASM_TARGET)/release
.PHONY: all clean build build-all node-esm package verify
all: clean build package
clean:
rm -rf $(ROOT)
build: build-all node-esm
build-all:
@echo "Building all target..."
RUSTFLAGS='-C opt-level=3 -C target-feature=+simd128' $(CARGO) build --target $(WASM_TARGET) --release --features wasm,talc,zeroize
@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
$(WASM_BINDGEN) --target nodejs --out-dir $(ROOT)/node $(TARGET_DIR)/$(CRATE).wasm
@mv $(ROOT)/bundler/$(CRATE)_bg.wasm $(ROOT)/$(CRATE)_bg.wasm
@cp $(ROOT)/bundler/$(CRATE)_bg.js $(ROOT)/$(CRATE)_bg.js
@rm -f $(ROOT)/web/$(CRATE)_bg.wasm $(ROOT)/node/$(CRATE)_bg.wasm
$(WASM_OPT) $(WASM_OPT_FLAGS) $(ROOT)/$(CRATE)_bg.wasm -o $(ROOT)/$(CRATE)_bg.wasm
@node -e "['bundler','web','node'].forEach(d=>{const f='$(ROOT)/'+d+'/$(CRATE).js';require('fs').writeFileSync(f,require('fs').readFileSync(f,'utf8').replace(/$(CRATE)_bg\.wasm/g,'../$(CRATE)_bg.wasm'))})"
@rm -f $(ROOT)/bundler/package.json $(ROOT)/web/package.json
@rm -f $(ROOT)/bundler/.gitignore $(ROOT)/web/.gitignore $(ROOT)/node/.gitignore
@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 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',\
type: 'module',\
version: '$(VERSION)',\
description: 'BLAKE3 hashing via Rust/WASM - works in Node.js (CJS + ESM), browsers, and bundlers',\
license: 'MIT OR Apache-2.0',\
repository: { type: 'git', url: 'https://github.com/UneBaguette/blake3.wasm' },\
main: 'index.js',\
types: 'index.d.ts',\
exports: { '.': {\
types: './index.d.ts',\
node: { require: './node/$(CRATE).js', import: './node-esm/index.mjs' },\
webpack: './bundler/$(CRATE).js',\
import: './web/$(CRATE).js',\
default: './web/$(CRATE).js'\
}},\
files: ['bundler/', 'web/', 'node/', 'node-esm/', 'index.js', 'index.d.ts', '$(CRATE)_bg.wasm', '$(CRATE)_bg.js', 'README.md', 'LICENSE'],\
keywords: ['blake3', 'wasm', 'hash', 'cryptography', 'wasm-bindgen']\
};\
require('fs').writeFileSync('./$(ROOT)/package.json', JSON.stringify(pkg, null, 2) + '\n');"
node-esm:
@echo "Generating node-esm wrapper..."
@mkdir -p $(ROOT)/node-esm
@node -e "\
const fs = require('fs'); \
const dts = fs.readFileSync('$(ROOT)/node/$(CRATE).d.ts', 'utf8'); \
const fns = [...dts.matchAll(/export function (\w+)/g)].map(m => m[1]); \
const cls = [...dts.matchAll(/export class (\w+)/g)].map(m => m[1]); \
const lines = [ \
\"import { createRequire } from 'module';\", \
\"const require = createRequire(import.meta.url);\", \
\"const mod = require('../node/$(CRATE).js');\", \
\"export default mod;\", \
...fns.map(n => 'export const ' + n + ' = mod.' + n + ';'), \
...cls.map(n => 'export const ' + n + ' = mod.' + n + ';'), \
]; \
fs.writeFileSync('$(ROOT)/node-esm/index.mjs', lines.join('\n') + '\n'); \
"
package:
@echo ""
@echo "Done! Package ready in $(ROOT)/"
@echo " node (CJS): $(ROOT)/node/"
@echo " node (ESM): $(ROOT)/node-esm/"
@echo " bundler: $(ROOT)/bundler/"
@echo " web: $(ROOT)/web/"
verify: package
cd $(ROOT) && npm pack --dry-run
+78 -49
View File
@@ -1,29 +1,22 @@
# blake3 to wasm
# blake3-wasm-rs
[![npm version](https://img.shields.io/npm/v/blake3-wasm-rs)](https://www.npmjs.com/package/blake3-wasm-rs)
[![CI](https://github.com/UneBaguette/blake3.wasm/actions/workflows/ci.yml/badge.svg)](https://github.com/UneBaguette/blake3.wasm/actions/workflows/ci.yml)
[![license](https://img.shields.io/npm/l/blake3-wasm-rs)](https://github.com/UneBaguette/blake3.wasm/blob/master/LICENSE)
[![npm downloads](https://img.shields.io/npm/dm/blake3-wasm-rs)](https://www.npmjs.com/package/blake3-wasm-rs)
**blake3.wasm** 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**.
**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
# 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
@@ -36,43 +29,79 @@ const key = new Uint8Array(32).fill(1);
// One-shot hashing
blake3.hash(data);
blake3.hashXof(data, 64); // variable output length
// MAC and key derivation
blake3.keyedHash(data, key);
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
const hasher = new blake3.Hasher();
hasher.update(data.slice(0, 5));
hasher.update(data.slice(5));
hasher.finalize();
```
#### OR
```js
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
// MAC and key derivation
keyedHash(data, key)
deriveKey('my context', key)
// Conctruct for Streaming
{
const h = new blake3.Hasher();
h.update(data.slice(0, 5));
h.update(data.slice(5));
h.finalize();
h.finalizeXof(64);
h.reset();
}
// Streaming
const h = new Hasher()
h.update(data.slice(0, 5))
h.update(data.slice(5))
h.finalize()
// Keyed (MAC mode)
const mac = blake3.Hasher.newKeyed(key);
mac.update(data);
mac.finalize();
// Streaming
// Key derivation mode
const kdf = blake3.Hasher.newDeriveKey('my app v1 :: subkey');
kdf.update(key);
kdf.finalize();
// Batch hashing without re-allocating
{
const 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';
```
## 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.
@@ -89,11 +118,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
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="pkg"
rm -rf "$ROOT"
echo "Building bundler target..."
wasm-pack build --target bundler -d "$ROOT/bundler"
echo "Building nodejs target..."
wasm-pack build --target nodejs -d "$ROOT/node"
echo "Building web target..."
wasm-pack build --target web -d "$ROOT/web"
# Generate node-esm wrapper from the nodejs build exports
echo "Generating node-esm wrapper..."
mkdir -p "$ROOT/node-esm"
cp README.md "$ROOT/README.md"
# Extract export names from the nodejs .js file
EXPORTS=$(grep -oP '(?<=module\.exports\.)\w+' "$ROOT/node/blake3_wasm_rs.js" | sort -u || true)
# Fallback: parse from .d.ts if module.exports pattern not found
if [ -z "$EXPORTS" ]; then
EXPORTS=$(grep -oP '(?<=export function )\w+' "$ROOT/node/blake3_wasm_rs.d.ts" | sort -u || true)
fi
# Also check for exported classes
CLASSES=$(grep -oP '(?<=export class )\w+' "$ROOT/node/blake3_wasm_rs.d.ts" | sort -u || true)
{
echo "import { createRequire } from 'module';"
echo "const require = createRequire(import.meta.url);"
echo "const mod = require('../node/blake3_wasm_rs.js');"
echo "export default mod;"
for name in $EXPORTS; do
echo "export const $name = mod.$name;"
done
for name in $CLASSES; do
echo "export const $name = mod.$name;"
done
} > "$ROOT/node-esm/index.mjs"
# Clean up wasm-pack generated package.json in each subfolder
rm -f "$ROOT/bundler/package.json" "$ROOT/node/package.json" "$ROOT/web/package.json"
rm -f "$ROOT/bundler/.gitignore" "$ROOT/node/.gitignore" "$ROOT/web/.gitignore"
# Generate root package.json
cat > "$ROOT/package.json" << 'EOF'
{
"name": "blake3-wasm-rs",
"version": "0.2.2",
"description": "BLAKE3 hashing via Rust/WASM - works in Node.js (CJS + ESM), browsers, and bundlers",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/UneBaguette/blake3.wasm"
},
"exports": {
".": {
"node": {
"require": "./node/blake3_wasm_rs.js",
"import": "./node-esm/index.mjs"
},
"import": "./bundler/blake3_wasm_rs.js",
"default": "./web/blake3_wasm_rs.js"
}
},
"types": "./bundler/blake3_wasm_rs.d.ts",
"files": [
"node/",
"node-esm/",
"bundler/",
"web/",
"README.md"
],
"keywords": [
"blake3",
"wasm",
"hash",
"cryptography",
"wasm-bindgen"
]
}
EOF
echo ""
echo "Done! Package ready in $ROOT/"
echo " node (CJS): $ROOT/node/"
echo " node (ESM): $ROOT/node-esm/"
echo " bundler: $ROOT/bundler/"
echo " web: $ROOT/web/"
echo ""
echo "Verify with: cd $ROOT && npm pack --dry-run"
+6
View File
@@ -0,0 +1,6 @@
// 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';
export type { default } from './web/blake3_wasm_rs.d.ts';
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright 2026 Thomas <[email protected]>
//
// blake3-wasm-rs. Auto-generated entry point
// Do not edit directly!
export { Hasher, deriveKey, hash, hashXof, keyedHash } from './bundler/blake3_wasm_rs.js';
+357 -33
View File
@@ -1,80 +1,251 @@
use wasm_bindgen::prelude::*;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright 2026 Thomas <[email protected]>
#[wasm_bindgen]
pub fn hash(value: &[u8]) -> Vec<u8> {
blake3::hash(value).as_bytes().to_vec()
#[cfg(all(
not(target_feature = "atomics"),
target_family = "wasm",
feature = "talc"
))]
#[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)
}
}
#[wasm_bindgen]
pub fn hash_xof(data: &[u8], out_len: usize) -> Vec<u8> {
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.
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.
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)
}
#[wasm_bindgen]
pub fn keyed_hash(data: &[u8], key: &[u8]) -> Result<Vec<u8>, JsError> {
/// Compute a keyed BLAKE3 hash (MAC). Key must be exactly 32 bytes.
/// Throws if the key length is wrong.
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"))?;
Ok(blake3::keyed_hash(key, data).as_bytes().to_vec())
.map_err(|_| err("key must be exactly 32 bytes"))?;
Ok(*blake3::keyed_hash(key, data).as_bytes())
}
#[wasm_bindgen]
pub fn derive_key(context: &str, key_material: &[u8]) -> Vec<u8> {
blake3::derive_key(context, key_material).to_vec()
/// Derive a 32-byte key from a context string and key material.
/// Context should be a hardcoded, globally unique, application-specific string.
pub fn derive_key(context: &str, key_material: &[u8]) -> [u8; 32] {
blake3::derive_key(context, key_material)
}
#[wasm_bindgen]
pub struct Hasher(blake3::Hasher);
#[wasm_bindgen]
impl Hasher {
#[wasm_bindgen(constructor)]
/// Create a new hasher for unkeyed hashing.
pub fn new() -> Self {
Hasher(blake3::Hasher::new())
}
pub fn new_keyed(key: &[u8]) -> Result<Hasher, JsError> {
/// Create a keyed hasher (MAC mode). Key must be exactly 32 bytes.
/// Throws if the key length is wrong.
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)))
}
/// 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()`.
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);
}
pub fn finalize(&self) -> Vec<u8> {
self.0.finalize().as_bytes().to_vec()
/// Return the 32-byte hash digest. Non-destructive. Can be called multiple times.
pub fn finalize(&self) -> [u8; 32] {
*self.0.finalize().as_bytes()
}
pub fn finalize_xof(&self, out_len: usize) -> Vec<u8> {
/// Return `out_len` bytes of extended output (XOF mode). Non-destructive.
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);
Ok(out)
}
/// Finalize the hash and reset the hasher in one call.
/// Useful for hashing multiple inputs sequentially without creating new instances.
pub fn finalize_and_reset(&mut self) -> [u8; 32] {
let out = *self.0.finalize().as_bytes();
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();
}
}
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);
@@ -82,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]
@@ -92,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");
@@ -109,31 +285,157 @@ mod tests {
let mut h = Hasher::new();
h.update(b"hello");
h.update(b"world");
assert_eq!(h.finalize(), oneshot);
}
#[test]
fn test_hasher_derive_key() {
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);
}
#[test]
fn test_hasher_finalize_and_reset() {
let mut h = Hasher::new();
h.update(b"hello");
let first = h.finalize_and_reset();
assert_eq!(first, hash(b"hello"));
// After reset, hashing different data should produce different output
h.update(b"world");
let second = h.finalize();
assert_eq!(second, hash(b"world"));
assert_ne!(first, second);
}
#[test]
fn test_keyed_hash_matches_streaming() {
let key = [42u8; 32];
let oneshot = keyed_hash(b"hello world", &key).unwrap();
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).unwrap();
let mut h = Hasher::new();
h.update(b"hello");
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).unwrap();
assert_eq!(&xof[..32], standard.as_slice());
}
#[test]
fn test_hasher_reset() {
let mut h = Hasher::new();
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());
}
// BLAKE3 official test vectors (from BLAKE3 spec)
// Reference: https://github.com/BLAKE3-team/BLAKE3/blob/master/test_vectors/test_vectors.json
// Input: 0x00..0xfa repeating pattern, first N bytes
fn test_input(len: usize) -> Vec<u8> {
(0..len).map(|i| (i % 251) as u8).collect()
}
#[test]
fn test_vector_empty() {
let expected =
hex::decode("af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262")
.unwrap();
assert_eq!(hash(&[]).as_slice(), expected.as_slice());
}
#[test]
fn test_vector_1_byte() {
let expected =
hex::decode("2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213")
.unwrap();
assert_eq!(hash(&test_input(1)).as_slice(), expected.as_slice());
}
#[test]
fn test_vector_1025_bytes() {
let expected =
hex::decode("d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444")
.unwrap();
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 expected =
hex::decode("92b2b75604ed3c761f9d6f62392c8a9227ad0ea3f09573e783f1498a4ed60d26")
.unwrap();
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());
@@ -143,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());
}
}