rust: upgrade crypto dependencies together
What changed, and why it matters
This is a large maintenance update for the BitBox02 hardware wallet's Rust cryptography libraries. The developers upgraded many crypto-related dependencies (such as those handling SHA-2 hashing, AEAD encryption, BLAKE2, and Ed25519 key derivation) to newer versions required by RustSec security advisories. They also adjusted build settings to keep the firmware small and preserve existing security behavior, such as clearing sensitive key material from memory. The commit itself is a routine, security-motivated dependency refresh rather than a fix for an active, exploitable bug in the device.
Treat this as a planned security maintenance update. Verify that the upgraded dependency versions correspond to known RustSec advisories, run the project's full test suite (especially crypto KATs and Noise/BitBox protocol tests), confirm firmware size and behavior are unchanged, and review any follow-up commits for additional API adaptation fixes. No emergency response is indicated by the commit alone.
Security signals we found
Dependency upgrade explicitly motivated by RustSec advisories
Cryptographic API migration across shared RustCrypto traits
Build flag changes to preserve compact SHA-2 backend and firmware size
Vendor statement that key derivation, signatures, and Noise behavior are preserved
Vendor statement that key/keystream zeroization is retained
Evidence from the diff
The commit upgrades the firmware’s Rust cryptographic dependency tree to address RustSec advisories. Major changes include: bumping aead 0.5→0.6, base16ct 0.2→1.0, blake2 0.10→0.11, chacha20poly1305, cipher, digest, hmac, p256, sha2/sha3, and bip32-ed25519 0.2.1→0.2.2. The diff shows API migrations (AeadInPlace→AeadInOut, generic-array→hybrid-array, digest 0.10→0.11, hmac 0.12→0.13) and build-system changes to retain the compact SHA-2 software backend via new –cfg flags in .cargo/config.toml, CMakeLists.txt, and CI. The vendor states that key derivation, signatures, and Noise wire behavior are preserved, and that key/keystream zeroization and inline Noise storage are retained. No specific CVE or active exploit is described in the commit or supplied references.
Changed components
Rust crypto dependency tree (aead, base16ct, blake2, chacha20poly1305, cipher, digest, hmac, p256, sha2, sha3, bip32-ed25519).cargo/config.tomlCMakeLists.txt.github/workflows/ci-common.ymlexternal/vendor vendored sourcesInspect captured patch +190524 / −52454
### .cargo/config.toml
@@ -6,11 +6,20 @@ include = [{ path = "config.local.toml", optional = true }]
# test` and other cargo-based builds. This is replicated in src/CMakeLists.txt,
# test/simulator-graphical*/CMakeLists.txt for CMake-based builds.
# See https://github.com/rust-bitcoin/rust-secp256k1/tree/7c8270a8506e31731e540fab7ee1abde1f48314e/secp256k1-sys#linking-to-external-symbols
-rustflags = ["--cfg", "rust_secp_no_symbol_renaming"]
+# The compact SHA-2 backend saves ~3kB (measured when first enabled).
+# See https://github.com/RustCrypto/hashes/pull/686.
+# Keep the SHA-2 flags in sync with CMakeLists.txt and .github/workflows/ci-common.yml.
+rustflags = [
+ "--cfg", "rust_secp_no_symbol_renaming",
+ "--cfg", 'sha2_backend="soft"',
+ "--cfg", 'sha2_backend_soft="compact"',
+]
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
rustflags = [
"--cfg", "rust_secp_no_symbol_renaming",
+ "--cfg", 'sha2_backend="soft"',
+ "--cfg", 'sha2_backend_soft="compact"',
"-C", "linker-plugin-lto",
# This is needed if your flash or ram addresses are not aligned to 0x10000 in memory.x
# See https://github.com/rust-embedded/cortex-m-quickstart/pull/95
### .github/workflows/ci-common.yml
@@ -15,8 +15,8 @@ on:
type: string
env:
CARGOFLAGS: "--locked"
- # RUSTFLAGS replaces .cargo/config.toml, so repeat the required secp256k1 cfg.
- RUSTFLAGS: "-Dwarnings --cfg=rust_secp_no_symbol_renaming"
+ # RUSTFLAGS replaces .cargo/config.toml, so repeat the secp256k1 and compact SHA-2 cfgs.
+ RUSTFLAGS: '-Dwarnings --cfg=rust_secp_no_symbol_renaming --cfg=sha2_backend="soft" --cfg=sha2_backend_soft="compact"'
CFLAGS: "-Werror"
jobs:
### CMakeLists.txt
@@ -178,6 +178,10 @@ endif()
# This is replicated in .cargo/config.toml because RUSTFLAGS here override the rustflags there.
string(APPEND RUSTFLAGS " --cfg=rust_secp_no_symbol_renaming")
+# Keep the compact SHA-2 backend in sync with .cargo/config.toml.
+string(APPEND RUSTFLAGS " --cfg=sha2_backend=\"soft\" --cfg=sha2_backend_soft=\"compact\"")
+separate_arguments(CARGO_ENV_FLAGS NATIVE_COMMAND "$ENV{CARGOFLAGS}")
+
#-----------------------------------------------------------------------------
# Print system information and build options
### external/vendor/aead/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"d25ef64c47aa2a16d9200724c0f56bddb4f5c24800986e070517867cfcdee0a4","CHANGELOG.md":"8870cb71cd8b46213591c7a4ee7ad80985600bd00c9f88331f825407498a00a7","Cargo.toml":"bf935971de51d6c168946e1822e1e4c3267aad0e1ae6e036b4e5baeb6d81a4be","Cargo.toml.orig":"c541eaa8f4355b379a5d3cf15e6ac710fde852fce72b5d5e9293f328d4f40622","LICENSE-APACHE":"b1cf9a3333ca78152b859012cd4a804156e5243e9ca20ad1df7327ba5ea7405c","LICENSE-MIT":"949ab7b3e7140fee216f06fe3a2bd67d68dd511f8ea73c1e01c98cb348e9c8ae","README.md":"8e195a2c3d0437b035de4640adabc6fb29ed91d814ec5073e7c2ae1a4d988748","src/dev.rs":"8a615fadb1236158cea9fde4ea96e8bb2ced4757c43b829c23eb143fc816d894","src/lib.rs":"477a851e2666a29dc3a724a75b7558d32d9ed7584364e1567dc6746c32a74fc5","src/stream.rs":"0b89b1e648972b2434cfed6556302f28ad2d8bdc11434f6905354167bf8a38e7"},"package":"d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"aab688881c8a5b1a0ba3088156dcca5862f7888520fbc6c2ce13987b9386ad57","CHANGELOG.md":"449fbb0fbfbf401b5e1d4b8383d1938b981d2bb03940109993b9e1811cdbe4f3","Cargo.lock":"2e275cfa6bd98da17d0eb94fdecf23f83f6da629fd8d83223194ec9020e77d97","Cargo.toml":"cda27d7960de6273a9969330ad54e6b87fbbf18e582da44d05ac2f2f972d0952","Cargo.toml.orig":"0da0e2362ce942618293c1a911cc955570becbf90f767c345b8f7c2e0d8a1554","LICENSE-APACHE":"b1cf9a3333ca78152b859012cd4a804156e5243e9ca20ad1df7327ba5ea7405c","LICENSE-MIT":"33b32a251d445c5c03a634e64c53314c55540fc367fabdd45d9b6c8f260c028c","README.md":"9b68d9e33e8b1ee904455d7e834b2a0a01a1d9eba4ae2ee279ca98941b8e2a28","src/dev.rs":"951c14eaa0517e1eaee035d4d4a204cd384a588b4be26a254240c42a015018ea","src/lib.rs":"a0c317d7c4a3209885193c93a357f0d86fb353bdb2837cfb889ab0ffc4bd7cbd","tests/data/postfix_fail.blb":"a5de9025a8dd4b8954f145462bdcc4d2f677fbab2971f6f61cbbf24ee12d0e37","tests/data/postfix_pass.blb":"4fa5d8e04fb8aa968ba079635e751ac89f0fa3b968d6cb83d89d81512bc45400","tests/data/prefix_fail.blb":"54fb9bf29f0d86525854a1762e89df55eef11f9ce860555d000e3fd1fd233a30","tests/data/prefix_pass.blb":"7b1c59d21eb68a8a97ed625bfe457bf95c005b344468d49f1330502c3a5e0777","tests/dummy.rs":"6678d520e4133e199c0fe2dfe9f0005f03159f7312e850d1255849db04b5d50f"},"package":"1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"}
\ No newline at end of file
### external/vendor/aead/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1ae238c527c204dd9590e3abc406cfbb342d46ea"
+ "sha1": "3d2d90045bffc402af4edb6a5a4dbb1e217329d1"
},
"path_in_vcs": "aead"
}
\ No newline at end of file
### external/vendor/aead/CHANGELOG.md
@@ -5,6 +5,50 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.6.1 (2026-06-17)
+### Changed
+- Have `getrandom` feature enable `rand_core` ([#2452])
+
+[#2452]: https://github.com/RustCrypto/traits/pull/2452
+
+## 0.6.0 (2026-06-08)
+### Added
+- Enable `missing_debug_implementations` lint and add `Debug` impls ([#1411])
+- `AeadCore::TAG_POSITION` and `TagPosition` enum ([#1798])
+- Re-export `crypto_common` as `common` ([#2237])
+
+### Changed
+- Replace `generic-array` with `hybrid-array` ([#1384])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1759])
+- Replace `AeadInPlace` with `AeadInOut` ([#1793])
+- Split `new_test!` into `new_pass_test!` and `new_fail_test!` ([#2019])
+- Bump `crypto-common` to v0.2 ([#2276])
+
+### Removed
+- `AeadCore::CiphertextOverhead` constant ([#1737])
+- Stateful AEAD traits: `AeadMut*` ([#1740])
+- `stream` module - extracted into `aead-stream` crate ([#1801])
+- `heapless` support - will be added back in a future patch release ([#1999])
+- Nonce generation APIs - use `Generate` trait instead ([#2098])
+
+### Fixed
+- Minor documentation error in `AeadCore::TagSize` ([#1351])
+
+[#1351]: https://github.com/RustCrypto/traits/pull/1351
+[#1384]: https://github.com/RustCrypto/traits/pull/1384
+[#1411]: https://github.com/RustCrypto/traits/pull/1411
+[#1737]: https://github.com/RustCrypto/traits/pull/1737
+[#1740]: https://github.com/RustCrypto/traits/pull/1740
+[#1759]: https://github.com/RustCrypto/traits/pull/1759
+[#1793]: https://github.com/RustCrypto/traits/pull/1793
+[#1798]: https://github.com/RustCrypto/traits/pull/1798
+[#1801]: https://github.com/RustCrypto/traits/pull/1801
+[#1999]: https://github.com/RustCrypto/traits/pull/1999
+[#2019]: https://github.com/RustCrypto/traits/pull/2019
+[#2098]: https://github.com/RustCrypto/traits/pull/2098
+[#2237]: https://github.com/RustCrypto/traits/pull/2237
+[#2276]: https://github.com/RustCrypto/traits/pull/2276
+
## 0.5.2 (2023-04-02)
### Added
- `arrayvec` feature ([#1219])
### external/vendor/aead/Cargo.lock
@@ -0,0 +1,443 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.6.1"
+dependencies = [
+ "arrayvec",
+ "blobby",
+ "bytes",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "bitflags"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "log"
+version = "0.4.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a"
+
+[[package]]
+name = "memchr"
+version = "2.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen 0.46.0",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/aead/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "aead"
-version = "0.5.2"
+version = "0.6.1"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
@@ -34,48 +40,84 @@ repository = "https://github.com/RustCrypto/traits"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = []
+default = ["rand_core"]
+dev = [
+ "blobby",
+ "alloc",
+]
+getrandom = [
+ "common/getrandom",
+ "rand_core",
]
+rand_core = ["common/rand_core"]
+
+[lib]
+name = "aead"
+path = "src/lib.rs"
+
+[[test]]
+name = "dummy"
+path = "tests/dummy.rs"
[dependencies.arrayvec]
version = "0.7"
optional = true
default-features = false
[dependencies.blobby]
-version = "0.3"
+version = "0.4"
optional = true
[dependencies.bytes]
-version = "1"
+version = "1.11.1"
optional = true
default-features = false
-[dependencies.crypto-common]
-version = "0.1.4"
+[dependencies.common]
+version = "0.2"
+package = "crypto-common"
-[dependencies.generic-array]
-version = "0.14"
-default-features = false
+[dependencies.inout]
+version = "0.2.2"
-[dependencies.heapless]
-version = "0.7"
-optional = true
-default-features = false
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
-[features]
-alloc = []
-default = ["rand_core"]
-dev = ["blobby"]
-getrandom = [
- "crypto-common/getrandom",
- "rand_core",
-]
-rand_core = ["crypto-common/rand_core"]
-std = [
- "alloc",
- "crypto-common/std",
-]
-stream = []
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/aead/Cargo.toml.orig
@@ -1,39 +1,38 @@
[package]
name = "aead"
-version = "0.5.2"
-description = """
-Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
-such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
-"""
+version = "0.6.1"
authors = ["RustCrypto Developers"]
-edition = "2021"
-license = "MIT OR Apache-2.0"
-readme = "README.md"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/aead"
+readme = "README.md"
repository = "https://github.com/RustCrypto/traits"
+license = "MIT OR Apache-2.0"
keywords = ["crypto", "encryption"]
categories = ["cryptography", "no-std"]
-rust-version = "1.56"
+description = """
+Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
+such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
+"""
[dependencies]
-crypto-common = "0.1.4"
-generic-array = { version = "0.14", default-features = false }
+common = { version = "0.2", package = "crypto-common" }
+inout = "0.2.2"
# optional dependencies
arrayvec = { version = "0.7", optional = true, default-features = false }
-blobby = { version = "0.3", optional = true }
-bytes = { version = "1", optional = true, default-features = false }
-heapless = { version = "0.7", optional = true, default-features = false }
+blobby = { version = "0.4", optional = true }
+bytes = { version = "1.11.1", optional = true, default-features = false }
[features]
default = ["rand_core"]
alloc = []
-std = ["alloc", "crypto-common/std"]
-dev = ["blobby"]
-getrandom = ["crypto-common/getrandom", "rand_core"]
-rand_core = ["crypto-common/rand_core"]
-stream = []
+dev = ["blobby", "alloc"]
+getrandom = ["common/getrandom", "rand_core"]
+rand_core = ["common/rand_core"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/aead/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Copyright (c) 2019 MobileCoin, LLC
Permission is hereby granted, free of charge, to any
### external/vendor/aead/README.md
@@ -15,15 +15,6 @@ modern cryptographic implementations.
See [RustCrypto/AEADs] for cipher implementations which use this trait.
-[Documentation][docs-link]
-
-## Minimum Supported Rust Version
-
-Rust **1.56** or higher.
-
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
-
## SemVer Policy
- All on-by-default features of this library are covered by SemVer
@@ -51,11 +42,11 @@ dual licensed as above, without any additional terms or conditions.
[docs-image]: https://docs.rs/aead/badge.svg
[docs-link]: https://docs.rs/aead/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs
-[build-image]: https://github.com/RustCrypto/traits/workflows/aead/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/traits/actions?query=workflow%3Aaead
+[build-image]: https://github.com/RustCrypto/traits/actions/workflows/aead.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/traits/actions/workflows/aead.yml?query=branch:master
[//]: # (general links)
### external/vendor/aead/src/dev.rs
@@ -1,75 +1,191 @@
//! Development-related functionality
+
+#![allow(clippy::missing_errors_doc, reason = "dev module")]
+#![allow(clippy::missing_panics_doc, reason = "dev module")]
+#![allow(clippy::unwrap_in_result, reason = "dev module")]
+
+use crate::{
+ Aead, AeadInOut, Payload, Tag, TagPosition, array::typenum::Unsigned, inout::InOutBuf,
+};
pub use blobby;
+use common::KeyInit;
+
+/// AEAD test vector
+#[derive(Debug, Clone, Copy)]
+pub struct TestVector {
+ /// Initialization key
+ pub key: &'static [u8],
+ /// Nonce
+ pub nonce: &'static [u8],
+ /// Additional associated data
+ pub aad: &'static [u8],
+ /// Plaintext
+ pub plaintext: &'static [u8],
+ /// Ciphertext
+ pub ciphertext: &'static [u8],
+}
+
+/// Run AEAD test for the provided passing test vector
+#[allow(clippy::cast_possible_truncation)]
+pub fn pass_test<C: AeadInOut + KeyInit>(
+ &TestVector {
+ key,
+ nonce,
+ aad,
+ plaintext,
+ ciphertext,
+ }: &TestVector,
+) -> Result<(), &'static str> {
+ let nonce = nonce.try_into().expect("wrong nonce size");
+ let cipher = <C as KeyInit>::new_from_slice(key).expect("failed to initialize the cipher");
+
+ let res = cipher
+ .encrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: plaintext,
+ },
+ )
+ .map_err(|_| "encryption failure")?;
+ if res != ciphertext {
+ return Err("encrypted data is different from target ciphertext");
+ }
+
+ let res = cipher
+ .decrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: ciphertext,
+ },
+ )
+ .map_err(|_| "decryption failure")?;
+ if res != plaintext {
+ return Err("decrypted data is different from target plaintext");
+ }
+
+ let (ct, tag) = match C::TAG_POSITION {
+ TagPosition::Prefix => {
+ let (tag, ct) = ciphertext.split_at(C::TagSize::USIZE);
+ (ct, tag)
+ }
+ TagPosition::Postfix => ciphertext.split_at(plaintext.len()),
+ };
+ let tag: &Tag<C> = tag.try_into().expect("tag has correct length");
+
+ // Fill output buffer with "garbage" to test that its data does not get read during encryption
+ let mut buf: alloc::vec::Vec<u8> = (0..plaintext.len()).map(|i| i as u8).collect();
+ let inout_buf = InOutBuf::new(plaintext, &mut buf).expect("pt and buf have the same length");
+
+ let calc_tag = cipher
+ .encrypt_inout_detached(nonce, aad, inout_buf)
+ .map_err(|_| "encrypt_inout_detached: encryption failure")?;
+ if tag != &calc_tag {
+ return Err("encrypt_inout_detached: tag mismatch");
+ }
+ if ct != buf {
+ return Err("encrypt_inout_detached: ciphertext mismatch");
+ }
+
+ // Fill output buffer with "garbage"
+ buf.iter_mut()
+ .enumerate()
+ .for_each(|(i, v): (usize, &mut u8)| *v = i as u8);
+
+ let inout_buf = InOutBuf::new(ct, &mut buf).expect("ct and buf have the same length");
+ cipher
+ .decrypt_inout_detached(nonce, aad, inout_buf, tag)
+ .map_err(|_| "decrypt_inout_detached: decryption failure")?;
+ if plaintext != buf {
+ return Err("decrypt_inout_detached: plaintext mismatch");
+ }
+
+ Ok(())
+}
+
+/// Run AEAD test for the provided failing test vector
+pub fn fail_test<C: AeadInOut + KeyInit>(
+ &TestVector {
+ key,
+ nonce,
+ aad,
+ ciphertext,
+ ..
+ }: &TestVector,
+) -> Result<(), &'static str> {
+ let nonce = nonce.try_into().expect("wrong nonce size");
+ let cipher = <C as KeyInit>::new_from_slice(key).expect("failed to initialize the cipher");
+
+ let res = cipher.decrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: ciphertext,
+ },
+ );
+ if res.is_ok() {
+ Err("decryption must return error")
+ } else {
+ Ok(())
+ }
+}
-/// Define AEAD test
+/// Define AEAD test for passing test vectors
#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! new_test {
+macro_rules! new_pass_test {
($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
#[test]
fn $name() {
- use aead::{
- dev::blobby::Blob6Iterator,
- generic_array::{typenum::Unsigned, GenericArray},
- Aead, KeyInit, Payload,
- };
-
- fn run_test(
- key: &[u8],
- nonce: &[u8],
- aad: &[u8],
- pt: &[u8],
- ct: &[u8],
- pass: bool,
- ) -> Result<(), &'static str> {
- let key = key.try_into().map_err(|_| "wrong key size")?;
- let cipher = <$cipher>::new(key);
- let nonce = nonce.try_into().map_err(|_| "wrong nonce size")?;
-
- if !pass {
- let res = cipher.decrypt(nonce, Payload { aad: aad, msg: ct });
- if res.is_ok() {
- return Err("decryption must return error");
- }
- return Ok(());
- }
+ use $crate::dev::TestVector;
- let res = cipher
- .encrypt(nonce, Payload { aad: aad, msg: pt })
- .map_err(|_| "encryption failure")?;
- if res != ct {
- return Err("encrypted data is different from target ciphertext");
- }
- let res = cipher
- .decrypt(nonce, Payload { aad: aad, msg: ct })
- .map_err(|_| "decryption failure")?;
- if res != pt {
- return Err("decrypted data is different from target plaintext");
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $test_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, nonce, aad, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ let res = $crate::dev::pass_test::<$cipher>(tv);
+
+ if let Err(reason) = res {
+ panic!(
+ "\n\
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n"
+ );
}
- Ok(())
}
+ }
+ };
+}
+
+/// Define AEAD test for failing test vectors
+#[macro_export]
+macro_rules! new_fail_test {
+ ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
+ #[test]
+ fn $name() {
+ use $crate::dev::TestVector;
+
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $test_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, nonce, aad, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ let res = $crate::dev::fail_test::<$cipher>(tv);
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob6Iterator::new(data).unwrap().enumerate() {
- let [key, nonce, aad, pt, ct, status] = row.unwrap();
- let pass = match status[0] {
- 0 => false,
- 1 => true,
- _ => panic!("invalid value for pass flag"),
- };
- if let Err(reason) = run_test(key, nonce, aad, pt, ct, pass) {
+ if let Err(reason) = res {
panic!(
"\n\
- Failed test №{}\n\
- reason: \t{:?}\n\
- key:\t{:?}\n\
- nonce:\t{:?}\n\
- aad:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n\
- pass:\t{}\n\
- ",
- i, reason, key, nonce, aad, pt, ct, pass,
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n"
);
}
}
### external/vendor/aead/src/lib.rs
@@ -1,76 +1,40 @@
-//! [Authenticated Encryption with Associated Data] (AEAD) traits
-//!
-//! This crate provides an abstract interface for AEAD ciphers, which guarantee
-//! both confidentiality and integrity, even from a powerful attacker who is
-//! able to execute [chosen-ciphertext attacks]. The resulting security property,
-//! [ciphertext indistinguishability], is considered a basic requirement for
-//! modern cryptographic implementations.
-//!
-//! See [RustCrypto/AEADs] for cipher implementations which use this trait.
-//!
-//! [Authenticated Encryption with Associated Data]: https://en.wikipedia.org/wiki/Authenticated_encryption
-//! [chosen-ciphertext attacks]: https://en.wikipedia.org/wiki/Chosen-ciphertext_attack
-//! [ciphertext indistinguishability]: https://en.wikipedia.org/wiki/Ciphertext_indistinguishability
-//! [RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs
-
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
#![forbid(unsafe_code)]
-#![warn(clippy::unwrap_used, missing_docs, rust_2018_idioms)]
#[cfg(feature = "alloc")]
extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
-
#[cfg(feature = "dev")]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
pub mod dev;
-#[cfg(feature = "stream")]
-#[cfg_attr(docsrs, doc(cfg(feature = "stream")))]
-pub mod stream;
-
-pub use crypto_common::{Key, KeyInit, KeySizeUser};
-pub use generic_array::{self, typenum::consts};
+pub use common::{
+ self, Key, KeyInit, KeySizeUser,
+ array::{self, typenum::consts},
+};
#[cfg(feature = "arrayvec")]
-#[cfg_attr(docsrs, doc(cfg(feature = "arrayvec")))]
pub use arrayvec;
-
#[cfg(feature = "bytes")]
-#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub use bytes;
-
-#[cfg(feature = "getrandom")]
-#[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))]
-pub use crypto_common::rand_core::OsRng;
-
-#[cfg(feature = "heapless")]
-#[cfg_attr(docsrs, doc(cfg(feature = "heapless")))]
-pub use heapless;
-
#[cfg(feature = "rand_core")]
-#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
-pub use crypto_common::rand_core;
+pub use common::{Generate, rand_core};
+pub use inout;
+use common::array::{Array, ArraySize, typenum::Unsigned};
use core::fmt;
-use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};
+use inout::InOutBuf;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
-
#[cfg(feature = "bytes")]
use bytes::BytesMut;
-#[cfg(feature = "rand_core")]
-use rand_core::{CryptoRng, RngCore};
-
/// Error type.
///
/// This type is deliberately opaque as to avoid potential side-channel
@@ -87,83 +51,83 @@ impl fmt::Display for Error {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for Error {}
+impl core::error::Error for Error {}
-/// Nonce: single-use value for ensuring ciphertexts are unique
-pub type Nonce<A> = GenericArray<u8, <A as AeadCore>::NonceSize>;
+/// Nonce: single-use value for ensuring ciphertexts are unique.
+///
+/// AEAD algorithms accept a parameter to encryption/decryption called
+/// a "nonce" which must be unique every time encryption is performed and
+/// never repeated for the same key. The nonce is often prepended to the
+/// ciphertext, a.k.a. an explicit nonce, but may also be an implicit counter.
+///
+/// AEAD decryption takes the nonce which was originally used to produce a
+/// given ciphertext as a parameter along with the ciphertext itself.
+///
+/// # Generating random nonces
+///
+/// Nonces don't necessarily have to be random, but it is a simple strategy
+/// which can be implemented as follows using the [`Generate`] trait
+/// (requires `getrandom` feature):
+///
+/// ```text
+/// use aead::{Nonce, Generate};
+///
+/// let nonce = Nonce::<AeadAlg>::generate();
+/// ```
+///
+/// <div class="warning">
+/// AEAD algorithms often fail catastrophically if nonces are ever repeated
+/// (with SIV modes being an exception).
+///
+/// Using random nonces runs the risk of repeating them unless the nonce
+/// size is particularly large, e.g. 192-bit extended nonces used by the
+/// `XChaCha20Poly1305` and `XSalsa20Poly1305` constructions.
+///
+/// [NIST SP 800-38D] recommends the following:
+///
+/// > The total number of invocations of the authenticated encryption
+/// > function shall not exceed 2<sup>32</sup>, including all IV lengths and all
+/// > instances of the authenticated encryption function with the given key.
+///
+/// Following this guideline, only 4,294,967,296 messages with random
+/// nonces can be encrypted under a given key. While this bound is high,
+/// it's possible to encounter in practice, and systems which might
+/// reach it should consider alternatives to purely random nonces, like
+/// a counter or a combination of a random nonce + counter.
+///
+/// See the [`aead-stream`] crate for a ready-made implementation of the latter.
+/// </div>
+///
+/// [NIST SP 800-38D]: https://csrc.nist.gov/publications/detail/sp/800-38d/final
+/// [`aead-stream`]: https://docs.rs/aead-stream
+pub type Nonce<A> = Array<u8, <A as AeadCore>::NonceSize>;
/// Tag: authentication code which ensures ciphertexts are authentic
-pub type Tag<A> = GenericArray<u8, <A as AeadCore>::TagSize>;
+pub type Tag<A> = Array<u8, <A as AeadCore>::TagSize>;
+
+/// Enum which specifies tag position used by an AEAD algorithm.
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+pub enum TagPosition {
+ /// Postfix tag
+ Postfix,
+ /// Prefix tag
+ Prefix,
+}
-/// Authenticated Encryption with Associated Data (AEAD) algorithm core trait.
-///
-/// Defines nonce, tag, and overhead sizes that are consumed by various other
-/// `Aead*` traits.
+/// Authenticated Encryption with Associated Data (AEAD) algorithm.
pub trait AeadCore {
/// The length of a nonce.
- type NonceSize: ArrayLength<u8>;
-
- /// The maximum length of the nonce.
- type TagSize: ArrayLength<u8>;
+ type NonceSize: ArraySize;
- /// The upper bound amount of additional space required to support a
- /// ciphertext vs. a plaintext.
- type CiphertextOverhead: ArrayLength<u8> + Unsigned;
+ /// The maximum length of the tag.
+ type TagSize: ArraySize;
- /// Generate a random nonce for this AEAD algorithm.
- ///
- /// AEAD algorithms accept a parameter to encryption/decryption called
- /// a "nonce" which must be unique every time encryption is performed and
- /// never repeated for the same key. The nonce is often prepended to the
- /// ciphertext. The nonce used to produce a given ciphertext must be passed
- /// to the decryption function in order for it to decrypt correctly.
- ///
- /// Nonces don't necessarily have to be random, but it is one strategy
- /// which is implemented by this function.
- ///
- /// # ⚠️Security Warning
- ///
- /// AEAD algorithms often fail catastrophically if nonces are ever repeated
- /// (with SIV modes being an exception).
- ///
- /// Using random nonces runs the risk of repeating them unless the nonce
- /// size is particularly large (e.g. 192-bit extended nonces used by the
- /// `XChaCha20Poly1305` and `XSalsa20Poly1305` constructions.
- ///
- /// [NIST SP 800-38D] recommends the following:
- ///
- /// > The total number of invocations of the authenticated encryption
- /// > function shall not exceed 2^32, including all IV lengths and all
- /// > instances of the authenticated encryption function with the given key.
- ///
- /// Following this guideline, only 4,294,967,296 messages with random
- /// nonces can be encrypted under a given key. While this bound is high,
- /// it's possible to encounter in practice, and systems which might
- /// reach it should consider alternatives to purely random nonces, like
- /// a counter or a combination of a random nonce + counter.
- ///
- /// See the [`stream`] module for a ready-made implementation of the latter.
- ///
- /// [NIST SP 800-38D]: https://csrc.nist.gov/publications/detail/sp/800-38d/final
- #[cfg(feature = "rand_core")]
- #[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
- fn generate_nonce(mut rng: impl CryptoRng + RngCore) -> Nonce<Self>
- where
- Nonce<Self>: Default,
- {
- let mut nonce = Nonce::<Self>::default();
- rng.fill_bytes(&mut nonce);
- nonce
- }
+ /// The AEAD tag position.
+ const TAG_POSITION: TagPosition;
}
/// Authenticated Encryption with Associated Data (AEAD) algorithm.
-///
-/// This trait is intended for use with stateless AEAD algorithms. The
-/// [`AeadMut`] trait provides a stateful interface.
#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub trait Aead: AeadCore {
/// Encrypt the given plaintext payload, and return the resulting
/// ciphertext as a vector of bytes.
@@ -188,6 +152,9 @@ pub trait Aead: AeadCore {
/// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not
/// use a postfix tag will need to override this to correctly assemble the
/// ciphertext message.
+ ///
+ /// # Errors
+ /// AEAD algorithm implementations may return an error if the plaintext or AAD are too long.
fn encrypt<'msg, 'aad>(
&self,
nonce: &Nonce<Self>,
@@ -211,70 +178,81 @@ pub trait Aead: AeadCore {
/// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not
/// use a postfix tag will need to override this to correctly parse the
/// ciphertext message.
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
+ /// - if the `ciphertext` is too long
+ /// - if the `aad` is too long
fn decrypt<'msg, 'aad>(
&self,
nonce: &Nonce<Self>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>>;
}
-/// Stateful Authenticated Encryption with Associated Data algorithm.
#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
-pub trait AeadMut: AeadCore {
- /// Encrypt the given plaintext slice, and return the resulting ciphertext
- /// as a vector of bytes.
- ///
- /// See notes on [`Aead::encrypt()`] about allowable message payloads and
- /// Associated Additional Data (AAD).
+impl<T: AeadInOut> Aead for T {
fn encrypt<'msg, 'aad>(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>>;
+ ) -> Result<Vec<u8>> {
+ let payload = plaintext.into();
+ let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
+ buffer.extend_from_slice(payload.msg);
+ self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
+ Ok(buffer)
+ }
- /// Decrypt the given ciphertext slice, and return the resulting plaintext
- /// as a vector of bytes.
- ///
- /// See notes on [`Aead::encrypt()`] and [`Aead::decrypt()`] about allowable
- /// message payloads and Associated Additional Data (AAD).
fn decrypt<'msg, 'aad>(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>>;
+ ) -> Result<Vec<u8>> {
+ let payload = ciphertext.into();
+ let mut buffer = Vec::from(payload.msg);
+ self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
+ Ok(buffer)
+ }
}
-/// Implement the `decrypt_in_place` method on [`AeadInPlace`] and
-/// [`AeadMutInPlace]`, using a macro to gloss over the `&self` vs `&mut self`.
-///
-/// Assumes a postfix authentication tag. AEAD ciphers which do not use a
-/// postfix authentication tag will need to define their own implementation.
-macro_rules! impl_decrypt_in_place {
- ($aead:expr, $nonce:expr, $aad:expr, $buffer:expr) => {{
- if $buffer.len() < Self::TagSize::to_usize() {
- return Err(Error);
- }
+/// In-place and inout AEAD trait which handles the authentication tag as a return value/separate parameter.
+pub trait AeadInOut: AeadCore {
+ /// Encrypt the data in the provided [`InOutBuf`], returning the authentication tag.
+ ///
+ /// # Errors
+ /// AEAD algorithm implementations may return an error if the plaintext or AAD are too long.
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ associated_data: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>>;
- let tag_pos = $buffer.len() - Self::TagSize::to_usize();
- let (msg, tag) = $buffer.as_mut().split_at_mut(tag_pos);
- $aead.decrypt_in_place_detached($nonce, $aad, msg, Tag::<Self>::from_slice(tag))?;
- $buffer.truncate(tag_pos);
- Ok(())
- }};
-}
+ /// Decrypt the data in the provided [`InOutBuf`], returning an error in the event the
+ /// provided authentication tag is invalid for the given ciphertext (i.e. ciphertext
+ /// is modified/unauthentic).
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
+ /// - if the `ciphertext` is too long
+ /// - if the `aad` is too long
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ associated_data: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()>;
-/// In-place stateless AEAD trait.
-///
-/// This trait is both object safe and has no dependencies on `alloc` or `std`.
-pub trait AeadInPlace: AeadCore {
/// Encrypt the given buffer containing a plaintext message in-place.
///
/// The buffer must have sufficient capacity to store the ciphertext
/// message, which will always be larger than the original plaintext.
/// The exact size needed is cipher-dependent, but generally includes
/// the size of an authentication tag.
///
+ /// # Errors
/// Returns an error if the buffer has insufficient capacity to store the
/// resulting ciphertext message.
fn encrypt_in_place(
@@ -283,191 +261,151 @@ pub trait AeadInPlace: AeadCore {
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
- let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?;
- buffer.extend_from_slice(tag.as_slice())?;
+ match Self::TAG_POSITION {
+ TagPosition::Prefix => {
+ let msg_len = buffer.len();
+ buffer.extend_from_slice(&Tag::<Self>::default())?;
+ let buffer = buffer.as_mut();
+ let tag_size = Self::TagSize::USIZE;
+ buffer.copy_within(..msg_len, tag_size);
+ let (tag_dst, msg) = buffer.split_at_mut(tag_size);
+ let tag = self.encrypt_inout_detached(nonce, associated_data, msg.into())?;
+ tag_dst.copy_from_slice(&tag);
+ }
+ TagPosition::Postfix => {
+ let tag =
+ self.encrypt_inout_detached(nonce, associated_data, buffer.as_mut().into())?;
+ buffer.extend_from_slice(tag.as_slice())?;
+ }
+ }
Ok(())
}
- /// Encrypt the data in-place, returning the authentication tag
- fn encrypt_in_place_detached(
- &self,
- nonce: &Nonce<Self>,
- associated_data: &[u8],
- buffer: &mut [u8],
- ) -> Result<Tag<Self>>;
-
/// Decrypt the message in-place, returning an error in the event the
/// provided authentication tag does not match the given ciphertext.
///
/// The buffer will be truncated to the length of the original plaintext
/// message upon success.
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
fn decrypt_in_place(
&self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
- impl_decrypt_in_place!(self, nonce, associated_data, buffer)
+ let tag_size = Self::TagSize::USIZE;
+ let tagless_len = buffer.len().checked_sub(tag_size).ok_or(Error)?;
+
+ match Self::TAG_POSITION {
+ TagPosition::Prefix => {
+ let (tag, msg) = buffer.as_mut().split_at_mut(tag_size);
+ let tag = Tag::<Self>::try_from(&*tag).expect("tag length mismatch");
+ self.decrypt_inout_detached(nonce, associated_data, msg.into(), &tag)?;
+ buffer.as_mut().copy_within(tag_size.., 0);
+ }
+ TagPosition::Postfix => {
+ let (msg, tag) = buffer.as_mut().split_at_mut(tagless_len);
+ let tag = Tag::<Self>::try_from(&*tag).expect("tag length mismatch");
+ self.decrypt_inout_detached(nonce, associated_data, msg.into(), &tag)?;
+ }
+ }
+ buffer.truncate(tagless_len);
+ Ok(())
}
-
- /// Decrypt the message in-place, returning an error in the event the provided
- /// authentication tag does not match the given ciphertext (i.e. ciphertext
- /// is modified/unauthentic)
- fn decrypt_in_place_detached(
- &self,
- nonce: &Nonce<Self>,
- associated_data: &[u8],
- buffer: &mut [u8],
- tag: &Tag<Self>,
- ) -> Result<()>;
}
-/// In-place stateful AEAD trait.
+/// Legacy in-place stateless AEAD trait.
///
-/// This trait is both object safe and has no dependencies on `alloc` or `std`.
-pub trait AeadMutInPlace: AeadCore {
+/// NOTE: deprecated! Please migrate to [`AeadInOut`].
+#[deprecated(since = "0.6.0", note = "use `AeadInOut` instead")]
+#[allow(clippy::missing_errors_doc)]
+pub trait AeadInPlace: AeadCore {
/// Encrypt the given buffer containing a plaintext message in-place.
- ///
- /// The buffer must have sufficient capacity to store the ciphertext
- /// message, which will always be larger than the original plaintext.
- /// The exact size needed is cipher-dependent, but generally includes
- /// the size of an authentication tag.
- ///
- /// Returns an error if the buffer has insufficient capacity to store the
- /// resulting ciphertext message.
+ #[deprecated(since = "0.6.0", note = "use `AeadInOut::encrypt_in_place` instead")]
fn encrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
- ) -> Result<()> {
- let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?;
- buffer.extend_from_slice(tag.as_slice())?;
- Ok(())
- }
+ buffer: &mut dyn Buffer,
+ ) -> Result<()>;
/// Encrypt the data in-place, returning the authentication tag
+ #[deprecated(
+ since = "0.6.0",
+ note = "use `AeadInOut::encrypt_inout_detached` instead"
+ )]
fn encrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag<Self>>;
/// Decrypt the message in-place, returning an error in the event the
/// provided authentication tag does not match the given ciphertext.
- ///
- /// The buffer will be truncated to the length of the original plaintext
- /// message upon success.
+ #[deprecated(since = "0.6.0", note = "use `AeadInOut::decrypt_in_place` instead")]
fn decrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
- ) -> Result<()> {
- impl_decrypt_in_place!(self, nonce, associated_data, buffer)
- }
+ buffer: &mut dyn Buffer,
+ ) -> Result<()>;
- /// Decrypt the data in-place, returning an error in the event the provided
+ /// Decrypt the message in-place, returning an error in the event the provided
/// authentication tag does not match the given ciphertext (i.e. ciphertext
/// is modified/unauthentic)
+ #[deprecated(
+ since = "0.6.0",
+ note = "use `AeadInOut::decrypt_inout_detached` instead"
+ )]
fn decrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag<Self>,
) -> Result<()>;
}
-#[cfg(feature = "alloc")]
-impl<Alg: AeadInPlace> Aead for Alg {
- fn encrypt<'msg, 'aad>(
- &self,
- nonce: &Nonce<Self>,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- fn decrypt<'msg, 'aad>(
- &self,
- nonce: &Nonce<Self>,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-}
-
-#[cfg(feature = "alloc")]
-impl<Alg: AeadMutInPlace> AeadMut for Alg {
- fn encrypt<'msg, 'aad>(
- &mut self,
- nonce: &Nonce<Self>,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- fn decrypt<'msg, 'aad>(
- &mut self,
- nonce: &Nonce<Self>,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-}
-
-impl<Alg: AeadInPlace> AeadMutInPlace for Alg {
+#[allow(deprecated)]
+impl<T: AeadInOut> AeadInPlace for T {
fn encrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
+ buffer: &mut dyn Buffer,
) -> Result<()> {
- <Self as AeadInPlace>::encrypt_in_place(self, nonce, associated_data, buffer)
+ <Self as AeadInOut>::encrypt_in_place(self, nonce, associated_data, buffer)
}
fn encrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag<Self>> {
- <Self as AeadInPlace>::encrypt_in_place_detached(self, nonce, associated_data, buffer)
+ self.encrypt_inout_detached(nonce, associated_data, buffer.into())
}
fn decrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
+ buffer: &mut dyn Buffer,
) -> Result<()> {
- <Self as AeadInPlace>::decrypt_in_place(self, nonce, associated_data, buffer)
+ <Self as AeadInOut>::decrypt_in_place(self, nonce, associated_data, buffer)
}
fn decrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag<Self>,
) -> Result<()> {
- <Self as AeadInPlace>::decrypt_in_place_detached(self, nonce, associated_data, buffer, tag)
+ self.decrypt_inout_detached(nonce, associated_data, buffer.into(), tag)
}
}
@@ -479,8 +417,7 @@ impl<Alg: AeadInPlace> AeadMutInPlace for Alg {
///
/// If you don't care about AAD, you can pass a `&[u8]` as the payload to
/// `encrypt`/`decrypt` and it will automatically be coerced to this type.
-#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+#[derive(Debug)]
pub struct Payload<'msg, 'aad> {
/// Message to be encrypted/decrypted
pub msg: &'msg [u8],
@@ -492,8 +429,7 @@ pub struct Payload<'msg, 'aad> {
pub aad: &'aad [u8],
}
-#[cfg(feature = "alloc")]
-impl<'msg, 'aad> From<&'msg [u8]> for Payload<'msg, 'aad> {
+impl<'msg> From<&'msg [u8]> for Payload<'msg, '_> {
fn from(msg: &'msg [u8]) -> Self {
Self { msg, aad: b"" }
}
@@ -514,10 +450,13 @@ pub trait Buffer: AsRef<[u8]> + AsMut<[u8]> {
self.as_ref().is_empty()
}
- /// Extend this buffer from the given slice
+ /// Extend this buffer from the given slice.
+ ///
+ /// # Errors
+ /// If the buffer has insufficient capacity.
fn extend_from_slice(&mut self, other: &[u8]) -> Result<()>;
- /// Truncate this buffer to the given size
+ /// Truncate this buffer to the given size.
fn truncate(&mut self, len: usize);
}
@@ -563,29 +502,3 @@ impl<const N: usize> Buffer for arrayvec::ArrayVec<u8, N> {
arrayvec::ArrayVec::truncate(self, len);
}
}
-
-#[cfg(feature = "heapless")]
-impl<const N: usize> Buffer for heapless::Vec<u8, N> {
- fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> {
- heapless::Vec::extend_from_slice(self, other).map_err(|_| Error)
- }
-
- fn truncate(&mut self, len: usize) {
- heapless::Vec::truncate(self, len);
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// Ensure that `AeadInPlace` is object-safe
- #[allow(dead_code)]
- type DynAeadInPlace<N, T, O> =
- dyn AeadInPlace<NonceSize = N, TagSize = T, CiphertextOverhead = O>;
-
- /// Ensure that `AeadMutInPlace` is object-safe
- #[allow(dead_code)]
- type DynAeadMutInPlace<N, T, O> =
- dyn AeadMutInPlace<NonceSize = N, TagSize = T, CiphertextOverhead = O>;
-}
### external/vendor/aead/src/stream.rs
@@ -1,542 +0,0 @@
-//! Streaming AEAD support.
-//!
-//! Implementation of the STREAM online authenticated encryption construction
-//! as described in the paper
-//! [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1].
-//!
-//! ## About
-//!
-//! The STREAM construction supports encrypting/decrypting sequences of AEAD
-//! message segments, which is useful in cases where the overall message is too
-//! large to fit in a single buffer and needs to be processed incrementally.
-//!
-//! STREAM defends against reordering and truncation attacks which are common
-//! in naive schemes which attempt to provide these properties, and is proven
-//! to meet the security definition of "nonce-based online authenticated
-//! encryption" (nOAE) as given in the aforementioned paper.
-//!
-//! ## Diagram
-//!
-//! 
-//!
-//! Legend:
-//!
-//! - 𝐄k: AEAD encryption under key `k`
-//! - 𝐌: message
-//! - 𝐍: nonce
-//! - 𝐀: additional associated data
-//! - 𝐂: ciphertext
-//! - 𝜏: MAC tag
-//!
-//! [1]: https://eprint.iacr.org/2015/189.pdf
-
-#![allow(clippy::upper_case_acronyms)]
-
-use crate::{AeadCore, AeadInPlace, Buffer, Error, Key, KeyInit, Result};
-use core::ops::{AddAssign, Sub};
-use generic_array::{
- typenum::{Unsigned, U4, U5},
- ArrayLength, GenericArray,
-};
-
-#[cfg(feature = "alloc")]
-use {crate::Payload, alloc::vec::Vec};
-
-/// Nonce as used by a given AEAD construction and STREAM primitive.
-pub type Nonce<A, S> = GenericArray<u8, NonceSize<A, S>>;
-
-/// Size of a nonce as used by a STREAM construction, sans the overhead of
-/// the STREAM protocol itself.
-pub type NonceSize<A, S> =
- <<A as AeadCore>::NonceSize as Sub<<S as StreamPrimitive<A>>::NonceOverhead>>::Output;
-
-/// STREAM encryptor instantiated with [`StreamBE32`] as the underlying
-/// STREAM primitive.
-pub type EncryptorBE32<A> = Encryptor<A, StreamBE32<A>>;
-
-/// STREAM decryptor instantiated with [`StreamBE32`] as the underlying
-/// STREAM primitive.
-pub type DecryptorBE32<A> = Decryptor<A, StreamBE32<A>>;
-
-/// STREAM encryptor instantiated with [`StreamLE31`] as the underlying
-/// STREAM primitive.
-pub type EncryptorLE31<A> = Encryptor<A, StreamLE31<A>>;
-
-/// STREAM decryptor instantiated with [`StreamLE31`] as the underlying
-/// STREAM primitive.
-pub type DecryptorLE31<A> = Decryptor<A, StreamLE31<A>>;
-
-/// Create a new STREAM from the provided AEAD.
-pub trait NewStream<A>: StreamPrimitive<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<Self::NonceOverhead>,
- NonceSize<A, Self>: ArrayLength<u8>,
-{
- /// Create a new STREAM with the given key and nonce.
- fn new(key: &Key<A>, nonce: &Nonce<A, Self>) -> Self
- where
- A: KeyInit,
- Self: Sized,
- {
- Self::from_aead(A::new(key), nonce)
- }
-
- /// Create a new STREAM from the given AEAD cipher.
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self;
-}
-
-/// Low-level STREAM implementation.
-///
-/// This trait provides a particular "flavor" of STREAM, as there are
-/// different ways the specifics of the construction can be implemented.
-///
-/// Deliberately immutable and stateless to permit parallel operation.
-pub trait StreamPrimitive<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<Self::NonceOverhead>,
- NonceSize<A, Self>: ArrayLength<u8>,
-{
- /// Number of bytes this STREAM primitive requires from the nonce.
- type NonceOverhead: ArrayLength<u8>;
-
- /// Type used as the STREAM counter.
- type Counter: AddAssign + Copy + Default + Eq;
-
- /// Value to use when incrementing the STREAM counter (i.e. one)
- const COUNTER_INCR: Self::Counter;
-
- /// Maximum value of the STREAM counter.
- const COUNTER_MAX: Self::Counter;
-
- /// Encrypt an AEAD message in-place at the given position in the STREAM.
- fn encrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()>;
-
- /// Decrypt an AEAD message in-place at the given position in the STREAM.
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()>;
-
- /// Encrypt the given plaintext payload, and return the resulting
- /// ciphertext as a vector of bytes.
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- fn encrypt<'msg, 'aad>(
- &self,
- position: Self::Counter,
- last_block: bool,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + A::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- /// Decrypt the given ciphertext slice, and return the resulting plaintext
- /// as a vector of bytes.
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- fn decrypt<'msg, 'aad>(
- &self,
- position: Self::Counter,
- last_block: bool,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- /// Obtain [`Encryptor`] for this [`StreamPrimitive`].
- fn encryptor(self) -> Encryptor<A, Self>
- where
- Self: Sized,
- {
- Encryptor::from_stream_primitive(self)
- }
-
- /// Obtain [`Decryptor`] for this [`StreamPrimitive`].
- fn decryptor(self) -> Decryptor<A, Self>
- where
- Self: Sized,
- {
- Decryptor::from_stream_primitive(self)
- }
-}
-
-/// Implement a stateful STREAM object (i.e. encryptor or decryptor)
-macro_rules! impl_stream_object {
- (
- $name:ident,
- $next_method:tt,
- $next_in_place_method:tt,
- $last_method:tt,
- $last_in_place_method:tt,
- $op:tt,
- $in_place_op:tt,
- $op_desc:expr,
- $obj_desc:expr
- ) => {
- #[doc = "Stateful STREAM object which can"]
- #[doc = $op_desc]
- #[doc = "AEAD messages one-at-a-time."]
- #[doc = ""]
- #[doc = "This corresponds to the "]
- #[doc = $obj_desc]
- #[doc = "object as defined in the paper"]
- #[doc = "[Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]."]
- #[doc = ""]
- #[doc = "[1]: https://eprint.iacr.org/2015/189.pdf"]
- pub struct $name<A, S>
- where
- A: AeadInPlace,
- S: StreamPrimitive<A>,
- A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
- NonceSize<A, S>: ArrayLength<u8>,
- {
- /// Underlying STREAM primitive.
- stream: S,
-
- /// Current position in the STREAM.
- position: S::Counter,
- }
-
- impl<A, S> $name<A, S>
- where
- A: AeadInPlace,
- S: StreamPrimitive<A>,
- A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
- NonceSize<A, S>: ArrayLength<u8>,
- {
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given AEAD key and nonce."]
- pub fn new(key: &Key<A>, nonce: &Nonce<A, S>) -> Self
- where
- A: KeyInit,
- S: NewStream<A>,
- {
- Self::from_stream_primitive(S::new(key, nonce))
- }
-
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given AEAD primitive."]
- pub fn from_aead(aead: A, nonce: &Nonce<A, S>) -> Self
- where
- A: KeyInit,
- S: NewStream<A>,
- {
- Self::from_stream_primitive(S::from_aead(aead, nonce))
- }
-
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given STREAM primitive."]
- pub fn from_stream_primitive(stream: S) -> Self {
- Self {
- stream,
- position: Default::default(),
- }
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the next AEAD message in this STREAM, returning the"]
- #[doc = "result as a [`Vec`]."]
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- pub fn $next_method<'msg, 'aad>(
- &mut self,
- payload: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- if self.position == S::COUNTER_MAX {
- // Counter overflow. Note that the maximum counter value is
- // deliberately disallowed, as it would preclude being able
- // to encrypt a last block (i.e. with `$last_in_place_method`)
- return Err(Error);
- }
-
- let result = self.stream.$op(self.position, false, payload)?;
-
- // Note: overflow checked above
- self.position += S::COUNTER_INCR;
- Ok(result)
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the next AEAD message in this STREAM in-place."]
- pub fn $next_in_place_method(
- &mut self,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- if self.position == S::COUNTER_MAX {
- // Counter overflow. Note that the maximum counter value is
- // deliberately disallowed, as it would preclude being able
- // to encrypt a last block (i.e. with `$last_in_place_method`)
- return Err(Error);
- }
-
- self.stream
- .$in_place_op(self.position, false, associated_data, buffer)?;
-
- // Note: overflow checked above
- self.position += S::COUNTER_INCR;
- Ok(())
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the last AEAD message in this STREAM,"]
- #[doc = "consuming the "]
- #[doc = $obj_desc]
- #[doc = "object in order to prevent further use."]
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- pub fn $last_method<'msg, 'aad>(
- self,
- payload: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- self.stream.$op(self.position, true, payload)
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the last AEAD message in this STREAM in-place,"]
- #[doc = "consuming the "]
- #[doc = $obj_desc]
- #[doc = "object in order to prevent further use."]
- pub fn $last_in_place_method(
- self,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- self.stream
- .$in_place_op(self.position, true, associated_data, buffer)
- }
- }
- };
-}
-
-impl_stream_object!(
- Encryptor,
- encrypt_next,
- encrypt_next_in_place,
- encrypt_last,
- encrypt_last_in_place,
- encrypt,
- encrypt_in_place,
- "encrypt",
- "ℰ STREAM encryptor"
-);
-
-impl_stream_object!(
- Decryptor,
- decrypt_next,
- decrypt_next_in_place,
- decrypt_last,
- decrypt_last_in_place,
- decrypt,
- decrypt_in_place,
- "decrypt",
- "𝒟 STREAM decryptor"
-);
-
-/// The original "Rogaway-flavored" STREAM as described in the paper
-/// [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1].
-///
-/// Uses a 32-bit big endian counter and 1-byte "last block" flag stored as
-/// the last 5-bytes of the AEAD nonce.
-///
-/// [1]: https://eprint.iacr.org/2015/189.pdf
-pub struct StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- /// Underlying AEAD cipher
- aead: A,
-
- /// Nonce (sans STREAM overhead)
- nonce: Nonce<A, Self>,
-}
-
-impl<A> NewStream<A> for StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
- Self {
- aead,
- nonce: nonce.clone(),
- }
- }
-}
-
-impl<A> StreamPrimitive<A> for StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- type NonceOverhead = U5;
- type Counter = u32;
- const COUNTER_INCR: u32 = 1;
- const COUNTER_MAX: u32 = core::u32::MAX;
-
- fn encrypt_in_place(
- &self,
- position: u32,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block);
- self.aead.encrypt_in_place(&nonce, associated_data, buffer)
- }
-
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block);
- self.aead.decrypt_in_place(&nonce, associated_data, buffer)
- }
-}
-
-impl<A> StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- /// Compute the full AEAD nonce including the STREAM counter and last
- /// block flag.
- fn aead_nonce(&self, position: u32, last_block: bool) -> crate::Nonce<A> {
- let mut result = GenericArray::default();
-
- // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics)
- let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
- prefix.copy_from_slice(&self.nonce);
-
- let (counter, flag) = tail.split_at_mut(4);
- counter.copy_from_slice(&position.to_be_bytes());
- flag[0] = last_block as u8;
-
- result
- }
-}
-
-/// STREAM as instantiated with a 31-bit little endian counter and 1-bit
-/// "last block" flag stored as the most significant bit of the counter
-/// when interpreted as a 32-bit integer.
-///
-/// The 31-bit + 1-bit value is stored as the last 4 bytes of the AEAD nonce.
-pub struct StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- /// Underlying AEAD cipher
- aead: A,
-
- /// Nonce (sans STREAM overhead)
- nonce: Nonce<A, Self>,
-}
-
-impl<A> NewStream<A> for StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
- Self {
- aead,
- nonce: nonce.clone(),
- }
- }
-}
-
-impl<A> StreamPrimitive<A> for StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- type NonceOverhead = U4;
- type Counter = u32;
- const COUNTER_INCR: u32 = 1;
- const COUNTER_MAX: u32 = 0xfff_ffff;
-
- fn encrypt_in_place(
- &self,
- position: u32,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block)?;
- self.aead.encrypt_in_place(&nonce, associated_data, buffer)
- }
-
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block)?;
- self.aead.decrypt_in_place(&nonce, associated_data, buffer)
- }
-}
-
-impl<A> StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- /// Compute the full AEAD nonce including the STREAM counter and last
- /// block flag.
- fn aead_nonce(&self, position: u32, last_block: bool) -> Result<crate::Nonce<A>> {
- if position > Self::COUNTER_MAX {
- return Err(Error);
- }
-
- let mut result = GenericArray::default();
-
- // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics)
- let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
- prefix.copy_from_slice(&self.nonce);
-
- let position_with_flag = position | ((last_block as u32) << 31);
- tail.copy_from_slice(&position_with_flag.to_le_bytes());
-
- Ok(result)
- }
-}
### external/vendor/aead/tests/data/postfix_fail.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/postfix_pass.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/prefix_fail.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/prefix_pass.blb
[binary or diff unavailable]
### external/vendor/aead/tests/dummy.rs
@@ -0,0 +1,195 @@
+//! This module defines dummy (horribly insecure!) AEAD implementations
+//! to test implementation of the AEAD traits and helper macros in the `dev` module.
+
+#![cfg(feature = "dev")]
+#![allow(missing_docs, reason = "tests")]
+#![allow(clippy::trivially_copy_pass_by_ref, reason = "tests")]
+#![allow(clippy::unwrap_used, reason = "tests")]
+
+use aead::{
+ AeadCore, AeadInOut, Error, Key, KeyInit, KeySizeUser, Nonce, Result, Tag, TagPosition,
+ array::Array, consts::U8,
+};
+use core::fmt;
+use inout::InOutBuf;
+
+struct DummyAead {
+ key: [u8; 8],
+}
+
+impl fmt::Debug for DummyAead {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("DummyAead").finish_non_exhaustive()
+ }
+}
+
+impl DummyAead {
+ fn process_aad(&self, nonce: &[u8; 8], aad: &[u8]) -> u64 {
+ let mut tag = u64::from_le_bytes(*nonce);
+ let key = u64::from_le_bytes(self.key);
+
+ let mut aad_iter = aad.chunks_exact(8);
+ for chunk in &mut aad_iter {
+ tag ^= u64::from_le_bytes(chunk.try_into().unwrap());
+ tag = tag.wrapping_add(key);
+ }
+ let aad_rem = aad_iter.remainder();
+ if !aad_rem.is_empty() {
+ let mut chunk = [0u8; 8];
+ chunk[..aad_rem.len()].copy_from_slice(aad_rem);
+ tag ^= u64::from_le_bytes(chunk);
+ tag = tag.wrapping_add(key);
+ }
+
+ tag
+ }
+
+ fn encrypt_inner(
+ &self,
+ nonce: &[u8; 8],
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<[u8; 8]> {
+ let mut tag = self.process_aad(nonce, aad);
+
+ let (blocks, mut rem) = buffer.into_chunks::<U8>();
+ for mut block in blocks {
+ block.xor_in2out(&self.key.into());
+ tag ^= u64::from_be_bytes(block.get_out().0);
+ }
+
+ if !rem.is_empty() {
+ rem.xor_in2out(&self.key[..rem.len()]);
+
+ let out_rem = rem.get_out();
+ let mut block = [0u8; 8];
+ block[..out_rem.len()].copy_from_slice(out_rem);
+ tag ^= u64::from_le_bytes(block);
+ }
+
+ Ok(tag.to_le_bytes())
+ }
+
+ fn decrypt_inner(
+ &self,
+ nonce: &[u8; 8],
+ aad: &[u8],
+ mut buffer: InOutBuf<'_, '_, u8>,
+ tag: &[u8; 8],
+ ) -> Result<()> {
+ let exp_tag = u64::from_le_bytes(*tag);
+ let mut tag = self.process_aad(nonce, aad);
+
+ let (blocks, mut rem) = buffer.reborrow().into_chunks::<U8>();
+ for mut block in blocks {
+ tag ^= u64::from_be_bytes(block.get_in().0);
+ block.xor_in2out(&self.key.into());
+ }
+
+ if !rem.is_empty() {
+ let in_rem = rem.get_in();
+ let mut block = [0u8; 8];
+ block[..in_rem.len()].copy_from_slice(in_rem);
+ tag ^= u64::from_le_bytes(block);
+
+ rem.xor_in2out(&self.key[..rem.len()]);
+ }
+
+ if tag == exp_tag {
+ Ok(())
+ } else {
+ buffer.get_out().fill(0);
+ Err(Error)
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct PrefixDummyAead(DummyAead);
+
+impl KeySizeUser for PrefixDummyAead {
+ type KeySize = U8;
+}
+
+impl KeyInit for PrefixDummyAead {
+ fn new(key: &Key<Self>) -> Self {
+ Self(DummyAead { key: key.0 })
+ }
+}
+
+impl AeadCore for PrefixDummyAead {
+ type NonceSize = U8;
+ type TagSize = U8;
+ const TAG_POSITION: TagPosition = TagPosition::Prefix;
+}
+
+impl AeadInOut for PrefixDummyAead {
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>> {
+ self.0.encrypt_inner(nonce.into(), aad, buffer).map(Array)
+ }
+
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()> {
+ self.0.decrypt_inner(nonce.into(), aad, buffer, tag.into())
+ }
+}
+
+#[derive(Debug)]
+pub struct PostfixDummyAead(DummyAead);
+
+impl KeySizeUser for PostfixDummyAead {
+ type KeySize = U8;
+}
+
+impl KeyInit for PostfixDummyAead {
+ fn new(key: &Key<Self>) -> Self {
+ Self(DummyAead { key: key.0 })
+ }
+}
+
+impl AeadCore for PostfixDummyAead {
+ type NonceSize = U8;
+ type TagSize = U8;
+ const TAG_POSITION: TagPosition = TagPosition::Postfix;
+}
+
+impl AeadInOut for PostfixDummyAead {
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>> {
+ self.0.encrypt_inner(nonce.into(), aad, buffer).map(Array)
+ }
+
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()> {
+ self.0.decrypt_inner(nonce.into(), aad, buffer, tag.into())
+ }
+}
+
+#[cfg(feature = "dev")]
+mod tests {
+ use super::{PostfixDummyAead, PrefixDummyAead};
+
+ aead::new_pass_test!(dummy_prefix_pass, "prefix_pass", PrefixDummyAead);
+ aead::new_fail_test!(dummy_prefix_fail, "prefix_fail", PrefixDummyAead);
+ aead::new_pass_test!(dummy_postfix_pass, "postfix_pass", PostfixDummyAead);
+ aead::new_fail_test!(dummy_postfix_fail, "postfix_fail", PostfixDummyAead);
+}
### external/vendor/base16ct/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"61e987635c874915b3f443ae090ab3e290dbc924fa295ecd30000ea90ef56f1a","CHANGELOG.md":"4804ca1b5d84da4177354125912a29ca7a9a6a4ebba5b752fcee61911c9fe23f","Cargo.toml":"5050aa1f3351bf8c11a55b9695a41f5ec4652c95d7243c5b45a301692e2782e6","Cargo.toml.orig":"1c06e13c10380bc494ec2909809e4d38ac1dd7875f0d676ea3b7c3df3628b57c","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"0aa8963e105e8b6e02f634484145d4e5b0f42d0a6dd05c16f8148f033383adef","README.md":"535e9fe765cd20cc185be3458871253bca8ded1c2132e6e20ed3706044ddf2e9","benches/mod.rs":"976e6c0443e69a0578a2cf2252c4ed486ff0dc39823d0c369625e31c89941657","src/display.rs":"7042d46254a4fe4c1d66fe41be90916010247fd6dbdf3e87532541aa1a199696","src/error.rs":"8c5ac9c8d2d3b6fe18d8cf56d7e48149fb4d44c32ccb71f566f243c70e9bb187","src/lib.rs":"be52249977ee3d023a22beb0f805ad2d2bd69333cd17a0670c92002e57557ce9","src/lower.rs":"5ed8a602a6fbbe15c01c27a18a579a9df0599cecab7bd0420b26862c62ea91aa","src/mixed.rs":"12fc969194a5bf4776c9f1ccfd208c1abfa9e0abcd265a9b493f0af8382163dc","src/upper.rs":"c75c9b6ef7eddc5e23ef1699b1445ddf729e031a13e328c9e9b181e681daeec1","tests/lib.rs":"1b5ae439670c8c1ca3843922bd484dc642b660d91f401a29fa279d9e01fdab92"},"package":"4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"82c6aaf4f1ee71c1a6a4e032c566292f1720415831469cc9d1d26c94b7042ea8","CHANGELOG.md":"b2e1c87ae9da42e56f8c3870a60d04c16fab092c3b6da647c863cda01e18011a","Cargo.lock":"f0014bb1c2ab24d793a3a8501854b7fe5b5d7e0513cf75bd846b171ed7eafdea","Cargo.toml":"71f43fd6a618c6914ea149f9adb39d11a39876071ea01556b8bee0e93d9d632e","Cargo.toml.orig":"be56ce3a1760d8860032adc72ba887a735b93f1a087f43946a68312b8f411161","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"54fb6dfe99a6906f862aa40282f0e8e9d9d0f22d57d99ab8acbaf4c8ceaa70e0","README.md":"e84a0d385575ff9e54c3b89265c8da316b9a8673a0a7c11c3a728e76a557cdb5","benches/mod.rs":"be5c1574736c0d48f1df7b00a4fb9935e4b850cda1685d8cd5bc61a4411b6094","src/display.rs":"9e45093df7c2a3c758e499d3fec1d60e400df554f158f0d26bc6e93f98ff43e0","src/error.rs":"56b2c8893aec1331796a4c951476e2e20b45b55848d14e1116dbf4a1f195e589","src/lib.rs":"178db5fdbf52816e139a958b2739494d4b17f8e54905ab9155ef1c84410fedb8","src/lower.rs":"21b523f53f17b14051d60d2792b9186ad7ce744f4ee8fb3584cd3ecad7c032d9","src/mixed.rs":"2d13475dc62ff8431daa6792f3240e11d22f0f93c221529645f5080fbedb73c8","src/upper.rs":"e527d6a26c14698e988317b7e8a5d15e65e50fdee67b5e11da512f51349982ab","tests/lib.rs":"1b5ae439670c8c1ca3843922bd484dc642b660d91f401a29fa279d9e01fdab92"},"package":"fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"}
\ No newline at end of file
### external/vendor/base16ct/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1987929403b544d4632121aacff3d28aa09a0771"
+ "sha1": "071bfe69e2010e869397d27c63a88f188bd6477b"
},
"path_in_vcs": "base16ct"
}
\ No newline at end of file
### external/vendor/base16ct/CHANGELOG.md
@@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 1.0.0 (2026-01-03)
+### Fixed
+- Switch from `doc_auto_cfg` to `doc_cfg` ([#2072])
+
+[#2072]: https://github.com/RustCrypto/formats/pull/2072
+
+## 0.3.0 (2025-08-20)
+### Changed
+- Upgrade to 2024 edition; MSRV 1.85 ([#1670])
+- Use `core::error:Error` ([#1842])
+
+### Removed
+- `std` feature ([#2004])
+
+[#1670]: https://github.com/RustCrypto/formats/pull/1670
+[#1842]: https://github.com/RustCrypto/formats/pull/1842
+[#2004]: https://github.com/RustCrypto/formats/pull/2004
+
## 0.2.0 (2023-02-26)
### Changed
- MSRV 1.60 ([#802])
### external/vendor/base16ct/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "base16ct"
+version = "1.0.0"
### external/vendor/base16ct/Cargo.toml
@@ -10,16 +10,23 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.60"
+edition = "2024"
+rust-version = "1.85"
name = "base16ct"
-version = "0.2.0"
+version = "1.0.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Pure Rust implementation of Base16 a.k.a hexadecimal (RFC 4648) which avoids
any usages of data-dependent branches/LUTs and thereby provides portable
-\"best effort\" constant-time operation and embedded-friendly no_std support
+"best effort" constant-time operation and embedded-friendly no_std support
"""
+homepage = "https://github.com/RustCrypto/formats/tree/master/base16ct"
documentation = "https://docs.rs/base16ct"
readme = "README.md"
keywords = [
@@ -34,7 +41,8 @@ categories = [
"parser-implementations",
]
license = "Apache-2.0 OR MIT"
-repository = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+repository = "https://github.com/RustCrypto/formats"
+resolver = "2"
[package.metadata.docs.rs]
all-features = true
@@ -45,4 +53,15 @@ rustdoc-args = [
[features]
alloc = []
-std = ["alloc"]
+
+[lib]
+name = "base16ct"
+path = "src/lib.rs"
+
+[[test]]
+name = "lib"
+path = "tests/lib.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
### external/vendor/base16ct/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "base16ct"
-version = "0.2.0"
+version = "1.0.0"
description = """
Pure Rust implementation of Base16 a.k.a hexadecimal (RFC 4648) which avoids
any usages of data-dependent branches/LUTs and thereby provides portable
@@ -9,16 +9,16 @@ any usages of data-dependent branches/LUTs and thereby provides portable
authors = ["RustCrypto Developers"]
license = "Apache-2.0 OR MIT"
documentation = "https://docs.rs/base16ct"
-repository = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+homepage = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+repository = "https://github.com/RustCrypto/formats"
categories = ["cryptography", "encoding", "no-std", "parser-implementations"]
keywords = ["crypto", "hex", "hexadecimal"]
readme = "README.md"
-edition = "2021"
-rust-version = "1.60"
+edition = "2024"
+rust-version = "1.85"
[features]
alloc = []
-std = ["alloc"]
[package.metadata.docs.rs]
all-features = true
### external/vendor/base16ct/LICENSE-MIT
@@ -1,5 +1,5 @@
Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
-Copyright (c) 2022 The RustCrypto Project Developers
+Copyright (c) 2022-2025 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/base16ct/README.md
@@ -18,12 +18,12 @@ Supports `no_std` environments and avoids heap allocations in the core API
[Documentation][docs-link]
-## Minimum Supported Rust Version
+## Minimum Supported Rust Version (MSRV) Policy
-This crate requires **Rust 1.60** at a minimum.
+MSRV increases are not considered breaking changes and can happen in patch releases.
-We may change the MSRV in the future, but it will be accompanied by a minor
-version bump.
+The crate MSRV accounts for all supported targets and crate feature combinations, excluding
+explicitly unstable features.
## License
@@ -42,14 +42,14 @@ dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
-[crate-image]: https://buildstats.info/crate/base16ct
+[crate-image]: https://img.shields.io/crates/v/base16ct
[crate-link]: https://crates.io/crates/base16ct
[docs-image]: https://docs.rs/base16ct/badge.svg
[docs-link]: https://docs.rs/base16ct/
[build-image]: https://github.com/RustCrypto/formats/actions/workflows/base16ct.yml/badge.svg
[build-link]: https://github.com/RustCrypto/formats/actions/workflows/base16ct.yml
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/300570-formats
### external/vendor/base16ct/benches/mod.rs
@@ -1,7 +1,7 @@
#![feature(test)]
extern crate test;
-use test::{black_box, Bencher};
+use test::{Bencher, black_box};
#[bench]
fn decode_lower(b: &mut Bencher) {
### external/vendor/base16ct/src/display.rs
@@ -6,7 +6,7 @@ pub struct HexDisplay<'a>(pub &'a [u8]);
impl fmt::Display for HexDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{:X}", self)
+ write!(f, "{self:X}")
}
}
### external/vendor/base16ct/src/error.rs
@@ -22,11 +22,10 @@ impl fmt::Display for Error {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for Error {}
+impl core::error::Error for Error {}
-impl From<Error> for core::fmt::Error {
- fn from(_: Error) -> core::fmt::Error {
- core::fmt::Error::default()
+impl From<Error> for fmt::Error {
+ fn from(_: Error) -> fmt::Error {
+ fmt::Error
}
}
### external/vendor/base16ct/src/lib.rs
@@ -1,5 +1,5 @@
#![no_std]
-#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
@@ -62,8 +62,6 @@
#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
/// Function for decoding and encoding lower Base16 (hex)
pub mod lower;
### external/vendor/base16ct/src/lower.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, encoded_len, Error};
+use crate::{Error, decode_inner, encoded_len};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, String, Vec};
+use crate::{String, Vec, decoded_len};
/// Decode a lower Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
### external/vendor/base16ct/src/mixed.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, Error};
+use crate::{Error, decode_inner};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, Vec};
+use crate::{Vec, decoded_len};
/// Decode a mixed Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
### external/vendor/base16ct/src/upper.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, encoded_len, Error};
+use crate::{Error, decode_inner, encoded_len};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, String, Vec};
+use crate::{String, Vec, decoded_len};
/// Decode an upper Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
@@ -46,7 +46,7 @@ pub fn encode_string(input: &[u8]) -> String {
let res = encode(input, &mut dst).expect("dst length is correct");
debug_assert_eq!(elen, res.len());
- unsafe { crate::String::from_utf8_unchecked(dst) }
+ unsafe { String::from_utf8_unchecked(dst) }
}
/// Decode a single nibble of upper hex
### external/vendor/bip32-ed25519/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".github/workflows/ci.yml":"d0ff5825b83ec08980dbb04e73e937b936197b228b1bb011bcaafd3e77c28688","Cargo.toml":"adfbd61e5383bc0797d07f7ca8066f036d608eb0a8a8b94b0324de8253d3b23d","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"5530596cde343de2238ec3276d94599ff6e78b7b7a20f6143162b3eceb727f29","README.md":"99a18dfc2a588d8b8cb3c287dad52d2e76c2b2b3be0e7a95cce19f509e9d59d7","rustfmt.toml":"f32d2f03b3f4b1e295c79ed49d543f1205c7dac7c3dc74f05a5a27af4fea0584","src/arbitrary.rs":"ecb52788eec1142459ab252c320a5f0e421eb63cf959260b16e689ccfc8f2590","src/bigint.rs":"756b33c8d971b282b43268671c08fb4d8af095a6ebb6e9dc0c750631650e4d14","src/lib.rs":"5744fd99f11d4a98bf88a5f4e9f73e13eb56cf7b29bacd8ebd98736bd06d88af","tests/table_test.rs":"2507b6b762fa27044a0a3922073ee50e4bcfc2f66b10f8e3ac9d36a12818c51f","tests/testdata/gen_table.py":"2fd91055920d9ac4cfb6c004b96aca42aaf2e3cf074d0d49d48ada993abdaedf","tests/testdata/table.json":"9e37a43d759f793b091f87488ea4b6d733154a10d29554c5103e12d617ae70cd"},"package":null}
\ No newline at end of file
+{"files":{".github/workflows/ci.yml":"d0ff5825b83ec08980dbb04e73e937b936197b228b1bb011bcaafd3e77c28688","Cargo.toml":"0d6a579aca6b22f48fc66ae32bab55413e48b8d4c8d8a5d28644b84fa42b9dc5","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"5530596cde343de2238ec3276d94599ff6e78b7b7a20f6143162b3eceb727f29","README.md":"99a18dfc2a588d8b8cb3c287dad52d2e76c2b2b3be0e7a95cce19f509e9d59d7","rustfmt.toml":"f32d2f03b3f4b1e295c79ed49d543f1205c7dac7c3dc74f05a5a27af4fea0584","src/arbitrary.rs":"ecb52788eec1142459ab252c320a5f0e421eb63cf959260b16e689ccfc8f2590","src/bigint.rs":"756b33c8d971b282b43268671c08fb4d8af095a6ebb6e9dc0c750631650e4d14","src/lib.rs":"0dfd4c92271d5f3dbe2c0355265a975d60851a0feb0ba89031a74693acaf93a0","tests/table_test.rs":"0fa26516ff1b0fb4622ca1a6f32eaf30b90e1fcb0ec46f8667e91e99005180c1","tests/testdata/gen_table.py":"2fd91055920d9ac4cfb6c004b96aca42aaf2e3cf074d0d49d48ada993abdaedf","tests/testdata/table.json":"9e37a43d759f793b091f87488ea4b6d733154a10d29554c5103e12d617ae70cd"},"package":null}
\ No newline at end of file
### external/vendor/bip32-ed25519/Cargo.toml
@@ -12,7 +12,7 @@
[package]
edition = "2024"
name = "bip32-ed25519"
-version = "0.2.1"
+version = "0.2.2"
authors = ["Shift Crypto AG <support@shiftcrypto.ch>"]
build = false
autolib = false
@@ -38,31 +38,30 @@ name = "table_test"
path = "tests/table_test.rs"
[dependencies.curve25519-dalek]
-version = "4"
+version = "5.0"
default-features = false
[dependencies.digest]
-version = "0.10"
+version = "0.11"
default-features = false
[dependencies.hmac]
-version = "0.12"
-features = ["reset"]
+version = "0.13"
default-features = false
[dependencies.zeroize]
-version = "1"
+version = "1.9"
features = ["zeroize_derive"]
[dev-dependencies]
-ed25519-bip32 = "0.4.0"
-num-bigint = "0.4.0"
-quickcheck = "1"
-quickcheck_macros = "1"
-serde_json = "1.0.48"
+ed25519-bip32 = "0.5.0"
+num-bigint = "0.5.1"
+quickcheck = "1.1"
+quickcheck_macros = "1.2"
+serde_json = "1.0.154"
[dev-dependencies.ed25519-dalek]
-version = "2.0.0"
+version = "3.0.0"
features = ["hazmat"]
default-features = false
@@ -71,9 +70,9 @@ version = "0.4.3"
features = ["serde"]
[dev-dependencies.serde]
-version = "1.0.104"
+version = "1.0.229"
features = ["derive"]
[dev-dependencies.sha2]
-version = "0.10"
+version = "0.11"
default-features = false
### external/vendor/bip32-ed25519/src/lib.rs
@@ -15,8 +15,8 @@ use alloc::boxed::Box;
use core::convert::TryInto;
use core::ops::{Deref, DerefMut};
-use digest::{Digest, core_api::BlockSizeUser, typenum::U64};
-use hmac::{Mac, SimpleHmac};
+use digest::{Digest, block_api::BlockSizeUser, typenum::U64};
+use hmac::{KeyInit, Mac, SimpleHmac};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use curve25519_dalek::{
### external/vendor/bip32-ed25519/tests/table_test.rs
@@ -1,13 +1,11 @@
+// Compare our key derivation with ed25519_bip32 using the same test vectors.
+
use serde::Deserialize;
use std::fs::File;
use std::io::BufReader;
-// Our crate:
use bip32_ed25519::{ED25519_EXPANDED_SECRET_KEY_SIZE, Xprv};
-// Another crate for comparison:
-use ed25519_bip32;
-
fn mk_other_xprv(
key: &[u8; ED25519_EXPANDED_SECRET_KEY_SIZE],
chain_code: &[u8; 32],
### external/vendor/blake2/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"4a6647eae78567b5ffee84c768035d1cc1291d305162b99d7add8c72d05a3441","CHANGELOG.md":"3ef44e9baac1fd907756799009f4452ace487c9e80b32518fe2bdb758929255f","Cargo.toml":"44e9d8775828733264ddd041abf6faab096ddc25b4d6138c0274a5c98b000bda","Cargo.toml.orig":"52e3b2e2163a7fa9c44f030daf65707bbcadb5f620657acaa47c7574909a6319","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"9c768944eb4a0422ca2efc25ea9fb2fb9e7fbd3fdb04e86b87366339cb7466db","README.md":"b0218e8484d85a340ca0e21c13752355e7a24e17497e62bdb674717f5eb88bec","benches/mod.rs":"f61c6cacfe1a3f70940806d0213572f7887dc1ecc9c1946a868baad3e8a6c341","src/as_bytes.rs":"01e8e60ef0a9b68fa6bae6c1577f3967aef442c245003967604eef7e9ccae5a9","src/consts.rs":"03edc1d4697a6074c9389202324444f27625ef11f17d34cc86b83d0dda920e79","src/lib.rs":"4014e33ab4dbe879ebf8168a4cbe88f71b837589e1cd238fd469e0579337f9ff","src/macros.rs":"4d92b71adb3f464758635fa00058d478b814bb5004e5677055815547acf3a698","src/simd.rs":"79d6d11d14664c908c2f6a2120c23e8de0e0422b610a8b838aa95ba469ef43fc","src/simd/simd_opt.rs":"b254d82005e288f1d07531ef71b2468be0bc70ae9bdba1b46001acac4db283fe","src/simd/simd_opt/u32x4.rs":"f87ab763a2f7a60e0192c9eb16df3fd172f7e1747cd26e081b5e7f074701b13c","src/simd/simd_opt/u64x4.rs":"6f9e371ec300bbb3af4f4f6d9b052257eb4da669b5595b16b17f4710559f5b85","src/simd/simdint.rs":"3b506bb05761752142f61ca8de138958af9a050ddcfe5bbf454dd9a003bf71c3","src/simd/simdop.rs":"6154f31c9675f33ba476eb6d5378deda657afc79ad43be1c9257f4f4306e43ce","src/simd/simdty.rs":"24e6e7eac6005eec0aceec7b96b3a8e04ca695479bfd22e704f51926515f6f13","tests/data/blake2b/fixed.blb":"b8e100fe195f7c201973fdcb6cfcd23cc752f5c8c9431a3076208ec81709d658","tests/data/blake2b/mac.blb":"79b14e080b63c0860823c7837b8b005d9b9fbeab6cd2eaa072621ff377eafd7a","tests/data/blake2b/variable.blb":"c91130bc29c9fad4c952b79c4126bebd752073d033bf41bfe54dd656b37698e9","tests/data/blake2s/mac.blb":"4bca0c66c84951babf34ff95b9d8b0d5f6332403000bbd40cebcc142ff22d832","tests/data/blake2s/variable.blb":"ef88d9f6407013337ac8ed587ec1552b502f1001e029291c6075b40e44e3d63a","tests/mac.rs":"1e5c414e1cd44cc023ea3b7dc8a154fe8a6b36dce496a3b7a5b933e412ed51c0","tests/mod.rs":"d2da3d57ecaddbfcf292fd0475ebfd988efd52f992bd08113ef4b990f961087d","tests/persona.rs":"5e7131d30c3b4a777cc8bd8c74c00cf418d80241da10a7b74e12282c8e3fd775"},"package":"46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"dc55676bed5522173a0baf94b038de34c10f1b2e803c40813441e25df6bf76fb","CHANGELOG.md":"60a32facded37f95db2c89e295f7280b4bd17b1b4847d2bb17126c7cb01aea09","Cargo.lock":"aa51a39fe57519335f332b45500c9f35d4a45c84d6cbc8463ba107c11f9c83ac","Cargo.toml":"2ebca3b53e39bae23244d2a83997b4cfcf18efe61297a0b0d8812f7829c94c8a","Cargo.toml.orig":"e0b6c564059c0f225bcc13401df1e86bd4aa7052f782764d6bb8112d08ffb8fe","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"3721e5764ca384059a3521d84c0fb40373894a099d8246fe76bf0d7418041846","README.md":"1d69f2703bc40269549abf1363b2fc77b0f7735be61e81766522394e2958e089","benches/mod.rs":"f61c6cacfe1a3f70940806d0213572f7887dc1ecc9c1946a868baad3e8a6c341","src/consts.rs":"fc125936729983d132a43c3a51df53efe0076424bb3b2e69d9ff13bc0d8b4f2f","src/lib.rs":"a2454ef04822408b8043216ce202cc96bf11d4b69c38a93efbe3a3479955319f","src/macros.rs":"a2af7261ea14747e094d1f63e7ea29051e95a41fe3bc80e77bcc63ffd4121e1e","src/simd.rs":"718011e305dfc2633ecc7fa397519cf59c4e581f1c56535b32ee595b1870c16e","tests/data/blake2b_kat.blb":"349fe288feb3454cc92bafec3a8dc288c5f866ad0f14ad1a88adcfedcd820160","tests/data/blake2b_mac_kat.blb":"59571b8b46a5aca8d4f220b7d2a26c0d3ea5b8091792ddc5ed39fb3d9c7a684d","tests/data/blake2b_variable_kat.blb":"3e5a2d116ae86e83cee17507bc47591be189d8ed75329df166198b5821749904","tests/data/blake2s_mac_kat.blb":"b92e00d6ea305740f5b0d605c1fca621f085da3466c938307aa36b913a6f0dff","tests/data/blake2s_variable_kat.blb":"3fc58809bface0b49de94a6b44b32773216da671c20976732b7a427abd2e7ad1","tests/mac.rs":"685068303355059636b59eab6ec57442e324e740800aadbad796bdd3b2f3f0bb","tests/mod.rs":"f8e158d0d3dd63b0c93b6788fce808c9e05fb59d2e6b5b22e61c12482e895fb3","tests/persona.rs":"1d72409e123ccc890599efa22cb9ac8883a9180e89d58b41a841ed875f80b1c9","tests/unkeyed.rs":"88b80ba41741e88e49b36b655ec73e4b618c3c3ddf5317789f580fecee5a4b70"},"package":"5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"}
\ No newline at end of file
### external/vendor/blake2/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1f727ce37ff40fa0cce84eb8543a45bdd3ca4a4e"
+ "sha1": "fa3084083d946ac12436567d5a59c0935d5db1fa"
},
"path_in_vcs": "blake2"
}
\ No newline at end of file
### external/vendor/blake2/CHANGELOG.md
@@ -5,6 +5,37 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.11.0 (2026-08-26)
+### Added
+- `zeroize` support ([#545])
+- `Blake2b128`, `Blake2b256`, `Blake2s128` type aliases ([#564])
+- `CustomizedInit` support ([#664])
+- `alloc` crate feature ([#678])
+
+### Changed
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#652])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+- Update to `digest` v0.11
+- Replace type aliases with newtypes ([#678])
+
+### Removed
+- `std` crate feature ([#678])
+- `Blake2bVar` and `Blake2sVar` types ([#744])
+- SIMD support ([#898])
+
+### Fixed
+- Handling of unkeyed hashes in keyed mode ([#510], [#612])
+
+[#510]: https://github.com/RustCrypto/hashes/pull/510
+[#545]: https://github.com/RustCrypto/hashes/pull/545
+[#564]: https://github.com/RustCrypto/hashes/pull/564
+[#612]: https://github.com/RustCrypto/hashes/pull/612
+[#652]: https://github.com/RustCrypto/hashes/pull/652
+[#664]: https://github.com/RustCrypto/hashes/pull/664
+[#678]: https://github.com/RustCrypto/hashes/pull/678
+[#744]: https://github.com/RustCrypto/hashes/pull/744
+[#898]: https://github.com/RustCrypto/hashes/pull/898
+
## 0.10.6 (2022-12-16)
### Added
- `size_opt` Cargo feature ([#440])
### external/vendor/blake2/Cargo.lock
@@ -0,0 +1,91 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "blake2"
+version = "0.11.0"
+dependencies = [
+ "digest",
+ "hex-literal",
+]
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "ctutils",
+ "zeroize",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/blake2/Cargo.toml
@@ -10,15 +10,21 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
name = "blake2"
-version = "0.10.6"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "BLAKE2 hash functions"
documentation = "https://docs.rs/blake2"
readme = "README.md"
keywords = [
- "crypto",
"blake2",
"hash",
"digest",
@@ -30,22 +36,47 @@ categories = [
license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/hashes"
+[package.metadata.docs.rs]
+all-features = true
+
+[features]
+alloc = ["digest/alloc"]
+default = ["alloc"]
+reset = []
+size_opt = []
+zeroize = ["digest/zeroize"]
+
+[lib]
+name = "blake2"
+path = "src/lib.rs"
+
+[[test]]
+name = "mac"
+path = "tests/mac.rs"
+
+[[test]]
+name = "mod"
+path = "tests/mod.rs"
+
+[[test]]
+name = "persona"
+path = "tests/persona.rs"
+
+[[test]]
+name = "unkeyed"
+path = "tests/unkeyed.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
+
[dependencies.digest]
-version = "0.10.3"
+version = "0.11"
features = ["mac"]
[dev-dependencies.digest]
-version = "0.10.3"
+version = "0.11"
features = ["dev"]
[dev-dependencies.hex-literal]
-version = "0.2.2"
-
-[features]
-default = ["std"]
-reset = []
-simd = []
-simd_asm = ["simd_opt"]
-simd_opt = ["simd"]
-size_opt = []
-std = ["digest/std"]
+version = "1"
### external/vendor/blake2/Cargo.toml.orig
@@ -1,28 +1,30 @@
[package]
name = "blake2"
-version = "0.10.6"
-description = "BLAKE2 hash functions"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-readme = "README.md"
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/blake2"
+readme = "README.md"
repository = "https://github.com/RustCrypto/hashes"
-keywords = ["crypto", "blake2", "hash", "digest"]
+license = "MIT OR Apache-2.0"
+keywords = ["blake2", "hash", "digest"]
categories = ["cryptography", "no-std"]
+description = "BLAKE2 hash functions"
[dependencies]
-digest = { version = "0.10.3", features = ["mac"] }
+digest = { version = "0.11", features = ["mac"] }
[dev-dependencies]
-digest = { version = "0.10.3", features = ["dev"] }
-hex-literal = "0.2.2"
+digest = { version = "0.11", features = ["dev"] }
+hex-literal = "1"
[features]
-default = ["std"]
-std = ["digest/std"]
+default = ["alloc"]
+alloc = ["digest/alloc"]
+zeroize = ["digest/zeroize"]
reset = [] # Enable reset functionality
-simd = []
-simd_opt = ["simd"]
-simd_asm = ["simd_opt"]
size_opt = [] # Optimize for code size. Removes some `inline(always)`
+
+[package.metadata.docs.rs]
+all-features = true
### external/vendor/blake2/LICENSE-MIT
@@ -1,5 +1,6 @@
-Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros
+Copyright (c) 2017-2026 The RustCrypto Project Developers
Copyright (c) 2017 Artyom Pavlov
+Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/blake2/README.md
@@ -2,33 +2,65 @@
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
-Pure Rust implementation of the [BLAKE2 hash function][1] family.
+Pure Rust implementation of the [BLAKE2] hash function family.
+
+## Examples
+
+### Fixed output size
+
+```rust
+use blake2::{Blake2b512, Blake2s256, Digest};
+use hex_literal::hex;
+
+// create a Blake2b512 object
+let mut hasher = Blake2b512::new();
+
+// write input message
+hasher.update(b"hello world");
+
+// read hash digest and consume hasher
+let hash = hasher.finalize();
+assert_eq!(hash, hex!(
+ "021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbc"
+ "c05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0"
+));
+
+// same example for Blake2s256:
+let mut hasher = Blake2s256::new();
+hasher.update(b"hello world");
+let hash = hasher.finalize();
+assert_eq!(hash, hex!("9aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b"));
+```
-[Documentation][docs-link]
+See the [`digest`] crate docs for additional examples.
-## Minimum Supported Rust Version
+### Variable output size
-Rust **1.41** or higher.
+This implementation supports output sizes variable at compile time:
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+```rust
+use blake2::{Blake2b, Digest, digest::consts::U10};
+use hex_literal::hex;
-## SemVer Policy
+type Blake2b80 = Blake2b<U10>;
-- All on-by-default features of this library are covered by SemVer
-- MSRV is considered exempt from SemVer as noted above
+let mut hasher = Blake2b80::new();
+hasher.update(b"my_input");
+let res = hasher.finalize();
+assert_eq!(res, hex!("2cc55c84e416924e6400"));
+```
## License
-Licensed under either of:
+The crate is licensed under either of:
- * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
- * [MIT license](http://opensource.org/licenses/MIT)
+* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
+* [MIT license](http://opensource.org/licenses/MIT)
at your option.
@@ -47,10 +79,11 @@ dual licensed as above, without any additional terms or conditions.
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260041-hashes
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
-[build-image]: https://github.com/RustCrypto/hashes/workflows/blake2/badge.svg?branch=master
-[build-link]: https://github.com/RustCrypto/hashes/actions?query=workflow%3Ablake2
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
+[build-image]: https://github.com/RustCrypto/hashes/actions/workflows/blake2.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/hashes/actions/workflows/blake2.yml?query=branch:master
[//]: # (general links)
-[1]: https://blake2.net/
+[BLAKE2]: https://blake2.net/
+[`digest`]: https://docs.rs/digest
### external/vendor/blake2/src/as_bytes.rs
@@ -1,45 +0,0 @@
-// Copyright 2016 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use core::mem;
-use core::slice;
-
-#[allow(clippy::missing_safety_doc)]
-pub unsafe trait Safe {}
-
-pub trait AsBytes {
- fn as_bytes(&self) -> &[u8];
- fn as_mut_bytes(&mut self) -> &mut [u8];
-}
-
-impl<T: Safe> AsBytes for [T] {
- #[inline]
- fn as_bytes(&self) -> &[u8] {
- unsafe {
- slice::from_raw_parts(self.as_ptr() as *const u8, self.len() * mem::size_of::<T>())
- }
- }
-
- #[inline]
- fn as_mut_bytes(&mut self) -> &mut [u8] {
- unsafe {
- slice::from_raw_parts_mut(
- self.as_mut_ptr() as *mut u8,
- self.len() * mem::size_of::<T>(),
- )
- }
- }
-}
-
-unsafe impl Safe for u8 {}
-unsafe impl Safe for u16 {}
-unsafe impl Safe for u32 {}
-unsafe impl Safe for u64 {}
-unsafe impl Safe for i8 {}
-unsafe impl Safe for i16 {}
-unsafe impl Safe for i32 {}
-unsafe impl Safe for i64 {}
### external/vendor/blake2/src/consts.rs
@@ -1,6 +1,4 @@
-#![allow(clippy::unreadable_literal)]
-
-pub static SIGMA: [[usize; 16]; 12] = [
+pub(crate) static SIGMA: [[usize; 16]; 12] = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
@@ -15,7 +13,7 @@ pub static SIGMA: [[usize; 16]; 12] = [
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
];
-pub static BLAKE2B_IV: [u64; 8] = [
+pub(crate) static BLAKE2B_IV: [u64; 8] = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
@@ -26,22 +24,6 @@ pub static BLAKE2B_IV: [u64; 8] = [
0x5be0cd19137e2179,
];
-/*
-pub const BLAKE2B_BLOCKBYTES : usize = 128;
-pub const BLAKE2B_OUTBYTES : usize = 64;
-pub const BLAKE2B_KEYBYTES : usize = 64;
-pub const BLAKE2B_SALTBYTES : usize = 16;
-pub const BLAKE2B_PERSONALBYTES : usize = 16;
-*/
-
-pub static BLAKE2S_IV: [u32; 8] = [
+pub(crate) static BLAKE2S_IV: [u32; 8] = [
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
];
-
-/*
-pub const BLAKE2S_BLOCKBYTES : usize = 64;
-pub const BLAKE2S_OUTBYTES : usize = 32;
-pub const BLAKE2S_KEYBYTES : usize = 32;
-pub const BLAKE2S_SALTBYTES : usize = 8;
-pub const BLAKE2S_PERSONALBYTES : usize = 8;
-*/
### external/vendor/blake2/src/lib.rs
@@ -1,115 +1,41 @@
-//! An implementation of the [BLAKE2][1] hash functions.
-//!
-//! # Usage
-//!
-//! [`Blake2b512`] and [`Blake2s256`] can be used in the following way:
-//!
-//! ```rust
-//! use blake2::{Blake2b512, Blake2s256, Digest};
-//! use hex_literal::hex;
-//!
-//! // create a Blake2b512 object
-//! let mut hasher = Blake2b512::new();
-//!
-//! // write input message
-//! hasher.update(b"hello world");
-//!
-//! // read hash digest and consume hasher
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("
-//! 021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbc
-//! c05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0
-//! ")[..]);
-//!
-//! // same example for Blake2s256:
-//! let mut hasher = Blake2s256::new();
-//! hasher.update(b"hello world");
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("
-//! 9aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b
-//! ")[..]);
-//! ```
-//!
-//! Also see [RustCrypto/hashes](https://github.com/RustCrypto/hashes) readme.
-//!
-//! ## Variable output size
-//!
-//! This implementation supports run and compile time variable sizes.
-//!
-//! Run time variable output example:
-//! ```rust
-//! use blake2::Blake2bVar;
-//! use blake2::digest::{Update, VariableOutput};
-//! use hex_literal::hex;
-//!
-//! let mut hasher = Blake2bVar::new(10).unwrap();
-//! hasher.update(b"my_input");
-//! let mut buf = [0u8; 10];
-//! hasher.finalize_variable(&mut buf).unwrap();
-//! assert_eq!(buf, hex!("2cc55c84e416924e6400"));
-//! ```
-//!
-//! Compile time variable output example:
-//! ```rust
-//! use blake2::{Blake2b, Digest, digest::consts::U10};
-//! use hex_literal::hex;
-//!
-//! type Blake2b80 = Blake2b<U10>;
-//!
-//! let mut hasher = Blake2b80::new();
-//! hasher.update(b"my_input");
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("2cc55c84e416924e6400")[..]);
-//! ```
-//!
-//! # Acknowledgment
-//! Based on the [blake2-rfc][2] crate.
-//!
-//! [1]: https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2
-//! [2]: https://github.com/cesarb/blake2-rfc
-
#![no_std]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
-#![cfg_attr(feature = "simd", feature(platform_intrinsics, repr_simd))]
-#![cfg_attr(feature = "simd", allow(incomplete_features))]
-
-#[cfg(feature = "std")]
-extern crate std;
+#![cfg_attr(docsrs, feature(doc_cfg))]
pub use digest::{self, Digest};
-use core::{convert::TryInto, fmt, marker::PhantomData, ops::Div};
+use core::{fmt, marker::PhantomData, ops::Div};
use digest::{
- block_buffer::{Lazy, LazyBuffer},
- consts::{U128, U32, U4, U64},
- core_api::{
- AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper,
- CtVariableCoreWrapper, OutputSizeUser, RtVariableCoreWrapper, TruncSide, UpdateCore,
- VariableOutputCore,
+ CustomizedInit, FixedOutput, HashMarker, InvalidOutputSize, MacMarker, Output, Update,
+ array::{Array, ArraySize},
+ block_api::{
+ AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, OutputSizeUser, TruncSide,
+ UpdateCore, VariableOutputCore, VariableOutputCoreCustomized,
},
- crypto_common::{InvalidLength, Key, KeyInit, KeySizeUser},
- generic_array::{ArrayLength, GenericArray},
- typenum::{IsLessOrEqual, LeEq, NonZero, Unsigned},
- FixedOutput, HashMarker, InvalidOutputSize, MacMarker, Output, Update,
+ block_buffer::{Lazy, LazyBuffer},
+ common::{InvalidLength, Key, KeyInit, KeySizeUser},
+ consts::{U4, U16, U32, U64, U128},
+ typenum::{IsLessOrEqual, True, Unsigned},
};
#[cfg(feature = "reset")]
use digest::{FixedOutputReset, Reset};
-mod as_bytes;
+#[cfg(feature = "zeroize")]
+use digest::zeroize::{Zeroize, ZeroizeOnDrop};
+
mod consts;
mod simd;
#[macro_use]
mod macros;
-use as_bytes::AsBytes;
use consts::{BLAKE2B_IV, BLAKE2S_IV};
-use simd::{u32x4, u64x4, Vector4};
+use simd::{u32x4, u64x4};
blake2_impl!(
Blake2bVarCore,
@@ -127,12 +53,30 @@ blake2_impl!(
"Blake2b instance with a fixed output.",
);
-/// BLAKE2b which allows to choose output size at runtime.
-pub type Blake2bVar = RtVariableCoreWrapper<Blake2bVarCore>;
-/// Core hasher state of BLAKE2b generic over output size.
-pub type Blake2bCore<OutSize> = CtVariableCoreWrapper<Blake2bVarCore, OutSize>;
-/// BLAKE2b generic over output size.
-pub type Blake2b<OutSize> = CoreWrapper<Blake2bCore<OutSize>>;
+digest::buffer_ct_variable!(
+ /// BLAKE2b generic over output size.
+ pub struct Blake2b<OutSize>(Blake2bVarCore);
+ exclude: SerializableState;
+ max_size: U64;
+);
+
+// TODO: impl in the macro
+impl<OutSize> CustomizedInit for Blake2b<OutSize>
+where
+ OutSize: ArraySize + IsLessOrEqual<U64, Output = True>,
+{
+ fn new_customized(customization: &[u8]) -> Self {
+ Self {
+ core: CustomizedInit::new_customized(customization),
+ buffer: Default::default(),
+ }
+ }
+}
+
+/// BLAKE2b-128 hasher state.
+pub type Blake2b128 = Blake2b<U16>;
+/// BLAKE2b-256 hasher state.
+pub type Blake2b256 = Blake2b<U32>;
/// BLAKE2b-512 hasher state.
pub type Blake2b512 = Blake2b<U64>;
@@ -157,12 +101,28 @@ blake2_impl!(
"Blake2s instance with a fixed output.",
);
-/// BLAKE2s which allows to choose output size at runtime.
-pub type Blake2sVar = RtVariableCoreWrapper<Blake2sVarCore>;
-/// Core hasher state of BLAKE2s generic over output size.
-pub type Blake2sCore<OutSize> = CtVariableCoreWrapper<Blake2sVarCore, OutSize>;
-/// BLAKE2s generic over output size.
-pub type Blake2s<OutSize> = CoreWrapper<Blake2sCore<OutSize>>;
+digest::buffer_ct_variable!(
+ /// BLAKE2s generic over output size.
+ pub struct Blake2s<OutSize>(Blake2sVarCore);
+ exclude: SerializableState;
+ max_size: U32;
+);
+
+// TODO: impl in the macro
+impl<OutSize> CustomizedInit for Blake2s<OutSize>
+where
+ OutSize: ArraySize + IsLessOrEqual<U32, Output = True>,
+{
+ fn new_customized(customization: &[u8]) -> Self {
+ Self {
+ core: CustomizedInit::new_customized(customization),
+ buffer: Default::default(),
+ }
+ }
+}
+
+/// BLAKE2s-128 hasher state.
+pub type Blake2s128 = Blake2s<U16>;
/// BLAKE2s-256 hasher state.
pub type Blake2s256 = Blake2s<U32>;
### external/vendor/blake2/src/macros.rs
@@ -44,8 +44,7 @@ macro_rules! blake2_impl {
// salt is two words long
if salt.len() < length {
- let mut padded_salt =
- GenericArray::<u8, <$bytes as Div<U4>>::Output>::default();
+ let mut padded_salt = Array::<u8, <$bytes as Div<U4>>::Output>::default();
for i in 0..salt.len() {
padded_salt[i] = salt[i];
}
@@ -63,8 +62,7 @@ macro_rules! blake2_impl {
// persona is also two words long
if persona.len() < length {
- let mut padded_persona =
- GenericArray::<u8, <$bytes as Div<U4>>::Output>::default();
+ let mut padded_persona = Array::<u8, <$bytes as Div<U4>>::Output>::default();
for i in 0..persona.len() {
padded_persona[i] = persona[i];
}
@@ -95,13 +93,14 @@ macro_rules! blake2_impl {
fn finalize_with_flag(
&mut self,
- final_block: &GenericArray<u8, $block_size>,
+ final_block: &Array<u8, $block_size>,
flag: $word,
out: &mut Output<Self>,
) {
self.compress(final_block, !0, flag);
- let buf = [self.h[0].to_le(), self.h[1].to_le()];
- out.copy_from_slice(buf.as_bytes())
+ let n = size_of::<$vec>();
+ out[..n].copy_from_slice(self.h[0].to_le().as_bytes());
+ out[n..].copy_from_slice(self.h[1].to_le().as_bytes());
}
fn compress(&mut self, block: &Block<Self>, f0: $word, f1: $word) {
@@ -224,7 +223,7 @@ macro_rules! blake2_impl {
) {
self.t += buffer.get_pos() as u64;
let block = buffer.pad_with_zeros();
- self.finalize_with_flag(block, 0, out);
+ self.finalize_with_flag(&block, 0, out);
}
}
@@ -248,6 +247,26 @@ macro_rules! blake2_impl {
f.write_str(concat!(stringify!($name), " { ... }"))
}
}
+
+ impl Drop for $name {
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ {
+ self.h.zeroize();
+ self.t.zeroize();
+ }
+ }
+ }
+
+ impl VariableOutputCoreCustomized for $name {
+ #[inline]
+ fn new_customized(customization: &[u8], output_size: usize) -> Self {
+ Self::new_with_params(&[], customization, 0, output_size)
+ }
+ }
+
+ #[cfg(feature = "zeroize")]
+ impl ZeroizeOnDrop for $name {}
};
}
@@ -259,66 +278,72 @@ macro_rules! blake2_mac_impl {
#[doc=$doc]
pub struct $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
core: $hash,
buffer: LazyBuffer<<$hash as BlockSizeUser>::BlockSize>,
#[cfg(feature = "reset")]
- key_block: Key<Self>,
+ key_block: Option<Key<Self>>,
_out: PhantomData<OutSize>,
}
impl<OutSize> $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
/// Create new instance using provided key, salt, and persona.
///
- /// Key length should not be bigger than block size, salt and persona
- /// length should not be bigger than quarter of block size. If any
- /// of those conditions is false the method will return an error.
+ /// Setting key to `None` indicates unkeyed usage.
+ ///
+ /// # Errors
+ ///
+ /// If key is `Some`, then its length should not be zero or bigger
+ /// than the block size. The salt and persona length should not be
+ /// bigger than quarter of block size. If any of those conditions is
+ /// false the method will return an error.
#[inline]
pub fn new_with_salt_and_personal(
- key: &[u8],
+ key: Option<&[u8]>,
salt: &[u8],
persona: &[u8],
) -> Result<Self, InvalidLength> {
- let kl = key.len();
+ let kl = key.map_or(0, |k| k.len());
let bs = <$hash as BlockSizeUser>::BlockSize::USIZE;
let qbs = bs / 4;
- if kl > bs || salt.len() > qbs || persona.len() > qbs {
+ if key.is_some() && kl == 0 || kl > bs || salt.len() > qbs || persona.len() > qbs {
return Err(InvalidLength);
}
- let mut padded_key = Block::<$hash>::default();
- padded_key[..kl].copy_from_slice(key);
+ let buffer = if let Some(k) = key {
+ let mut padded_key = Block::<$hash>::default();
+ padded_key[..kl].copy_from_slice(k);
+ LazyBuffer::new(&padded_key)
+ } else {
+ LazyBuffer::default()
+ };
Ok(Self {
- core: <$hash>::new_with_params(salt, persona, key.len(), OutSize::USIZE),
- buffer: LazyBuffer::new(&padded_key),
+ core: <$hash>::new_with_params(salt, persona, kl, OutSize::USIZE),
+ buffer,
#[cfg(feature = "reset")]
- key_block: {
+ key_block: key.map(|k| {
let mut t = Key::<Self>::default();
- t[..kl].copy_from_slice(key);
+ t[..kl].copy_from_slice(k);
t
- },
+ }),
_out: PhantomData,
})
}
}
impl<OutSize> KeySizeUser for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
type KeySize = $max_size;
}
impl<OutSize> KeyInit for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn new(key: &Key<Self>) -> Self {
@@ -340,7 +365,7 @@ macro_rules! blake2_mac_impl {
key_block: {
let mut t = Key::<Self>::default();
t[..kl].copy_from_slice(key);
- t
+ Some(t)
},
_out: PhantomData,
})
@@ -349,8 +374,7 @@ macro_rules! blake2_mac_impl {
impl<OutSize> Update for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn update(&mut self, input: &[u8]) {
@@ -361,16 +385,14 @@ macro_rules! blake2_mac_impl {
impl<OutSize> OutputSizeUser for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size> + 'static,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
type OutputSize = OutSize;
}
impl<OutSize> FixedOutput for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size> + 'static,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn finalize_into(mut self, out: &mut Output<Self>) {
@@ -384,23 +406,25 @@ macro_rules! blake2_mac_impl {
#[cfg(feature = "reset")]
impl<OutSize> Reset for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
fn reset(&mut self) {
self.core.reset();
- let kl = self.key_block.len();
- let mut padded_key = Block::<$hash>::default();
- padded_key[..kl].copy_from_slice(&self.key_block);
- self.buffer = LazyBuffer::new(&padded_key);
+ self.buffer = if let Some(k) = self.key_block {
+ let kl = k.len();
+ let mut padded_key = Block::<$hash>::default();
+ padded_key[..kl].copy_from_slice(&k);
+ LazyBuffer::new(&padded_key)
+ } else {
+ LazyBuffer::default()
+ }
}
}
#[cfg(feature = "reset")]
impl<OutSize> FixedOutputReset for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn finalize_into_reset(&mut self, out: &mut Output<Self>) {
@@ -412,21 +436,40 @@ macro_rules! blake2_mac_impl {
}
}
- impl<OutSize> MacMarker for $name<OutSize>
- where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ impl<OutSize> MacMarker for $name<OutSize> where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>
{
}
impl<OutSize> fmt::Debug for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{} {{ ... }}", stringify!($name), OutSize::USIZE)
}
}
+
+ impl<OutSize> Drop for $name<OutSize>
+ where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
+ {
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ {
+ // `self.core` zeroized by its `Drop` impl
+ self.buffer.zeroize();
+ #[cfg(feature = "reset")]
+ if let Some(mut key_block) = self.key_block {
+ key_block.zeroize();
+ }
+ }
+ }
+ }
+ #[cfg(feature = "zeroize")]
+ impl<OutSize> ZeroizeOnDrop for $name<OutSize> where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>
+ {
+ }
};
}
### external/vendor/blake2/src/simd.rs
@@ -1,63 +1,46 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-mod simd_opt;
-mod simdint;
-mod simdop;
-mod simdty;
-
-pub use self::simdty::{u32x4, u64x4};
-
-pub trait Vector4<T>: Copy {
- fn gather(src: &[T], i0: usize, i1: usize, i2: usize, i3: usize) -> Self;
-
- #[allow(clippy::wrong_self_convention)]
- fn from_le(self) -> Self;
- fn to_le(self) -> Self;
-
- fn wrapping_add(self, rhs: Self) -> Self;
-
- fn rotate_right_const(self, n: u32) -> Self;
-
- fn shuffle_left_1(self) -> Self;
- fn shuffle_left_2(self) -> Self;
- fn shuffle_left_3(self) -> Self;
-
- #[inline(always)]
- fn shuffle_right_1(self) -> Self {
- self.shuffle_left_3()
- }
- #[inline(always)]
- fn shuffle_right_2(self) -> Self {
- self.shuffle_left_2()
- }
- #[inline(always)]
- fn shuffle_right_3(self) -> Self {
- self.shuffle_left_1()
- }
-}
+use core::ops::{Add, BitXor, Shl, Shr};
+
+#[cfg(feature = "zeroize")]
+use digest::zeroize::Zeroize;
macro_rules! impl_vector4 {
($vec:ident, $word:ident) => {
- impl Vector4<$word> for $vec {
+ #[derive(Clone, Copy, Debug)]
+ #[repr(C)]
+ pub(crate) struct $vec(
+ pub(crate) $word,
+ pub(crate) $word,
+ pub(crate) $word,
+ pub(crate) $word,
+ );
+
+ impl $vec {
+ #[inline(always)]
+ pub(crate) fn new(e0: $word, e1: $word, e2: $word, e3: $word) -> Self {
+ Self(e0, e1, e2, e3)
+ }
+
#[inline(always)]
- fn gather(src: &[$word], i0: usize, i1: usize, i2: usize, i3: usize) -> Self {
+ pub(crate) fn gather(
+ src: &[$word],
+ i0: usize,
+ i1: usize,
+ i2: usize,
+ i3: usize,
+ ) -> Self {
$vec::new(src[i0], src[i1], src[i2], src[i3])
}
#[cfg(target_endian = "little")]
#[inline(always)]
- fn from_le(self) -> Self {
+ #[allow(clippy::wrong_self_convention)]
+ pub(crate) fn from_le(self) -> Self {
self
}
#[cfg(not(target_endian = "little"))]
#[inline(always)]
- fn from_le(self) -> Self {
+ pub(crate) fn from_le(self) -> Self {
$vec::new(
$word::from_le(self.0),
$word::from_le(self.1),
@@ -68,13 +51,13 @@ macro_rules! impl_vector4 {
#[cfg(target_endian = "little")]
#[inline(always)]
- fn to_le(self) -> Self {
+ pub(crate) fn to_le(self) -> Self {
self
}
#[cfg(not(target_endian = "little"))]
#[inline(always)]
- fn to_le(self) -> Self {
+ pub(crate) fn to_le(self) -> Self {
$vec::new(
self.0.to_le(),
self.1.to_le(),
@@ -84,55 +67,118 @@ macro_rules! impl_vector4 {
}
#[inline(always)]
- fn wrapping_add(self, rhs: Self) -> Self {
+ pub(crate) fn wrapping_add(self, rhs: Self) -> Self {
self + rhs
}
#[inline(always)]
- fn rotate_right_const(self, n: u32) -> Self {
- simd_opt::$vec::rotate_right_const(self, n)
+ pub(crate) fn rotate_right_const(self, n: u32) -> Self {
+ $vec::new(
+ self.0.rotate_right(n),
+ self.1.rotate_right(n),
+ self.2.rotate_right(n),
+ self.3.rotate_right(n),
+ )
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_1(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [1, 2, 3, 0];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn shuffle_left_1(self) -> Self {
+ $vec::new(self.1, self.2, self.3, self.0)
}
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_1(self) -> Self {
- $vec::new(self.1, self.2, self.3, self.0)
+ pub(crate) fn shuffle_left_2(self) -> Self {
+ $vec::new(self.2, self.3, self.0, self.1)
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_2(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [2, 3, 0, 1];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn shuffle_left_3(self) -> Self {
+ $vec::new(self.3, self.0, self.1, self.2)
}
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_2(self) -> Self {
- $vec::new(self.2, self.3, self.0, self.1)
+ pub(crate) fn shuffle_right_1(self) -> Self {
+ self.shuffle_left_3()
+ }
+ #[inline(always)]
+ pub(crate) fn shuffle_right_2(self) -> Self {
+ self.shuffle_left_2()
+ }
+ #[inline(always)]
+ pub(crate) fn shuffle_right_3(self) -> Self {
+ self.shuffle_left_1()
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_3(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [3, 0, 1, 2];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn as_bytes(&self) -> &[u8] {
+ let p = self as *const Self as *const u8;
+ unsafe { core::slice::from_raw_parts(p, core::mem::size_of::<Self>()) }
}
+ }
+
+ impl Add for $vec {
+ type Output = Self;
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_3(self) -> Self {
- $vec::new(self.3, self.0, self.1, self.2)
+ fn add(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0.wrapping_add(rhs.0),
+ self.1.wrapping_add(rhs.1),
+ self.2.wrapping_add(rhs.2),
+ self.3.wrapping_add(rhs.3),
+ )
+ }
+ }
+
+ impl BitXor for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn bitxor(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 ^ rhs.0,
+ self.1 ^ rhs.1,
+ self.2 ^ rhs.2,
+ self.3 ^ rhs.3,
+ )
+ }
+ }
+
+ impl Shl<$vec> for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn shl(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 << rhs.0,
+ self.1 << rhs.1,
+ self.2 << rhs.2,
+ self.3 << rhs.3,
+ )
+ }
+ }
+
+ impl Shr<$vec> for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn shr(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 >> rhs.0,
+ self.1 >> rhs.1,
+ self.2 >> rhs.2,
+ self.3 >> rhs.3,
+ )
+ }
+ }
+
+ #[cfg(feature = "zeroize")]
+ impl Zeroize for $vec {
+ fn zeroize(&mut self) {
+ self.0.zeroize();
+ self.1.zeroize();
+ self.2.zeroize();
+ self.3.zeroize();
}
}
};
### external/vendor/blake2/src/simd/simd_opt.rs
@@ -1,52 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#[allow(unused_macros)]
-#[cfg(feature = "simd")]
-macro_rules! transmute_shuffle {
- ($tmp:ident, $shuffle:ident, $vec:expr, $idx_n:expr, $idx:expr) => {
- unsafe {
- use crate::simd::simdint::$shuffle;
- use crate::simd::simdty::$tmp;
- use core::mem::transmute;
-
- const IDX: [u32; $idx_n] = $idx;
- let tmp_i: $tmp = transmute($vec);
- let tmp_o: $tmp = $shuffle(tmp_i, tmp_i, IDX);
- transmute(tmp_o)
- }
- };
-}
-
-#[cfg(feature = "simd")]
-pub mod u32x4;
-#[cfg(feature = "simd")]
-pub mod u64x4;
-
-#[cfg(not(feature = "simd"))]
-macro_rules! simd_opt {
- ($vec:ident) => {
- pub mod $vec {
- use crate::simd::simdty::$vec;
-
- #[inline(always)]
- pub fn rotate_right_const(vec: $vec, n: u32) -> $vec {
- $vec::new(
- vec.0.rotate_right(n),
- vec.1.rotate_right(n),
- vec.2.rotate_right(n),
- vec.3.rotate_right(n),
- )
- }
- }
- };
-}
-
-#[cfg(not(feature = "simd"))]
-simd_opt!(u32x4);
-#[cfg(not(feature = "simd"))]
-simd_opt!(u64x4);
### external/vendor/blake2/src/simd/simd_opt/u32x4.rs
@@ -1,69 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use crate::simd::simdty::u32x4;
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
- match n {
- 16 => rotate_right_16(vec),
- 8 => rotate_right_8(vec),
- _ => rotate_right_any(vec, n),
- }
-}
-
-#[cfg(not(feature = "simd_opt"))]
-#[inline(always)]
-pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
- rotate_right_any(vec, n)
-}
-
-#[inline(always)]
-fn rotate_right_any(vec: u32x4, n: u32) -> u32x4 {
- let r = n as u32;
- let l = 32 - r;
-
- (vec >> u32x4::new(r, r, r, r)) ^ (vec << u32x4::new(l, l, l, l))
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_16(vec: u32x4) -> u32x4 {
- if cfg!(target_feature = "ssse3") {
- // pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x16,
- simd_shuffle16,
- vec,
- 16,
- [2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]
- )
- } else if cfg!(any(target_feature = "sse2", target_feature = "neon")) {
- // pshuflw+pshufhw (SSE2) / vrev (NEON)
- transmute_shuffle!(u16x8, simd_shuffle8, vec, 8, [1, 0, 3, 2, 5, 4, 7, 6])
- } else {
- rotate_right_any(vec, 16)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_8(vec: u32x4) -> u32x4 {
- if cfg!(target_feature = "ssse3") {
- // pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x16,
- simd_shuffle16,
- vec,
- 16,
- [1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]
- )
- } else {
- rotate_right_any(vec, 8)
- }
-}
### external/vendor/blake2/src/simd/simd_opt/u64x4.rs
@@ -1,143 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use crate::simd::simdty::u64x4;
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 {
- match n {
- 32 => rotate_right_32(vec),
- 24 => rotate_right_24(vec),
- 16 => rotate_right_16(vec),
- _ => rotate_right_any(vec, n),
- }
-}
-
-#[cfg(not(feature = "simd_opt"))]
-#[inline(always)]
-pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 {
- rotate_right_any(vec, n)
-}
-
-#[inline(always)]
-fn rotate_right_any(vec: u64x4, n: u32) -> u64x4 {
- let r = n as u64;
- let l = 64 - r;
-
- (vec >> u64x4::new(r, r, r, r)) ^ (vec << u64x4::new(l, l, l, l))
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_32(vec: u64x4) -> u64x4 {
- if cfg!(any(target_feature = "sse2", target_feature = "neon")) {
- // 2 x pshufd (SSE2) / vpshufd (AVX2) / 2 x vrev (NEON)
- transmute_shuffle!(u32x8, simd_shuffle8, vec, 8, [1, 0, 3, 2, 5, 4, 7, 6])
- } else {
- rotate_right_any(vec, 32)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_24(vec: u64x4) -> u64x4 {
- if cfg!(all(
- feature = "simd_asm",
- target_feature = "neon",
- target_arch = "arm"
- )) {
- // 4 x vext (NEON)
- rotate_right_vext(vec, 3)
- } else if cfg!(target_feature = "ssse3") {
- // 2 x pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x32,
- simd_shuffle32,
- vec,
- 32,
- [
- 3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10, 19, 20, 21, 22, 23, 16, 17,
- 18, 27, 28, 29, 30, 31, 24, 25, 26
- ]
- )
- } else {
- rotate_right_any(vec, 24)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_16(vec: u64x4) -> u64x4 {
- if cfg!(all(
- feature = "simd_asm",
- target_feature = "neon",
- target_arch = "arm"
- )) {
- // 4 x vext (NEON)
- rotate_right_vext(vec, 2)
- } else if cfg!(target_feature = "ssse3") {
- // 2 x pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x32,
- simd_shuffle32,
- vec,
- 32,
- [
- 2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9, 18, 19, 20, 21, 22, 23, 16,
- 17, 26, 27, 28, 29, 30, 31, 24, 25
- ]
- )
- } else if cfg!(target_feature = "sse2") {
- // 2 x pshuflw+pshufhw (SSE2)
- transmute_shuffle!(
- u16x16,
- simd_shuffle16,
- vec,
- 16,
- [1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]
- )
- } else {
- rotate_right_any(vec, 16)
- }
-}
-
-#[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))]
-mod simd_asm_neon_arm {
- use crate::simd::simdty::{u64x2, u64x4};
-
- #[inline(always)]
- fn vext_u64(vec: u64x2, b: u8) -> u64x2 {
- unsafe {
- let result: u64x2;
- asm!("vext.8 ${0:e}, ${1:e}, ${1:e}, $2\nvext.8 ${0:f}, ${1:f}, ${1:f}, $2"
- : "=w" (result)
- : "w" (vec), "n" (b));
- result
- }
- }
-
- #[inline(always)]
- pub fn rotate_right_vext(vec: u64x4, b: u8) -> u64x4 {
- use crate::simd::simdint::{simd_shuffle2, simd_shuffle4};
-
- unsafe {
- let tmp0 = vext_u64(simd_shuffle2(vec, vec, [0, 1]), b);
- let tmp1 = vext_u64(simd_shuffle2(vec, vec, [2, 3]), b);
- simd_shuffle4(tmp0, tmp1, [0, 1, 2, 3])
- }
- }
-}
-
-#[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))]
-use self::simd_asm_neon_arm::rotate_right_vext;
-
-#[cfg(feature = "simd_opt")]
-#[cfg(not(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm")))]
-fn rotate_right_vext(_vec: u64x4, _n: u8) -> u64x4 {
- unreachable!()
-}
### external/vendor/blake2/src/simd/simdint.rs
@@ -1,22 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#![allow(dead_code)]
-
-#[cfg(feature = "simd")]
-extern "platform-intrinsic" {
- pub fn simd_add<T>(x: T, y: T) -> T;
- pub fn simd_shl<T>(x: T, y: T) -> T;
- pub fn simd_shr<T>(x: T, y: T) -> T;
- pub fn simd_xor<T>(x: T, y: T) -> T;
-
- pub fn simd_shuffle2<T, U>(v: T, w: T, idx: [u32; 2]) -> U;
- pub fn simd_shuffle4<T, U>(v: T, w: T, idx: [u32; 4]) -> U;
- pub fn simd_shuffle8<T, U>(v: T, w: T, idx: [u32; 8]) -> U;
- pub fn simd_shuffle16<T, U>(v: T, w: T, idx: [u32; 16]) -> U;
- pub fn simd_shuffle32<T, U>(v: T, w: T, idx: [u32; 32]) -> U;
-}
### external/vendor/blake2/src/simd/simdop.rs
@@ -1,103 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#[cfg(feature = "simd")]
-use crate::simd::simdint;
-use crate::simd::simdty::{u32x4, u64x4};
-
-use core::ops::{Add, BitXor, Shl, Shr};
-
-macro_rules! impl_ops {
- ($vec:ident) => {
- impl Add for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn add(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_add(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn add(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0.wrapping_add(rhs.0),
- self.1.wrapping_add(rhs.1),
- self.2.wrapping_add(rhs.2),
- self.3.wrapping_add(rhs.3),
- )
- }
- }
-
- impl BitXor for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn bitxor(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_xor(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn bitxor(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 ^ rhs.0,
- self.1 ^ rhs.1,
- self.2 ^ rhs.2,
- self.3 ^ rhs.3,
- )
- }
- }
-
- impl Shl<$vec> for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn shl(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_shl(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn shl(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 << rhs.0,
- self.1 << rhs.1,
- self.2 << rhs.2,
- self.3 << rhs.3,
- )
- }
- }
-
- impl Shr<$vec> for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn shr(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_shr(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn shr(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 >> rhs.0,
- self.1 >> rhs.1,
- self.2 >> rhs.2,
- self.3 >> rhs.3,
- )
- }
- }
- };
-}
-
-impl_ops!(u32x4);
-impl_ops!(u64x4);
### external/vendor/blake2/src/simd/simdty.rs
@@ -1,77 +0,0 @@
-// Copyright 2016 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#![allow(dead_code, non_camel_case_types)]
-
-use crate::as_bytes::Safe;
-
-#[cfg(feature = "simd")]
-macro_rules! decl_simd {
- ($($decl:item)*) => {
- $(
- #[derive(Clone, Copy, Debug)]
- #[repr(simd)]
- $decl
- )*
- }
-}
-
-#[cfg(not(feature = "simd"))]
-macro_rules! decl_simd {
- ($($decl:item)*) => {
- $(
- #[derive(Clone, Copy, Debug)]
- #[repr(C)]
- $decl
- )*
- }
-}
-
-decl_simd! {
- pub struct Simd2<T>(pub T, pub T);
- pub struct Simd4<T>(pub T, pub T, pub T, pub T);
- pub struct Simd8<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
- pub struct Simd16<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
- pub struct Simd32<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
-}
-
-pub type u64x2 = Simd2<u64>;
-
-pub type u32x4 = Simd4<u32>;
-pub type u64x4 = Simd4<u64>;
-
-pub type u16x8 = Simd8<u16>;
-pub type u32x8 = Simd8<u32>;
-
-pub type u8x16 = Simd16<u8>;
-pub type u16x16 = Simd16<u16>;
-
-pub type u8x32 = Simd32<u8>;
-
-impl<T> Simd4<T> {
- #[inline(always)]
- pub fn new(e0: T, e1: T, e2: T, e3: T) -> Simd4<T> {
- Simd4(e0, e1, e2, e3)
- }
-}
-
-unsafe impl<T: Safe> Safe for Simd2<T> {}
-unsafe impl<T: Safe> Safe for Simd4<T> {}
-unsafe impl<T: Safe> Safe for Simd8<T> {}
-unsafe impl<T: Safe> Safe for Simd16<T> {}
-unsafe impl<T: Safe> Safe for Simd32<T> {}
### external/vendor/blake2/tests/data/blake2b/fixed.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b/variable.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_mac_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_variable_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s/variable.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s_mac_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s_variable_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/mac.rs
@@ -1,22 +1,24 @@
#[cfg(not(feature = "reset"))]
-use digest::new_mac_test as new_test;
+use digest::dev::mac_test as test_fn;
#[cfg(feature = "reset")]
-use digest::new_resettable_mac_test as new_test;
+use digest::dev::reset_mac_test as test_fn;
-new_test!(blake2b_mac, "blake2b/mac", blake2::Blake2bMac512);
-new_test!(blake2s_mac, "blake2s/mac", blake2::Blake2sMac256);
+use digest::new_mac_test;
+
+new_mac_test!(blake2b_mac_kat, blake2::Blake2bMac512, test_fn);
+new_mac_test!(blake2s_mac_kat, blake2::Blake2sMac256, test_fn);
#[test]
fn blake2b_new_test() {
- use blake2::digest::{generic_array::GenericArray, KeyInit, Mac};
+ use blake2::digest::{KeyInit, Mac, array::Array};
fn run<T: Mac + KeyInit>(key: &[u8]) {
const DATA: &[u8] = &[42; 300];
- let res1 = <T as Mac>::new(GenericArray::from_slice(key))
+ let res1 = T::new(&Array::try_from(key).unwrap())
.chain_update(DATA)
.finalize()
.into_bytes();
- let res2 = <T as Mac>::new_from_slice(&key)
+ let res2 = T::new_from_slice(key)
.unwrap()
.chain_update(DATA)
.finalize()
@@ -27,3 +29,13 @@ fn blake2b_new_test() {
run::<blake2::Blake2sMac256>(&[0x42; 32]);
run::<blake2::Blake2bMac512>(&[0x42; 64]);
}
+
+#[test]
+fn mac_refuses_empty_keys() {
+ assert!(
+ blake2::Blake2bMac512::new_with_salt_and_personal(Some(&[]), b"salt", b"persona").is_err()
+ );
+ assert!(
+ blake2::Blake2sMac256::new_with_salt_and_personal(Some(&[]), b"salt", b"persona").is_err()
+ );
+}
### external/vendor/blake2/tests/mod.rs
@@ -1,19 +1,7 @@
#[cfg(feature = "reset")]
-use digest::dev::{fixed_reset_test as fixed_fn, variable_reset_test as varaible_fn};
+use digest::dev::fixed_reset_test as fixed_test;
#[cfg(not(feature = "reset"))]
-use digest::dev::{fixed_test as fixed_fn, variable_test as varaible_fn};
+use digest::dev::fixed_test;
use digest::new_test;
-new_test!(blake2b_fixed, "blake2b/fixed", blake2::Blake2b512, fixed_fn,);
-new_test!(
- blake2b_variable,
- "blake2b/variable",
- blake2::Blake2bVar,
- varaible_fn,
-);
-new_test!(
- blake2s_variable,
- "blake2s/variable",
- blake2::Blake2sVar,
- varaible_fn,
-);
+new_test!(blake2b_kat, blake2::Blake2b512, fixed_test);
### external/vendor/blake2/tests/persona.rs
@@ -1,40 +1,51 @@
-use blake2::{digest::FixedOutput, Blake2bMac512, Blake2sMac256};
+use blake2::digest::CustomizedInit;
+use blake2::{Blake2b128, Blake2bMac512, Blake2sMac256, digest::FixedOutput};
+use digest::Update;
use hex_literal::hex;
#[test]
-#[rustfmt::skip]
fn blake2s_persona() {
- let key= hex!("
- 000102030405060708090a0b0c0d0e0f
- 101112131415161718191a1b1c1d1e1f
- ");
+ let key = hex!(
+ "000102030405060708090a0b0c0d0e0f"
+ "101112131415161718191a1b1c1d1e1f"
+ );
let persona = b"personal";
- let ctx = Blake2sMac256::new_with_salt_and_personal(&key, &[], persona).unwrap();
+ let ctx = Blake2sMac256::new_with_salt_and_personal(Some(&key), &[], persona).unwrap();
assert_eq!(
- ctx.finalize_fixed()[..],
- hex!("
- 25a4ee63b594aed3f88a971e1877ef70
- 99534f9097291f88fb86c79b5e70d022
- ")[..],
+ ctx.finalize_fixed(),
+ hex!(
+ "25a4ee63b594aed3f88a971e1877ef70"
+ "99534f9097291f88fb86c79b5e70d022"
+ ),
);
}
#[test]
-#[rustfmt::skip]
fn blake2b_persona() {
- let key = hex!("
- 000102030405060708090a0b0c0d0e0f
- 101112131415161718191a1b1c1d1e1f
- ");
let persona = b"personal";
- let ctx = Blake2bMac512::new_with_salt_and_personal(&key, &[], persona).unwrap();
+ let mut ctx = Blake2b128::new_customized(persona);
+ ctx.update(b"hello");
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!("5a5eb0aecc053af1ce6de25354c1c761"),
+ );
+}
+
+#[test]
+fn blake2b_mac_persona() {
+ let key = hex!(
+ "000102030405060708090a0b0c0d0e0f"
+ "101112131415161718191a1b1c1d1e1f"
+ );
+ let persona = b"personal";
+ let ctx = Blake2bMac512::new_with_salt_and_personal(Some(&key), &[], persona).unwrap();
assert_eq!(
- ctx.finalize_fixed()[..],
- hex!("
- 03de3b295dcfc3b25b05abb09bc95fe3
- e9ff3073638badc68101d1e42019d077
- 1dd07525a3aae8318e92c5e5d967ba92
- e4810d0021d7bf3b49da0b4b4a8a4e1f
- ")[..],
+ ctx.finalize_fixed(),
+ hex!(
+ "03de3b295dcfc3b25b05abb09bc95fe3"
+ "e9ff3073638badc68101d1e42019d077"
+ "1dd07525a3aae8318e92c5e5d967ba92"
+ "e4810d0021d7bf3b49da0b4b4a8a4e1f"
+ ),
);
}
### external/vendor/blake2/tests/unkeyed.rs
@@ -0,0 +1,28 @@
+use blake2::{Blake2bMac512, Blake2sMac256, digest::FixedOutput};
+use hex_literal::hex;
+
+#[test]
+fn blake2s_unkeyed() {
+ let ctx = Blake2sMac256::new_with_salt_and_personal(None, b"salt", b"persona").unwrap();
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!(
+ "d7de83e2b1fedd9755db747235b7ba4b"
+ "f9773a16b91c6b241e4b1d926160d9eb"
+ ),
+ );
+}
+
+#[test]
+fn blake2b_unkeyed() {
+ let ctx = Blake2bMac512::new_with_salt_and_personal(None, b"salt", b"persona").unwrap();
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!(
+ "fa3cd38902ae0602d8f0066f18c579fa"
+ "e8068074fbe91f9f5774f841f5ab51fe"
+ "39140ad78d6576f8a0b9f8f4c2642211"
+ "11c9911d8ba1dbefcd034acdbedb8cde"
+ ),
+ );
+}
### external/vendor/block-buffer/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"ff7b73e928510ade7bc98871aaae74feb00659d74def593c837ce19caa611661","CHANGELOG.md":"3876f3ab367ed87a7f7503c88974f6fd093110bf0a789045311a0add637d26ad","Cargo.toml":"962dea1846765a31fc94d41855ff83811ffdf63b581c4b5e66f115178a41db4f","Cargo.toml.orig":"59ab4cd406fb1bac488c873ca65628fbed0a18559fdd6dd7396a81a5a5ab22d8","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"d5c22aa3118d240e877ad41c5d9fa232f9c77d757d4aac0c2f943afc0a95e0ef","README.md":"9bf3545872bdad2fb41557be5cefc21a48f0c7804f8124e24b67760429036472","src/lib.rs":"0d03d0cff909f4dc6ba6899e7ac8c02f408213fdc9e8347a5147e1c88da18c98","src/sealed.rs":"65afa9015a3ddb8d1a56733ef3103b1459842f69155f00cefdb235dc73255d4e","tests/mod.rs":"a42403629557eea432a8797f2d81a4ab65de15ce9a2db933496c53f05669e1d7"},"package":"69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"50b907904eaa909701b4edd0778bd5db559eb2daae0f556c1d88ba7b1c632527","CHANGELOG.md":"d91f98ee0ff8d181f721ff2e50a14f45866853cbc5e33a399eb0b6dde6b127c3","Cargo.lock":"0d1213da8127e64c4a43264120140d5062b3a8da271a236a3f6ff5ff53ba776c","Cargo.toml":"f21191120ab1d04327657b7125f25b0e3f2bce34af5e921d3c66d24de11d5e60","Cargo.toml.orig":"6ccb29916ec67b7d6e3a86203a8296795e8f3e25ae94a307ede8fdc79f07aee1","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"98181e7249d0c01737645ec982499ce99a0f07eb8f7d625b8840d799d10dbc01","README.md":"745dfdacff2e7ed7321d5f859a7072dbac37675ca0d94554ee7ec6045e9b8ea7","src/lib.rs":"1e1f665e68a16b6a18ea547aec36d9855163bd79a27c2b293a7a7708dde68a28","src/read.rs":"790b7bc1d6e87c0ee797b41e18aa3c394aa561c3074047c72590b33c9cee0f8d","src/sealed.rs":"7ad84c528060c27e148e568dc4934ab7704259bdf0c41f1ab59043255d53da3f","tests/mod.rs":"543dab1816c288334cca9b9d61dbe89ee1b4862c15fee5fb028ad5c6bb4fa60f"},"package":"d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"}
\ No newline at end of file
### external/vendor/block-buffer/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "02a49a322dbadb27dc6c155f979ea7a1018ae9e4"
+ "sha1": "cbd0963c685df025c42bed31f78c50d1bada3805"
},
"path_in_vcs": "block-buffer"
}
\ No newline at end of file
### external/vendor/block-buffer/CHANGELOG.md
@@ -4,6 +4,46 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.12.1 (2026-06-11)
+### Fixed
+- Exception safety bug ([#1487])
+
+[#1487]: https://github.com/RustCrypto/utils/pull/1487
+
+## 0.12.0 (2026-02-24)
+### Added
+- `BlockSizes` trait implemented for sizes bigger than `U0` and smaller than `U256` ([#1455])
+
+### Changed
+- Block sizes used by `BlockBuffer` and `ReadBuffer` are now bound by `BlockSizes` ([#1455])
+
+[#1455]: https://github.com/RustCrypto/utils/pull/1455
+
+## 0.11.0 (2025-11-07)
+### Added
+- `ReadBuffer` type ([#823])
+- Optional implementation of the `Zeroize` trait ([#963])
+- Generic `serialize` and `deserialize` methods ([#1200])
+- `ReadBuffer::{read_cached, write_block, reset}` methods ([#1201])
+
+### Changed
+- Block sizes must be bigger than 0 and smaller than 256.
+ This is enforced using compile-time monomorphization errors. ([#1115])
+- Size of `EagerBuffer` is equal to buffer size, while previously it was equal
+ to buffer size plus one byte ([#823])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1149])
+
+### Removed
+- `EagerBuffer::set_data` method. Use the `ReadBuffer` type instead. ([#823])
+
+[#823]: https://github.com/RustCrypto/utils/pull/823
+[#963]: https://github.com/RustCrypto/utils/pull/963
+[#1115]: https://github.com/RustCrypto/utils/pull/1115
+[#1115]: https://github.com/RustCrypto/utils/pull/1116
+[#1149]: https://github.com/RustCrypto/utils/pull/1149
+[#1200]: https://github.com/RustCrypto/utils/pull/1200
+[#1201]: https://github.com/RustCrypto/utils/pull/1201
+
## 0.10.3 (2022-09-04)
### Added
- `try_new` method ([#799])
### external/vendor/block-buffer/Cargo.lock
@@ -0,0 +1,39 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+dependencies = [
+ "hex-literal",
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
### external/vendor/block-buffer/Cargo.toml
@@ -10,11 +10,18 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
name = "block-buffer"
-version = "0.10.3"
+version = "0.12.1"
authors = ["RustCrypto Developers"]
-description = "Buffer type for block processing of data"
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Buffer types for block processing of data"
documentation = "https://docs.rs/block-buffer"
readme = "README.md"
keywords = [
@@ -28,5 +35,61 @@ categories = [
license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/utils"
-[dependencies.generic-array]
-version = "0.14"
+[lib]
+name = "block_buffer"
+path = "src/lib.rs"
+
+[[test]]
+name = "mod"
+path = "tests/mod.rs"
+
+[dependencies.hybrid-array]
+version = "0.4"
+
+[dependencies.zeroize]
+version = "1.8"
+optional = true
+default-features = false
+
+[dev-dependencies.hex-literal]
+version = "1"
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+doc_markdown = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/block-buffer/Cargo.toml.orig
@@ -1,15 +1,23 @@
[package]
name = "block-buffer"
-version = "0.10.3"
+version = "0.12.1"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-description = "Buffer type for block processing of data"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/block-buffer"
+readme = "README.md"
repository = "https://github.com/RustCrypto/utils"
+license = "MIT OR Apache-2.0"
keywords = ["block", "buffer"]
categories = ["cryptography", "no-std"]
-edition = "2018"
-readme = "README.md"
+description = "Buffer types for block processing of data"
[dependencies]
-generic-array = "0.14"
+hybrid-array = "0.4"
+zeroize = { version = "1.8", optional = true, default-features = false }
+
+[dev-dependencies]
+hex-literal = "1"
+
+[lints]
+workspace = true
### external/vendor/block-buffer/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2018-2019 The RustCrypto Project Developers
+Copyright (c) 2018-2025 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/block-buffer/README.md
@@ -2,10 +2,10 @@
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
Buffer type for block processing of data with minimized amount of unreachable panics.
@@ -29,11 +29,11 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
[docs-image]: https://docs.rs/block-buffer/badge.svg
[docs-link]: https://docs.rs/block-buffer/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260052-utils
-[build-image]: https://github.com/RustCrypto/utils/workflows/block-buffer/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml
+[build-image]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml?query=branch:master
[//]: # (general links)
### external/vendor/block-buffer/src/lib.rs
@@ -1,23 +1,62 @@
//! Fixed size buffer for block processing of data.
+//!
+//! # Examples
+//! ```
+//! use block_buffer::{EagerBuffer, array::typenum::U4};
+//!
+//! let mut buf = EagerBuffer::<U4>::default();
+//!
+//! let mut accum = Vec::new();
+//! let msg1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+//! let msg2: &[u8] = &[10, 11, 12];
+//!
+//! buf.digest_blocks(msg1, |blocks| accum.extend_from_slice(blocks));
+//! buf.digest_blocks(msg2, |blocks| accum.extend_from_slice(blocks));
+//!
+//! assert_eq!(accum.len(), 3);
+//! assert_eq!(accum[0], [0, 1, 2, 3]);
+//! assert_eq!(accum[1], [4, 5, 6, 7]);
+//! assert_eq!(accum[2], [8, 9, 10, 11]);
+//!
+//! let padded_block = buf.pad_with_zeros();
+//! assert_eq!(padded_block, [12, 0, 0, 0]);
+//! ```
+//!
+//! Note that block size used with buffers MUST be bigger than zero and smaller than 256.
+//! You will get a compilation error with an invalid block size:
+//!
+//! ```compile_fail
+//! use block_buffer::{EagerBuffer, array::typenum::U0};
+//! let buf = EagerBuffer::<U0>::default();
+//! ```
+//! ```compile_fail
+//! use block_buffer::{EagerBuffer, array::typenum::U256};
+//! let buf = EagerBuffer::<U256>::default();
+//! ```
#![no_std]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
+#![allow(clippy::undocumented_unsafe_blocks)] // TODO(tarcieri): document all unsafe blocks
-pub use generic_array;
+pub use hybrid_array as array;
-use core::{fmt, marker::PhantomData, slice};
-use generic_array::{
- typenum::{IsLess, Le, NonZero, U256},
- ArrayLength, GenericArray,
-};
+use array::{Array, ArraySize, typenum::Sum};
+use core::{fmt, mem::MaybeUninit, ptr, slice};
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
+
+mod read;
mod sealed;
-/// Block on which `BlockBuffer` operates.
-pub type Block<BlockSize> = GenericArray<u8, BlockSize>;
+pub use read::ReadBuffer;
+
+/// Trait implemented for supported block sizes, i.e. for types from `U1` to `U255`.
+pub trait BlockSizes: ArraySize + sealed::BlockSizes {}
+
+impl<T: ArraySize + sealed::BlockSizes> BlockSizes for T {}
/// Trait for buffer kinds.
pub trait BufferKind: sealed::Sealed {}
@@ -33,6 +72,7 @@ pub struct Eager {}
pub struct Lazy {}
impl BufferKind for Eager {}
+
impl BufferKind for Lazy {}
/// Eager block buffer.
@@ -51,89 +91,73 @@ impl fmt::Display for Error {
}
/// Buffer for block processing of data.
-#[derive(Debug)]
-pub struct BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
- buffer: Block<BlockSize>,
- pos: u8,
- _pd: PhantomData<Kind>,
+pub struct BlockBuffer<BS: BlockSizes, K: BufferKind> {
+ buffer: MaybeUninit<Array<u8, BS>>,
+ pos: K::Pos,
}
-impl<BlockSize, Kind> Default for BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> Default for BlockBuffer<BS, K> {
+ #[inline]
fn default() -> Self {
- Self {
- buffer: Default::default(),
- pos: 0,
- _pd: PhantomData,
- }
+ let mut buffer = MaybeUninit::uninit();
+ let mut pos = Default::default();
+ K::set_pos(&mut buffer, &mut pos, 0);
+ Self { buffer, pos }
}
}
-impl<BlockSize, Kind> Clone for BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> Clone for BlockBuffer<BS, K> {
+ #[inline]
fn clone(&self) -> Self {
- Self {
- buffer: self.buffer.clone(),
- pos: self.pos,
- _pd: PhantomData,
- }
+ // SAFETY: `BlockBuffer` does not implement `Drop` (i.e. it could be a `Copy` type),
+ // so we can safely clone it using `ptr::read`.
+ unsafe { ptr::read(self) }
}
}
-impl<BlockSize, Kind> BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> fmt::Debug for BlockBuffer<BS, K> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ f.debug_struct(K::NAME)
+ .field("pos", &self.get_pos())
+ .field("block_size", &BS::USIZE)
+ .field("data", &self.get_data())
+ .finish()
+ }
+}
+
+impl<BS: BlockSizes, K: BufferKind> BlockBuffer<BS, K> {
/// Create new buffer from slice.
///
/// # Panics
/// If slice length is not valid for used buffer kind.
#[inline(always)]
+ #[must_use]
+ #[track_caller]
pub fn new(buf: &[u8]) -> Self {
- Self::try_new(buf).unwrap()
+ Self::try_new(buf).expect("invalid slice length for buffer kind")
}
/// Create new buffer from slice.
///
- /// Returns an error if slice length is not valid for used buffer kind.
+ /// # Errors
+ /// If slice length is not valid for used buffer kind.
#[inline(always)]
pub fn try_new(buf: &[u8]) -> Result<Self, Error> {
- let pos = buf.len();
- if !Kind::invariant(pos, BlockSize::USIZE) {
+ if !K::invariant(buf.len(), BS::USIZE) {
return Err(Error);
}
- let mut buffer = Block::<BlockSize>::default();
- buffer[..pos].copy_from_slice(buf);
- Ok(Self {
- buffer,
- pos: pos as u8,
- _pd: PhantomData,
- })
+ let mut res = Self::default();
+ // SAFETY: we have checked that buffer length satisfies the buffer kind invariant
+ unsafe {
+ res.set_data_unchecked(buf);
+ }
+ Ok(res)
}
/// Digest data in `input` in blocks of size `BlockSize` using
/// the `compress` function, which accepts slice of blocks.
#[inline]
- pub fn digest_blocks(
- &mut self,
- mut input: &[u8],
- mut compress: impl FnMut(&[Block<BlockSize>]),
- ) {
+ pub fn digest_blocks(&mut self, mut input: &[u8], mut compress: impl FnMut(&[Array<u8, BS>])) {
let pos = self.get_pos();
// using `self.remaining()` for some reason
// prevents panic elimination
@@ -146,49 +170,72 @@ where
// `pos + n` which results in it inserting unreachable
// panic branches. Using `unreachable_unchecked` in `get_pos`
// we convince compiler that `BlockSize - pos` never underflows.
- if Kind::invariant(n, rem) {
- // double slicing allows to remove panic branches
- self.buffer[pos..][..n].copy_from_slice(input);
- self.set_pos_unchecked(pos + n);
+ if K::invariant(n, rem) {
+ // SAFETY: we have checked that length of `input` is smaller than
+ // number of remaining bytes in `buffer`, so we can safely write data
+ // into them and update cursor position.
+ unsafe {
+ let buf_ptr = self.buffer.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::copy_nonoverlapping(input.as_ptr(), buf_ptr, input.len());
+ self.set_pos_unchecked(pos + input.len());
+ }
return;
}
if pos != 0 {
let (left, right) = input.split_at(rem);
input = right;
- self.buffer[pos..].copy_from_slice(left);
- compress(slice::from_ref(&self.buffer));
+
+ let g = ResetGuard(self);
+ let buf = &mut g.0.buffer;
+ // SAFETY: length of `left` is equal to number of remaining bytes in `buffer`,
+ // so we can copy data into it and process `buffer` as fully initialized block.
+ // Note that this code can temporarily break the eager buffer invariant,
+ // but we reset the buffer immediately after `compress` using `Drop` impl of
+ // `ResetGuard`, so this code is safe even if `compress` panics.
+ let block = unsafe {
+ let buf_ptr = buf.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::copy_nonoverlapping(left.as_ptr(), buf_ptr, left.len());
+ buf.assume_init_ref()
+ };
+ compress(slice::from_ref(block));
}
- let (blocks, leftover) = Kind::split_blocks(input);
+ let (blocks, leftover) = K::split_blocks(input);
if !blocks.is_empty() {
compress(blocks);
}
- let n = leftover.len();
- self.buffer[..n].copy_from_slice(leftover);
- self.set_pos_unchecked(n);
+ // SAFETY: `leftover` is always smaller than block size,
+ // so it satisfies the method's safety requirements for all buffer kinds
+ unsafe {
+ self.set_data_unchecked(leftover);
+ }
}
/// Reset buffer by setting cursor position to zero.
#[inline(always)]
pub fn reset(&mut self) {
- self.set_pos_unchecked(0);
+ // SAFETY: 0 is always valid position
+ unsafe {
+ self.set_pos_unchecked(0);
+ }
}
/// Pad remaining data with zeros and return resulting block.
#[inline(always)]
- pub fn pad_with_zeros(&mut self) -> &mut Block<BlockSize> {
- let pos = self.get_pos();
- self.buffer[pos..].iter_mut().for_each(|b| *b = 0);
- self.set_pos_unchecked(0);
- &mut self.buffer
+ pub fn pad_with_zeros(&mut self) -> Array<u8, BS> {
+ let mut res = Array::<u8, BS>::default();
+ let data = self.get_data();
+ res[..data.len()].copy_from_slice(data);
+ self.reset();
+ res
}
/// Return current cursor position.
#[inline(always)]
pub fn get_pos(&self) -> usize {
- let pos = self.pos as usize;
- if !Kind::invariant(pos, BlockSize::USIZE) {
+ let pos = K::get_pos(&self.buffer, &self.pos);
+ if !K::invariant(pos, BS::USIZE) {
debug_assert!(false);
// SAFETY: `pos` never breaks the invariant
unsafe {
@@ -201,79 +248,114 @@ where
/// Return slice of data stored inside the buffer.
#[inline(always)]
pub fn get_data(&self) -> &[u8] {
- &self.buffer[..self.get_pos()]
+ // SAFETY: the `buffer` field is properly initialized up to `self.get_pos()`.
+ // `get_pos` never returns position bigger than buffer size.
+ unsafe { slice::from_raw_parts(self.buffer.as_ptr().cast(), self.get_pos()) }
}
/// Set buffer content and cursor position.
///
/// # Panics
/// If `pos` is bigger or equal to block size.
#[inline]
- pub fn set(&mut self, buf: Block<BlockSize>, pos: usize) {
- assert!(Kind::invariant(pos, BlockSize::USIZE));
- self.buffer = buf;
- self.set_pos_unchecked(pos);
+ pub fn set(&mut self, buf: Array<u8, BS>, pos: usize) {
+ assert!(K::invariant(pos, BS::USIZE));
+ self.buffer = MaybeUninit::new(buf);
+ // SAFETY: we have asserted that `pos` satisfies the invariant and
+ // the `buffer` field is fully initialized
+ unsafe {
+ self.set_pos_unchecked(pos);
+ }
}
- /// Return size of the internall buffer in bytes.
+ /// Return size of the internal buffer in bytes.
#[inline(always)]
pub fn size(&self) -> usize {
- BlockSize::USIZE
+ BS::USIZE
}
- /// Return number of remaining bytes in the internall buffer.
+ /// Return number of remaining bytes in the internal buffer.
#[inline(always)]
pub fn remaining(&self) -> usize {
self.size() - self.get_pos()
}
+ /// Set buffer position.
+ ///
+ /// # Safety
+ /// Bytes in the range of `0..pos` in the `buffer` field must be properly initialized.
+ ///
+ /// `pos` must satisfy invariant of buffer kind, i.e. for eager hashes it must be
+ /// strictly smaller than block size and for lazy hashes it must be smaller or equal
+ /// to block size.
+ #[inline(always)]
+ unsafe fn set_pos_unchecked(&mut self, pos: usize) {
+ debug_assert!(K::invariant(pos, BS::USIZE));
+ K::set_pos(&mut self.buffer, &mut self.pos, pos);
+ }
+
+ /// Set buffer data.
+ ///
+ /// # Safety
+ /// Length of `buf` must satisfy invariant of buffer kind, i.e. for eager hashes it must be
+ /// strictly smaller than block size and for lazy hashes it must be smaller or equal
+ /// to block size.
#[inline(always)]
- fn set_pos_unchecked(&mut self, pos: usize) {
- debug_assert!(Kind::invariant(pos, BlockSize::USIZE));
- self.pos = pos as u8;
+ unsafe fn set_data_unchecked(&mut self, buf: &[u8]) {
+ unsafe {
+ self.set_pos_unchecked(buf.len());
+ let dst_ptr: *mut u8 = self.buffer.as_mut_ptr().cast();
+ ptr::copy_nonoverlapping(buf.as_ptr(), dst_ptr, buf.len());
+ }
}
}
-impl<BlockSize> BlockBuffer<BlockSize, Eager>
+/// Size of serialized `BlockBuffer` in bytes.
+pub type SerializedBufferSize<BS, K> = Sum<BS, <K as sealed::Sealed>::Overhead>;
+/// `BlockBuffer` serialized as a byte array.
+pub type SerializedBuffer<BS, K> = Array<u8, SerializedBufferSize<BS, K>>;
+
+impl<BS: BlockSizes, K: BufferKind> BlockBuffer<BS, K>
where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
+ BS: core::ops::Add<K::Overhead>,
+ Sum<BS, K::Overhead>: ArraySize,
{
- /// Set `data` to generated blocks.
- #[inline]
- pub fn set_data(
- &mut self,
- mut data: &mut [u8],
- mut process_blocks: impl FnMut(&mut [Block<BlockSize>]),
- ) {
- let pos = self.get_pos();
- let r = self.remaining();
- let n = data.len();
- if pos != 0 {
- if n < r {
- // double slicing allows to remove panic branches
- data.copy_from_slice(&self.buffer[pos..][..n]);
- self.set_pos_unchecked(pos + n);
- return;
- }
- let (left, right) = data.split_at_mut(r);
- data = right;
- left.copy_from_slice(&self.buffer[pos..]);
+ /// Serialize buffer into a byte array.
+ #[allow(clippy::missing_panics_doc)]
+ pub fn serialize(&self) -> SerializedBuffer<BS, K> {
+ let mut buf = SerializedBuffer::<BS, K>::default();
+ let data = self.get_data();
+ let (pos, block) = buf.split_at_mut(1);
+ pos[0] = u8::try_from(data.len()).expect("buffer size is smaller than 256");
+ block[..data.len()].copy_from_slice(data);
+ buf
+ }
+
+ /// Deserialize buffer from a byte array.
+ ///
+ /// # Errors
+ /// If `buf` does not represent a valid serialization of `BlockBuffer`.
+ pub fn deserialize(buf: &SerializedBuffer<BS, K>) -> Result<Self, Error> {
+ let (pos, block) = buf.split_at(1);
+ let pos = usize::from(pos[0]);
+
+ if !<K as sealed::Sealed>::invariant(pos, BS::USIZE) {
+ return Err(Error);
}
- let (blocks, leftover) = to_blocks_mut(data);
- process_blocks(blocks);
+ let (data, tail) = block.split_at(pos);
- let n = leftover.len();
- if n != 0 {
- let mut block = Default::default();
- process_blocks(slice::from_mut(&mut block));
- leftover.copy_from_slice(&block[..n]);
- self.buffer = block;
+ if tail.iter().any(|&b| b != 0) {
+ return Err(Error);
}
- self.set_pos_unchecked(n);
+
+ let mut res = Self::default();
+ unsafe { res.set_data_unchecked(data) };
+ Ok(res)
}
+}
+impl<BS: BlockSizes> BlockBuffer<BS, Eager> {
/// Compress remaining data after padding it with `delim`, zeros and
/// the `suffix` bytes. If there is not enough unused space, `compress`
/// will be called twice.
@@ -285,60 +367,85 @@ where
&mut self,
delim: u8,
suffix: &[u8],
- mut compress: impl FnMut(&Block<BlockSize>),
+ mut compress: impl FnMut(&Array<u8, BS>),
) {
- if suffix.len() > BlockSize::USIZE {
- panic!("suffix is too long");
- }
let pos = self.get_pos();
- self.buffer[pos] = delim;
- for b in &mut self.buffer[pos + 1..] {
- *b = 0;
+ let size = self.size();
+ // Number of bytes remaining in the buffer after `delim` is written to it
+ // This never underflows since for eager buffers `size` is always greater than `pos`.
+ let pad_len = size - pos - 1;
+
+ let suffix_dst_pos = size
+ .checked_sub(suffix.len())
+ .expect("suffix must be smaller than buffer block size");
+
+ let g = ResetGuard(self);
+ // SAFETY: we fully initialize the buffer. Note that we may temporarily break
+ // the buffer invariant, but we restore it using `ResetGuard`,
+ // which works even if `compress` panics.
+ let buf = unsafe {
+ let p: *mut u8 = g.0.buffer.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::write(p, delim);
+ ptr::write_bytes(p.add(1), 0, pad_len);
+ g.0.buffer.assume_init_mut()
+ };
+
+ if pad_len < suffix.len() {
+ compress(buf);
+ buf.fill(0);
}
- let n = self.size() - suffix.len();
- if self.size() - pos - 1 < suffix.len() {
- compress(&self.buffer);
- let mut block = Block::<BlockSize>::default();
- block[n..].copy_from_slice(suffix);
- compress(&block);
- } else {
- self.buffer[n..].copy_from_slice(suffix);
- compress(&self.buffer);
- }
- self.set_pos_unchecked(0)
+ buf[suffix_dst_pos..].copy_from_slice(suffix);
+ compress(buf);
}
/// Pad message with 0x80, zeros and 64-bit message length using
/// big-endian byte order.
#[inline]
- pub fn len64_padding_be(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len64_padding_be(&mut self, data_len: u64, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
}
/// Pad message with 0x80, zeros and 64-bit message length using
/// little-endian byte order.
#[inline]
- pub fn len64_padding_le(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len64_padding_le(&mut self, data_len: u64, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_le_bytes(), compress);
}
/// Pad message with 0x80, zeros and 128-bit message length using
/// big-endian byte order.
#[inline]
- pub fn len128_padding_be(&mut self, data_len: u128, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len128_padding_be(&mut self, data_len: u128, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
}
}
-/// Split message into mutable slice of parallel blocks, blocks, and leftover bytes.
-#[inline(always)]
-fn to_blocks_mut<N: ArrayLength<u8>>(data: &mut [u8]) -> (&mut [Block<N>], &mut [u8]) {
- let nb = data.len() / N::USIZE;
- let (left, right) = data.split_at_mut(nb * N::USIZE);
- let p = left.as_mut_ptr() as *mut Block<N>;
- // SAFETY: we guarantee that `blocks` does not point outside of `data`, and `p` is valid for
- // mutation
- let blocks = unsafe { slice::from_raw_parts_mut(p, nb) };
- (blocks, right)
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes, K: BufferKind> Zeroize for BlockBuffer<BS, K> {
+ #[inline]
+ fn zeroize(&mut self) {
+ self.buffer.zeroize();
+ self.pos.zeroize();
+ }
+}
+
+impl<BS: BlockSizes, K: BufferKind> Drop for BlockBuffer<BS, K> {
+ #[inline]
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ self.zeroize();
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes, K: BufferKind> ZeroizeOnDrop for BlockBuffer<BS, K> {}
+
+/// Resets the referenced buffer on drop.
+struct ResetGuard<'a, BS: BlockSizes, K: BufferKind>(&'a mut BlockBuffer<BS, K>);
+
+impl<BS: BlockSizes, K: BufferKind> Drop for ResetGuard<'_, BS, K> {
+ fn drop(&mut self) {
+ self.0.reset();
+ }
}
### external/vendor/block-buffer/src/read.rs
@@ -0,0 +1,199 @@
+use super::{Array, BlockSizes, Error};
+use core::fmt;
+
+/// Buffer for reading block-generated data.
+pub struct ReadBuffer<BS: BlockSizes> {
+ /// The first byte of the block is used as cursor position.
+ /// `&buffer[usize::from(buffer[0])..]` is interpreted as unread bytes.
+ /// The cursor position is always bigger than zero and smaller than or equal to block size.
+ buffer: Array<u8, BS>,
+}
+
+impl<BS: BlockSizes> fmt::Debug for ReadBuffer<BS> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ReadBuffer")
+ .field("remaining_data", &self.remaining())
+ .finish_non_exhaustive()
+ }
+}
+
+impl<BS: BlockSizes> Default for ReadBuffer<BS> {
+ #[inline]
+ fn default() -> Self {
+ let buffer = Default::default();
+ let mut res = Self { buffer };
+ // SAFETY: `BS::USIZE` satisfies the `set_pos_unchecked` safety contract
+ unsafe { res.set_pos_unchecked(BS::USIZE) };
+ res
+ }
+}
+
+impl<BS: BlockSizes> Clone for ReadBuffer<BS> {
+ #[inline]
+ fn clone(&self) -> Self {
+ let buffer = self.buffer.clone();
+ Self { buffer }
+ }
+}
+
+impl<BS: BlockSizes> ReadBuffer<BS> {
+ /// Return current cursor position, i.e. how many bytes were read from the buffer.
+ #[inline(always)]
+ pub fn get_pos(&self) -> usize {
+ let pos = self.buffer[0];
+ if pos == 0 || pos > BS::U8 {
+ debug_assert!(false);
+ // SAFETY: `pos` never breaks the invariant
+ unsafe {
+ core::hint::unreachable_unchecked();
+ }
+ }
+ pos as usize
+ }
+
+ /// Return size of the internal buffer in bytes.
+ #[inline(always)]
+ pub fn size(&self) -> usize {
+ BS::USIZE
+ }
+
+ /// Return number of remaining bytes in the internal buffer.
+ #[inline(always)]
+ pub fn remaining(&self) -> usize {
+ self.size() - self.get_pos()
+ }
+
+ /// Set cursor position.
+ ///
+ /// # Safety
+ /// `pos` must be smaller than or equal to the buffer block size and be bigger than zero.
+ #[inline(always)]
+ #[allow(clippy::cast_possible_truncation)]
+ unsafe fn set_pos_unchecked(&mut self, pos: usize) {
+ debug_assert!(pos != 0 && pos <= BS::USIZE);
+ self.buffer[0] = pos as u8;
+ }
+
+ /// Read up to `len` bytes of remaining data in the buffer.
+ ///
+ /// Returns slice with length of `ret_len = min(len, buffer.remaining())` bytes
+ /// and sets the cursor position to `buffer.get_pos() + ret_len`.
+ #[inline(always)]
+ pub fn read_cached(&mut self, len: usize) -> &[u8] {
+ let rem = self.remaining();
+ let new_len = core::cmp::min(rem, len);
+ let pos = self.get_pos();
+
+ // SAFETY: `pos + new_len` is not equal to zero and not bigger than block size
+ unsafe { self.set_pos_unchecked(pos + new_len) };
+ &self.buffer[pos..][..new_len]
+ }
+
+ /// Write new block and consume `read_len` bytes from it.
+ ///
+ /// If `read_len` is equal to zero, immediately returns without calling the closures.
+ /// Otherwise, the method calls `gen_block` to fill the internal buffer,
+ /// passes to `read_fn` slice with first `read_len` bytes of the block,
+ /// and sets the cursor position to `read_len`.
+ ///
+ /// # Panics
+ /// If `read_len` is bigger than block size.
+ #[inline(always)]
+ pub fn write_block(
+ &mut self,
+ read_len: usize,
+ gen_block: impl FnOnce(&mut Array<u8, BS>),
+ read_fn: impl FnOnce(&[u8]),
+ ) {
+ if read_len == 0 {
+ return;
+ }
+ assert!(read_len < BS::USIZE);
+
+ let g = ResetGuard(self);
+ let buf = &mut g.0.buffer;
+
+ // Note that generated block is likely to break the `ReadBuffer` invariant.
+ // We restore it using `set_pos_unchecked` below and in case if one of the closures
+ // panic the buffer gets reset by the guard.
+ gen_block(buf);
+ read_fn(&buf[..read_len]);
+
+ core::mem::forget(g);
+
+ // We checked that `read_len` satisfies the `set_pos_unchecked` safety contract
+ unsafe { self.set_pos_unchecked(read_len) };
+ }
+
+ /// Reset buffer into exhausted state.
+ pub fn reset(&mut self) {
+ self.buffer[0] = BS::U8;
+ }
+
+ /// Write remaining data inside buffer into `buf`, fill remaining space
+ /// in `buf` with blocks generated by `gen_block`, and save leftover data
+ /// from the last generated block into the buffer for future use.
+ #[inline]
+ pub fn read(&mut self, buf: &mut [u8], mut gen_block: impl FnMut(&mut Array<u8, BS>)) {
+ let head_ks = self.read_cached(buf.len());
+ let (head, buf) = buf.split_at_mut(head_ks.len());
+ let (blocks, tail) = Array::slice_as_chunks_mut(buf);
+
+ head.copy_from_slice(head_ks);
+ for block in blocks {
+ gen_block(block);
+ }
+
+ self.write_block(tail.len(), gen_block, |tail_ks| {
+ tail.copy_from_slice(tail_ks);
+ });
+ }
+
+ /// Serialize buffer into a byte array.
+ #[inline]
+ pub fn serialize(&self) -> Array<u8, BS> {
+ let pos = self.get_pos();
+ let mut res = self.buffer.clone();
+ // zeroize "garbage" data
+ for b in &mut res[1..pos] {
+ *b = 0;
+ }
+ res
+ }
+
+ /// Deserialize buffer from a byte array.
+ ///
+ /// # Errors
+ /// - If the first byte is `0`.
+ /// - If the first byte is bigger than `BS`.
+ #[inline]
+ pub fn deserialize(buffer: &Array<u8, BS>) -> Result<Self, Error> {
+ let pos = usize::from(buffer[0]);
+ if pos == 0 || pos > BS::USIZE || buffer[1..pos].iter().any(|&b| b != 0) {
+ Err(Error)
+ } else {
+ let buffer = buffer.clone();
+ Ok(Self { buffer })
+ }
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes> Drop for ReadBuffer<BS> {
+ fn drop(&mut self) {
+ use zeroize::Zeroize;
+ self.buffer.zeroize();
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes> zeroize::ZeroizeOnDrop for ReadBuffer<BS> {}
+
+/// Resets the referenced buffer on drop.
+struct ResetGuard<'a, BS: BlockSizes>(&'a mut ReadBuffer<BS>);
+
+impl<BS: BlockSizes> Drop for ResetGuard<'_, BS> {
+ fn drop(&mut self) {
+ self.0.reset();
+ }
+}
### external/vendor/block-buffer/src/sealed.rs
@@ -1,67 +1,106 @@
-use super::{ArrayLength, Block};
-use core::slice;
+use hybrid_array::{
+ sizes::{U0, U1, U256},
+ typenum::{IsLess, NonZero, True, Unsigned},
+};
+
+use super::{Array, ArraySize};
+use core::{mem::MaybeUninit, ptr};
+
+type Block<N> = MaybeUninit<Array<u8, N>>;
/// Sealed trait for buffer kinds.
pub trait Sealed {
+ #[cfg(not(feature = "zeroize"))]
+ type Pos: Default + Clone;
+ #[cfg(feature = "zeroize")]
+ type Pos: Default + Clone + zeroize::Zeroize;
+
+ type Overhead: ArraySize;
+
+ const NAME: &'static str;
+
+ fn get_pos<N: ArraySize>(buf: &Block<N>, pos: &Self::Pos) -> usize;
+
+ fn set_pos<N: ArraySize>(buf: &mut Block<N>, pos: &mut Self::Pos, val: usize);
+
/// Invariant guaranteed by a buffer kind, i.e. with correct
/// buffer code this function always returns true.
fn invariant(pos: usize, block_size: usize) -> bool;
- /// Split input data into slice fo blocks and tail.
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]);
+ /// Split input data into slice of blocks and tail.
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]);
}
impl Sealed for super::Eager {
+ type Pos = ();
+ type Overhead = U0;
+ const NAME: &'static str = "BlockBuffer<Eager>";
+
+ fn get_pos<N: ArraySize>(buf: &Block<N>, _pos: &Self::Pos) -> usize {
+ // SAFETY: last byte in `buf` for eager hashes is always properly initialized
+ let pos = unsafe {
+ let buf_ptr = buf.as_ptr().cast::<u8>();
+ let last_byte_ptr = buf_ptr.add(N::USIZE - 1);
+ ptr::read(last_byte_ptr)
+ };
+ pos as usize
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ fn set_pos<N: ArraySize>(buf: &mut Block<N>, _pos: &mut Self::Pos, val: usize) {
+ debug_assert!(u8::try_from(val).is_ok());
+ // SAFETY: we write to the last byte of `buf` which is always safe
+ unsafe {
+ let buf_ptr = buf.as_mut_ptr().cast::<u8>();
+ let last_byte_ptr = buf_ptr.add(N::USIZE - 1);
+ ptr::write(last_byte_ptr, val as u8);
+ }
+ }
+
#[inline(always)]
fn invariant(pos: usize, block_size: usize) -> bool {
pos < block_size
}
#[inline(always)]
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]) {
- let nb = data.len() / N::USIZE;
- let blocks_len = nb * N::USIZE;
- let tail_len = data.len() - blocks_len;
- // SAFETY: we guarantee that created slices do not point
- // outside of `data`
- unsafe {
- let blocks_ptr = data.as_ptr() as *const Block<N>;
- let tail_ptr = data.as_ptr().add(blocks_len);
- (
- slice::from_raw_parts(blocks_ptr, nb),
- slice::from_raw_parts(tail_ptr, tail_len),
- )
- }
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]) {
+ Array::slice_as_chunks(data)
}
}
impl Sealed for super::Lazy {
+ type Pos = u8;
+ type Overhead = U1;
+ const NAME: &'static str = "BlockBuffer<Lazy>";
+
+ fn get_pos<N: ArraySize>(_buf_val: &Block<N>, pos: &Self::Pos) -> usize {
+ *pos as usize
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ fn set_pos<N: ArraySize>(_: &mut Block<N>, pos: &mut Self::Pos, val: usize) {
+ debug_assert!(u8::try_from(val).is_ok());
+ *pos = val as u8;
+ }
+
#[inline(always)]
fn invariant(pos: usize, block_size: usize) -> bool {
pos <= block_size
}
#[inline(always)]
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]) {
- if data.is_empty() {
- return (&[], &[]);
- }
- let (nb, tail_len) = if data.len() % N::USIZE == 0 {
- (data.len() / N::USIZE - 1, N::USIZE)
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]) {
+ let (blocks, tail) = Array::slice_as_chunks(data);
+ if data.is_empty() || !tail.is_empty() {
+ (blocks, tail)
} else {
- let nb = data.len() / N::USIZE;
- (nb, data.len() - nb * N::USIZE)
- };
- let blocks_len = nb * N::USIZE;
- // SAFETY: we guarantee that created slices do not point
- // outside of `data`
- unsafe {
- let blocks_ptr = data.as_ptr() as *const Block<N>;
- let tail_ptr = data.as_ptr().add(blocks_len);
- (
- slice::from_raw_parts(blocks_ptr, nb),
- slice::from_raw_parts(tail_ptr, tail_len),
- )
+ let (tail, blocks) = blocks.split_last().expect("`blocks` can not be empty");
+ (blocks, tail)
}
}
}
+
+/// Sealed trait implemented for sizes from `U1` to `U255`.
+pub trait BlockSizes {}
+
+impl<T: Unsigned> BlockSizes for T where Self: IsLess<U256, Output = True> + NonZero {}
### external/vendor/block-buffer/tests/mod.rs
@@ -1,10 +1,19 @@
+//! `block-buffer` tests.
+
use block_buffer::{
- generic_array::typenum::{U10, U16, U24, U4, U8},
- Block, EagerBuffer, LazyBuffer,
+ EagerBuffer, LazyBuffer, ReadBuffer,
+ array::{
+ Array,
+ typenum::{U4, U8, U10, U16, U24},
+ },
};
+use hex_literal::hex;
+
+use core::{array, panic::AssertUnwindSafe};
+use std::panic::catch_unwind;
#[test]
-fn test_eager_digest_pad() {
+fn test_eager_digest() {
let mut buf = EagerBuffer::<U4>::default();
let inputs = [
&b"01234567"[..],
@@ -39,7 +48,7 @@ fn test_eager_digest_pad() {
}
#[test]
-fn test_lazy_digest_pad() {
+fn test_lazy_digest() {
let mut buf = LazyBuffer::<U4>::default();
let inputs = [
&b"01234567"[..],
@@ -73,36 +82,82 @@ fn test_lazy_digest_pad() {
}
#[test]
-fn test_eager_set_data() {
- let mut buf = EagerBuffer::<U4>::default();
+fn digest_pad_combinations() {
+ let delim = 0x80;
+ let data: [u8; 7] = array::from_fn(|i| u8::try_from(i).unwrap());
+ let suffix: [u8; 7] = array::from_fn(|i| u8::try_from(i + 0x10).unwrap());
+
+ for data_len in 0..data.len() {
+ for suffix_len in 0..suffix.len() {
+ let data = &data[..data_len];
+ let suffix = &suffix[..suffix_len];
+ let mut buf = EagerBuffer::<U8>::default();
+
+ buf.digest_blocks(data, |_| panic!("should not be called"));
+
+ let mut accum = Vec::with_capacity(2 * buf.size());
+ buf.digest_pad(delim, suffix, |block| accum.extend_from_slice(block));
+
+ assert!(accum.len() <= 2 * buf.size());
+ assert_eq!(buf.get_pos(), 0);
+
+ let (res_data, rem) = accum.split_at(data_len);
+ let (res_delim, rem) = rem.split_at(1);
+ let (res_zeros, res_suffix) = rem.split_at(rem.len() - suffix_len);
+
+ assert_eq!(res_data, data);
+ assert_eq!(res_delim, &[delim]);
+ assert!(res_zeros.iter().all(|&b| b == 0));
+ assert_eq!(res_suffix, suffix);
+ }
+ }
+}
+
+#[test]
+fn test_read() {
+ type Buf = ReadBuffer<U4>;
+ let mut buf = Buf::default();
let mut n = 0u8;
- let mut gen = |blocks: &mut [Block<U4>]| {
- for block in blocks {
- block.iter_mut().for_each(|b| *b = n);
+ let mut g = |block: &mut Array<u8, U4>| {
+ block.iter_mut().for_each(|b| {
+ *b = n;
n += 1;
- }
+ });
};
- let mut out = [0u8; 6];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [0, 0, 0, 0, 1, 1]);
- assert_eq!(buf.get_pos(), 2);
+ let res = buf.read_cached(0);
+ assert!(res.is_empty());
+ let res = buf.read_cached(10);
+ assert!(res.is_empty());
- let mut out = [0u8; 3];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [1, 1, 2]);
- assert_eq!(buf.get_pos(), 1);
+ buf.write_block(2, &mut g, |buf| assert_eq!(buf, [0, 1]));
+ assert_eq!(buf.remaining(), 2);
- let mut out = [0u8; 3];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [2, 2, 2]);
- assert_eq!(n, 3);
- assert_eq!(buf.get_pos(), 0);
+ let res = buf.read_cached(1);
+ assert_eq!(res, [2]);
+ let res = buf.read_cached(10);
+ assert_eq!(res, [3]);
+ assert_eq!(buf.remaining(), 0);
+
+ buf.write_block(0, |_| unreachable!(), |_| unreachable!());
+ buf.write_block(3, &mut g, |buf| assert_eq!(buf, [4, 5, 6]));
+ assert_eq!(buf.remaining(), 1);
+
+ buf.write_block(0, |_| unreachable!(), |_| unreachable!());
+ assert_eq!(buf.remaining(), 1);
+ let res = buf.read_cached(10);
+ assert_eq!(res, [7]);
+
+ buf.write_block(1, &mut g, |buf| assert_eq!(buf, [8]));
+ assert_eq!(buf.remaining(), 3);
+
+ let res = buf.read_cached(10);
+ assert_eq!(res, [9, 10, 11]);
+ assert_eq!(buf.remaining(), 0);
}
#[test]
-#[rustfmt::skip]
fn test_eager_paddings() {
let mut buf_be = EagerBuffer::<U8>::new(&[0x42]);
let mut buf_le = buf_be.clone();
@@ -112,20 +167,8 @@ fn test_eager_paddings() {
buf_be.len64_padding_be(len, |block| out_be.extend(block));
buf_le.len64_padding_le(len, |block| out_le.extend(block));
- assert_eq!(
- out_be,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- ],
- );
- assert_eq!(
- out_le,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
- ],
- );
+ assert_eq!(out_be, hex!("4280000000000000 0001020304050607"));
+ assert_eq!(out_le, hex!("4280000000000000 0706050403020100"));
let mut buf_be = EagerBuffer::<U10>::new(&[0x42]);
let mut buf_le = buf_be.clone();
@@ -134,27 +177,19 @@ fn test_eager_paddings() {
buf_be.len64_padding_be(len, |block| out_be.extend(block));
buf_le.len64_padding_le(len, |block| out_le.extend(block));
- assert_eq!(
- out_be,
- [0x42, 0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
- );
- assert_eq!(
- out_le,
- [0x42, 0x80, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00],
- );
+ assert_eq!(out_be, hex!("42800001020304050607"));
+ assert_eq!(out_le, hex!("42800706050403020100"));
let mut buf = EagerBuffer::<U16>::new(&[0x42]);
let mut out = Vec::<u8>::new();
let len = 0x0001_0203_0405_0607_0809_0a0b_0c0d_0e0f;
buf.len128_padding_be(len, |block| out.extend(block));
assert_eq!(
out,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- ],
+ hex!(
+ "42800000000000000000000000000000"
+ "000102030405060708090a0b0c0d0e0f"
+ ),
);
let mut buf = EagerBuffer::<U24>::new(&[0x42]);
@@ -163,28 +198,18 @@ fn test_eager_paddings() {
buf.len128_padding_be(len, |block| out.extend(block));
assert_eq!(
out,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- ],
+ hex!("4280000000000000 0001020304050607 08090a0b0c0d0e0f")
);
let mut buf = EagerBuffer::<U4>::new(&[0x42]);
let mut out = Vec::<u8>::new();
- buf.digest_pad(0xff, &[0x10, 0x11, 0x12], |block| out.extend(block));
- assert_eq!(
- out,
- [0x42, 0xff, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12],
- );
+ buf.digest_pad(0xff, &hex!("101112"), |block| out.extend(block));
+ assert_eq!(out, hex!("42ff000000101112"));
let mut buf = EagerBuffer::<U4>::new(&[0x42]);
let mut out = Vec::<u8>::new();
- buf.digest_pad(0xff, &[0x10, 0x11], |block| out.extend(block));
- assert_eq!(
- out,
- [0x42, 0xff, 0x10, 0x11],
- );
+ buf.digest_pad(0xff, &hex!("1011"), |block| out.extend(block));
+ assert_eq!(out, hex!("42ff1011"));
}
#[test]
@@ -194,3 +219,217 @@ fn test_try_new() {
assert!(LazyBuffer::<U4>::try_new(&[0; 4]).is_ok());
assert!(LazyBuffer::<U4>::try_new(&[0; 5]).is_err());
}
+
+#[test]
+fn test_eager_serialize() {
+ type Buf = EagerBuffer<U4>;
+
+ let mut buf1 = Buf::default();
+ let ser0 = buf1.serialize();
+ assert_eq!(&ser0[..], &[0, 0, 0, 0]);
+ assert_eq!(Buf::deserialize(&ser0).unwrap().serialize(), ser0);
+
+ buf1.digest_blocks(&[41, 42], |_| {});
+
+ let ser1 = buf1.serialize();
+ assert_eq!(&ser1[..], &[2, 41, 42, 0]);
+
+ let mut buf2 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+
+ buf1.digest_blocks(&[43], |_| {});
+ buf2.digest_blocks(&[43], |_| {});
+
+ let ser2 = buf1.serialize();
+ assert_eq!(&ser2[..], &[3, 41, 42, 43]);
+ assert_eq!(buf1.serialize(), ser2);
+
+ let mut buf3 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf3.serialize(), ser2);
+
+ buf1.digest_blocks(&[44], |_| {});
+ buf2.digest_blocks(&[44], |_| {});
+ buf3.digest_blocks(&[44], |_| {});
+
+ let ser3 = buf1.serialize();
+ assert_eq!(&ser3[..], &[0, 0, 0, 0]);
+ assert_eq!(buf2.serialize(), ser3);
+ assert_eq!(buf3.serialize(), ser3);
+
+ // Invalid position
+ let buf = Array([0, 0, 0, 4]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([0, 0, 0, 10]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([0, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([1, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([2, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn test_lazy_serialize() {
+ type Buf = LazyBuffer<U4>;
+
+ let mut buf1 = Buf::default();
+ let ser0 = buf1.serialize();
+ assert_eq!(&ser0[..], &[0, 0, 0, 0, 0]);
+ Buf::deserialize(&ser0).unwrap();
+ assert_eq!(Buf::deserialize(&ser0).unwrap().serialize(), ser0);
+
+ buf1.digest_blocks(&[41, 42], |_| {});
+
+ let ser1 = buf1.serialize();
+ assert_eq!(&ser1[..], &[2, 41, 42, 0, 0]);
+
+ let mut buf2 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+
+ buf1.digest_blocks(&[43], |_| {});
+ buf2.digest_blocks(&[43], |_| {});
+
+ let ser2 = buf1.serialize();
+ assert_eq!(&ser2[..], &[3, 41, 42, 43, 0]);
+ assert_eq!(buf1.serialize(), ser2);
+
+ let mut buf3 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf3.serialize(), ser2);
+
+ buf1.digest_blocks(&[44], |_| {});
+ buf2.digest_blocks(&[44], |_| {});
+ buf3.digest_blocks(&[44], |_| {});
+
+ let ser3 = buf1.serialize();
+ assert_eq!(&ser3[..], &[4, 41, 42, 43, 44]);
+ assert_eq!(buf2.serialize(), ser3);
+ assert_eq!(buf3.serialize(), ser3);
+
+ buf1.digest_blocks(&[45], |_| {});
+ buf2.digest_blocks(&[45], |_| {});
+ buf3.digest_blocks(&[45], |_| {});
+
+ let ser4 = buf1.serialize();
+ assert_eq!(&ser4[..], &[1, 45, 0, 0, 0]);
+ assert_eq!(buf2.serialize(), ser4);
+ assert_eq!(buf3.serialize(), ser4);
+
+ // Invalid position
+ let buf = Array([10, 0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([5, 0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([0, 1, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([1, 0, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([2, 0, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([3, 0, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn test_read_serialize() {
+ type Buf = ReadBuffer<U4>;
+
+ let mut n = 0u8;
+ let mut g = |block: &mut Array<u8, U4>| {
+ block.iter_mut().for_each(|b| {
+ *b = n;
+ n += 1;
+ });
+ };
+
+ let mut buf = Buf::default();
+ let ser1 = buf.serialize();
+ assert_eq!(&ser1[..], &[4, 0, 0, 0]);
+ assert_eq!(Buf::deserialize(&ser1).unwrap().serialize(), ser1);
+
+ let mut buf1 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+ assert_eq!(buf1.remaining(), 0);
+ assert_eq!(buf1.read_cached(10), []);
+
+ buf.write_block(2, &mut g, |buf| assert_eq!(buf, [0, 1]));
+
+ let ser2 = buf.serialize();
+ assert_eq!(&ser2[..], &[2, 0, 2, 3]);
+
+ let mut buf2 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf2.serialize(), ser2);
+ assert_eq!(buf2.remaining(), 2);
+ assert_eq!(buf2.read_cached(10), [2, 3]);
+
+ // Invalid position
+ let buf = Array([0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([5, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([10, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([2, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([3, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([4, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn eager_buffer_exception_safety() {
+ let mut buf = EagerBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.digest_blocks(b"ab", |_| {});
+ buf.digest_blocks(b"cd", |_| panic!("compression panic"));
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+
+ let mut buf = EagerBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.digest_pad(0x80, &[0xFF; 2], |_| panic!("compression panic"));
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+}
+
+#[test]
+fn read_buffer_exception_safety() {
+ let mut buf = ReadBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.write_block(
+ 1,
+ |block| {
+ block[0] = 0xFF;
+ panic!("block generation panic");
+ },
+ |_| {},
+ );
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+
+ let mut buf = ReadBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.write_block(
+ 1,
+ |block| block.0 = [0xFF; 4],
+ |_| panic!("data read panic"),
+ );
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+}
### external/vendor/chacha20/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"1e717a0a3af924ef26b5349baa318d74772df13682532289b569f771cca3bf08","CHANGELOG.md":"cc005edfbbe3e406f9b908cc1f4a25c0fddc862e3d01840052c4ba0e238e68cd","Cargo.toml":"ed1dc396afc4669bcefbd7b6b0fdb77db889e745be889454a10670c14c1a50d6","Cargo.toml.orig":"693a20d2603da94969ec53144742b23a6d3a5d8db3585593a86c9fb623d524e7","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b6f6f01b03ee7e93c0ae96d62ed39527e98a120fb951afc9de456a741ef3f204","README.md":"a801378a1347d00327a45b1cdeddf3f0dac0ad577bc70d313114daebc8ac5b7b","benches/mod.rs":"ef9cff285db7037458f550f40b7c6e7f7f0d9e687bf61d796a83cbc034db57ae","src/backends.rs":"497002020de5081a68736e9a86c73d68dcfe66ae77354f42e6041256bcd8ca68","src/backends/avx2.rs":"21a0955e674e510996ddaea8de9e17d8fc67bd1da8f386203b9a3cf9cb82fe9d","src/backends/neon.rs":"5530258e3113dbcba6dbbda189621b5a3993fbdc0e1b88e342e27895274c9138","src/backends/soft.rs":"c6d6fbf33f80262eb77a5a171ade2b06365cd84501479aec97a4e932046f0a14","src/backends/sse2.rs":"3a0a1c08728e3641cf98f3e59b7fe6063df569ebfe3fa1817583dcff85655fbb","src/legacy.rs":"67345897d9ba3815879a3ccd7970920de11bfbb988aa79b925893e4d84ed202c","src/lib.rs":"4112893bb7a5eb6cdb269200c816befaeadecf7e932ab2612c0941b7f7d7c6c3","src/xchacha.rs":"f1599eedd6b2db835939d96bb65b647e9279c045592858f270ead3a4a77b360a","tests/data/chacha20-legacy.blb":"439fed37a60f1a56f5c343df168998ec8fe7fe6dcaeb07f8992a5602590aa73b","tests/data/chacha20.blb":"da4ce597c2c73b2e1827bfc2b992b856c5581afeb22deeab58fc3c2092da0c6b","tests/mod.rs":"79684247bf681350c6784af0b042cd519fd24af80904af35252f3bdb10178476"},"package":"c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"69523f9d6c632db59fc022665e18e658a339c3f5579a8435526f536a7241123c","CHANGELOG.md":"62b490baa02637dc7810a52716a1b7c2cdbce591fab695df87d843857cdd47cd","Cargo.lock":"700dfe85f890b63ad04e31fa68e2102b72f034fd8bc3216780a7b5875a762c31","Cargo.toml":"b48970318446b5a41b06b1e27f2e691b6fc9245ee82beabde925f0a0889d58ba","Cargo.toml.orig":"ce1889452c49e116d1e4e3b1af355947a57852804ec9687220d1e1579983b8c4","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b8c6939380a400f53e11923d50fcc4dd2fa1ba8339fd9d04cda38a0251b6c9b0","README.md":"e5495c78bf5270bcca880e0f68c552d435dabd92764c9cc2f62b574b2d75588d","benches/mod.rs":"93ca43362e31d6707f131e8c4484cfb3aaa209058510b40ff7805601f57c68ab","src/backends.rs":"a5b51ab7b20fdb7d99c29b231bfbc8fc643f1002ad2155f4e6757be9cc990105","src/backends/avx2.rs":"c44c34d86ab9d896ac8b863e611f496cda31b5d731b1c860f70c0772426da918","src/backends/avx512.rs":"b4e945d887f0fb11e2dc6a757f7dc01e7553d486ae8d381964defaf8857d9ab6","src/backends/neon.rs":"5d29e3c2da18ea649f6e19fc339bb6253611db18cafcba4993155b70d096f102","src/backends/soft.rs":"120bcf4bc535c3fbcc3b4e2bdc0f021e44fae553bf5bb3a532271b2a08dc2149","src/backends/sse2.rs":"6e03915126187bf361567e39a0e0dc35366468b35b8f2bf87f11a62762e79d3f","src/chacha.rs":"323b76530ad49db28cb1764dbee7843908af21ae85918e4ade04abad8a4614bb","src/legacy.rs":"f5e9dc27cc2c911d087f198bcdbbbb9a1f55c873c5bbd6e79280d1628f72ab49","src/lib.rs":"b539477230a58abfa2e2ab8dd62c017ffc84f3a7680971c5496973185c543c20","src/rng.rs":"8f1367fed752857f0c6ec9c7a7bd154417a80b780b342c9346af4f16b3089bde","src/variants.rs":"79bb423dd0ef0ac690334915baea48db17f055797175c22b1bcbed0714dd9f88","src/xchacha.rs":"86de92973ea8701003c97994fb95fe33099dc0fe0938c27d10f20e95d4b94000","tests/data/chacha20-legacy.blb":"2405a7f849b5db6ae8f6ba79dd943632f7ba3f9839a9c4db86a79a1f069e5e30","tests/data/chacha20.blb":"2686172dba8dd9a5f20d37881b3bf8ef68a9a5106cb8178628ca892e2a5d9052","tests/kats.rs":"ea16474f269f1c5edb5551ecfbfb40bc0fac06b3f293c2365b1442b5338c684f","tests/rng.rs":"eb59c35b32f11e72a6dc04ca790b5efc35331c8315b4039222847eb3c6abcfe9"},"package":"65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"}
\ No newline at end of file
### external/vendor/chacha20/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "b5d39c45c45df97335f4b6effb853cde97810de1"
+ "sha1": "6b236b758a0279f64d777797514813b2cb572c8b"
},
"path_in_vcs": "chacha20"
}
\ No newline at end of file
### external/vendor/chacha20/CHANGELOG.md
@@ -5,6 +5,56 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.10.2 (2026-08-27)
+### Fixed
+- Use of SSE4.1 intrinsic in SSE2 backend of RNG and legacy (64-bit counter) variants ([#580])
+
+[#580]: https://github.com/RustCrypto/stream-ciphers/pull/580
+
+## 0.10.1 (2026-06-24)
+### Added
+- `ChaCha20LegacyCore` type and `Nonce` type alias ([#570])
+
+[#570]: https://github.com/RustCrypto/stream-ciphers/pull/570
+
+## 0.10.0 (2026-02-07)
+### Added
+- `rand_core` v0.10 support ([#333], [#513])
+- 64-bit counter support ([#439])
+- `{get,set}_block_pos` inherent methods ([#516])
+- AVX-512 backend - requires `--cfg chacha20_avx512` to enable ([#477])
+- Inherent methods for RNG state (de)serialization ([#541])
+
+### Changed
+- Bump `cipher` from `0.4` to `0.5` - replaces `generic-array` with `hybrid-array` ([#338], [#521])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#397])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+- Bump `cpufeatures` to v0.3 ([#530])
+- `--cfg chacha20_backend="..."` replaces previous `chacha20_force*` ([#520])
+ - `chacha20_force_avx2` => `chacha20_backend="avx2"`
+ - `chacha20_force_avx512` => `chacha20_backend="avx512"`
+ - `chacha20_force_soft` => `chacha20_backend="soft"`
+ - `chacha20_force_sse2` => `chacha20_backend="sse2"`
+
+### Removed
+- `chacha20_force_neon` cfg attribute - now on-by-default for supported targets ([#361])
+- `std` feature ([#397])
+- `Clone` impls ([#462])
+
+[#333]: https://github.com/RustCrypto/stream-ciphers/pull/333
+[#338]: https://github.com/RustCrypto/stream-ciphers/pull/338
+[#361]: https://github.com/RustCrypto/stream-ciphers/pull/361
+[#397]: https://github.com/RustCrypto/stream-ciphers/pull/397
+[#439]: https://github.com/RustCrypto/stream-ciphers/pull/439
+[#462]: https://github.com/RustCrypto/stream-ciphers/pull/462
+[#477]: https://github.com/RustCrypto/stream-ciphers/pull/477
+[#513]: https://github.com/RustCrypto/stream-ciphers/pull/513
+[#516]: https://github.com/RustCrypto/stream-ciphers/pull/516
+[#520]: https://github.com/RustCrypto/stream-ciphers/pull/520
+[#521]: https://github.com/RustCrypto/stream-ciphers/pull/521
+[#530]: https://github.com/RustCrypto/stream-ciphers/pull/530
+[#541]: https://github.com/RustCrypto/stream-ciphers/pull/541
+
## 0.9.1 (2023-04-01)
### Added
- NEON support via `chacha20_force_neon` cfg attribute ([#310], [#317])
### external/vendor/chacha20/Cargo.lock
@@ -0,0 +1,114 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+ "hex-literal",
+ "rand_core",
+ "zeroize",
+]
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/chacha20/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "chacha20"
-version = "0.9.1"
+version = "0.10.2"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits
from the RustCrypto `cipher` crate, with optional architecture-specific
@@ -35,33 +41,107 @@ categories = [
"cryptography",
"no-std",
]
-license = "Apache-2.0 OR MIT"
+license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/stream-ciphers"
-resolver = "1"
+resolver = "2"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
-]
+
+[features]
+default = ["cipher"]
+legacy = ["cipher"]
+rng = ["dep:rand_core"]
+xchacha = ["cipher"]
+
+[lib]
+name = "chacha20"
+path = "src/lib.rs"
+
+[[test]]
+name = "kats"
+path = "tests/kats.rs"
+
+[[test]]
+name = "rng"
+path = "tests/rng.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
[dependencies.cfg-if]
version = "1"
[dependencies.cipher]
-version = "0.4.4"
+version = "0.5"
+features = ["stream-wrapper"]
+optional = true
+
+[dependencies.rand_core]
+version = "0.10"
+optional = true
+default-features = false
+
+[dependencies.zeroize]
+version = "1.8.1"
+optional = true
+default-features = false
[dev-dependencies.cipher]
-version = "0.4.4"
+version = "0.5"
features = ["dev"]
[dev-dependencies.hex-literal]
-version = "0.3.3"
+version = "1"
-[features]
-std = ["cipher/std"]
-zeroize = ["cipher/zeroize"]
+[target.'cfg(any(target_arch = "x86_64", target_arch = "x86"))'.dependencies.cpufeatures]
+version = "0.3"
-[target."cfg(any(target_arch = \"x86_64\", target_arch = \"x86\"))".dependencies.cpufeatures]
-version = "0.2"
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unreachable_pub = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
+
+[lints.rust.unexpected_cfgs]
+level = "warn"
+priority = 0
+check-cfg = [
+ "cfg(chacha20_avx512)",
+ 'cfg(chacha20_backend, values("avx2", "avx512", "soft", "sse2"))',
+]
### external/vendor/chacha20/Cargo.toml.orig
@@ -1,38 +1,90 @@
[package]
name = "chacha20"
-version = "0.9.1"
+version = "0.10.2"
+authors = ["RustCrypto Developers"]
+edition = "2024"
+rust-version = "1.85"
+documentation = "https://docs.rs/chacha20"
+readme = "README.md"
+repository = "https://github.com/RustCrypto/stream-ciphers"
+license = "MIT OR Apache-2.0"
+keywords = ["crypto", "stream-cipher", "chacha8", "chacha12", "xchacha20"]
+categories = ["cryptography", "no-std"]
description = """
The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits
from the RustCrypto `cipher` crate, with optional architecture-specific
hardware acceleration (AVX2, SSE2). Additionally provides the ChaCha8, ChaCha12,
XChaCha20, XChaCha12 and XChaCha8 stream ciphers, and also optional
rand_core-compatible RNGs based on those ciphers.
"""
-authors = ["RustCrypto Developers"]
-license = "Apache-2.0 OR MIT"
-edition = "2021"
-rust-version = "1.56"
-readme = "README.md"
-documentation = "https://docs.rs/chacha20"
-repository = "https://github.com/RustCrypto/stream-ciphers"
-keywords = ["crypto", "stream-cipher", "chacha8", "chacha12", "xchacha20"]
-categories = ["cryptography", "no-std"]
[dependencies]
cfg-if = "1"
-cipher = "0.4.4"
+cipher = { version = "0.5", optional = true, features = ["stream-wrapper"] }
+rand_core = { version = "0.10", optional = true, default-features = false }
+
+# `zeroize` is an explicit dependency because this crate may be used without the `cipher` crate
+zeroize = { version = "1.8.1", optional = true, default-features = false }
[target.'cfg(any(target_arch = "x86_64", target_arch = "x86"))'.dependencies]
-cpufeatures = "0.2"
+cpufeatures = "0.3"
[dev-dependencies]
-cipher = { version = "0.4.4", features = ["dev"] }
-hex-literal = "0.3.3"
+cipher = { version = "0.5", features = ["dev"] }
+hex-literal = "1"
[features]
-std = ["cipher/std"]
-zeroize = ["cipher/zeroize"]
+default = ["cipher"]
+legacy = ["cipher"]
+rng = ["dep:rand_core"]
+xchacha = ["cipher"]
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unreachable_pub = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
+
+[lints.rust.unexpected_cfgs]
+level = "warn"
+check-cfg = [
+ 'cfg(chacha20_avx512)',
+ 'cfg(chacha20_backend, values("avx2", "avx512", "soft", "sse2"))'
+]
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+trivially_copy_pass_by_ref = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/chacha20/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019-2023 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/chacha20/README.md
@@ -2,44 +2,24 @@
[![Crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
[![HAZMAT][hazmat-image]][hazmat-link]
-Pure Rust implementation of the [ChaCha20 Stream Cipher][1].
-
-[Documentation][docs-link]
-
-<img src="https://raw.githubusercontent.com/RustCrypto/meta/master/img/stream-ciphers/chacha20.png" width="300px">
-
-## About
+Implementation of the [ChaCha] family of stream ciphers.
-[ChaCha20][1] is a [stream cipher][2] which is designed to support
-high-performance software implementations.
+ChaCha improves upon the previous [Salsa] family of stream ciphers
+with increased per-round diffusion at no cost to performance.
-It improves upon the previous [Salsa20][3] stream cipher with increased
-per-round diffusion at no cost to performance.
+This crate also contains an implementation of the [XChaCha] family of stream ciphers
+with an extended 192-bit (24-byte) nonce, gated under the `xchacha` Cargo feature,
+and "legacy" (a.k.a "djb") variant with 64-bit nonce, gated under the `legacy` crate feature.
-This crate also contains an implementation of [XChaCha20][4]: a variant
-of ChaCha20 with an extended 192-bit (24-byte) nonce, gated under the
-`chacha20` Cargo feature (on-by-default).
-
-## Implementations
-
-This crate contains the following implementations of ChaCha20, all of which
-work on stable Rust with the following `RUSTFLAGS`:
-
-- `x86` / `x86_64`
- - `avx2`: (~1.4cpb) `-Ctarget-cpu=haswell -Ctarget-feature=+avx2`
- - `sse2`: (~2.5cpb) `-Ctarget-feature=+sse2` (on by default on x86 CPUs)
-- `aarch64`
- - `neon` (~2-3x faster than `soft`) requires Rust 1.61+ and the `neon` feature enabled
-- Portable
- - `soft`: (~5 cpb on x86/x86_64)
-
-NOTE: cpb = cycles per byte (smaller is better)
+**WARNING:** This implementation internally uses 32-bit counter,
+while the original "legacy" variant implementation uses 64-bit counter.
+In other words, it does not allow encryption of more than 256 GiB of data.
## Security
@@ -49,30 +29,79 @@ This crate does not ensure ciphertexts are authentic (i.e. by using a MAC to
verify ciphertext integrity), which can lead to serious vulnerabilities
if used incorrectly!
-To avoid this, use an [AEAD][5] mode based on ChaCha20, i.e. [ChaCha20Poly1305][6].
-See the [RustCrypto/AEADs][7] repository for more information.
+To avoid this, use an [AEAD] mode based on ChaCha20, e.g. [`chacha20poly1305`].
+See the [RustCrypto/AEADs] repository for more information.
USE AT YOUR OWN RISK!
### Notes
-This crate has received one [security audit by NCC Group][8], with no significant
-findings. We would like to thank [MobileCoin][9] for funding the audit.
+This crate has received one [security audit by NCC Group][NCC-AUDIT], with no significant
+findings. We would like to thank [MobileCoin] for funding the audit.
All implementations contained in the crate (along with the underlying ChaCha20
stream cipher itself) are designed to execute in constant time.
-## Minimum Supported Rust Version
+## Examples
+
+```rust
+// This example requires `cipher` crate feature
+#[cfg(feature = "cipher")] {
+
+use chacha20::ChaCha20;
+use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
+use hex_literal::hex;
+
+let key = [0x42; 32];
+let nonce = [0x24; 12];
+let plaintext = hex!("000102030405060708090A0B0C0D0E0F");
+let ciphertext = hex!("e405626e4f1236b3670ee428332ea20e");
+
+// Key and IV must be references to the `Array` type.
+// Here we use the `Into` trait to convert arrays into it.
+let mut cipher = ChaCha20::new(&key.into(), &nonce.into());
+
+let mut buffer = plaintext;
+
+// apply keystream (encrypt)
+cipher.apply_keystream(&mut buffer);
+assert_eq!(buffer, ciphertext);
+
+let ciphertext = buffer;
+
+// ChaCha ciphers support seeking
+cipher.seek(0u32);
+
+// decrypt ciphertext by applying keystream again
+cipher.apply_keystream(&mut buffer);
+assert_eq!(buffer, plaintext);
+
+// stream ciphers can be used with streaming messages
+cipher.seek(0u32);
+for chunk in buffer.chunks_mut(3) {
+ cipher.apply_keystream(chunk);
+}
+assert_eq!(buffer, ciphertext);
+}
+```
+
+## Configuration Flags
-Rust **1.56** or higher.
+You can modify crate using the following configuration flags:
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+- `chacha20_backend="avx2"`: force AVX2 backend on x86/x86_64 targets.
+ Requires enabled AVX2 target feature. Ignored on non-x86(_64) targets.
+- `chacha20_backend="avx512"`: force AVX-512 backend on x86/x86_64 targets.
+ Requires enabled AVX-512 target feature (MSRV 1.89). Ignored on non-x86(_64) targets.
+- `chacha20_backend="soft"`: force software backend.
+- `chacha20_backend="sse2"`: force SSE2 backend on x86/x86_64 targets.
+ Requires enabled SSE2 target feature. Ignored on non-x86(-64) targets.
-## SemVer Policy
+To use the MSRV 1.89 AVX-512 support with autodetection, you must enable it using
+`chacha20_avx512` configuration flag.
-- All on-by-default features of this library are covered by SemVer
-- MSRV is considered exempt from SemVer as noted above
+The flags can be enabled using `RUSTFLAGS` environmental variable
+(e.g. `RUSTFLAGS='--cfg chacha20_backend="avx2"'`) or by modifying `.cargo/config.toml`.
## License
@@ -95,23 +124,22 @@ dual licensed as above, without any additional terms or conditions.
[crate-link]: https://crates.io/crates/chacha20
[docs-image]: https://docs.rs/chacha20/badge.svg
[docs-link]: https://docs.rs/chacha20/
+[build-image]: https://github.com/RustCrypto/stream-ciphers/actions/workflows/chacha20.yml/badge.svg
+[build-link]: https://github.com/RustCrypto/stream-ciphers/actions/workflows/chacha20.yml
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260049-stream-ciphers
-[build-image]: https://github.com/RustCrypto/stream-ciphers/workflows/chacha20/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/stream-ciphers/actions?query=workflow%3Achacha20
[hazmat-image]: https://img.shields.io/badge/crypto-hazmat%E2%9A%A0-red.svg
[hazmat-link]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md
[//]: # (footnotes)
-[1]: https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant
-[2]: https://en.wikipedia.org/wiki/Stream_cipher
-[3]: https://en.wikipedia.org/wiki/Salsa20
-[4]: https://tools.ietf.org/html/draft-arciszewski-xchacha-02
-[5]: https://en.wikipedia.org/wiki/Authenticated_encryption
-[6]: https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305
-[7]: https://github.com/RustCrypto/AEADs
-[8]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
-[9]: https://www.mobilecoin.com/
+[ChaCha]: https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant
+[Salsa]: https://en.wikipedia.org/wiki/Salsa20
+[XChaCha]: https://tools.ietf.org/html/draft-arciszewski-xchacha-02
+[AEAD]: https://en.wikipedia.org/wiki/Authenticated_encryption
+[`chacha20poly1305`]: https://docs.rs/chacha20poly1305
+[RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs
+[NCC-AUDIT]: https://web.archive.org/web/20240108154854/https://research.nccgroup.com/wp-content/uploads/2020/02/NCC_Group_MobileCoin_RustCrypto_AESGCM_ChaCha20Poly1305_Implementation_Review_2020-02-12_v1.0.pdf
+[MobileCoin]: https://www.mobilecoin.com/
### external/vendor/chacha20/benches/mod.rs
@@ -1,3 +1,4 @@
+//! Basic benchmarks
#![feature(test)]
extern crate test;
### external/vendor/chacha20/src/backends.rs
@@ -1,21 +1,30 @@
+#![cfg(any(feature = "cipher", feature = "rng"))]
+
use cfg_if::cfg_if;
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
pub(crate) mod soft;
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ pub(crate) mod avx512;
+ // AVX-2 backend needed for RNG if enabled
+ #[cfg(feature = "rng")]
+ pub(crate) mod avx2;
+ } else if #[cfg(chacha20_backend = "avx2")] {
pub(crate) mod avx2;
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
pub(crate) mod sse2;
} else {
pub(crate) mod soft;
+ #[cfg(chacha20_avx512)]
+ pub(crate) mod avx512;
pub(crate) mod avx2;
pub(crate) mod sse2;
}
}
- } else if #[cfg(all(chacha20_force_neon, target_arch = "aarch64", target_feature = "neon"))] {
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
pub(crate) mod neon;
} else {
pub(crate) mod soft;
### external/vendor/chacha20/src/backends/avx2.rs
@@ -1,9 +1,25 @@
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+//! AVX2 backend.
+
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::cast_possible_wrap, reason = "needs triage")]
+#![allow(clippy::cast_sign_loss, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use crate::{Rounds, Variant};
+use core::marker::PhantomData;
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::{STATE_WORDS, chacha::Block};
+
+#[cfg(feature = "cipher")]
use cipher::{
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
consts::{U4, U64},
- BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamBackend,
};
-use core::marker::PhantomData;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
@@ -17,25 +33,36 @@ const N: usize = PAR_BLOCKS / 2;
#[inline]
#[target_feature(enable = "avx2")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
+#[cfg(feature = "cipher")]
+#[cfg_attr(chacha20_backend = "avx512", expect(unused))]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
{
- let state_ptr = state.as_ptr() as *const __m128i;
+ let state_ptr = state.as_ptr().cast::<__m128i>();
let v = [
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(0))),
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(1))),
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(2))),
];
let mut c = _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(3)));
- c = _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0));
+ c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0)),
+ 8 => _mm256_add_epi64(c, _mm256_set_epi64x(0, 1, 0, 0)),
+ _ => unreachable!(),
+ };
let mut ctr = [c; N];
for i in 0..N {
ctr[i] = c;
- c = _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 2, 0, 0, 0, 2));
+ c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 2, 0, 0, 0, 2)),
+ 8 => _mm256_add_epi64(c, _mm256_set_epi64x(0, 2, 0, 2)),
+ _ => unreachable!(),
+ };
}
- let mut backend = Backend::<R> {
+ let mut backend = Backend::<R, V> {
v,
ctr,
_pd: PhantomData,
@@ -44,34 +71,79 @@ where
f.call(&mut backend);
state[12] = _mm256_extract_epi32(backend.ctr[0], 0) as u32;
+ match size_of::<V::Counter>() {
+ 4 => {}
+ 8 => state[13] = _mm256_extract_epi32(backend.ctr[0], 1) as u32,
+ _ => unreachable!(),
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx2")]
+#[cfg(feature = "rng")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let state_ptr = core.state.as_ptr().cast::<__m128i>();
+ let v = [
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(0))),
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(1))),
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(2))),
+ ];
+ let mut c = _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(3)));
+ c = _mm256_add_epi64(c, _mm256_set_epi64x(0, 1, 0, 0));
+ let mut ctr = [c; N];
+ for i in 0..N {
+ ctr[i] = c;
+ c = _mm256_add_epi64(c, _mm256_set_epi64x(0, 2, 0, 2));
+ }
+ let mut backend = Backend::<R, V> {
+ v,
+ ctr,
+ _pd: PhantomData,
+ };
+
+ backend.rng_gen_par_ks_blocks(buffer);
+
+ core.state[12] = _mm256_extract_epi32(backend.ctr[0], 0) as u32;
+ core.state[13] = _mm256_extract_epi32(backend.ctr[0], 1) as u32;
}
-struct Backend<R: Unsigned> {
+struct Backend<R: Rounds, V: Variant> {
v: [__m256i; 3],
ctr: [__m256i; N],
- _pd: PhantomData<R>,
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
type ParBlocksSize = U4;
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
unsafe {
let res = rounds::<R>(&self.v, &self.ctr);
for c in self.ctr.iter_mut() {
- *c = _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 1));
+ *c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 1)),
+ 8 => _mm256_add_epi64(*c, _mm256_set_epi64x(0, 1, 0, 1)),
+ _ => unreachable!(),
+ };
}
let res0: [__m128i; 8] = core::mem::transmute(res[0]);
- let block_ptr = block.as_mut_ptr() as *mut __m128i;
+ let block_ptr = block.as_mut_ptr().cast::<__m128i>();
for i in 0..4 {
_mm_storeu_si128(block_ptr.add(i), res0[2 * i]);
}
@@ -85,10 +157,41 @@ impl<R: Unsigned> StreamBackend for Backend<R> {
let pb = PAR_BLOCKS as i32;
for c in self.ctr.iter_mut() {
- *c = _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, pb, 0, 0, 0, pb));
+ *c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, pb, 0, 0, 0, pb)),
+ 8 => {
+ _mm256_add_epi64(*c, _mm256_set_epi64x(0, i64::from(pb), 0, i64::from(pb)))
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ let mut block_ptr = blocks.as_mut_ptr().cast::<__m128i>();
+ for v in vs {
+ let t: [__m128i; 8] = core::mem::transmute(v);
+ for i in 0..4 {
+ _mm_storeu_si128(block_ptr.add(i), t[2 * i]);
+ _mm_storeu_si128(block_ptr.add(4 + i), t[2 * i + 1]);
+ }
+ block_ptr = block_ptr.add(8);
+ }
+ }
+ }
+}
+
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ fn rng_gen_par_ks_blocks(&mut self, blocks: &mut [u32; 64]) {
+ unsafe {
+ let vs = rounds::<R>(&self.v, &self.ctr);
+
+ let pb = PAR_BLOCKS as i32;
+ for c in self.ctr.iter_mut() {
+ *c = _mm256_add_epi64(*c, _mm256_set_epi64x(0, i64::from(pb), 0, i64::from(pb)));
}
- let mut block_ptr = blocks.as_mut_ptr() as *mut __m128i;
+ let mut block_ptr = blocks.as_mut_ptr().cast::<__m128i>();
for v in vs {
let t: [__m128i; 8] = core::mem::transmute(v);
for i in 0..4 {
@@ -103,12 +206,12 @@ impl<R: Unsigned> StreamBackend for Backend<R> {
#[inline]
#[target_feature(enable = "avx2")]
-unsafe fn rounds<R: Unsigned>(v: &[__m256i; 3], c: &[__m256i; N]) -> [[__m256i; 4]; N] {
+unsafe fn rounds<R: Rounds>(v: &[__m256i; 3], c: &[__m256i; N]) -> [[__m256i; 4]; N] {
let mut vs: [[__m256i; 4]; N] = [[_mm256_setzero_si256(); 4]; N];
for i in 0..N {
vs[i] = [v[0], v[1], v[2], c[i]];
}
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
double_quarter_round(&mut vs);
}
### external/vendor/chacha20/src/backends/avx512.rs
@@ -0,0 +1,625 @@
+#![allow(unsafe_op_in_unsafe_fn)]
+use crate::{Rounds, Variant};
+use core::marker::PhantomData;
+
+#[cfg(feature = "cipher")]
+use crate::{STATE_WORDS, chacha::Block};
+
+#[cfg(feature = "cipher")]
+use cipher::{
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U16, U64},
+};
+
+#[cfg(target_arch = "x86")]
+use core::arch::x86::*;
+#[cfg(target_arch = "x86_64")]
+use core::arch::x86_64::*;
+
+/// Maximum number of blocks processed in parallel.
+/// We also support 8 and 4 in gen_tail_blocks.
+const MAX_PAR_BLOCKS: usize = 16;
+
+/// Divisor to compute `N`, the number of __m512i needed
+/// to represent a number of parallel blocks.
+const BLOCKS_PER_VECTOR: usize = 4;
+
+const MAX_N: usize = MAX_PAR_BLOCKS / BLOCKS_PER_VECTOR;
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+#[cfg(feature = "cipher")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
+where
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
+{
+ let simd_state = state.as_mut_ptr().cast::<i32>();
+
+ let mut backend = Backend::<R, V> {
+ state: [
+ _mm_loadu_epi32(simd_state),
+ _mm_loadu_epi32(simd_state.add(4)),
+ _mm_loadu_epi32(simd_state.add(8)),
+ ],
+ ctr: _mm_loadu_epi32(simd_state.add(12)),
+ _pd: PhantomData,
+ };
+
+ f.call(&mut backend);
+
+ // Update counter in the persistent state
+ state[12] = _mm_extract_epi32::<0>(backend.ctr) as u32;
+ if size_of::<V::Counter>() == 8 {
+ state[13] = _mm_extract_epi32::<1>(backend.ctr) as u32;
+ }
+}
+
+struct Backend<R: Rounds, V: Variant> {
+ state: [__m128i; 3],
+ ctr: __m128i,
+ _pd: PhantomData<(R, V)>,
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn increment_ctr(&mut self, amount: usize) {
+ match size_of::<V::Counter>() {
+ 4 => {
+ self.ctr = _mm_add_epi32(self.ctr, _mm_set_epi32(0, 0, 0, amount as i32));
+ }
+ 8 => {
+ self.ctr = _mm_add_epi64(self.ctr, _mm_set_epi64x(0, amount as i64));
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ /// Generates blocks using the 512-bit-wide dispatch
+ /// with up to `N` vectors processed in parallel, producing
+ /// `N * BLOCKS_PER_VECTOR` blocks.
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn gen_blocks_fullwidth<const N: usize>(&mut self, blocks: &mut [Block]) {
+ let par_blocks = N * BLOCKS_PER_VECTOR;
+ assert!(blocks.len() <= par_blocks);
+
+ let mut ctrs = [_mm512_broadcast_i32x4(self.ctr); N];
+ for i in 0..ctrs.len() {
+ match size_of::<V::Counter>() {
+ 4 => {
+ ctrs[i] = _mm512_add_epi32(
+ ctrs[i],
+ _mm512_set_epi32(
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 3) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 2) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 1) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR) as i32,
+ ),
+ );
+ }
+ 8 => {
+ ctrs[i] = _mm512_add_epi64(
+ ctrs[i],
+ _mm512_set_epi64(
+ 0,
+ (i * BLOCKS_PER_VECTOR + 3) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 2) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 1) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR) as i64,
+ ),
+ );
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ self.increment_ctr(blocks.len());
+
+ let result = rounds::<N, R>(&self.state.map(|v| _mm512_broadcast_i32x4(v)), &ctrs);
+
+ for i in 0..N {
+ let result_vectors = result[i];
+
+ // We have our data in SIMD vectors in the following layout
+ // (using a, b, c, and d to indicate the resp. 4 rows of each block,
+ // and Bn to denote the nth block):
+ // result_vectors[0]:
+ // B0a0 B0a1 B0a2 B0a3
+ // B1a0 B1a1 B1a2 B1a3
+ // ...
+ // B3a0 B3a1 B3a2 B3a2
+ //
+ // result_vectors[1]:
+ // B0b0 B0b1 B0b2 B0b3
+ // B1b0 B1b1 B1b2 B1b3
+ // ...
+ // B3b0 B3b1 B3b2 B3b2
+ //
+ // and so on for result_vectors[2] (storing c values) and result_vectors[3] (storing d values).
+ //
+ // To store to memory, we need to transpose to the following format:
+ // transposed[0]:
+ // B0a0 B0a1 B0a2 B0a3
+ // B0b0 B0b1 B0b2 B0b3
+ // B0c0 B0c1 B0c2 B0c3
+ // B0d0 B0d1 B0d2 B0d3
+ //
+ // and so on, such that each 512-bit SIMD vector
+ // contains a single contiguous block.
+ //
+ // We achieve this transposition using the following
+ // sequence of shuffles.
+
+ let temp_abab_block01 = _mm512_permutex2var_epi64(
+ result_vectors[0],
+ _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11),
+ result_vectors[1],
+ );
+ let temp_abab_block23 = _mm512_permutex2var_epi64(
+ result_vectors[0],
+ _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15),
+ result_vectors[1],
+ );
+
+ let temp_cdcd_block01 = _mm512_permutex2var_epi64(
+ result_vectors[2],
+ _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11),
+ result_vectors[3],
+ );
+ let temp_cdcd_block23 = _mm512_permutex2var_epi64(
+ result_vectors[2],
+ _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15),
+ result_vectors[3],
+ );
+
+ let block0 =
+ _mm512_shuffle_i32x4::<0b01_00_01_00>(temp_abab_block01, temp_cdcd_block01);
+ let block1 =
+ _mm512_shuffle_i32x4::<0b11_10_11_10>(temp_abab_block01, temp_cdcd_block01);
+ let block2 =
+ _mm512_shuffle_i32x4::<0b01_00_01_00>(temp_abab_block23, temp_cdcd_block23);
+ let block3 =
+ _mm512_shuffle_i32x4::<0b11_10_11_10>(temp_abab_block23, temp_cdcd_block23);
+
+ for (j, src_block) in [block0, block1, block2, block3].into_iter().enumerate() {
+ let dst_index = i * BLOCKS_PER_VECTOR + j;
+ if dst_index < blocks.len() {
+ _mm512_storeu_si512((&raw mut blocks[dst_index]).cast(), src_block);
+ }
+ }
+ }
+ }
+
+ /// Generates up to 2 blocks using 256-bit vectors.
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn gen_blocks_halfwidth(&mut self, blocks: &mut [Block]) {
+ assert!(blocks.len() <= 2);
+
+ let mut ctr = _mm256_broadcast_i32x4(self.ctr);
+
+ match size_of::<V::Counter>() {
+ 4 => {
+ ctr = _mm256_add_epi32(ctr, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0));
+ }
+ 8 => {
+ ctr = _mm256_add_epi64(ctr, _mm256_set_epi64x(0, 1, 0, 0));
+ }
+ _ => unreachable!(),
+ }
+
+ self.increment_ctr(blocks.len());
+
+ let block_vectors = rounds_halfwide::<R>([
+ _mm256_broadcast_i32x4(self.state[0]),
+ _mm256_broadcast_i32x4(self.state[1]),
+ _mm256_broadcast_i32x4(self.state[2]),
+ ctr,
+ ]);
+
+ // Similar transpose operation as
+ // in gen_blocks_fullwidth.
+
+ let block0_ab = _mm256_permutex2var_epi64(
+ block_vectors[0],
+ _mm256_setr_epi64x(0, 1, 4, 5),
+ block_vectors[1],
+ );
+ let block0_cd = _mm256_permutex2var_epi64(
+ block_vectors[2],
+ _mm256_setr_epi64x(0, 1, 4, 5),
+ block_vectors[3],
+ );
+ let block1_ab = _mm256_permutex2var_epi64(
+ block_vectors[0],
+ _mm256_setr_epi64x(2, 3, 6, 7),
+ block_vectors[1],
+ );
+ let block1_cd = _mm256_permutex2var_epi64(
+ block_vectors[2],
+ _mm256_setr_epi64x(2, 3, 6, 7),
+ block_vectors[3],
+ );
+
+ for (i, (block_part_ab, block_part_cd)) in [(block0_ab, block0_cd), (block1_ab, block1_cd)]
+ .into_iter()
+ .enumerate()
+ {
+ if i < blocks.len() {
+ let dst = (&raw mut blocks[i]).cast::<i32>();
+ _mm256_storeu_epi32(dst, block_part_ab);
+ _mm256_storeu_epi32(
+ dst.add(size_of::<Block>() / 2 / size_of::<i32>()),
+ block_part_cd,
+ );
+ }
+ }
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
+ type BlockSize = U64;
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ type ParBlocksSize = U16;
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
+ #[inline]
+ fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks<Self>) {
+ unsafe { self.gen_blocks_fullwidth::<MAX_N>(blocks) }
+ }
+
+ #[inline(always)]
+ fn gen_ks_block(&mut self, block: &mut Block) {
+ // Fallback for generating a single block using quarter-width vectors
+ // (128).
+
+ unsafe {
+ let state = [self.state[0], self.state[1], self.state[2], self.ctr];
+
+ self.increment_ctr(1);
+
+ let result = rounds_quarterwide::<R>(state);
+
+ for row in 0..4 {
+ let dst = block.as_mut_ptr().cast::<i32>().add(row * 4);
+ _mm_storeu_epi32(dst, result[row]);
+ }
+ }
+ }
+
+ #[inline]
+ fn gen_tail_blocks(&mut self, blocks: &mut [cipher::Block<Self>]) {
+ assert!(blocks.len() < MAX_PAR_BLOCKS);
+
+ if blocks.is_empty() {
+ return;
+ }
+
+ // Fallback for generating a number of blocks less than
+ // MAX_PAR_BLOCKS.
+ unsafe {
+ if blocks.len() == 1 {
+ self.gen_ks_block(&mut blocks[0]);
+ } else if blocks.len() == 2 {
+ self.gen_blocks_halfwidth(blocks);
+ } else if blocks.len() <= 4 {
+ self.gen_blocks_fullwidth::<1>(blocks);
+ } else if blocks.len() <= 8 {
+ self.gen_blocks_fullwidth::<2>(blocks);
+ } else {
+ self.gen_blocks_fullwidth::<MAX_N>(blocks);
+ }
+ }
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn rounds<const N: usize, R: Rounds>(
+ v: &[__m512i; 3],
+ c: &[__m512i; N],
+) -> [[__m512i; 4]; N] {
+ let mut vs: [[__m512i; 4]; N] = [[_mm512_setzero_si512(); 4]; N];
+ for i in 0..N {
+ vs[i] = [v[0], v[1], v[2], c[i]];
+ }
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut vs);
+ }
+
+ for i in 0..N {
+ for j in 0..3 {
+ vs[i][j] = _mm512_add_epi32(vs[i][j], v[j]);
+ }
+ vs[i][3] = _mm512_add_epi32(vs[i][3], c[i]);
+ }
+
+ vs
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn double_quarter_round<const N: usize>(v: &mut [[__m512i; 4]; N]) {
+ add_xor_rot(v);
+ rows_to_cols(v);
+ add_xor_rot(v);
+ cols_to_rows(v);
+}
+
+/// The goal of this function is to transform the state words from:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c0, c1, c2, c3] [ 8, 9, 10, 11]
+/// [d0, d1, d2, d3] [12, 13, 14, 15]
+/// ```
+///
+/// to:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b1, b2, b3, b0] == [ 5, 6, 7, 4]
+/// [c2, c3, c0, c1] [10, 11, 8, 9]
+/// [d3, d0, d1, d2] [15, 12, 13, 14]
+/// ```
+///
+/// so that we can apply [`add_xor_rot`] to the resulting columns, and have it compute the
+/// "diagonal rounds" (as defined in RFC 7539) in parallel. In practice, this shuffle is
+/// non-optimal: the last state word to be altered in `add_xor_rot` is `b`, so the shuffle
+/// blocks on the result of `b` being calculated.
+///
+/// We can optimize this by observing that the four quarter rounds in `add_xor_rot` are
+/// data-independent: they only access a single column of the state, and thus the order of
+/// the columns does not matter. We therefore instead shuffle the other three state words,
+/// to obtain the following equivalent layout:
+/// ```text
+/// [a3, a0, a1, a2] [ 3, 0, 1, 2]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c1, c2, c3, c0] [ 9, 10, 11, 8]
+/// [d2, d3, d0, d1] [14, 15, 12, 13]
+/// ```
+///
+/// See https://github.com/sneves/blake2-avx2/pull/4 for additional details. The earliest
+/// known occurrence of this optimization is in floodyberry's SSE4 ChaCha code from 2014:
+/// - https://github.com/floodyberry/chacha-opt/blob/0ab65cb99f5016633b652edebaf3691ceb4ff753/chacha_blocks_ssse3-64.S#L639-L643
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn rows_to_cols<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ for [a, _, c, d] in vs {
+ *c = _mm512_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm512_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm512_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+ }
+}
+
+/// The goal of this function is to transform the state words from:
+/// ```text
+/// [a3, a0, a1, a2] [ 3, 0, 1, 2]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c1, c2, c3, c0] [ 9, 10, 11, 8]
+/// [d2, d3, d0, d1] [14, 15, 12, 13]
+/// ```
+///
+/// to:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c0, c1, c2, c3] [ 8, 9, 10, 11]
+/// [d0, d1, d2, d3] [12, 13, 14, 15]
+/// ```
+///
+/// reversing the transformation of [`rows_to_cols`].
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn cols_to_rows<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ for [a, _, c, d] in vs {
+ *c = _mm512_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm512_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm512_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn add_xor_rot<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ for [a, b, _, d] in vs.iter_mut() {
+ *a = _mm512_add_epi32(*a, *b);
+ *d = _mm512_xor_si512(*d, *a);
+ *d = _mm512_rol_epi32::<16>(*d);
+ }
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ for [_, b, c, d] in vs.iter_mut() {
+ *c = _mm512_add_epi32(*c, *d);
+ *b = _mm512_xor_si512(*b, *c);
+ *b = _mm512_rol_epi32::<12>(*b);
+ }
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ for [a, b, _, d] in vs.iter_mut() {
+ *a = _mm512_add_epi32(*a, *b);
+ *d = _mm512_xor_si512(*d, *a);
+ *d = _mm512_rol_epi32::<8>(*d);
+ }
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ for [_, b, c, d] in vs.iter_mut() {
+ *c = _mm512_add_epi32(*c, *d);
+ *b = _mm512_xor_si512(*b, *c);
+ *b = _mm512_rol_epi32::<7>(*b);
+ }
+}
+
+// Below is another implementation of the round application
+// that uses 256-bit vectors instead of 512-bit (but, unlike
+// the avx2 module, can use new AVX-512 instructions like rotates).
+// It is used for tail processing of shorter outputs,
+// since 256-bit instructions can be faster and lower latency
+// than 512-bit instructions on certain microarchitectures (e.g. Zen 4).
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn rounds_halfwide<R: Rounds>(v_in: [__m256i; 4]) -> [__m256i; 4] {
+ let mut v = v_in;
+
+ for _ in 0..R::COUNT {
+ double_quarter_round_halfwide(&mut v);
+ }
+
+ for (a, b) in v.iter_mut().zip(v_in) {
+ *a = _mm256_add_epi32(*a, b);
+ }
+
+ v
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn double_quarter_round_halfwide(v: &mut [__m256i; 4]) {
+ add_xor_rot_halfwide(v);
+ rows_to_cols_halfwide(v);
+ add_xor_rot_halfwide(v);
+ cols_to_rows_halfwide(v);
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn rows_to_cols_halfwide(v: &mut [__m256i; 4]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ let [a, _, c, d] = v;
+ *c = _mm256_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm256_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm256_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn cols_to_rows_halfwide(v: &mut [__m256i; 4]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ let [a, _, c, d] = v;
+ *c = _mm256_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm256_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm256_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn add_xor_rot_halfwide(v: &mut [__m256i; 4]) {
+ let [a, b, c, d] = v;
+
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm256_add_epi32(*a, *b);
+ *d = _mm256_xor_si256(*d, *a);
+ *d = _mm256_rol_epi32::<16>(*d);
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm256_add_epi32(*c, *d);
+ *b = _mm256_xor_si256(*b, *c);
+ *b = _mm256_rol_epi32::<12>(*b);
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm256_add_epi32(*a, *b);
+ *d = _mm256_xor_si256(*d, *a);
+ *d = _mm256_rol_epi32::<8>(*d);
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm256_add_epi32(*c, *d);
+ *b = _mm256_xor_si256(*b, *c);
+ *b = _mm256_rol_epi32::<7>(*b);
+}
+
+// Finally, below is an implementation using 128-bit vectors
+// for the case of generating a single block.
+
+#[inline(always)]
+unsafe fn rounds_quarterwide<R: Rounds>(v_in: [__m128i; 4]) -> [__m128i; 4] {
+ let mut v = v_in;
+
+ for _ in 0..R::COUNT {
+ double_quarter_round_quarterwide(&mut v);
+ }
+
+ for (a, b) in v.iter_mut().zip(v_in) {
+ *a = _mm_add_epi32(*a, b);
+ }
+
+ v
+}
+
+#[inline(always)]
+unsafe fn double_quarter_round_quarterwide(v: &mut [__m128i; 4]) {
+ add_xor_rot_quarterwide(v);
+ rows_to_cols_quarterwide(v);
+ add_xor_rot_quarterwide(v);
+ cols_to_rows_quarterwide(v);
+}
+
+#[inline(always)]
+unsafe fn rows_to_cols_quarterwide(v: &mut [__m128i; 4]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ let [a, _, c, d] = v;
+ *c = _mm_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+}
+
+#[inline(always)]
+unsafe fn cols_to_rows_quarterwide(v: &mut [__m128i; 4]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ let [a, _, c, d] = v;
+ *c = _mm_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+}
+
+#[inline(always)]
+unsafe fn add_xor_rot_quarterwide(v: &mut [__m128i; 4]) {
+ let [a, b, c, d] = v;
+
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_rol_epi32::<16>(*d);
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_rol_epi32::<12>(*b);
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_rol_epi32::<8>(*d);
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_rol_epi32::<7>(*b);
+}
### external/vendor/chacha20/src/backends/neon.rs
@@ -1,356 +1,364 @@
//! NEON-optimized implementation for aarch64 CPUs.
//!
//! Adapted from the Crypto++ `chacha_simd` implementation by Jack Lloyd and
-//! Jeffrey Walton (public domain).
+//! Jeffrey Walton (public domain), but uses **8-block** outer batches for
+//! bulk paths (see `ChaCha20_512_neon` in OpenSSL).
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+
+use crate::{Rounds, STATE_WORDS, Variant};
+use core::{arch::aarch64::*, marker::PhantomData};
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+
+#[cfg(feature = "cipher")]
use cipher::{
- consts::{U4, U64},
- BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamBackend,
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U8, U64},
};
-use core::{arch::aarch64::*, marker::PhantomData};
-#[inline]
-#[target_feature(enable = "neon")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
-where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
-{
- let mut backend = Backend::<R> {
- state: [
+struct Backend<R: Rounds, V: Variant> {
+ state: [uint32x4_t; 4],
+ ctrs: [uint32x4_t; 8],
+ _pd: PhantomData<(R, V)>,
+}
+
+macro_rules! add_counter {
+ ($a:expr, $b:expr, $variant:ty) => {
+ match size_of::<<$variant>::Counter>() {
+ 4 => vaddq_u32($a, $b),
+ 8 => vreinterpretq_u32_u64(vaddq_u64(
+ vreinterpretq_u64_u32($a),
+ vreinterpretq_u64_u32($b),
+ )),
+ _ => unreachable!(),
+ }
+ };
+}
+
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline]
+ unsafe fn new(state: &mut [u32; STATE_WORDS]) -> Self {
+ let state = [
vld1q_u32(state.as_ptr().offset(0)),
vld1q_u32(state.as_ptr().offset(4)),
vld1q_u32(state.as_ptr().offset(8)),
vld1q_u32(state.as_ptr().offset(12)),
- ],
- _pd: PhantomData,
- };
+ ];
+ let ctrs = [
+ vld1q_u32([1, 0, 0, 0].as_ptr()),
+ vld1q_u32([2, 0, 0, 0].as_ptr()),
+ vld1q_u32([3, 0, 0, 0].as_ptr()),
+ vld1q_u32([4, 0, 0, 0].as_ptr()),
+ vld1q_u32([5, 0, 0, 0].as_ptr()),
+ vld1q_u32([6, 0, 0, 0].as_ptr()),
+ vld1q_u32([7, 0, 0, 0].as_ptr()),
+ vld1q_u32([8, 0, 0, 0].as_ptr()),
+ ];
+ Backend::<R, V> {
+ state,
+ ctrs,
+ _pd: PhantomData,
+ }
+ }
+}
+
+#[inline]
+#[cfg(feature = "cipher")]
+#[target_feature(enable = "neon")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
+where
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(state);
f.call(&mut backend);
- vst1q_u32(state.as_mut_ptr().offset(12), backend.state[3]);
+ match size_of::<V::Counter>() {
+ 4 => state[12] = vgetq_lane_u32(backend.state[3], 0),
+ 8 => vst1q_u64(
+ state.as_mut_ptr().offset(12).cast::<u64>(),
+ vreinterpretq_u64_u32(backend.state[3]),
+ ),
+ _ => unreachable!(),
+ }
}
-struct Backend<R: Unsigned> {
- state: [uint32x4_t; 4],
- _pd: PhantomData<R>,
+/// Sets up backend and blindly writes 4 blocks to dest_ptr.
+#[cfg(feature = "rng")]
+#[inline]
+#[target_feature(enable = "neon")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(&mut core.state);
+
+ backend.write_par_ks_blocks(buffer);
+
+ vst1q_u64(
+ core.state.as_mut_ptr().offset(12).cast::<u64>(),
+ vreinterpretq_u64_u32(backend.state[3]),
+ );
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
- type ParBlocksSize = U4;
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ /// Match OpenSSL's large-buffer path: 8 blocks
+ type ParBlocksSize = U8;
}
-macro_rules! add64 {
+/// Evaluates to `a = a + b`, where the operands are u32x4s
+macro_rules! add_assign_vec {
($a:expr, $b:expr) => {
- vreinterpretq_u32_u64(vaddq_u64(
- vreinterpretq_u64_u32($a),
- vreinterpretq_u64_u32($b),
- ))
+ $a = vaddq_u32($a, $b)
};
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
let state3 = self.state[3];
let mut par = ParBlocks::<Self>::default();
self.gen_par_ks_blocks(&mut par);
*block = par[0];
+
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- self.state[3] = add64!(state3, vld1q_u32([1, 0, 0, 0].as_ptr()));
+ self.state[3] = add_counter!(state3, vld1q_u32([1, 0, 0, 0].as_ptr()), V);
}
}
#[inline(always)]
- fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks<Self>) {
- macro_rules! rotate_left {
- ($v:ident, 8) => {{
- let maskb = [3u8, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14];
- let mask = vld1q_u8(maskb.as_ptr());
-
- vreinterpretq_u32_u8(vqtbl1q_u8(vreinterpretq_u8_u32($v), mask))
- }};
- ($v:ident, 16) => {
- vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32($v)))
- };
- ($v:ident, $r:literal) => {
- vorrq_u32(vshlq_n_u32($v, $r), vshrq_n_u32($v, 32 - $r))
- };
- }
-
- macro_rules! extract {
- ($v:ident, $s:literal) => {
- vextq_u32($v, $v, $s)
- };
- }
-
+ fn gen_par_ks_blocks(&mut self, dest: &mut ParBlocks<Self>) {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- let ctrs = [
- vld1q_u32([1, 0, 0, 0].as_ptr()),
- vld1q_u32([2, 0, 0, 0].as_ptr()),
- vld1q_u32([3, 0, 0, 0].as_ptr()),
- vld1q_u32([4, 0, 0, 0].as_ptr()),
+ let mut blocks = [
+ [self.state[0], self.state[1], self.state[2], self.state[3]],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[0], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[1], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[2], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[3], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[4], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[5], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[6], V),
+ ],
];
- let mut r0_0 = self.state[0];
- let mut r0_1 = self.state[1];
- let mut r0_2 = self.state[2];
- let mut r0_3 = self.state[3];
-
- let mut r1_0 = self.state[0];
- let mut r1_1 = self.state[1];
- let mut r1_2 = self.state[2];
- let mut r1_3 = add64!(r0_3, ctrs[0]);
-
- let mut r2_0 = self.state[0];
- let mut r2_1 = self.state[1];
- let mut r2_2 = self.state[2];
- let mut r2_3 = add64!(r0_3, ctrs[1]);
-
- let mut r3_0 = self.state[0];
- let mut r3_1 = self.state[1];
- let mut r3_2 = self.state[2];
- let mut r3_3 = add64!(r0_3, ctrs[2]);
-
- for _ in 0..R::USIZE {
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 16);
- r1_3 = rotate_left!(r1_3, 16);
- r2_3 = rotate_left!(r2_3, 16);
- r3_3 = rotate_left!(r3_3, 16);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 12);
- r1_1 = rotate_left!(r1_1, 12);
- r2_1 = rotate_left!(r2_1, 12);
- r3_1 = rotate_left!(r3_1, 12);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 8);
- r1_3 = rotate_left!(r1_3, 8);
- r2_3 = rotate_left!(r2_3, 8);
- r3_3 = rotate_left!(r3_3, 8);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 7);
- r1_1 = rotate_left!(r1_1, 7);
- r2_1 = rotate_left!(r2_1, 7);
- r3_1 = rotate_left!(r3_1, 7);
-
- r0_1 = extract!(r0_1, 1);
- r0_2 = extract!(r0_2, 2);
- r0_3 = extract!(r0_3, 3);
-
- r1_1 = extract!(r1_1, 1);
- r1_2 = extract!(r1_2, 2);
- r1_3 = extract!(r1_3, 3);
-
- r2_1 = extract!(r2_1, 1);
- r2_2 = extract!(r2_2, 2);
- r2_3 = extract!(r2_3, 3);
-
- r3_1 = extract!(r3_1, 1);
- r3_2 = extract!(r3_2, 2);
- r3_3 = extract!(r3_3, 3);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 16);
- r1_3 = rotate_left!(r1_3, 16);
- r2_3 = rotate_left!(r2_3, 16);
- r3_3 = rotate_left!(r3_3, 16);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 12);
- r1_1 = rotate_left!(r1_1, 12);
- r2_1 = rotate_left!(r2_1, 12);
- r3_1 = rotate_left!(r3_1, 12);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 8);
- r1_3 = rotate_left!(r1_3, 8);
- r2_3 = rotate_left!(r2_3, 8);
- r3_3 = rotate_left!(r3_3, 8);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 7);
- r1_1 = rotate_left!(r1_1, 7);
- r2_1 = rotate_left!(r2_1, 7);
- r3_1 = rotate_left!(r3_1, 7);
-
- r0_1 = extract!(r0_1, 3);
- r0_2 = extract!(r0_2, 2);
- r0_3 = extract!(r0_3, 1);
-
- r1_1 = extract!(r1_1, 3);
- r1_2 = extract!(r1_2, 2);
- r1_3 = extract!(r1_3, 1);
-
- r2_1 = extract!(r2_1, 3);
- r2_2 = extract!(r2_2, 2);
- r2_3 = extract!(r2_3, 1);
-
- r3_1 = extract!(r3_1, 3);
- r3_2 = extract!(r3_2, 2);
- r3_3 = extract!(r3_3, 1);
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut blocks);
}
- r0_0 = vaddq_u32(r0_0, self.state[0]);
- r0_1 = vaddq_u32(r0_1, self.state[1]);
- r0_2 = vaddq_u32(r0_2, self.state[2]);
- r0_3 = vaddq_u32(r0_3, self.state[3]);
-
- r1_0 = vaddq_u32(r1_0, self.state[0]);
- r1_1 = vaddq_u32(r1_1, self.state[1]);
- r1_2 = vaddq_u32(r1_2, self.state[2]);
- r1_3 = vaddq_u32(r1_3, self.state[3]);
- r1_3 = add64!(r1_3, ctrs[0]);
-
- r2_0 = vaddq_u32(r2_0, self.state[0]);
- r2_1 = vaddq_u32(r2_1, self.state[1]);
- r2_2 = vaddq_u32(r2_2, self.state[2]);
- r2_3 = vaddq_u32(r2_3, self.state[3]);
- r2_3 = add64!(r2_3, ctrs[1]);
-
- r3_0 = vaddq_u32(r3_0, self.state[0]);
- r3_1 = vaddq_u32(r3_1, self.state[1]);
- r3_2 = vaddq_u32(r3_2, self.state[2]);
- r3_3 = vaddq_u32(r3_3, self.state[3]);
- r3_3 = add64!(r3_3, ctrs[2]);
-
- vst1q_u8(blocks[0].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r0_0));
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r0_1),
- );
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r0_2),
- );
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r0_3),
- );
-
- vst1q_u8(blocks[1].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r1_0));
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r1_1),
- );
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r1_2),
- );
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r1_3),
- );
-
- vst1q_u8(blocks[2].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r2_0));
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r2_1),
- );
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r2_2),
- );
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r2_3),
- );
-
- vst1q_u8(blocks[3].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r3_0));
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r3_1),
- );
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r3_2),
- );
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r3_3),
- );
-
- self.state[3] = add64!(self.state[3], ctrs[3]);
+ for block in 0..8 {
+ // add state to block
+ for state_row in 0..3 {
+ add_assign_vec!(blocks[block][state_row], self.state[state_row]);
+ }
+ if block > 0 {
+ add_assign_vec!(
+ blocks[block][3],
+ add_counter!(self.state[3], self.ctrs[block - 1], V)
+ );
+ } else {
+ add_assign_vec!(blocks[block][3], self.state[3]);
+ }
+ // write blocks to dest
+ for state_row in 0..4 {
+ vst1q_u8(
+ dest[block].as_mut_ptr().add(state_row << 4),
+ vreinterpretq_u8_u32(blocks[block][state_row]),
+ );
+ }
+ }
+ self.state[3] = add_counter!(self.state[3], self.ctrs[7], V);
}
}
}
+
+macro_rules! rotate_left {
+ ($v:expr, 8) => {{
+ let maskb = [3u8, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14];
+ let mask = vld1q_u8(maskb.as_ptr());
+
+ $v = vreinterpretq_u32_u8(vqtbl1q_u8(vreinterpretq_u8_u32($v), mask))
+ }};
+ ($v:expr, 16) => {
+ $v = vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32($v)))
+ };
+ ($v:expr, $r:literal) => {
+ $v = vorrq_u32(vshlq_n_u32($v, $r), vshrq_n_u32($v, 32 - $r))
+ };
+}
+
+macro_rules! extract {
+ ($v:expr, $s:literal) => {
+ $v = vextq_u32($v, $v, $s)
+ };
+}
+
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ /// Generates `num_blocks` blocks and blindly writes them to `dest_ptr`
+ ///
+ /// `num_blocks` must be greater than 0, and less than or equal to 4.
+ ///
+ /// # Safety
+ /// `dest_ptr` must have at least `64 * num_blocks` bytes available to be
+ /// overwritten, or else it could produce undefined behavior
+ #[cfg(feature = "rng")]
+ unsafe fn write_par_ks_blocks(&mut self, buffer: &mut [u32; 64]) {
+ let mut blocks = [
+ [self.state[0], self.state[1], self.state[2], self.state[3]],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[0], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[1], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[2], V),
+ ],
+ ];
+
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut blocks);
+ }
+
+ let mut dest_ptr = buffer.as_mut_ptr().cast::<u8>();
+ for block in 0..4 {
+ // add state to block
+ for state_row in 0..3 {
+ add_assign_vec!(blocks[block][state_row], self.state[state_row]);
+ }
+ if block > 0 {
+ add_assign_vec!(
+ blocks[block][3],
+ add_counter!(self.state[3], self.ctrs[block - 1], V)
+ );
+ } else {
+ add_assign_vec!(blocks[block][3], self.state[3]);
+ }
+ // write blocks to buffer
+ for state_row in 0..4 {
+ #[allow(clippy::cast_sign_loss)]
+ vst1q_u8(
+ dest_ptr.offset(state_row << 4),
+ vreinterpretq_u8_u32(blocks[block][state_row as usize]),
+ );
+ }
+ dest_ptr = dest_ptr.add(64);
+ }
+ self.state[3] = add_counter!(self.state[3], self.ctrs[3], V);
+ }
+}
+
+#[inline]
+unsafe fn double_quarter_round<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ add_xor_rot(blocks);
+ rows_to_cols(blocks);
+ add_xor_rot(blocks);
+ cols_to_rows(blocks);
+}
+
+#[inline]
+unsafe fn add_xor_rot<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ /// Evaluates to `a = a ^ b`, where the operands are u32x4s
+ macro_rules! xor_assign_vec {
+ ($a:expr, $b:expr) => {
+ $a = veorq_u32($a, $b)
+ };
+ }
+ for block in blocks.iter_mut() {
+ // this part of the code cannot be reduced much more without having
+ // to deal with some problems regarding `rotate_left` requiring the second
+ // argument to be a const, and const arrays cannot be indexed by non-consts
+ add_assign_vec!(block[0], block[1]);
+ xor_assign_vec!(block[3], block[0]);
+ rotate_left!(block[3], 16);
+
+ add_assign_vec!(block[2], block[3]);
+ xor_assign_vec!(block[1], block[2]);
+ rotate_left!(block[1], 12);
+
+ add_assign_vec!(block[0], block[1]);
+ xor_assign_vec!(block[3], block[0]);
+ rotate_left!(block[3], 8);
+
+ add_assign_vec!(block[2], block[3]);
+ xor_assign_vec!(block[1], block[2]);
+ rotate_left!(block[1], 7);
+ }
+}
+
+#[inline]
+unsafe fn rows_to_cols<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ for block in blocks.iter_mut() {
+ extract!(block[1], 1);
+ extract!(block[2], 2);
+ extract!(block[3], 3);
+ }
+}
+
+#[inline]
+unsafe fn cols_to_rows<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ for block in blocks.iter_mut() {
+ extract!(block[1], 3);
+ extract!(block[2], 2);
+ extract!(block[3], 1);
+ }
+}
### external/vendor/chacha20/src/backends/soft.rs
@@ -1,39 +1,72 @@
-//! Portable implementation which does not rely on architecture-specific
-//! intrinsics.
+//! Portable implementation which does not rely on architecture-specific intrinsics.
-use crate::{Block, ChaChaCore, Unsigned, STATE_WORDS};
+#![allow(clippy::cast_possible_truncation)]
+
+use crate::{ChaChaCore, Rounds, STATE_WORDS, Variant, quarter_round};
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+#[cfg(feature = "cipher")]
use cipher::{
+ BlockSizeUser, ParBlocksSizeUser, StreamCipherBackend,
consts::{U1, U64},
- BlockSizeUser, ParBlocksSizeUser, StreamBackend,
};
-pub(crate) struct Backend<'a, R: Unsigned>(pub(crate) &'a mut ChaChaCore<R>);
+#[cfg(feature = "rng")]
+use crate::rng::BLOCK_WORDS;
-impl<'a, R: Unsigned> BlockSizeUser for Backend<'a, R> {
+pub(crate) struct Backend<'a, R: Rounds, V: Variant>(pub(crate) &'a mut ChaChaCore<R, V>);
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<'_, R, V> {
type BlockSize = U64;
}
-impl<'a, R: Unsigned> ParBlocksSizeUser for Backend<'a, R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<'_, R, V> {
type ParBlocksSize = U1;
}
-impl<'a, R: Unsigned> StreamBackend for Backend<'a, R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<'_, R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
let res = run_rounds::<R>(&self.0.state);
- self.0.state[12] = self.0.state[12].wrapping_add(1);
+ let mut ctr = (u64::from(self.0.state[13]) << 32) | u64::from(self.0.state[12]);
+ ctr = ctr.wrapping_add(1);
+ self.0.state[12] = ctr as u32;
+ if size_of::<V::Counter>() == 8 {
+ self.0.state[13] = (ctr >> 32) as u32;
+ }
for (chunk, val) in block.chunks_exact_mut(4).zip(res.iter()) {
chunk.copy_from_slice(&val.to_le_bytes());
}
}
}
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<'_, R, V> {
+ #[inline(always)]
+ pub(crate) fn gen_ks_blocks(&mut self, buffer: &mut [u32; 64]) {
+ for block in 0..4 {
+ let res = run_rounds::<R>(&self.0.state);
+ let mut ctr = (u64::from(self.0.state[13]) << 32) | u64::from(self.0.state[12]);
+ ctr = ctr.wrapping_add(1);
+ self.0.state[12] = ctr as u32;
+ self.0.state[13] = (ctr >> 32) as u32;
+
+ buffer[block * BLOCK_WORDS as usize..(block + 1) * BLOCK_WORDS as usize]
+ .copy_from_slice(&res);
+ }
+ }
+}
+
#[inline(always)]
-fn run_rounds<R: Unsigned>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
+fn run_rounds<R: Rounds>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
let mut res = *state;
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
// column rounds
quarter_round(0, 4, 8, 12, &mut res);
quarter_round(1, 5, 9, 13, &mut res);
@@ -52,22 +85,3 @@ fn run_rounds<R: Unsigned>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
}
res
}
-
-/// The ChaCha20 quarter round function
-fn quarter_round(a: usize, b: usize, c: usize, d: usize, state: &mut [u32; STATE_WORDS]) {
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(16);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(12);
-
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(8);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(7);
-}
### external/vendor/chacha20/src/backends/sse2.rs
@@ -1,7 +1,22 @@
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+//! SSE2 backend.
+
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::cast_possible_wrap, reason = "needs triage")]
+#![allow(clippy::cast_sign_loss, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use crate::{Rounds, STATE_WORDS, Variant};
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+#[cfg(feature = "cipher")]
use cipher::{
- consts::{U1, U64},
- BlockSizeUser, ParBlocksSizeUser, StreamBackend,
+ BlockSizeUser, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U4, U64},
};
use core::marker::PhantomData;
@@ -10,75 +25,157 @@ use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
+const PAR_BLOCKS: usize = 4;
+
#[inline]
#[target_feature(enable = "sse2")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
+#[cfg(feature = "cipher")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
{
- let state_ptr = state.as_ptr() as *const __m128i;
- let mut backend = Backend::<R> {
- v: [
- _mm_loadu_si128(state_ptr.add(0)),
- _mm_loadu_si128(state_ptr.add(1)),
- _mm_loadu_si128(state_ptr.add(2)),
- _mm_loadu_si128(state_ptr.add(3)),
- ],
- _pd: PhantomData,
- };
-
+ let mut backend = Backend::<R, V>::new(state);
f.call(&mut backend);
+ backend.save_ctr(state);
+}
- state[12] = _mm_cvtsi128_si32(backend.v[3]) as u32;
+#[inline]
+#[target_feature(enable = "sse2")]
+#[cfg(feature = "rng")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(&core.state);
+ backend.gen_ks_blocks(buffer);
+ backend.save_ctr(&mut core.state);
}
-struct Backend<R: Unsigned> {
+struct Backend<R: Rounds, V: Variant> {
v: [__m128i; 4],
- _pd: PhantomData<R>,
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ unsafe fn new(state: &[u32; STATE_WORDS]) -> Self {
+ let state_ptr = state.as_ptr().cast::<__m128i>();
+ Self {
+ v: core::array::from_fn(|i| _mm_loadu_si128(state_ptr.add(i))),
+ _pd: PhantomData,
+ }
+ }
+
+ unsafe fn save_ctr(self, state: &mut [u32; STATE_WORDS]) {
+ let state_ptr = state.as_mut_ptr().cast::<__m128i>();
+ _mm_storeu_si128(state_ptr.add(3), self.v[3]);
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
- type ParBlocksSize = U1;
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ type ParBlocksSize = U4;
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
unsafe {
- let res = rounds::<R>(&self.v);
- self.v[3] = _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, 1));
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, 1)),
+ 8 => _mm_add_epi64(self.v[3], _mm_set_epi64x(0, 1)),
+ _ => unreachable!(),
+ };
- let block_ptr = block.as_mut_ptr() as *mut __m128i;
+ let block_ptr = block.as_mut_ptr().cast::<__m128i>();
for i in 0..4 {
- _mm_storeu_si128(block_ptr.add(i), res[i]);
+ _mm_storeu_si128(block_ptr.add(i), res[0][i]);
+ }
+ }
+ }
+
+ #[inline(always)]
+ fn gen_par_ks_blocks(&mut self, blocks: &mut cipher::ParBlocks<Self>) {
+ unsafe {
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, PAR_BLOCKS as i32)),
+ 8 => _mm_add_epi64(self.v[3], _mm_set_epi64x(0, PAR_BLOCKS as i64)),
+ _ => unreachable!(),
+ };
+
+ let blocks_ptr = blocks.as_mut_ptr().cast::<__m128i>();
+ for block in 0..PAR_BLOCKS {
+ for i in 0..4 {
+ _mm_storeu_si128(blocks_ptr.add(i + block * PAR_BLOCKS), res[block][i]);
+ }
+ }
+ }
+ }
+}
+
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ fn gen_ks_blocks(&mut self, block: &mut [u32; 64]) {
+ const _: () = assert!(4 * PAR_BLOCKS * size_of::<__m128i>() == size_of::<[u32; 64]>());
+ unsafe {
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = _mm_add_epi64(self.v[3], _mm_set_epi64x(0, PAR_BLOCKS as i64));
+
+ let blocks_ptr = block.as_mut_ptr().cast::<__m128i>();
+ for block in 0..PAR_BLOCKS {
+ for i in 0..4 {
+ _mm_storeu_si128(blocks_ptr.add(i + block * PAR_BLOCKS), res[block][i]);
+ }
}
}
}
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn rounds<R: Unsigned>(v: &[__m128i; 4]) -> [__m128i; 4] {
- let mut res = *v;
- for _ in 0..R::USIZE {
+unsafe fn rounds<R: Rounds, V: Variant>(v: &[__m128i; 4]) -> [[__m128i; 4]; PAR_BLOCKS] {
+ let mut res = [*v; 4];
+ for block in 1..PAR_BLOCKS {
+ res[block][3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(res[block][3], _mm_set_epi32(0, 0, 0, block as i32)),
+ 8 => _mm_add_epi64(res[block][3], _mm_set_epi64x(0, block as i64)),
+ _ => unreachable!(),
+ }
+ }
+
+ for _ in 0..R::COUNT {
double_quarter_round(&mut res);
}
- for i in 0..4 {
- res[i] = _mm_add_epi32(res[i], v[i]);
+ for block in 0..PAR_BLOCKS {
+ for i in 0..3 {
+ res[block][i] = _mm_add_epi32(res[block][i], v[i]);
+ }
+ let ctr = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(v[3], _mm_set_epi32(0, 0, 0, block as i32)),
+ 8 => _mm_add_epi64(v[3], _mm_set_epi64x(0, block as i64)),
+ _ => unreachable!(),
+ };
+ res[block][3] = _mm_add_epi32(res[block][3], ctr);
}
res
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn double_quarter_round(v: &mut [__m128i; 4]) {
+unsafe fn double_quarter_round(v: &mut [[__m128i; 4]; PAR_BLOCKS]) {
add_xor_rot(v);
rows_to_cols(v);
add_xor_rot(v);
@@ -122,11 +219,13 @@ unsafe fn double_quarter_round(v: &mut [__m128i; 4]) {
/// - https://github.com/floodyberry/chacha-opt/blob/0ab65cb99f5016633b652edebaf3691ceb4ff753/chacha_blocks_ssse3-64.S#L639-L643
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn rows_to_cols([a, _, c, d]: &mut [__m128i; 4]) {
- // c >>>= 32; d >>>= 64; a >>>= 96;
- *c = _mm_shuffle_epi32(*c, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
- *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
- *a = _mm_shuffle_epi32(*a, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+unsafe fn rows_to_cols(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, _, c, d] in blocks.iter_mut() {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ *c = _mm_shuffle_epi32(*c, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32(*a, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+ }
}
/// The goal of this function is to transform the state words from:
@@ -148,33 +247,37 @@ unsafe fn rows_to_cols([a, _, c, d]: &mut [__m128i; 4]) {
/// reversing the transformation of [`rows_to_cols`].
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn cols_to_rows([a, _, c, d]: &mut [__m128i; 4]) {
- // c <<<= 32; d <<<= 64; a <<<= 96;
- *c = _mm_shuffle_epi32(*c, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
- *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
- *a = _mm_shuffle_epi32(*a, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+unsafe fn cols_to_rows(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, _, c, d] in blocks.iter_mut() {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ *c = _mm_shuffle_epi32(*c, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32(*a, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+ }
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn add_xor_rot([a, b, c, d]: &mut [__m128i; 4]) {
- // a += b; d ^= a; d <<<= (16, 16, 16, 16);
- *a = _mm_add_epi32(*a, *b);
- *d = _mm_xor_si128(*d, *a);
- *d = _mm_xor_si128(_mm_slli_epi32(*d, 16), _mm_srli_epi32(*d, 16));
-
- // c += d; b ^= c; b <<<= (12, 12, 12, 12);
- *c = _mm_add_epi32(*c, *d);
- *b = _mm_xor_si128(*b, *c);
- *b = _mm_xor_si128(_mm_slli_epi32(*b, 12), _mm_srli_epi32(*b, 20));
-
- // a += b; d ^= a; d <<<= (8, 8, 8, 8);
- *a = _mm_add_epi32(*a, *b);
- *d = _mm_xor_si128(*d, *a);
- *d = _mm_xor_si128(_mm_slli_epi32(*d, 8), _mm_srli_epi32(*d, 24));
-
- // c += d; b ^= c; b <<<= (7, 7, 7, 7);
- *c = _mm_add_epi32(*c, *d);
- *b = _mm_xor_si128(*b, *c);
- *b = _mm_xor_si128(_mm_slli_epi32(*b, 7), _mm_srli_epi32(*b, 25));
+unsafe fn add_xor_rot(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, b, c, d] in blocks.iter_mut() {
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_xor_si128(_mm_slli_epi32(*d, 16), _mm_srli_epi32(*d, 16));
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_xor_si128(_mm_slli_epi32(*b, 12), _mm_srli_epi32(*b, 20));
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_xor_si128(_mm_slli_epi32(*d, 8), _mm_srli_epi32(*d, 24));
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_xor_si128(_mm_slli_epi32(*b, 7), _mm_srli_epi32(*b, 25));
+ }
}
### external/vendor/chacha20/src/chacha.rs
@@ -0,0 +1,38 @@
+use cipher::{
+ IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCoreWrapper,
+ array::Array,
+ consts::{U12, U32, U64},
+};
+
+use crate::{ChaChaCore, R8, R12, R20, Rounds, variants::Ietf};
+
+/// Key type used by all ChaCha variants.
+pub type Key = Array<u8, U32>;
+
+/// Nonce type used by ChaCha variants.
+pub type Nonce = Array<u8, U12>;
+
+/// ChaCha8 stream cipher (reduced-round variant of [`ChaCha20`] with 8 rounds)
+pub type ChaCha8 = StreamCipherCoreWrapper<ChaChaCore<R8, Ietf>>;
+
+/// ChaCha12 stream cipher (reduced-round variant of [`ChaCha20`] with 12 rounds)
+pub type ChaCha12 = StreamCipherCoreWrapper<ChaChaCore<R12, Ietf>>;
+
+/// ChaCha20 stream cipher (RFC 8439 version with 96-bit nonce)
+pub type ChaCha20 = StreamCipherCoreWrapper<ChaChaCore<R20, Ietf>>;
+
+pub(crate) type Block = Array<u8, U64>;
+
+impl<R: Rounds> KeySizeUser for ChaChaCore<R, Ietf> {
+ type KeySize = U32;
+}
+
+impl<R: Rounds> IvSizeUser for ChaChaCore<R, Ietf> {
+ type IvSize = U12;
+}
+impl<R: Rounds> KeyIvInit for ChaChaCore<R, Ietf> {
+ #[inline]
+ fn new(key: &Key, iv: &Nonce) -> Self {
+ ChaChaCore::<R, Ietf>::new_internal(key.as_ref(), iv.as_ref())
+ }
+}
### external/vendor/chacha20/src/legacy.rs
@@ -1,28 +1,20 @@
//! Legacy version of ChaCha20 with a 64-bit nonce
-use super::{ChaChaCore, Key, Nonce};
+use crate::{ChaChaCore, Key, R20, variants::Legacy};
use cipher::{
- consts::{U10, U32, U64, U8},
- generic_array::GenericArray,
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
+ IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCoreWrapper,
+ array::Array,
+ consts::{U8, U32},
};
-#[cfg(feature = "zeroize")]
-use cipher::zeroize::ZeroizeOnDrop;
-
/// Nonce type used by [`ChaCha20Legacy`].
-pub type LegacyNonce = GenericArray<u8, U8>;
+pub type LegacyNonce = Array<u8, U8>;
/// The ChaCha20 stream cipher (legacy "djb" construction with 64-bit nonce).
-///
-/// **WARNING:** this implementation uses 32-bit counter, while the original
-/// implementation uses 64-bit counter. In other words, it does
-/// not allow encrypting of more than 256 GiB of data.
pub type ChaCha20Legacy = StreamCipherCoreWrapper<ChaCha20LegacyCore>;
/// The ChaCha20 stream cipher (legacy "djb" construction with 64-bit nonce).
-pub struct ChaCha20LegacyCore(ChaChaCore<U10>);
+pub type ChaCha20LegacyCore = ChaChaCore<R20, Legacy>;
impl KeySizeUser for ChaCha20LegacyCore {
type KeySize = U32;
@@ -32,45 +24,9 @@ impl IvSizeUser for ChaCha20LegacyCore {
type IvSize = U8;
}
-impl BlockSizeUser for ChaCha20LegacyCore {
- type BlockSize = U64;
-}
-
impl KeyIvInit for ChaCha20LegacyCore {
#[inline(always)]
fn new(key: &Key, iv: &LegacyNonce) -> Self {
- let mut padded_iv = Nonce::default();
- padded_iv[4..].copy_from_slice(iv);
- ChaCha20LegacyCore(ChaChaCore::new(key, &padded_iv))
- }
-}
-
-impl StreamCipherCore for ChaCha20LegacyCore {
- #[inline(always)]
- fn remaining_blocks(&self) -> Option<usize> {
- self.0.remaining_blocks()
- }
-
- #[inline(always)]
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
- self.0.process_with_backend(f);
+ ChaChaCore::<R20, Legacy>::new_internal(key.as_ref(), iv.as_ref())
}
}
-
-impl StreamCipherSeekCore for ChaCha20LegacyCore {
- type Counter = u32;
-
- #[inline(always)]
- fn get_block_pos(&self) -> u32 {
- self.0.get_block_pos()
- }
-
- #[inline(always)]
- fn set_block_pos(&mut self, pos: u32) {
- self.0.set_block_pos(pos);
- }
-}
-
-#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl ZeroizeOnDrop for ChaCha20LegacyCore {}
### external/vendor/chacha20/src/lib.rs
@@ -1,177 +1,112 @@
-//! Implementation of the [ChaCha] family of stream ciphers.
-//!
-//! Cipher functionality is accessed using traits from re-exported [`cipher`] crate.
-//!
-//! ChaCha stream ciphers are lightweight and amenable to fast, constant-time
-//! implementations in software. It improves upon the previous [Salsa] design,
-//! providing increased per-round diffusion with no cost to performance.
-//!
-//! This crate contains the following variants of the ChaCha20 core algorithm:
-//!
-//! - [`ChaCha20`]: standard IETF variant with 96-bit nonce
-//! - [`ChaCha8`] / [`ChaCha12`]: reduced round variants of ChaCha20
-//! - [`XChaCha20`]: 192-bit extended nonce variant
-//! - [`XChaCha8`] / [`XChaCha12`]: reduced round variants of XChaCha20
-//! - [`ChaCha20Legacy`]: "djb" variant with 64-bit nonce.
-//! **WARNING:** This implementation internally uses 32-bit counter,
-//! while the original implementation uses 64-bit counter. In other words,
-//! it does not allow encryption of more than 256 GiB of data.
-//!
-//! # ⚠️ Security Warning: Hazmat!
-//!
-//! This crate does not ensure ciphertexts are authentic, which can lead to
-//! serious vulnerabilities if used incorrectly!
-//!
-//! If in doubt, use the [`chacha20poly1305`] crate instead, which provides
-//! an authenticated mode on top of ChaCha20.
-//!
-//! **USE AT YOUR OWN RISK!**
-//!
-//! # Diagram
-//!
-//! This diagram illustrates the ChaCha quarter round function.
-//! Each round consists of four quarter-rounds:
-//!
-//! <img src="https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/img/stream-ciphers/chacha20.png" width="300px">
-//!
-//! Legend:
-//!
-//! - ⊞ add
-//! - ‹‹‹ rotate
-//! - ⊕ xor
-//!
-//! # Example
-//! ```
-//! use chacha20::ChaCha20;
-//! // Import relevant traits
-//! use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
-//! use hex_literal::hex;
-//!
-//! let key = [0x42; 32];
-//! let nonce = [0x24; 12];
-//! let plaintext = hex!("00010203 04050607 08090A0B 0C0D0E0F");
-//! let ciphertext = hex!("e405626e 4f1236b3 670ee428 332ea20e");
-//!
-//! // Key and IV must be references to the `GenericArray` type.
-//! // Here we use the `Into` trait to convert arrays into it.
-//! let mut cipher = ChaCha20::new(&key.into(), &nonce.into());
-//!
-//! let mut buffer = plaintext.clone();
-//!
-//! // apply keystream (encrypt)
-//! cipher.apply_keystream(&mut buffer);
-//! assert_eq!(buffer, ciphertext);
-//!
-//! let ciphertext = buffer.clone();
-//!
-//! // ChaCha ciphers support seeking
-//! cipher.seek(0u32);
-//!
-//! // decrypt ciphertext by applying keystream again
-//! cipher.apply_keystream(&mut buffer);
-//! assert_eq!(buffer, plaintext);
-//!
-//! // stream ciphers can be used with streaming messages
-//! cipher.seek(0u32);
-//! for chunk in buffer.chunks_mut(3) {
-//! cipher.apply_keystream(chunk);
-//! }
-//! assert_eq!(buffer, ciphertext);
-//! ```
-//!
-//! # Configuration Flags
-//!
-//! You can modify crate using the following configuration flags:
-//!
-//! - `chacha20_force_avx2`: force AVX2 backend on x86/x86_64 targets.
-//! Requires enabled AVX2 target feature. Ignored on non-x86(-64) targets.
-//! - `chacha20_force_neon`: force NEON backend on ARM targets.
-//! Requires enabled NEON target feature. Ignored on non-ARM targets. Nightly-only.
-//! - `chacha20_force_soft`: force software backend.
-//! - `chacha20_force_sse2`: force SSE2 backend on x86/x86_64 targets.
-//! Requires enabled SSE2 target feature. Ignored on non-x86(-64) targets.
-//!
-//! The flags can be enabled using `RUSTFLAGS` environmental variable
-//! (e.g. `RUSTFLAGS="--cfg chacha20_force_avx2"`) or by modifying `.cargo/config`.
-//!
-//! You SHOULD NOT enable several `force` flags simultaneously.
-//!
-//! [ChaCha]: https://tools.ietf.org/html/rfc8439
-//! [Salsa]: https://en.wikipedia.org/wiki/Salsa20
-//! [`chacha20poly1305`]: https://docs.rs/chacha20poly1305
-
#![no_std]
-#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
-#![allow(clippy::needless_range_loop)]
-#![warn(missing_docs, rust_2018_idioms, trivial_casts, unused_qualifications)]
-
-pub use cipher;
-
-use cfg_if::cfg_if;
-use cipher::{
- consts::{U10, U12, U32, U4, U6, U64},
- generic_array::{typenum::Unsigned, GenericArray},
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
-};
-use core::marker::PhantomData;
+#![cfg_attr(docsrs, feature(doc_cfg))]
-#[cfg(feature = "zeroize")]
-use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
+pub mod variants;
mod backends;
+#[cfg(feature = "cipher")]
+mod chacha;
+#[cfg(feature = "legacy")]
mod legacy;
+#[cfg(feature = "rng")]
+mod rng;
+#[cfg(feature = "xchacha")]
mod xchacha;
+#[cfg(feature = "cipher")]
+pub use chacha::{ChaCha8, ChaCha12, ChaCha20, Key, Nonce};
+#[cfg(feature = "cipher")]
+pub use cipher;
+#[cfg(feature = "cipher")]
+pub use cipher::KeyIvInit;
+#[cfg(feature = "legacy")]
pub use legacy::{ChaCha20Legacy, ChaCha20LegacyCore, LegacyNonce};
-pub use xchacha::{hchacha, XChaCha12, XChaCha20, XChaCha8, XChaChaCore, XNonce};
+#[cfg(feature = "rng")]
+pub use rand_core;
+#[cfg(feature = "rng")]
+pub use rng::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng, Seed, SerializedRngState};
+#[cfg(feature = "xchacha")]
+pub use xchacha::{XChaCha8, XChaCha12, XChaCha20, XNonce, hchacha};
+
+use cfg_if::cfg_if;
+use core::{fmt, marker::PhantomData};
+use variants::Variant;
+
+#[cfg(feature = "cipher")]
+use cipher::{BlockSizeUser, StreamCipherCore, StreamCipherSeekCore, consts::U64};
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
/// State initialization constant ("expand 32-byte k")
+#[cfg(any(feature = "cipher", feature = "rng"))]
const CONSTANTS: [u32; 4] = [0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574];
/// Number of 32-bit words in the ChaCha state
const STATE_WORDS: usize = 16;
-/// Block type used by all ChaCha variants.
-type Block = GenericArray<u8, U64>;
+/// Marker type for a number of ChaCha rounds to perform.
+pub trait Rounds: Copy {
+ /// The amount of rounds to perform
+ const COUNT: usize;
+}
+
+/// 8-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R8;
-/// Key type used by all ChaCha variants.
-pub type Key = GenericArray<u8, U32>;
+impl Rounds for R8 {
+ const COUNT: usize = 4;
+}
-/// Nonce type used by ChaCha variants.
-pub type Nonce = GenericArray<u8, U12>;
+/// 12-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R12;
-/// ChaCha8 stream cipher (reduced-round variant of [`ChaCha20`] with 8 rounds)
-pub type ChaCha8 = StreamCipherCoreWrapper<ChaChaCore<U4>>;
+impl Rounds for R12 {
+ const COUNT: usize = 6;
+}
-/// ChaCha12 stream cipher (reduced-round variant of [`ChaCha20`] with 12 rounds)
-pub type ChaCha12 = StreamCipherCoreWrapper<ChaChaCore<U6>>;
+/// 20-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R20;
-/// ChaCha20 stream cipher (RFC 8439 version with 96-bit nonce)
-pub type ChaCha20 = StreamCipherCoreWrapper<ChaChaCore<U10>>;
+impl Rounds for R20 {
+ const COUNT: usize = 10;
+}
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
type Tokens = ();
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ #[cfg(not(all(target_feature = "avx512f", target_feature = "avx512vl")))]
+ compile_error!("You must enable `avx512f` and `avx512vl` target features with \
+ `chacha20_backend = "avx512"` configuration option");
+ type Tokens = ();
+ } else if #[cfg(chacha20_backend = "avx2")] {
#[cfg(not(target_feature = "avx2"))]
compile_error!("You must enable `avx2` target feature with \
- `chacha20_force_avx2` configuration option");
+ `chacha20_backend = "avx2"` configuration option");
type Tokens = ();
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
#[cfg(not(target_feature = "sse2"))]
compile_error!("You must enable `sse2` target feature with \
- `chacha20_force_sse2` configuration option");
+ `chacha20_backend = "sse2"` configuration option");
type Tokens = ();
} else {
+ #[cfg(chacha20_avx512)]
+ cpufeatures::new!(avx512_cpuid, "avx512f", "avx512vl");
cpufeatures::new!(avx2_cpuid, "avx2");
cpufeatures::new!(sse2_cpuid, "sse2");
+ #[cfg(chacha20_avx512)]
+ type Tokens = (avx512_cpuid::InitToken, avx2_cpuid::InitToken, sse2_cpuid::InitToken);
+ #[cfg(not(chacha20_avx512))]
type Tokens = (avx2_cpuid::InitToken, sse2_cpuid::InitToken);
}
}
@@ -181,51 +116,64 @@ cfg_if! {
}
/// The ChaCha core function.
-pub struct ChaChaCore<R: Unsigned> {
+pub struct ChaChaCore<R: Rounds, V: Variant> {
/// Internal state of the core function
state: [u32; STATE_WORDS],
/// CPU target feature tokens
#[allow(dead_code)]
tokens: Tokens,
- /// Number of rounds to perform
- rounds: PhantomData<R>,
+ /// Number of rounds to perform and the cipher variant
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> KeySizeUser for ChaChaCore<R> {
- type KeySize = U32;
-}
+impl<R: Rounds, V: Variant> ChaChaCore<R, V> {
+ /// Constructs a ChaChaCore with the specified `key` and `iv`.
+ ///
+ /// You must ensure that the iv is of the correct size when using this method
+ /// directly.
+ ///
+ /// # Panics
+ /// If `iv.len()` is not equal to 4, 8, or 12.
+ #[must_use]
+ #[cfg(any(feature = "cipher", feature = "rng"))]
+ fn new_internal(key: &[u8; 32], iv: &[u8]) -> Self {
+ assert!(matches!(iv.len(), 4 | 8 | 12));
-impl<R: Unsigned> IvSizeUser for ChaChaCore<R> {
- type IvSize = U12;
-}
+ let mut state = [0u32; STATE_WORDS];
-impl<R: Unsigned> BlockSizeUser for ChaChaCore<R> {
- type BlockSize = U64;
-}
+ let ctr_size = size_of::<V::Counter>() / size_of::<u32>();
+ let (const_dst, state_rem) = state.split_at_mut(4);
+ let (key_dst, state_rem) = state_rem.split_at_mut(8);
+ let (_ctr_dst, iv_dst) = state_rem.split_at_mut(ctr_size);
-impl<R: Unsigned> KeyIvInit for ChaChaCore<R> {
- #[inline]
- fn new(key: &Key, iv: &Nonce) -> Self {
- let mut state = [0u32; STATE_WORDS];
- state[0..4].copy_from_slice(&CONSTANTS);
- let key_chunks = key.chunks_exact(4);
- for (val, chunk) in state[4..12].iter_mut().zip(key_chunks) {
- *val = u32::from_le_bytes(chunk.try_into().unwrap());
- }
- let iv_chunks = iv.chunks_exact(4);
- for (val, chunk) in state[13..16].iter_mut().zip(iv_chunks) {
- *val = u32::from_le_bytes(chunk.try_into().unwrap());
+ const_dst.copy_from_slice(&CONSTANTS);
+
+ // TODO(tarcieri): when MSRV 1.88, use `[T]::as_chunks` to avoid panic
+ #[allow(clippy::unwrap_used, reason = "MSRV TODO")]
+ {
+ for (src, dst) in key.chunks_exact(4).zip(key_dst) {
+ *dst = u32::from_le_bytes(src.try_into().unwrap());
+ }
+
+ assert_eq!(size_of_val(iv_dst), size_of_val(iv));
+ for (src, dst) in iv.chunks_exact(4).zip(iv_dst) {
+ *dst = u32::from_le_bytes(src.try_into().unwrap());
+ }
}
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
let tokens = ();
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(chacha20_backend = "avx512")] {
let tokens = ();
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "avx2")] {
let tokens = ();
+ } else if #[cfg(chacha20_backend = "sse2")] {
+ let tokens = ();
+ } else if #[cfg(chacha20_avx512)] {
+ let tokens = (avx512_cpuid::init(), avx2_cpuid::init(), sse2_cpuid::init());
} else {
let tokens = (avx2_cpuid::init(), sse2_cpuid::init());
}
@@ -234,54 +182,114 @@ impl<R: Unsigned> KeyIvInit for ChaChaCore<R> {
let tokens = ();
}
}
-
Self {
state,
tokens,
- rounds: PhantomData,
+ _pd: PhantomData,
}
}
+
+ /// Get the current block position.
+ #[inline(always)]
+ #[must_use]
+ pub fn get_block_pos(&self) -> V::Counter {
+ V::get_block_pos(&self.state[12..])
+ }
+
+ /// Set the block position.
+ #[inline(always)]
+ pub fn set_block_pos(&mut self, pos: V::Counter) {
+ V::set_block_pos(&mut self.state[12..], pos);
+ }
}
-impl<R: Unsigned> StreamCipherCore for ChaChaCore<R> {
+impl<R: Rounds, V: Variant> fmt::Debug for ChaChaCore<R, V> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "ChaChaCore<R: {}, V: {}-bit)> {{ ... }}",
+ R::COUNT,
+ size_of::<V::Counter>() * 8
+ )
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherSeekCore for ChaChaCore<R, V> {
+ type Counter = V::Counter;
+
+ #[inline(always)]
+ fn get_block_pos(&self) -> Self::Counter {
+ self.get_block_pos()
+ }
+
+ #[inline(always)]
+ fn set_block_pos(&mut self, pos: Self::Counter) {
+ self.set_block_pos(pos);
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherCore for ChaChaCore<R, V> {
#[inline(always)]
fn remaining_blocks(&self) -> Option<usize> {
- let rem = u32::MAX - self.get_block_pos();
- rem.try_into().ok()
+ V::remaining_blocks(self.get_block_pos())
}
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
+ fn process_with_backend(
+ &mut self,
+ f: impl cipher::StreamCipherClosure<BlockSize = Self::BlockSize>,
+ ) {
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
f.call(&mut backends::soft::Backend(self));
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ unsafe {
+ backends::avx512::inner::<R, _, V>(&mut self.state, f);
+ }
+ } else if #[cfg(chacha20_backend = "avx2")] {
unsafe {
- backends::avx2::inner::<R, _>(&mut self.state, f);
+ backends::avx2::inner::<R, _, V>(&mut self.state, f);
}
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
unsafe {
- backends::sse2::inner::<R, _>(&mut self.state, f);
+ backends::sse2::inner::<R, _, V>(&mut self.state, f);
}
} else {
+ #[cfg(chacha20_avx512)]
+ let (avx512_token, avx2_token, sse2_token) = self.tokens;
+ #[cfg(not(chacha20_avx512))]
let (avx2_token, sse2_token) = self.tokens;
+
+ #[cfg(chacha20_avx512)]
+ if avx512_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
+ unsafe {
+ backends::avx512::inner::<R, _, V>(&mut self.state, f);
+ }
+ return;
+ }
if avx2_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
unsafe {
- backends::avx2::inner::<R, _>(&mut self.state, f);
+ backends::avx2::inner::<R, _, V>(&mut self.state, f);
}
} else if sse2_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
unsafe {
- backends::sse2::inner::<R, _>(&mut self.state, f);
+ backends::sse2::inner::<R, _, V>(&mut self.state, f);
}
} else {
f.call(&mut backends::soft::Backend(self));
}
}
}
- } else if #[cfg(all(chacha20_force_neon, target_arch = "aarch64", target_feature = "neon"))] {
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- backends::neon::inner::<R, _>(&mut self.state, f);
+ backends::neon::inner::<R, _, V>(&mut self.state, f);
}
} else {
f.call(&mut backends::soft::Backend(self));
@@ -290,28 +298,46 @@ impl<R: Unsigned> StreamCipherCore for ChaChaCore<R> {
}
}
-impl<R: Unsigned> StreamCipherSeekCore for ChaChaCore<R> {
- type Counter = u32;
-
- #[inline(always)]
- fn get_block_pos(&self) -> u32 {
- self.state[12]
- }
-
- #[inline(always)]
- fn set_block_pos(&mut self, pos: u32) {
- self.state[12] = pos;
- }
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for ChaChaCore<R, V> {
+ type BlockSize = U64;
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> Drop for ChaChaCore<R> {
+impl<R: Rounds, V: Variant> Drop for ChaChaCore<R, V> {
fn drop(&mut self) {
self.state.zeroize();
}
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> ZeroizeOnDrop for ChaChaCore<R> {}
+impl<R: Rounds, V: Variant> ZeroizeOnDrop for ChaChaCore<R, V> {}
+
+/// The ChaCha20 quarter round function
+///
+/// We located this function in the root of the crate as we want it to be available
+/// for the soft backend and for xchacha.
+#[allow(dead_code)]
+pub(crate) fn quarter_round(
+ a: usize,
+ b: usize,
+ c: usize,
+ d: usize,
+ state: &mut [u32; STATE_WORDS],
+) {
+ state[a] = state[a].wrapping_add(state[b]);
+ state[d] ^= state[a];
+ state[d] = state[d].rotate_left(16);
+
+ state[c] = state[c].wrapping_add(state[d]);
+ state[b] ^= state[c];
+ state[b] = state[b].rotate_left(12);
+
+ state[a] = state[a].wrapping_add(state[b]);
+ state[d] ^= state[a];
+ state[d] = state[d].rotate_left(8);
+
+ state[c] = state[c].wrapping_add(state[d]);
+ state[b] ^= state[c];
+ state[b] = state[b].rotate_left(7);
+}
### external/vendor/chacha20/src/rng.rs
@@ -0,0 +1,344 @@
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use core::fmt;
+
+use rand_core::{
+ Infallible, SeedableRng, TryCryptoRng, TryRng,
+ block::{BlockRng, Generator},
+};
+
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
+
+use crate::{
+ ChaChaCore, R8, R12, R20, Rounds, backends,
+ variants::{Legacy, Variant},
+};
+
+use cfg_if::cfg_if;
+
+/// Seed value used to initialize ChaCha-based RNGs.
+pub type Seed = [u8; 32];
+
+/// Serialized RNG state.
+pub type SerializedRngState = [u8; 49];
+
+/// Number of 32-bit words per ChaCha block (fixed by algorithm definition).
+pub(crate) const BLOCK_WORDS: u8 = 16;
+
+/// Number of blocks generated by RNG core.
+const BUF_BLOCKS: u8 = 4;
+/// Buffer size in words used by buffered RNG.
+const BUFFER_SIZE: usize = (BLOCK_WORDS * BUF_BLOCKS) as usize;
+
+impl<R: Rounds, V: Variant> SeedableRng for ChaChaCore<R, V> {
+ type Seed = Seed;
+
+ #[inline]
+ fn from_seed(seed: Self::Seed) -> Self {
+ ChaChaCore::new_internal(&seed, &[0u8; 8])
+ }
+}
+
+impl<R: Rounds, V: Variant> Generator for ChaChaCore<R, V> {
+ type Output = [u32; BUFFER_SIZE];
+
+ /// Generates 4 blocks in parallel with avx2 & neon, but merely fills
+ /// 4 blocks with sse2 & soft
+ fn generate(&mut self, buffer: &mut [u32; BUFFER_SIZE]) {
+ cfg_if! {
+ if #[cfg(chacha20_backend = "soft")] {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ } else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
+ cfg_if! {
+ // AVX-512 doesn't support RNG, so use AVX-2 instead
+ if #[cfg(any(chacha20_backend = "avx2", chacha20_backend = "avx512"))] {
+ unsafe {
+ backends::avx2::rng_inner::<R, V>(self, buffer);
+ }
+ } else if #[cfg(chacha20_backend = "sse2")] {
+ unsafe {
+ backends::sse2::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ #[cfg(chacha20_avx512)]
+ let (_avx512_token, avx2_token, sse2_token) = self.tokens;
+ #[cfg(not(chacha20_avx512))]
+ let (avx2_token, sse2_token) = self.tokens;
+
+ if avx2_token.get() {
+ unsafe {
+ backends::avx2::rng_inner::<R, V>(self, buffer);
+ }
+ } else if sse2_token.get() {
+ unsafe {
+ backends::sse2::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ }
+ }
+ }
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
+ unsafe {
+ backends::neon::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ }
+ }
+ }
+
+ // `Drop` impl of `BlockRng` calls this method and passes reference to
+ // its internal buffer in `output`. So we zeroize its contents here.
+ #[cfg(feature = "zeroize")]
+ fn drop(&mut self, output: &mut Self::Output) {
+ output.zeroize();
+ }
+}
+
+macro_rules! impl_chacha_rng {
+ ($Rng:ident, $rounds:ident) => {
+ /// A cryptographically secure random number generator that uses the ChaCha stream cipher.
+ ///
+ /// See the [crate docs][crate] for more information about the underlying stream cipher.
+ ///
+ /// This RNG implementation uses a 64-bit counter and 64-bit stream identifier (a.k.a nonce).
+ /// A 64-bit counter over 64-byte (16 word) blocks allows 1 ZiB of output before cycling,
+ /// and the stream identifier allows 2<sup>64</sup> unique streams of output per seed.
+ /// Both counter and stream are initialized to zero but may be set via the [`set_word_pos`]
+ /// and [`set_stream`] methods.
+ ///
+ /// [`set_word_pos`]: Self::set_word_pos
+ /// [`set_stream`]: Self::set_stream
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ #[doc = concat!("use chacha20::", stringify!($Rng), ";")]
+ /// use rand_core::{SeedableRng, Rng};
+ ///
+ /// let seed = [42u8; 32];
+ #[doc = concat!("let mut rng = ", stringify!($Rng), "::from_seed(seed);")]
+ ///
+ /// let random_u32 = rng.next_u32();
+ /// let random_u64 = rng.next_u64();
+ ///
+ /// let mut random_bytes = [0u8; 3];
+ /// rng.fill_bytes(&mut random_bytes);
+ /// ```
+ ///
+ /// See the [`rand`](https://docs.rs/rand/) crate for more advanced RNG functionality.
+ pub struct $Rng {
+ core: BlockRng<ChaChaCore<$rounds, Legacy>>,
+ }
+
+ impl SeedableRng for $Rng {
+ type Seed = Seed;
+
+ #[inline]
+ fn from_seed(seed: Self::Seed) -> Self {
+ let core = ChaChaCore::new_internal(&seed, &[0u8; 8]);
+ Self {
+ core: BlockRng::new(core),
+ }
+ }
+ }
+
+ impl TryRng for $Rng {
+ type Error = Infallible;
+
+ #[inline]
+ fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
+ Ok(self.core.next_word())
+ }
+ #[inline]
+ fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
+ Ok(self.core.next_u64_from_u32())
+ }
+ #[inline]
+ fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
+ self.core.fill_bytes(dest);
+ Ok(())
+ }
+ }
+
+ impl TryCryptoRng for $Rng {}
+
+ #[cfg(feature = "zeroize")]
+ impl ZeroizeOnDrop for $Rng {}
+
+ // We use custom implementation of `PartialEq` because RNG states
+ // may buffer different parts of the same keystream, while keeping
+ // buffer cursor pointing towards the same keystream point.
+ impl PartialEq<$Rng> for $Rng {
+ fn eq(&self, rhs: &$Rng) -> bool {
+ (self.get_seed() == rhs.get_seed())
+ && (self.get_stream() == rhs.get_stream())
+ && (self.get_word_pos() == rhs.get_word_pos())
+ }
+ }
+
+ impl Eq for $Rng {}
+
+ // Custom Debug implementation that does not expose the internal state
+ impl fmt::Debug for $Rng {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(f, concat!(stringify!($Rng), " {{ ... }}"))
+ }
+ }
+
+ impl $Rng {
+ /// Get the offset from the start of the stream, in 32-bit words.
+ ///
+ /// Since the generated blocks are 16 words (2<sup>4</sup>) long and the
+ /// counter is 64-bits, the offset is a 68-bit number. Sub-word offsets are
+ /// not supported, hence the result can simply be multiplied by 4 to get a
+ /// byte-offset.
+ #[inline]
+ #[must_use]
+ pub fn get_word_pos(&self) -> u128 {
+ let mut block_counter = (u64::from(self.core.core.state[13]) << 32)
+ | u64::from(self.core.core.state[12]);
+ if self.core.word_offset() != 0 {
+ block_counter = block_counter.wrapping_sub(u64::from(BUF_BLOCKS));
+ }
+ let word_pos = u128::from(block_counter) * u128::from(BLOCK_WORDS)
+ + self.core.word_offset() as u128;
+ // eliminate bits above the 68th bit
+ word_pos & ((1 << 68) - 1)
+ }
+
+ /// Set the offset from the start of the stream, in 32-bit words.
+ ///
+ /// **This value will be erased when calling `set_stream()`,
+ /// so call `set_stream()` before calling `set_word_pos()`**
+ /// if you intend on using both of them together.
+ ///
+ /// As with `get_word_pos`, we use a 68-bit number. Since the generator
+ /// simply cycles at the end of its period (1 ZiB), we ignore the upper
+ /// 60 bits.
+ #[inline]
+ pub fn set_word_pos(&mut self, word_offset: u128) {
+ let index = (word_offset % u128::from(BLOCK_WORDS)) as usize;
+ let counter = word_offset / u128::from(BLOCK_WORDS);
+ //self.set_block_pos(counter as u64);
+ self.core.core.state[12] = counter as u32;
+ self.core.core.state[13] = (counter >> 32) as u32;
+ self.core.reset_and_skip(index);
+ }
+
+ /// Sets the block pos and resets the RNG's index.
+ ///
+ /// **This value will be erased when calling `set_stream()`,
+ /// so call `set_stream()` before calling `set_block_pos()`**
+ /// if you intend on using both of them together.
+ ///
+ /// The word pos will be equal to `block_pos * 16 words per block`.
+ #[inline]
+ #[allow(unused)]
+ pub fn set_block_pos(&mut self, block_pos: u64) {
+ self.core.reset_and_skip(0);
+ self.core.core.set_block_pos(block_pos);
+ }
+
+ /// Get the block pos.
+ #[inline]
+ #[allow(unused)]
+ #[must_use]
+ pub fn get_block_pos(&self) -> u64 {
+ let counter = self.core.core.get_block_pos();
+ let offset = self.core.word_offset();
+ if offset != 0 {
+ counter - u64::from(BUF_BLOCKS) + offset as u64 / u64::from(BLOCK_WORDS)
+ } else {
+ counter
+ }
+ }
+
+ /// Set the stream ID and reset the `word_pos` to 0.
+ #[inline]
+ pub fn set_stream(&mut self, stream: u64) {
+ self.core.core.state[14] = stream as u32;
+ self.core.core.state[15] = (stream >> 32) as u32;
+ self.set_block_pos(0);
+ }
+
+ /// Get the stream number (nonce).
+ #[inline]
+ #[must_use]
+ pub fn get_stream(&self) -> u64 {
+ let mut result = [0u8; 8];
+ result[..4].copy_from_slice(&self.core.core.state[14].to_le_bytes());
+ result[4..].copy_from_slice(&self.core.core.state[15].to_le_bytes());
+ u64::from_le_bytes(result)
+ }
+
+ /// Get the RNG seed.
+ #[inline]
+ #[must_use]
+ pub fn get_seed(&self) -> [u8; 32] {
+ let seed = &self.core.core.state[4..12];
+ let mut result = [0u8; 32];
+ for (src, dst) in seed.iter().zip(result.chunks_exact_mut(4)) {
+ dst.copy_from_slice(&src.to_le_bytes())
+ }
+ result
+ }
+
+ /// Serialize RNG state.
+ ///
+ /// # Warning
+ /// Leaking serialized RNG state to an attacker defeats security properties
+ /// provided by the RNG.
+ #[inline]
+ pub fn serialize_state(&self) -> SerializedRngState {
+ let seed = self.get_seed();
+ let stream = self.get_stream().to_le_bytes();
+ let word_pos = self.get_word_pos().to_le_bytes();
+
+ let mut res = [0u8; 49];
+ let (seed_dst, res_rem) = res.split_at_mut(32);
+ let (stream_dst, word_pos_dst) = res_rem.split_at_mut(8);
+
+ seed_dst.copy_from_slice(&seed);
+ stream_dst.copy_from_slice(&stream);
+ word_pos_dst.copy_from_slice(&word_pos[..9]);
+
+ debug_assert_eq!(&word_pos[9..], &[0u8; 7]);
+
+ res
+ }
+
+ /// Deserialize RNG state.
+ #[inline]
+ pub fn deserialize_state(state: &SerializedRngState) -> Self {
+ let (seed, state_rem) = state.split_at(32);
+ let (stream, word_pos_raw) = state_rem.split_at(8);
+
+ let seed: &[u8; 32] = seed.try_into().expect("seed.len() is equal to 32");
+ let stream: &[u8; 8] = stream.try_into().expect("stream.len() is equal to 8");
+
+ // Note that we use only 68 bits from `word_pos_raw`, i.e. 4 remaining bits
+ // get ignored and should be equal to zero in practice.
+ let mut word_pos_buf = [0u8; 16];
+ word_pos_buf[..9].copy_from_slice(word_pos_raw);
+ let word_pos = u128::from_le_bytes(word_pos_buf);
+
+ let core = ChaChaCore::new_internal(seed, stream);
+ let mut res = Self {
+ core: BlockRng::new(core),
+ };
+
+ res.set_word_pos(word_pos);
+ res
+ }
+ }
+ };
+}
+
+impl_chacha_rng!(ChaCha8Rng, R8);
+impl_chacha_rng!(ChaCha12Rng, R12);
+impl_chacha_rng!(ChaCha20Rng, R20);
### external/vendor/chacha20/src/variants.rs
@@ -0,0 +1,84 @@
+//! ChaCha variant-specific configurations.
+
+mod sealed {
+ pub trait Sealed {}
+}
+
+/// A trait that distinguishes some ChaCha variants. Contains configurations
+/// for "Legacy" DJB variant and the IETF variant.
+pub trait Variant: sealed::Sealed {
+ /// The counter's type.
+ #[cfg(not(feature = "cipher"))]
+ type Counter: Copy;
+
+ /// The counter's type.
+ #[cfg(feature = "cipher")]
+ type Counter: cipher::StreamCipherCounter;
+
+ /// Takes a slice of `state[12..NONCE_INDEX]` to convert it into
+ /// `Self::Counter`.
+ fn get_block_pos(row: &[u32]) -> Self::Counter;
+
+ /// Breaks down the `Self::Counter` type into a u32 array for setting the
+ /// block pos.
+ fn set_block_pos(row: &mut [u32], pos: Self::Counter);
+
+ /// A helper method for calculating the remaining blocks using these types
+ fn remaining_blocks(block_pos: Self::Counter) -> Option<usize>;
+}
+
+/// IETF ChaCha configuration to use a 32-bit counter and 96-bit nonce.
+#[derive(Clone, Copy, Debug)]
+pub enum Ietf {}
+
+impl sealed::Sealed for Ietf {}
+
+impl Variant for Ietf {
+ type Counter = u32;
+
+ #[inline(always)]
+ fn get_block_pos(row: &[u32]) -> u32 {
+ row[0]
+ }
+
+ #[inline(always)]
+ fn set_block_pos(row: &mut [u32], pos: u32) {
+ row[0] = pos;
+ }
+
+ #[inline(always)]
+ fn remaining_blocks(block_pos: u32) -> Option<usize> {
+ let remaining = u32::MAX - block_pos;
+ remaining.try_into().ok()
+ }
+}
+
+/// DJB variant specific features: 64-bit counter and 64-bit nonce.
+#[cfg(any(feature = "legacy", feature = "rng"))]
+#[derive(Clone, Copy, Debug)]
+pub enum Legacy {}
+
+#[cfg(any(feature = "legacy", feature = "rng"))]
+impl sealed::Sealed for Legacy {}
+
+#[cfg(any(feature = "legacy", feature = "rng"))]
+impl Variant for Legacy {
+ type Counter = u64;
+
+ #[inline(always)]
+ fn get_block_pos(row: &[u32]) -> u64 {
+ (u64::from(row[1]) << 32) | u64::from(row[0])
+ }
+
+ #[inline(always)]
+ fn set_block_pos(row: &mut [u32], pos: u64) {
+ row[0] = (pos & 0xFFFF_FFFF) as u32;
+ row[1] = (pos >> 32) as u32;
+ }
+
+ #[inline(always)]
+ fn remaining_blocks(block_pos: u64) -> Option<usize> {
+ let remaining = u64::MAX - block_pos;
+ remaining.try_into().ok()
+ }
+}
### external/vendor/chacha20/src/xchacha.rs
@@ -1,18 +1,20 @@
//! XChaCha is an extended nonce variant of ChaCha
-use super::{ChaChaCore, Key, Nonce, CONSTANTS, STATE_WORDS};
+use crate::{
+ CONSTANTS, ChaChaCore, Key, R8, R12, R20, Rounds, STATE_WORDS, quarter_round, variants::Ietf,
+};
use cipher::{
- consts::{U10, U16, U24, U32, U4, U6, U64},
- generic_array::{typenum::Unsigned, GenericArray},
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
+ BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherClosure, StreamCipherCore,
+ StreamCipherCoreWrapper, StreamCipherSeekCore,
+ array::Array,
+ consts::{U4, U16, U24, U32, U64},
};
#[cfg(feature = "zeroize")]
-use cipher::zeroize::ZeroizeOnDrop;
+use zeroize::ZeroizeOnDrop;
/// Nonce type used by XChaCha variants.
-pub type XNonce = GenericArray<u8, U24>;
+pub type XNonce = Array<u8, U24>;
/// XChaCha is a ChaCha20 variant with an extended 192-bit (24-byte) nonce.
///
@@ -28,50 +30,55 @@ pub type XNonce = GenericArray<u8, U24>;
/// several interoperable libraries and protocols (e.g. libsodium, WireGuard)
/// and is documented in an (expired) IETF draft:
///
-/// <https://tools.ietf.org/html/draft-arciszewski-xchacha-03>
-pub type XChaCha20 = StreamCipherCoreWrapper<XChaChaCore<U10>>;
+/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha>
+pub type XChaCha20 = StreamCipherCoreWrapper<XChaChaCore<R20>>;
/// XChaCha12 stream cipher (reduced-round variant of [`XChaCha20`] with 12 rounds)
-pub type XChaCha12 = StreamCipherCoreWrapper<XChaChaCore<U6>>;
+pub type XChaCha12 = StreamCipherCoreWrapper<XChaChaCore<R12>>;
/// XChaCha8 stream cipher (reduced-round variant of [`XChaCha20`] with 8 rounds)
-pub type XChaCha8 = StreamCipherCoreWrapper<XChaChaCore<U4>>;
+pub type XChaCha8 = StreamCipherCoreWrapper<XChaChaCore<R8>>;
/// The XChaCha core function.
-pub struct XChaChaCore<R: Unsigned>(ChaChaCore<R>);
+#[derive(Debug)]
+pub struct XChaChaCore<R: Rounds>(ChaChaCore<R, Ietf>);
-impl<R: Unsigned> KeySizeUser for XChaChaCore<R> {
+impl<R: Rounds> KeySizeUser for XChaChaCore<R> {
type KeySize = U32;
}
-impl<R: Unsigned> IvSizeUser for XChaChaCore<R> {
+impl<R: Rounds> IvSizeUser for XChaChaCore<R> {
type IvSize = U24;
}
-impl<R: Unsigned> BlockSizeUser for XChaChaCore<R> {
+impl<R: Rounds> BlockSizeUser for XChaChaCore<R> {
type BlockSize = U64;
}
-impl<R: Unsigned> KeyIvInit for XChaChaCore<R> {
+impl<R: Rounds> KeyIvInit for XChaChaCore<R> {
fn new(key: &Key, iv: &XNonce) -> Self {
- let subkey = hchacha::<R>(key, iv[..16].as_ref().into());
- let mut padded_iv = Nonce::default();
- padded_iv[4..].copy_from_slice(&iv[16..]);
- XChaChaCore(ChaChaCore::new(&subkey, &padded_iv))
+ #[allow(clippy::unwrap_used)]
+ let subkey = hchacha::<R>(key, iv[..16].as_ref().try_into().unwrap());
+
+ let mut nonce = [0u8; 12];
+ // first 4 bytes are 0, last 8 bytes are last 8 from the iv
+ // according to draft-arciszewski-xchacha-03
+ nonce[4..].copy_from_slice(&iv[16..]);
+ Self(ChaChaCore::<R, Ietf>::new_internal(subkey.as_ref(), &nonce))
}
}
-impl<R: Unsigned> StreamCipherCore for XChaChaCore<R> {
+impl<R: Rounds> StreamCipherCore for XChaChaCore<R> {
#[inline(always)]
fn remaining_blocks(&self) -> Option<usize> {
self.0.remaining_blocks()
}
#[inline(always)]
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
+ fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = Self::BlockSize>) {
self.0.process_with_backend(f);
}
}
-impl<R: Unsigned> StreamCipherSeekCore for XChaChaCore<R> {
+impl<R: Rounds> StreamCipherSeekCore for XChaChaCore<R> {
type Counter = u32;
#[inline(always)]
@@ -86,8 +93,7 @@ impl<R: Unsigned> StreamCipherSeekCore for XChaChaCore<R> {
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> ZeroizeOnDrop for XChaChaCore<R> {}
+impl<R: Rounds> ZeroizeOnDrop for XChaChaCore<R> {}
/// The HChaCha function: adapts the ChaCha core function in the same
/// manner that HSalsa adapts the Salsa function.
@@ -103,21 +109,23 @@ impl<R: Unsigned> ZeroizeOnDrop for XChaChaCore<R> {}
/// For more information on HSalsa on which HChaCha is based, see:
///
/// <http://cr.yp.to/snuffle/xsalsa-20110204.pdf>
-pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> GenericArray<u8, U32> {
+#[must_use]
+pub fn hchacha<R: Rounds>(key: &Key, input: &Array<u8, U16>) -> Array<u8, U32> {
let mut state = [0u32; STATE_WORDS];
state[..4].copy_from_slice(&CONSTANTS);
- let key_chunks = key.chunks_exact(4);
+ // TODO(tarcieri): use `[T]::as_chunks` when MSRV 1.88
+ let key_chunks = Array::<u8, U4>::slice_as_chunks(key).0;
for (v, chunk) in state[4..12].iter_mut().zip(key_chunks) {
- *v = u32::from_le_bytes(chunk.try_into().unwrap());
+ *v = u32::from_le_bytes(chunk.0);
}
- let input_chunks = input.chunks_exact(4);
+ let input_chunks = Array::<u8, U4>::slice_as_chunks(input).0;
for (v, chunk) in state[12..16].iter_mut().zip(input_chunks) {
- *v = u32::from_le_bytes(chunk.try_into().unwrap());
+ *v = u32::from_le_bytes(chunk.0);
}
// R rounds consisting of R/2 column rounds and R/2 diagonal rounds
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
// column rounds
quarter_round(0, 4, 8, 12, &mut state);
quarter_round(1, 5, 9, 13, &mut state);
@@ -131,7 +139,7 @@ pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> Generic
quarter_round(3, 4, 9, 14, &mut state);
}
- let mut output = GenericArray::default();
+ let mut output = Array::default();
for (chunk, val) in output[..16].chunks_exact_mut(4).zip(&state[..4]) {
chunk.copy_from_slice(&val.to_le_bytes());
@@ -144,33 +152,13 @@ pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> Generic
output
}
-/// The ChaCha20 quarter round function
-// for simplicity this function is copied from the software backend
-fn quarter_round(a: usize, b: usize, c: usize, d: usize, state: &mut [u32; STATE_WORDS]) {
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(16);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(12);
-
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(8);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(7);
-}
-
#[cfg(test)]
mod hchacha20_tests {
use super::*;
use hex_literal::hex;
/// Test vectors from:
- /// https://tools.ietf.org/id/draft-arciszewski-xchacha-03.html#rfc.section.2.2.1
+ /// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#section-2.2.1
#[test]
fn test_vector() {
const KEY: [u8; 32] = hex!(
@@ -185,10 +173,7 @@ mod hchacha20_tests {
"a0f9e4d58a74a853c12ec41326d3ecdc"
);
- let actual = hchacha::<U10>(
- GenericArray::from_slice(&KEY),
- &GenericArray::from_slice(&INPUT),
- );
+ let actual = hchacha::<R20>(&KEY.into(), &INPUT.into());
assert_eq!(actual.as_slice(), &OUTPUT);
}
}
### external/vendor/chacha20/tests/data/chacha20-legacy.blb
[binary or diff unavailable]
### external/vendor/chacha20/tests/data/chacha20.blb
[binary or diff unavailable]
### external/vendor/chacha20/tests/kats.rs
@@ -1,15 +1,27 @@
//! Tests for ChaCha20 (IETF and "djb" versions) as well as XChaCha20
-use chacha20::{ChaCha20, ChaCha20Legacy, XChaCha20};
+#[cfg(feature = "cipher")]
+use chacha20::ChaCha20;
+
+#[cfg(feature = "legacy")]
+use chacha20::ChaCha20Legacy;
+
+#[cfg(feature = "xchacha")]
+use chacha20::XChaCha20;
// IETF version of ChaCha20 (96-bit nonce)
+#[cfg(feature = "cipher")]
cipher::stream_cipher_test!(chacha20_core, "chacha20", ChaCha20);
+#[cfg(feature = "cipher")]
cipher::stream_cipher_seek_test!(chacha20_seek, ChaCha20);
+#[cfg(feature = "xchacha")]
cipher::stream_cipher_seek_test!(xchacha20_seek, XChaCha20);
+#[cfg(feature = "legacy")]
cipher::stream_cipher_seek_test!(chacha20legacy_seek, ChaCha20Legacy);
+#[cfg(feature = "cipher")]
mod chacha20test {
- use chacha20::{ChaCha20, Key, Nonce};
- use cipher::{KeyIvInit, StreamCipher};
+ use chacha20::{ChaCha20, KeyIvInit};
+ use cipher::StreamCipher;
use hex_literal::hex;
//
@@ -59,7 +71,7 @@ mod chacha20test {
#[test]
fn chacha20_keystream() {
- let mut cipher = ChaCha20::new(&Key::from(KEY), &Nonce::from(IV));
+ let mut cipher = ChaCha20::new(&KEY.into(), &IV.into());
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -72,8 +84,8 @@ mod chacha20test {
#[test]
fn chacha20_encryption() {
- let mut cipher = ChaCha20::new(&Key::from(KEY), &Nonce::from(IV));
- let mut buf = PLAINTEXT.clone();
+ let mut cipher = ChaCha20::new(&KEY.into(), &IV.into());
+ let mut buf = PLAINTEXT;
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -85,6 +97,7 @@ mod chacha20test {
}
#[rustfmt::skip]
+#[cfg(feature = "xchacha")]
mod xchacha20 {
use chacha20::{Key, XChaCha20, XNonce};
use cipher::{KeyIvInit, StreamCipher};
@@ -94,7 +107,7 @@ mod xchacha20 {
//
// XChaCha20 test vectors from:
- // <https://tools.ietf.org/id/draft-arciszewski-xchacha-03.html#rfc.appendix.A.3.2>
+ // <https://datatracker.ietf.org/doc/html/draft-arciszewski-xchacha-03#appendix-A.2>
//
const KEY: [u8; 32] = hex!("
@@ -160,7 +173,7 @@ mod xchacha20 {
#[test]
fn xchacha20_encryption() {
let mut cipher = XChaCha20::new(&Key::from(KEY), &XNonce::from(IV));
- let mut buf = PLAINTEXT.clone();
+ let mut buf = PLAINTEXT;
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -175,11 +188,11 @@ mod xchacha20 {
#[cfg(feature = "legacy")]
#[rustfmt::skip]
mod legacy {
- use chacha20::{ChaCha20Legacy, Key, LegacyNonce};
- use cipher::{NewCipher, StreamCipher, StreamCipherSeek};
+ use chacha20::{ChaCha20Legacy, LegacyNonce};
+ use cipher::{StreamCipher, StreamCipherSeek, KeyIvInit};
use hex_literal::hex;
- cipher::stream_cipher_test!(chacha20_legacy_core, ChaCha20Legacy, "chacha20-legacy");
+ cipher::stream_cipher_test!(chacha20_legacy_core, "chacha20-legacy", ChaCha20Legacy);
cipher::stream_cipher_seek_test!(chacha20_legacy_seek, ChaCha20Legacy);
const KEY_LONG: [u8; 32] = hex!("
@@ -206,15 +219,15 @@ mod legacy {
for middle in idx..256 {
for last in middle..256 {
let mut cipher =
- ChaCha20Legacy::new(&Key::from(KEY_LONG), &LegacyNonce::from(IV_LONG));
+ ChaCha20Legacy::new(&KEY_LONG.into(), &LegacyNonce::from(IV_LONG));
let mut buf = [0; 256];
cipher.seek(idx as u64);
cipher.apply_keystream(&mut buf[idx..middle]);
cipher.apply_keystream(&mut buf[middle..last]);
for k in idx..last {
- assert_eq!(buf[k], EXPECTED_LONG[k])
+ assert_eq!(buf[k], EXPECTED_LONG[k]);
}
}
}
### external/vendor/chacha20/tests/rng.rs
@@ -0,0 +1,552 @@
+//! Random number generator tests.
+
+#![cfg(feature = "rng")]
+
+use chacha20::{
+ ChaCha8Rng, ChaCha12Rng, ChaCha20Rng, SerializedRngState,
+ rand_core::{Rng, SeedableRng},
+};
+use hex_literal::hex;
+
+const KEY: [u8; 32] = hex!("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20");
+const STREAM: u64 = 0xF0F1F2F3_F4F5F6F7;
+const BLOCK_WORDS: u8 = 16;
+
+#[test]
+fn test_rng_output() {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ let mut bytes = [0u8; 13];
+
+ rng.fill_bytes(&mut bytes);
+ let expected = hex!("B1697E9FC6461E1983D131CF69");
+ assert_eq!(bytes, expected);
+
+ rng.fill_bytes(&mut bytes);
+ let expected = hex!("A7A3FC134F149880E8BB2B5D23");
+ assert_eq!(bytes, expected);
+}
+
+#[test]
+fn test_chacha_true_values_a() {
+ // Test vectors 1 and 2 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8,
+ 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815,
+ 0x69b687c3, 0x8665eeb2,
+ ];
+ assert_eq!(results, expected);
+
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612,
+ 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51,
+ 0x1f0ae1ac, 0x6f4d794b,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_values_b() {
+ // Test vector 3 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = hex!("0000000000000000000000000000000000000000000000000000000000000001");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ // Skip block 0
+ for _ in 0..16 {
+ rng.next_u32();
+ }
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8,
+ 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8,
+ 0xebdd4aa6, 0xa0136c00,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_values_c() {
+ // Test vector 4 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = hex!("00FF000000000000000000000000000000000000000000000000000000000000");
+ let expected = [
+ 0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1,
+ 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5,
+ 0x87f47473, 0x96f0992e,
+ ];
+ let expected_end = 3 * 16;
+ let mut results = [0u32; 16];
+
+ // Test block 2 by skipping block 0 and 1
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ for _ in 0..32 {
+ rng1.next_u32();
+ }
+ for i in results.iter_mut() {
+ *i = rng1.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng1.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_word_pos`
+ let mut rng2 = ChaCha20Rng::from_seed(seed);
+ rng2.set_word_pos(2 * 16);
+ for i in results.iter_mut() {
+ *i = rng2.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng2.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_block_pos` and u32
+ let mut rng3 = ChaCha20Rng::from_seed(seed);
+ rng3.set_block_pos(2);
+ results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng3.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng3.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_block_pos` and [u8; 8]
+ let mut rng4 = ChaCha20Rng::from_seed(seed);
+ rng4.set_block_pos(2);
+ let mut buf = [0u8; 8];
+ for chunk in expected.chunks_exact(2) {
+ rng4.fill_bytes(&mut buf);
+ assert_eq!(buf[..4], chunk[0].to_le_bytes());
+ assert_eq!(buf[4..], chunk[1].to_le_bytes());
+ }
+ assert_eq!(rng4.get_word_pos(), expected_end);
+
+ // Test skipping behaviour with other types
+ let mut buf = [0u8; 32];
+ rng2.fill_bytes(&mut buf[..]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 8);
+ rng2.fill_bytes(&mut buf[0..25]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 15);
+ rng2.next_u64();
+ assert_eq!(rng2.get_word_pos(), expected_end + 17);
+ rng2.next_u32();
+ rng2.next_u64();
+ assert_eq!(rng2.get_word_pos(), expected_end + 20);
+ rng2.fill_bytes(&mut buf[0..1]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 21);
+}
+
+#[test]
+fn test_chacha_multiple_blocks() {
+ let seed = hex!("0000000001000000020000000300000004000000050000000600000007000000");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ // Store the 17*i-th 32-bit word,
+ // i.e., the i-th word of the i-th 16-word block
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ for _ in 0..16 {
+ rng.next_u32();
+ }
+ }
+ let expected = [
+ 0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186,
+ 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc,
+ 0x5f1c86d9, 0xc1f8e7f4,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_bytes() {
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+ let mut results = [0u8; 32];
+ rng.fill_bytes(&mut results);
+ let expected = hex!("76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7");
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_construction() {
+ let seed = hex!("0000000000000000010000000000000002000000000000000300000000000000");
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ assert_eq!(rng1.next_u32(), 137206642);
+
+ assert_eq!(rng1.get_seed(), seed);
+
+ let mut rng2 = ChaCha20Rng::from_rng(&mut rng1);
+ assert_eq!(rng2.next_u32(), 1325750369);
+}
+
+#[test]
+fn test_chacha_nonce() {
+ use hex_literal::hex;
+ // Test vector 5 from
+ // https://www.rfc-editor.org/rfc/rfc8439#section-2.3.2
+ let seed = hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ rng.set_stream(0x000000004a000000);
+ rng.set_block_pos(u64::from_le_bytes(hex!("0000000000000009")));
+
+ // The test vectors omit the first 64-bytes of the keystream
+ let mut discard_first_64 = [0u8; 64];
+ rng.fill_bytes(&mut discard_first_64);
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xe4e7f110, 0x15593bd1, 0x1fdd0f50, 0xc47120a3, 0xc7f4d1c7, 0x0368c033, 0x9aaa2204,
+ 0x4e6cd4c3, 0x466482d2, 0x09aa9f07, 0x05d7c214, 0xa2028bd9, 0xd19c12b5, 0xb94e16de,
+ 0xe883d0cb, 0x4e3c50a2,
+ ];
+
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_nonce_2() {
+ // Test vector 5 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ // Although we do not support setting a nonce, we try it here anyway so
+ // we can use this test vector.
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+ // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2
+ rng.set_stream(2u64 << (24 + 32));
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72,
+ 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8,
+ 0x398a19fa, 0x6ded1b53,
+ ];
+ assert_eq!(results, expected);
+}
+
+/// Test vector 9 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
+#[test]
+fn counter_wrap_1() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+ let block_pos = 18446744073709551615;
+ assert_eq!(block_pos, u64::MAX);
+ rng.set_block_pos(block_pos);
+
+ let mut output = [0u8; 64 * 3];
+ rng.fill_bytes(&mut output);
+ let expected = hex!(
+ "d7918cd8620cf832532652c04c01a553092cfb32e7b3f2f5467ae9674a2e9eec17368e"
+ "c8027a357c0c51e6ea747121fec45284be0f099d2b3328845607b1768976b8e0ada0f1"
+ "3d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d77"
+ "24e03fb8d84a376a43b8f41518a11cc387b669b2ee65869f07e7be5551387a98ba977c"
+ "732d080dcb0f29a048e3656912c6533e32ee7aed29b721769ce64e43d57133b074d839"
+ "d531ed1f28510afb45ace10a1f4b794d6f"
+ );
+ assert_eq!(expected, output);
+}
+
+/// Counts how many bytes were incorrect, and returns:
+///
+/// (`index_of_first_incorrect_word`, `num_incorrect_bytes`)
+fn count_incorrect_bytes(expected: &[u8], output: &[u8]) -> (Option<usize>, u32) {
+ assert_eq!(expected.len(), output.len());
+ let mut num_incorrect_bytes = 0;
+ let mut index_of_first_incorrect_word = None;
+ expected
+ .iter()
+ .enumerate()
+ .zip(output.iter())
+ .for_each(|((i, a), b)| {
+ if a.ne(b) {
+ if index_of_first_incorrect_word.is_none() {
+ index_of_first_incorrect_word = Some(i / 4);
+ }
+ num_incorrect_bytes += 1;
+ }
+ });
+ (index_of_first_incorrect_word, num_incorrect_bytes)
+}
+
+/// Test vector 8 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
+#[test]
+fn counter_overflow_and_diagnostics() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+ let block_pos = 4294967295;
+ assert_eq!(block_pos, u64::from(u32::MAX));
+ rng.set_block_pos(4294967295);
+
+ let mut output = [0u8; 64 * 4];
+ rng.fill_bytes(&mut output[..64 * 3]);
+ let block_before_overflow = hex!(
+ "ace4cd09e294d1912d4ad205d06f95d9c2f2bfcf453e8753f128765b62215f4d92c74f"
+ "2f626c6a640c0b1284d839ec81f1696281dafc3e684593937023b58b1d"
+ );
+ let first_block_after_overflow = hex!(
+ "3db41d3aa0d329285de6f225e6e24bd59c9a17006943d5c9b680e3873bdc683a581946"
+ "9899989690c281cd17c96159af0682b5b903468a61f50228cf09622b5a"
+ );
+ let second_block_after_overflow = hex!(
+ "46f0f6efee15c8f1b198cb49d92b990867905159440cc723916dc0012826981039ce17"
+ "66aa2542b05db3bd809ab142489d5dbfe1273e7399637b4b3213768aaa"
+ );
+ assert!(
+ output[..64].eq(&block_before_overflow),
+ "The first parblock was incorrect before overflow, indicating that ChaCha was not implemented correctly for this backend. Check the rounds() fn or the functions that it calls"
+ );
+
+ rng.set_block_pos(u64::from(u32::MAX) - 1);
+ let mut skipped_blocks = [0u8; 64 * 3];
+ rng.fill_bytes(&mut skipped_blocks);
+ rng.fill_bytes(&mut output[64 * 3..]);
+
+ output.chunks_exact(64).enumerate().skip(1).zip(&[first_block_after_overflow, second_block_after_overflow, second_block_after_overflow]).for_each(|((i, a), b)| {
+ let (index_of_first_incorrect_word, num_incorrect_bytes) = count_incorrect_bytes(a, b);
+ let msg = if num_incorrect_bytes == 0 {
+ "The block was correct and this will not be shown"
+ } else if num_incorrect_bytes > 32 {
+ "Most of the block was incorrect, indicating an issue with the counter using 32-bit addition towards the beginning of fn rounds()"
+ } else if num_incorrect_bytes <= 8 && matches!(index_of_first_incorrect_word, Some(12 | 13)) {
+ "When the state was added to the results/res buffer at the end of fn rounds, the counter was probably incremented in 32-bit fashion for this parblock"
+ } else {
+ // this is probably unreachable in the event of a failed assertion, but it depends on the seed
+ "Some of the block was incorrect"
+ };
+ assert!(a.eq(b), "PARBLOCK #{} uses incorrect counter addition\nDiagnostic = {}\nnum_incorrect_bytes = {}\nindex_of_first_incorrect_word = {:?}", i + 1, msg, num_incorrect_bytes, index_of_first_incorrect_word);
+ });
+}
+
+#[test]
+fn test_wrapping_add() {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ // test counter wrapping-add
+ rng.set_word_pos((1 << 68) - 65);
+ let mut output = [3u8; 1280];
+ rng.fill_bytes(&mut output);
+
+ assert_ne!(output, [0u8; 1280]);
+
+ assert!(rng.get_word_pos() < 2000);
+ assert!(rng.get_word_pos() != 0);
+}
+
+#[test]
+fn test_chacha_clone_streams() {
+ let seed = [
+ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0,
+ 0, 0,
+ ];
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ let mut rng2 = ChaCha20Rng::from_seed(seed);
+ for _ in 0..16 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+
+ rng1.set_stream(51);
+ assert_eq!(rng1.get_stream(), 51);
+ assert_eq!(rng2.get_stream(), 0);
+ let mut fill_1 = [0u8; 7];
+ rng1.fill_bytes(&mut fill_1);
+ let mut fill_2 = [0u8; 7];
+ rng2.fill_bytes(&mut fill_2);
+ assert_ne!(fill_1, fill_2);
+ for _ in 0..7 {
+ assert!(rng1.next_u64() != rng2.next_u64());
+ }
+ rng2.set_stream(51); // switch part way through block
+ for _ in 7..16 {
+ assert_ne!(rng1.next_u64(), rng2.next_u64());
+ }
+ rng1.set_stream(51);
+ rng2.set_stream(51);
+ for _ in 0..16 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+}
+
+#[test]
+fn test_chacha_word_pos_wrap_exact() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ // refilling the buffer in set_word_pos will wrap the block counter to 0
+ let last_block = (1 << 68) - u128::from(4 * BLOCK_WORDS);
+ rng.set_word_pos(last_block);
+ assert_eq!(rng.get_word_pos(), last_block);
+}
+
+#[test]
+fn test_chacha_word_pos_wrap_excess() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ // refilling the buffer in set_word_pos will wrap the block counter past 0
+ let last_block = (1 << 68) - u128::from(BLOCK_WORDS);
+ rng.set_word_pos(last_block);
+ assert_eq!(rng.get_word_pos(), last_block);
+}
+
+#[test]
+fn test_chacha_word_pos_zero() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ assert_eq!(rng.get_word_pos(), 0);
+ rng.set_word_pos(0);
+ assert_eq!(rng.get_word_pos(), 0);
+}
+
+#[test]
+#[allow(trivial_casts)]
+fn test_trait_objects() {
+ use rand_core::CryptoRng;
+
+ let seed = Default::default();
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ let rng2 = &mut ChaCha20Rng::from_seed(seed) as &mut dyn CryptoRng;
+ for _ in 0..1000 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+}
+
+/// If this test fails, the backend may not be
+/// performing 64-bit addition.
+#[test]
+fn counter_wrapping_64_bit_counter() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+
+ // get first four blocks and word pos
+ let mut first_blocks = [0u8; 64 * 4];
+ rng.fill_bytes(&mut first_blocks);
+ let first_blocks_end_word_pos = rng.get_word_pos();
+ let first_blocks_end_block_counter = rng.get_block_pos();
+
+ // get first four blocks after wrapping
+ rng.set_block_pos(u64::MAX);
+ let mut result = [0u8; 64 * 5];
+ rng.fill_bytes(&mut result);
+ assert_eq!(first_blocks_end_word_pos, rng.get_word_pos());
+ assert_eq!(first_blocks_end_block_counter, rng.get_block_pos());
+
+ if first_blocks[0..64 * 4].ne(&result[64..]) {
+ for (i, (a, b)) in first_blocks.iter().zip(result.iter().skip(64)).enumerate() {
+ assert!(!a.ne(b), "i = {}\na = {}\nb = {}", i, a, b);
+ }
+ }
+ assert_eq!(&first_blocks[0..64 * 4], &result[64..]);
+}
+
+/// If this test fails, the backend may be doing 32-bit addition.
+#[test]
+fn counter_not_wrapping_at_32_bits() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+
+ // get first four blocks and word pos
+ let mut first_blocks = [0u8; 64 * 4];
+ rng.fill_bytes(&mut first_blocks);
+ let first_blocks_end_word_pos = rng.get_word_pos();
+
+ // get first four blocks after the supposed overflow
+ rng.set_block_pos(u64::from(u32::MAX));
+ let mut result = [0u8; 64 * 5];
+ rng.fill_bytes(&mut result);
+ assert_ne!(first_blocks_end_word_pos, rng.get_word_pos());
+ assert_eq!(
+ rng.get_word_pos(),
+ first_blocks_end_word_pos + (1 << 32) * u128::from(BLOCK_WORDS)
+ );
+ assert_ne!(&first_blocks[0..64 * 4], &result[64..]);
+}
+
+#[test]
+fn test_chacha8rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha8Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha8Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_chacha12rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha12Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha12Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_chacha20rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha20Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_rng_serialized_state_stability() {
+ const EXPECTED: SerializedRngState = hex!(
+ "0102030405060708090A0B0C0D0E0F10"
+ "1112131415161718191A1B1C1D1E1F20"
+ "F7F6F5F4F3F2F1F06400000000000000"
+ "00"
+ );
+ let mut rng = ChaCha8Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+
+ let mut rng = ChaCha12Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+}
### external/vendor/chacha20poly1305/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"45a5fe10d6ba27fda2383958a2b2857fd8b55ce0ce4bea756d6eb065d5b9c6ce","CHANGELOG.md":"8643ef9b1f3920b7a210f0cd74fa93879c68e714cbd2ea45342729484f93e26b","Cargo.toml":"30017fe65d213d042250021badd66f323b8cbadbf95e693ef0c5e250799a0dd0","Cargo.toml.orig":"97a035c2f8eaf86bbcdedb4e74d1769741c3efe3324f5374308766e7aa657cf4","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"3c0dfa33fd2e6976038555b52095699452653b1fcabe113074f14e0848a6b11e","README.md":"cc9139618cff4acc0fb2cd09cefcd1c8a6f425bb4bc83668e07498c3202d9ee1","src/cipher.rs":"70f718a5fd9296f08b16fe42496103033b0150d7cfbb9baca012e2fb51fe8d4a","src/lib.rs":"e454914d6e98c3889cebc92c2eb9a1a43d23f60ca028df0954b55041bfed0d30","tests/data/wycheproof_chacha20poly1305.blb":"8bab32d17e5719eafdfca4adae8d85d5a67c800b7356647cd6b8f73eaa2459cb","tests/data/wycheproof_xchacha20poly1305.blb":"b1fcfcb93bc387431b390957214270e53a77746919c9fdfaf62c311d8836c687","tests/lib.rs":"00219ea42ae569919af93fe30a8c9ce1eb1aca2f26d44e011594850ab0b161c8"},"package":"10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"6c640f7d3c4b878f5efaee675685f09bbca18b84880d4b55f7b676165a81e33f","CHANGELOG.md":"58c36da6ae24394c5e39a2c494e93b88db4a22b6a4641d490bff59f025930064","Cargo.lock":"a66fb2e2410eaa5f94660d30cfad3eb172b43571f2bf4995b036ac237051063d","Cargo.toml":"7ec6e52abfdaf2440a83823ab022b76c366319bc4c610dd51e8b9d0b533b12dc","Cargo.toml.orig":"3b17182be9bcc2b818b6214a4a6fe18d0fa22492d23cdcaab4fc41251c3f9bed","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b8c6939380a400f53e11923d50fcc4dd2fa1ba8339fd9d04cda38a0251b6c9b0","README.md":"3ef6cfd941096d8ce8dda11058eb59cb0252fa08ebc4dfbc7adb44e33c5f60ea","src/cipher.rs":"96c6c14e10f0c81b78b743a2f8f74db2c9325e78119f7ff81a467af2f65958ad","src/lib.rs":"c5735fcb58bdd9c03975a376eb40b4e8698790f3ad72282823cfbdc2aa90335f","tests/data/wycheproof_chacha20poly1305_fail.blb":"2f0905a07a45c1d7955c0777617c98b701664c8f021f40d1ab60e7f0c5f8daaf","tests/data/wycheproof_chacha20poly1305_pass.blb":"87695fa84e7d146aad3a8b3290bf19e3cebf4e774ce3a8b56156f9418c28886b","tests/data/wycheproof_xchacha20poly1305_fail.blb":"b2a1c5222b93a0222a3c3ac71c5e2d46be3ab94eab7a77c8a84ada129c47cfd7","tests/data/wycheproof_xchacha20poly1305_pass.blb":"62d0cc0e50c121f59ddc0eb47fb74efe02f743970cb6eacb823062084ed62362","tests/lib.rs":"02b398b55dd393d896e2f111f202e86c72779036527a2afbc662bd41e1a29006"},"package":"9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"}
\ No newline at end of file
### external/vendor/chacha20poly1305/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "746f70a5f6c7371e723dc64e04f2115b56f24d27"
+ "sha1": "e37a978ccf0992d9053fbc039470d6527108e393"
},
"path_in_vcs": "chacha20poly1305"
}
\ No newline at end of file
### external/vendor/chacha20poly1305/CHANGELOG.md
@@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.11.0 (2026-06-28)
+### Added
+- `bytes` feature passthrough ([#631])
+
+### Changed
+- Bump `aead` from `0.5` to `0.6` ([#831])
+- Bump `chacha20` from `0.9` to `0.10` ([#796])
+- Bump `cipher` from `0.4` to `0.5` ([#583])
+- Bump `poly1305` from `0.8` to `0.9` ([#823])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#662])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+
+### Removed
+- `std` and `stream` features ([#662])
+
+[#583]: https://github.com/RustCrypto/AEADs/pull/583
+[#631]: https://github.com/RustCrypto/AEADs/pull/631
+[#662]: https://github.com/RustCrypto/AEADs/pull/662
+[#796]: https://github.com/RustCrypto/AEADs/pull/796
+[#823]: https://github.com/RustCrypto/AEADs/pull/823
+[#831]: https://github.com/RustCrypto/AEADs/pull/831
+
## 0.10.1 (2022-08-09)
### Added
- `rand_core` feature ([#467])
### external/vendor/chacha20poly1305/Cargo.lock
@@ -0,0 +1,198 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
+dependencies = [
+ "arrayvec",
+ "blobby",
+ "bytes",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f02882884d3e1bc524fb12c79f107f6ad0e1cfd498c536ffb494301740995dfe"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "bytes"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+ "zeroize",
+]
+
+[[package]]
+name = "chacha20poly1305"
+version = "0.11.0"
+dependencies = [
+ "aead",
+ "chacha20",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+]
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "poly1305"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00baa632505d05512f48a963e16051c54fda9a95cc9acea1a4e3c90991c4a2e"
+dependencies = [
+ "cpufeatures",
+ "universal-hash",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "universal-hash"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
+dependencies = [
+ "crypto-common",
+ "ctutils",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/chacha20poly1305/Cargo.toml
@@ -10,17 +10,25 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
+edition = "2024"
+rust-version = "1.85"
name = "chacha20poly1305"
-version = "0.10.1"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Pure Rust implementation of the ChaCha20Poly1305 Authenticated Encryption
with Additional Data Cipher (RFC 8439) with optional architecture-specific
hardware acceleration. Also contains implementations of the XChaCha20Poly1305
extended nonce variant of ChaCha20Poly1305, and the reduced-round
ChaCha8Poly1305 and ChaCha12Poly1305 lightweight variants.
"""
+homepage = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
documentation = "https://docs.rs/chacha20poly1305"
readme = "README.md"
keywords = [
@@ -35,53 +43,96 @@ categories = [
"no-std",
]
license = "Apache-2.0 OR MIT"
-repository = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+repository = "https://github.com/RustCrypto/AEADs"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = ["aead/alloc"]
+arrayvec = ["aead/arrayvec"]
+bytes = ["aead/bytes"]
+default = [
+ "alloc",
+ "getrandom",
]
+getrandom = ["aead/getrandom"]
+rand_core = ["aead/rand_core"]
+reduced-round = []
+zeroize = [
+ "dep:zeroize",
+ "chacha20/zeroize",
+]
+
+[lib]
+name = "chacha20poly1305"
+path = "src/lib.rs"
+
+[[test]]
+name = "lib"
+path = "tests/lib.rs"
[dependencies.aead]
-version = "0.5"
+version = "0.6"
default-features = false
[dependencies.chacha20]
-version = "0.9"
-features = ["zeroize"]
+version = "0.10"
+features = ["xchacha"]
+default-features = false
[dependencies.cipher]
-version = "0.4"
+version = "0.5"
[dependencies.poly1305]
-version = "0.8"
+version = "0.9"
[dependencies.zeroize]
-version = "1.5"
+version = "1.8"
+optional = true
default-features = false
[dev-dependencies.aead]
-version = "0.5"
+version = "0.6"
features = ["dev"]
default-features = false
-[features]
-alloc = ["aead/alloc"]
-default = [
- "alloc",
- "getrandom",
-]
-getrandom = [
- "aead/getrandom",
- "rand_core",
-]
-heapless = ["aead/heapless"]
-rand_core = ["aead/rand_core"]
-reduced-round = []
-std = [
- "aead/std",
- "alloc",
-]
-stream = ["aead/stream"]
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unsafe_code = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/chacha20poly1305/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "chacha20poly1305"
-version = "0.10.1"
+version = "0.11.0"
description = """
Pure Rust implementation of the ChaCha20Poly1305 Authenticated Encryption
with Additional Data Cipher (RFC 8439) with optional architecture-specific
@@ -9,34 +9,38 @@ extended nonce variant of ChaCha20Poly1305, and the reduced-round
ChaCha8Poly1305 and ChaCha12Poly1305 lightweight variants.
"""
authors = ["RustCrypto Developers"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0 OR MIT"
readme = "README.md"
documentation = "https://docs.rs/chacha20poly1305"
-repository = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+homepage = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+repository = "https://github.com/RustCrypto/AEADs"
keywords = ["aead", "chacha20", "poly1305", "xchacha20", "xchacha20poly1305"]
categories = ["cryptography", "no-std"]
+rust-version = "1.85"
[dependencies]
-aead = { version = "0.5", default-features = false }
-chacha20 = { version = "0.9", features = ["zeroize"] }
-cipher = "0.4"
-poly1305 = "0.8"
-zeroize = { version = "1.5", default-features = false }
+aead = { version = "0.6", default-features = false }
+chacha20 = { version = "0.10", default-features = false, features = ["xchacha"] }
+cipher = "0.5"
+poly1305 = "0.9"
+zeroize = { version = "1.8", optional = true, default-features = false }
[dev-dependencies]
-aead = { version = "0.5", features = ["dev"], default-features = false }
+aead = { version = "0.6", features = ["dev"], default-features = false }
[features]
-default = ["alloc", "getrandom"]
-std = ["aead/std", "alloc"]
-alloc = ["aead/alloc"]
-getrandom = ["aead/getrandom", "rand_core"]
-heapless = ["aead/heapless"]
-rand_core = ["aead/rand_core"]
+default = ["alloc", "getrandom"]
+alloc = ["aead/alloc"]
+arrayvec = ["aead/arrayvec"]
+bytes = ["aead/bytes"]
+getrandom = ["aead/getrandom"]
+rand_core = ["aead/rand_core"]
reduced-round = []
-stream = ["aead/stream"]
+zeroize = ["dep:zeroize", "chacha20/zeroize"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/chacha20poly1305/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/chacha20poly1305/README.md
@@ -48,8 +48,8 @@ certain 32-bit PowerPC CPUs and some non-ARM microcontrollers).
Licensed under either of:
- * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
- * [MIT license](http://opensource.org/licenses/MIT)
+ * [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
+ * [MIT license](https://opensource.org/licenses/MIT)
at your option.
@@ -61,12 +61,12 @@ dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
-[crate-image]: https://buildstats.info/crate/chacha20poly1305
+[crate-image]: https://img.shields.io/crates/v/chacha20poly1305
[crate-link]: https://crates.io/crates/chacha20poly1305
[docs-image]: https://docs.rs/chacha20poly1305/badge.svg
[docs-link]: https://docs.rs/chacha20poly1305/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs
[downloads-image]: https://img.shields.io/crates/d/chacha20poly1305.svg
@@ -79,5 +79,5 @@ dual licensed as above, without any additional terms or conditions.
[2]: https://en.wikipedia.org/wiki/Authenticated_encryption
[3]: https://github.com/RustCrypto/stream-ciphers/tree/master/chacha20
[4]: https://github.com/RustCrypto/universal-hashes/tree/master/poly1305
-[5]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
+[5]: https://web.archive.org/web/20200606025324/https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
[6]: https://www.mobilecoin.com/
### external/vendor/chacha20poly1305/src/cipher.rs
@@ -1,13 +1,12 @@
//! Core AEAD cipher implementation for (X)ChaCha20Poly1305.
use ::cipher::{StreamCipher, StreamCipherSeek};
-use aead::generic_array::GenericArray;
use aead::Error;
+use aead::{array::Array, inout::InOutBuf};
use poly1305::{
- universal_hash::{KeyInit, UniversalHash},
Poly1305,
+ universal_hash::{KeyInit, UniversalHash},
};
-use zeroize::Zeroize;
use super::Tag;
@@ -16,7 +15,7 @@ const BLOCK_SIZE: usize = 64;
/// Maximum number of blocks that can be encrypted with ChaCha20 before the
/// counter overflows.
-const MAX_BLOCKS: usize = core::u32::MAX as usize;
+const MAX_BLOCKS: usize = u32::MAX as usize;
/// ChaCha20Poly1305 instantiated with a particular nonce
pub(crate) struct Cipher<C>
@@ -35,10 +34,14 @@ where
pub(crate) fn new(mut cipher: C) -> Self {
// Derive Poly1305 key from the first 32-bytes of the ChaCha20 keystream
let mut mac_key = poly1305::Key::default();
- cipher.apply_keystream(&mut *mac_key);
+ cipher.apply_keystream(&mut mac_key);
- let mac = Poly1305::new(GenericArray::from_slice(&*mac_key));
- mac_key.zeroize();
+ let mac = Poly1305::new(&mac_key);
+ #[cfg(feature = "zeroize")]
+ {
+ use zeroize::Zeroize;
+ mac_key.zeroize();
+ }
// Set ChaCha20 counter to 1
cipher.seek(BLOCK_SIZE as u64);
@@ -47,10 +50,10 @@ where
}
/// Encrypt the given message in-place, returning the authentication tag
- pub(crate) fn encrypt_in_place_detached(
+ pub(crate) fn encrypt_inout_detached(
mut self,
associated_data: &[u8],
- buffer: &mut [u8],
+ mut buffer: InOutBuf<'_, '_, u8>,
) -> Result<Tag, Error> {
if buffer.len() / BLOCK_SIZE >= MAX_BLOCKS {
return Err(Error);
@@ -60,34 +63,34 @@ where
// TODO(tarcieri): interleave encryption with Poly1305
// See: <https://github.com/RustCrypto/AEADs/issues/74>
- self.cipher.apply_keystream(buffer);
- self.mac.update_padded(buffer);
+ self.cipher.apply_keystream_inout(buffer.reborrow());
+ self.mac.update_padded(buffer.get_out());
- self.authenticate_lengths(associated_data, buffer)?;
+ self.authenticate_lengths(associated_data, buffer.get_out())?;
Ok(self.mac.finalize())
}
/// Decrypt the given message, first authenticating ciphertext integrity
/// and returning an error if it's been tampered with.
- pub(crate) fn decrypt_in_place_detached(
+ pub(crate) fn decrypt_inout_detached(
mut self,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
tag: &Tag,
) -> Result<(), Error> {
if buffer.len() / BLOCK_SIZE >= MAX_BLOCKS {
return Err(Error);
}
self.mac.update_padded(associated_data);
- self.mac.update_padded(buffer);
- self.authenticate_lengths(associated_data, buffer)?;
+ self.mac.update_padded(buffer.get_in());
+ self.authenticate_lengths(associated_data, buffer.get_in())?;
// This performs a constant-time comparison using the `subtle` crate
if self.mac.verify(tag).is_ok() {
// TODO(tarcieri): interleave decryption with Poly1305
// See: <https://github.com/RustCrypto/AEADs/issues/74>
- self.cipher.apply_keystream(buffer);
+ self.cipher.apply_keystream_inout(buffer);
Ok(())
} else {
Err(Error)
@@ -99,7 +102,7 @@ where
let associated_data_len: u64 = associated_data.len().try_into().map_err(|_| Error)?;
let buffer_len: u64 = buffer.len().try_into().map_err(|_| Error)?;
- let mut block = GenericArray::default();
+ let mut block = Array::default();
block[..8].copy_from_slice(&associated_data_len.to_le_bytes());
block[8..].copy_from_slice(&buffer_len.to_le_bytes());
self.mac.update(&[block]);
### external/vendor/chacha20poly1305/src/lib.rs
@@ -5,7 +5,6 @@
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
//! ## Supported Algorithms
//!
@@ -14,26 +13,31 @@
//!
//! - [`XChaCha20Poly1305`] - ChaCha20Poly1305 variant with an extended 192-bit (24-byte) nonce.
//! - [`ChaCha8Poly1305`] / [`ChaCha12Poly1305`] - non-standard, reduced-round variants
-//! (gated under the `reduced-round` Cargo feature). See the [Too Much Crypto][5]
+//! (gated under the `reduced-round` Cargo feature). See the
+//! [Too Much Crypto](https://eprint.iacr.org/2019/1492.pdf)
//! paper for background and rationale on when these constructions could be used.
//! When in doubt, prefer [`ChaCha20Poly1305`].
-//! - [`XChaCha8Poly1305`] / [`XChaCha12Poly1305`] - same as above,
-//! but with an extended 192-bit (24-byte) nonce.
+//! - [`XChaCha8Poly1305`] / [`XChaCha12Poly1305`] - same as above, but with an extended
+//! 192-bit (24-byte) nonce.
//!
//! # Usage
//!
-#![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")]
-#![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+#![cfg_attr(feature = "getrandom", doc = "```")]
+#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `getrandom` feature is enabled
+//!
//! use chacha20poly1305::{
-//! aead::{Aead, AeadCore, KeyInit, OsRng},
+//! aead::{Aead, AeadCore, Generate, Key, KeyInit},
//! ChaCha20Poly1305, Nonce
//! };
//!
-//! let key = ChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<ChaCha20Poly1305>::generate();
//! let cipher = ChaCha20Poly1305::new(&key);
-//! let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
+//!
+//! let nonce = Nonce::generate(); // MUST be unique per message
//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
+//!
//! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?;
//! assert_eq!(&plaintext, b"plaintext message");
//! # Ok(())
@@ -45,46 +49,48 @@
//! This crate has an optional `alloc` feature which can be disabled in e.g.
//! microcontroller environments that don't have a heap.
//!
-//! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`]
+//! The [`AeadInOut::encrypt_in_place`] and [`AeadInOut::decrypt_in_place`]
//! methods accept any type that impls the [`aead::Buffer`] trait which
//! contains the plaintext for encryption or ciphertext for decryption.
//!
-//! Note that if you enable the `heapless` feature of this crate,
-//! you will receive an impl of [`aead::Buffer`] for `heapless::Vec`
-//! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]),
-//! which can then be passed as the `buffer` parameter to the in-place encrypt
+//! Enabling the `arrayvec` feature of this crate will provide an impl of
+//! [`aead::Buffer`] for `arrayvec::ArrayVec` (re-exported from the [`aead`] crate as
+//! [`aead::arrayvec::ArrayVec`]), and enabling the `bytes` feature of this crate will
+//! provide an impl of [`aead::Buffer`] for `bytes::BytesMut` (re-exported from the
+//! [`aead`] crate as [`aead::bytes::BytesMut`]).
+//!
+//! It can then be passed as the `buffer` parameter to the in-place encrypt
//! and decrypt methods:
//!
+#![cfg_attr(all(feature = "getrandom", feature = "arrayvec"), doc = "```")]
#![cfg_attr(
- all(feature = "getrandom", feature = "heapless", feature = "std"),
- doc = "```"
-)]
-#![cfg_attr(
- not(all(feature = "getrandom", feature = "heapless", feature = "std")),
+ not(all(feature = "getrandom", feature = "arrayvec")),
doc = "```ignore"
)]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `arrayvec` and `getrandom` features are enabled
+//!
//! use chacha20poly1305::{
-//! aead::{AeadCore, AeadInPlace, KeyInit, OsRng, heapless::Vec},
+//! aead::{AeadCore, AeadInOut, Generate, Key, KeyInit, arrayvec::ArrayVec},
//! ChaCha20Poly1305, Nonce,
//! };
//!
-//! let key = ChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<ChaCha20Poly1305>::generate();
//! let cipher = ChaCha20Poly1305::new(&key);
-//! let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
//!
-//! let mut buffer: Vec<u8, 128> = Vec::new(); // Note: buffer needs 16-bytes overhead for auth tag
-//! buffer.extend_from_slice(b"plaintext message");
+//! let nonce = Nonce::generate(); // MUST be unique per message
+//! let mut buffer: ArrayVec<u8, 128> = ArrayVec::new(); // Note: buffer needs 16-bytes overhead for auth tag
+//! buffer.try_extend_from_slice(b"plaintext message").unwrap();
//!
//! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext
//! cipher.encrypt_in_place(&nonce, b"", &mut buffer)?;
//!
//! // `buffer` now contains the message ciphertext
-//! assert_ne!(&buffer, b"plaintext message");
+//! assert_ne!(buffer.as_ref(), b"plaintext message");
//!
//! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext
//! cipher.decrypt_in_place(&nonce, b"", &mut buffer)?;
-//! assert_eq!(&buffer, b"plaintext message");
+//! assert_eq!(buffer.as_ref(), b"plaintext message");
//! # Ok(())
//! # }
//! ```
@@ -107,28 +113,30 @@
//! proof from the XSalsa20 paper to the construction in order to demonstrate
//! that XChaCha20 is secure if ChaCha20 is secure (see Section 3.1):
//!
-//! <https://tools.ietf.org/html/draft-arciszewski-xchacha-03>
+//! <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha>
//!
//! It is worth noting that NaCl/libsodium's default "secretbox" algorithm is
//! XSalsa20Poly1305, not XChaCha20Poly1305, and thus not compatible with
//! this library. If you are interested in that construction, please see the
-//! `xsalsa20poly1305` crate:
+//! `crypto_secretbox` crate:
//!
-//! <https://docs.rs/xsalsa20poly1305/>
+//! <https://docs.rs/crypto_secretbox/>
//!
//! # Usage
//!
-#![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")]
-#![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+#![cfg_attr(feature = "getrandom", doc = "```")]
+#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `getrandom` feature is enabled
+//!
//! use chacha20poly1305::{
-//! aead::{Aead, AeadCore, KeyInit, OsRng},
+//! aead::{Aead, AeadCore, Generate, Key, KeyInit},
//! XChaCha20Poly1305, XNonce
//! };
//!
-//! let key = XChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<XChaCha20Poly1305>::generate();
//! let cipher = XChaCha20Poly1305::new(&key);
-//! let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng); // 192-bits; unique per message
+//! let nonce = XNonce::generate(); // MUST be unique per message
//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
//! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?;
//! assert_eq!(&plaintext, b"plaintext message");
@@ -138,44 +146,44 @@
mod cipher;
-pub use aead::{self, consts, AeadCore, AeadInPlace, Error, KeyInit, KeySizeUser};
+pub use aead::{self, AeadCore, AeadInOut, Error, KeyInit, KeySizeUser, consts};
-use self::cipher::Cipher;
+use crate::cipher::Cipher;
use ::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
use aead::{
- consts::{U0, U12, U16, U24, U32},
- generic_array::{ArrayLength, GenericArray},
+ TagPosition,
+ array::{Array, ArraySize},
+ consts::{U12, U16, U24, U32},
+ inout::InOutBuf,
};
-use core::marker::PhantomData;
-use zeroize::{Zeroize, ZeroizeOnDrop};
-
use chacha20::{ChaCha20, XChaCha20};
+use core::{fmt, marker::PhantomData};
#[cfg(feature = "reduced-round")]
-use chacha20::{ChaCha12, ChaCha8, XChaCha12, XChaCha8};
+use chacha20::{ChaCha8, ChaCha12, XChaCha8, XChaCha12};
/// Key type (256-bits/32-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
+/// Implemented as an alias for [`Array`].
///
/// All [`ChaChaPoly1305`] variants (including `XChaCha20Poly1305`) use this
/// key type.
-pub type Key = GenericArray<u8, U32>;
+pub type Key = Array<u8, U32>;
/// Nonce type (96-bits/12-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
-pub type Nonce = GenericArray<u8, U12>;
+/// Implemented as an alias for [`Array`].
+pub type Nonce = Array<u8, U12>;
/// XNonce type (192-bits/24-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
-pub type XNonce = GenericArray<u8, U24>;
+/// Implemented as an alias for [`Array`].
+pub type XNonce = Array<u8, U24>;
/// Poly1305 tag.
///
-/// Implemented as an alias for [`GenericArray`].
-pub type Tag = GenericArray<u8, U16>;
+/// Implemented as an alias for [`Array`].
+pub type Tag = Array<u8, U16>;
/// ChaCha20Poly1305 Authenticated Encryption with Additional Data (AEAD).
pub type ChaCha20Poly1305 = ChaChaPoly1305<ChaCha20, U12>;
@@ -206,7 +214,7 @@ pub type XChaCha12Poly1305 = ChaChaPoly1305<XChaCha12, U24>;
/// Generic ChaCha+Poly1305 Authenticated Encryption with Additional Data (AEAD) construction.
///
/// See the [toplevel documentation](index.html) for a usage example.
-pub struct ChaChaPoly1305<C, N: ArrayLength<u8> = U12> {
+pub struct ChaChaPoly1305<C, N: ArraySize = U12> {
/// Secret key.
key: Key,
@@ -219,14 +227,14 @@ pub struct ChaChaPoly1305<C, N: ArrayLength<u8> = U12> {
impl<C, N> KeySizeUser for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
type KeySize = U32;
}
impl<C, N> KeyInit for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
#[inline]
fn new(key: &Key) -> Self {
@@ -240,45 +248,41 @@ where
impl<C, N> AeadCore for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
type NonceSize = N;
type TagSize = U16;
- type CiphertextOverhead = U0;
+ const TAG_POSITION: TagPosition = TagPosition::Postfix;
}
-impl<C, N> AeadInPlace for ChaChaPoly1305<C, N>
+impl<C, N> AeadInOut for ChaChaPoly1305<C, N>
where
C: KeyIvInit<KeySize = U32, IvSize = N> + StreamCipher + StreamCipherSeek,
- N: ArrayLength<u8>,
+ N: ArraySize,
{
- fn encrypt_in_place_detached(
+ fn encrypt_inout_detached(
&self,
nonce: &aead::Nonce<Self>,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
) -> Result<Tag, Error> {
- Cipher::new(C::new(&self.key, nonce)).encrypt_in_place_detached(associated_data, buffer)
+ Cipher::new(C::new(&self.key, nonce)).encrypt_inout_detached(associated_data, buffer)
}
- fn decrypt_in_place_detached(
+ fn decrypt_inout_detached(
&self,
nonce: &aead::Nonce<Self>,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
tag: &Tag,
) -> Result<(), Error> {
- Cipher::new(C::new(&self.key, nonce)).decrypt_in_place_detached(
- associated_data,
- buffer,
- tag,
- )
+ Cipher::new(C::new(&self.key, nonce)).decrypt_inout_detached(associated_data, buffer, tag)
}
}
impl<C, N> Clone for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
fn clone(&self) -> Self {
Self {
@@ -291,11 +295,25 @@ where
impl<C, N> Drop for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
fn drop(&mut self) {
- self.key.as_mut_slice().zeroize();
+ #[cfg(feature = "zeroize")]
+ {
+ use zeroize::Zeroize;
+ self.key.as_mut_slice().zeroize();
+ }
+ }
+}
+
+impl<C, N> fmt::Debug for ChaChaPoly1305<C, N>
+where
+ N: ArraySize,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ChaChaPoly1305").finish_non_exhaustive()
}
}
-impl<C, N: ArrayLength<u8>> ZeroizeOnDrop for ChaChaPoly1305<C, N> {}
+#[cfg(feature = "zeroize")]
+impl<C, N: ArraySize> zeroize::ZeroizeOnDrop for ChaChaPoly1305<C, N> {}
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305_fail.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305_pass.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305_fail.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305_pass.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/lib.rs
@@ -6,29 +6,39 @@ use chacha20poly1305::ChaCha20Poly1305;
use chacha20poly1305::XChaCha20Poly1305;
// Test vectors from Wycheproof
-aead::new_test!(
- wycheproof_chacha20poly1305,
- "wycheproof_chacha20poly1305",
+aead::new_pass_test!(
+ wycheproof_chacha20poly1305_pass,
+ "wycheproof_chacha20poly1305_pass",
ChaCha20Poly1305
);
-aead::new_test!(
- wycheproof_xchacha20poly1305,
- "wycheproof_xchacha20poly1305",
+aead::new_fail_test!(
+ wycheproof_chacha20poly1305_fail,
+ "wycheproof_chacha20poly1305_fail",
+ ChaCha20Poly1305
+);
+aead::new_pass_test!(
+ wycheproof_xchacha20poly1305_pass,
+ "wycheproof_xchacha20poly1305_pass",
+ XChaCha20Poly1305
+);
+aead::new_fail_test!(
+ wycheproof_xchacha20poly1305_fail,
+ "wycheproof_xchacha20poly1305_fail",
XChaCha20Poly1305
);
macro_rules! impl_tests {
($cipher:ty, $key:expr, $nonce:expr, $aad:expr, $plaintext:expr, $ciphertext:expr, $tag:expr) => {
#[test]
fn encrypt() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let payload = Payload {
msg: $plaintext,
aad: $aad,
};
- let ciphertext = <$cipher>::new(key).encrypt(nonce, payload).unwrap();
+ let ciphertext = <$cipher>::new(&key).encrypt(&nonce, payload).unwrap();
let tag_begins = ciphertext.len() - 16;
assert_eq!($ciphertext, &ciphertext[..tag_begins]);
@@ -37,8 +47,8 @@ macro_rules! impl_tests {
#[test]
fn decrypt() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let mut ciphertext = Vec::from($ciphertext);
ciphertext.extend_from_slice($tag);
@@ -47,15 +57,15 @@ macro_rules! impl_tests {
aad: $aad,
};
- let plaintext = <$cipher>::new(key).decrypt(nonce, payload).unwrap();
+ let plaintext = <$cipher>::new(&key).decrypt(&nonce, payload).unwrap();
assert_eq!($plaintext, plaintext.as_slice());
}
#[test]
fn decrypt_modified() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let mut ciphertext = Vec::from($ciphertext);
ciphertext.extend_from_slice($tag);
@@ -68,8 +78,8 @@ macro_rules! impl_tests {
aad: $aad,
};
- let cipher = <$cipher>::new(key);
- assert!(cipher.decrypt(nonce, payload).is_err());
+ let cipher = <$cipher>::new(&key);
+ assert!(cipher.decrypt(&nonce, payload).is_err());
}
};
}
@@ -96,9 +106,9 @@ const PLAINTEXT: &[u8] = b"Ladies and Gentlemen of the class of '99: \
/// <https://tools.ietf.org/html/rfc8439#section-2.8.2>
mod chacha20 {
use super::{AAD, KEY, PLAINTEXT};
- use chacha20poly1305::aead::generic_array::GenericArray;
- use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::ChaCha20Poly1305;
+ use chacha20poly1305::aead::array::Array;
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
const NONCE: &[u8; 12] = &[
0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
@@ -132,18 +142,18 @@ mod chacha20 {
#[test]
fn clone_impl() {
- let _ = ChaCha20Poly1305::new(GenericArray::from_slice(KEY)).clone();
+ let _ = ChaCha20Poly1305::new(KEY.into()).clone();
}
}
/// XChaCha20Poly1305 test vectors.
///
-/// From <https://tools.ietf.org/html/draft-arciszewski-xchacha-03#appendix-A.1>
+/// From <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.1>
mod xchacha20 {
use super::{AAD, KEY, PLAINTEXT};
- use chacha20poly1305::aead::generic_array::GenericArray;
- use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::XChaCha20Poly1305;
+ use chacha20poly1305::aead::array::Array;
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
const NONCE: &[u8; 24] = &[
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e,
### external/vendor/cipher/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"cd35050864931045c5251108168d7a28930c9a54ec68a22999116f1ba034d139","CHANGELOG.md":"76b65408515ba9ab7b04742e8ac7269ea7ec18001c218ac7739a0513b6dc055f","Cargo.toml":"14da8d3fa5933ee2ccfe67432b260db0c50a732db4c1e13303abadd09af9e634","Cargo.toml.orig":"b319f1dd839f54a1761578fff6de9a58d0a71fb3cb31881b62ccd1571ff0c761","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"5c7bd92d1f096f12203dc1b601e3cb17484fa1b023e30b6b8edcc80e416237ec","README.md":"be7477bf37a82e5286846153ee87ac556550f0cea503ba42a4e8d9065f848e4d","src/block.rs":"d360a0dbedc71a1702d7ada005a4b1fc7da98aae24e099e7a41ffedcb2b6b5c0","src/dev.rs":"82e51f2d453c922ccd40f16e9e2353e7f0e4fe0db74b810a75410f375709f3d7","src/dev/block.rs":"f4a4e194907751768242e95ddb702827399d3b742848b381de62e5e859610129","src/dev/stream.rs":"8b0cfcaf037cf469ed4112e63afeb0782e3c6e09477e3065842aaec65d66041e","src/errors.rs":"d2c026ff03556c6d0a284cbd81d8ddadf5e2b6ca66d47c39ee9d4393fb96e089","src/lib.rs":"5582e304d673d1dd9ffc16e8fa3d240bb43538471341ca3c99d841ea1be0581e","src/stream.rs":"9ab2d14811de520578dc66af29db7200f3fd9b04fecfc916acf524b9da46c0a6","src/stream_core.rs":"0546f72cdf1a91e095235044047ca52eda73a7fd972a45bc287e17407094bb13","src/stream_wrapper.rs":"bcf4c76bacd006d7a0a65605f23fe43dc4d6c535a59a37103ee6e044e692f7d7"},"package":"773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"a9861e72db50f80783a4e743a7129a5dd457d6fd1275ef28252f6c4af79554e6","CHANGELOG.md":"a8a99f9731115fa0eb271e2e687bfc580315648c5789b9559ad83e80e591db72","Cargo.lock":"08a46458af5efbcbb5a8e82b37a58d723a171b3847126275ed7bee1a330fb504","Cargo.toml":"8685a3b996d8d12e00d51d882425a409101d344f7efac1a48cf37a7509847c7f","Cargo.toml.orig":"75e90eee7bb7c8693451b1ce893104bcf616ed5cf8150e4574d39937768d3f79","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"950d712c518a02fcb7cff96950aee304a1cc5283361712c980ea21e8d6d669a5","README.md":"274b6472f637fdc8211b7396716016b9a91b5cbc59a7a3d59552355db785b11a","src/block.rs":"5aa181063d77cd7cb45b02fc400cf05aa8f29766c4b9f32226bd79e8386a12d8","src/block/backends.rs":"1647a4fde7e026e99205611fa179c88395fb67c312866c332c052184b914f943","src/block/ctx.rs":"c5e8e1599e0393b41ee601b9beedac2b1814d5d7800f046b991244c316ce7e93","src/dev.rs":"714bd891a70182125fbff1139c45d789d5943fcaae41604ad8ee41cf6b2139c6","src/dev/block_bench.rs":"d388849400aa1e0a65cbc528d2aac26d6f6dbe84b527609171989c2a9f30be6e","src/dev/block_cipher.rs":"ae78379371929a4dbaf14c25f362b9056bc22e81da47b065d558d1d2a4732d1a","src/dev/block_mode.rs":"de10a65369194d06de9b40e4541f69cad8cb59dc9ebfce1b440980b06abb83c7","src/dev/stream.rs":"2673eceb2d1aa44351eb39078b26e971d54a9754358a0d1cbc738c36900232f7","src/lib.rs":"2abd6484b6fbae1eb01f1f65ed26c2c20304fc91040d875d44b3f31bce555a57","src/stream.rs":"9558c02e4e05cc5f26a6d9e4ecae14e188432e0f4e0ef3dab909024a64ac7f09","src/stream/core_api.rs":"b79ca50449712d6aae8bc98447f80194217ff34572a225efd0d802cc475f4640","src/stream/errors.rs":"2e8ec1dc8d142daa70b61c849c80d0b3c61146bd0c511a03e0cc48d382a1bf6d","src/stream/wrapper.rs":"6fcf34c8511f80d46f0c48d5e52e3502641cd3ac8047fcb72336b0ac597e335b","src/tweak.rs":"d9e759821bcb790b4a4cc6f9a59dd809859915b8740a19eecce08027350ae1e3","src/tweak/ctx.rs":"34cd8d4118abd3cd57f56df74a9a6c1e9c0ebaf1926279acd7318c2c9b975ab9","src/tweak/zero.rs":"0162fdcaa6d4aefbe431f787f29155dbf10fe98549361a2348208800968d2ba2","tests/data/dummy_stream_cipher.blb":"b9573cccdb727cd7281940f69e934565c387e9074cbb4949358e20f0ea0e2c77","tests/stream.rs":"a98dabca3efc1cba888b2b0ed4a49b50286695b1dbbec69e4241053a263ab46e"},"package":"e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"}
\ No newline at end of file
### external/vendor/cipher/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "0af93f6076a76757c65cb2ef6f6abd9756440478"
+ "sha1": "f836f71fadb3b975b577a293d57851d044f0a44b"
},
"path_in_vcs": "cipher"
}
\ No newline at end of file
### external/vendor/cipher/CHANGELOG.md
@@ -5,6 +5,80 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.5.2 (2026-05-19)
+### Added
+- Re-export of `SetIvState` ([#2422])
+
+[#2422]: https://github.com/RustCrypto/traits/pull/2422
+
+## 0.5.1 (2026-02-25)
+### Changed
+- Block sizes no longer bounded by `crypto_common::BlockSizes` ([#2309])
+- `StreamCipherCoreWrapper` is now bounded by `block_buffer::BlockSizes`
+ instead of `crypto_common::BlockSizes` ([#2309])
+- Bump `block-buffer` dependency to v0.12 ([#2309])
+
+### Fixed
+- `Key:` option in the `stream_cipher_bench` macro ([#2290])
+
+[#2290]: https://github.com/RustCrypto/traits/pull/2290
+[#2309]: https://github.com/RustCrypto/traits/pull/2309
+
+## 0.5.0 (2026-02-04) [YANKED]
+Note: this version was yanked because v0.5.1 introduces breaking changes.
+Users should migrate to `cipher` v0.5.1 and `crypto-common` v0.2.1 using `cargo update`.
+
+### Added
+- Traits for tweakable block ciphers ([#1721])
+- Methods for writing keystream ([#1907])
+
+### Changed
+- Replaced `generic-array` with `hybrid-array` ([#1358])
+- Rename `BlockCipher*`/`BlockMode*` ([#1482])
+ - `BlockEncrypt` => `BlockCipherEncrypt`
+ - `BlockDecrypt` => `BlockCipherDecrypt`
+ - `BlockEncryptMut` => `BlockModeEncrypt`
+ - `BlockDecryptMut` => `BlockModeDecrypt`
+- Split `BlockBackend` traits into 4 specific traits: ([#1636])
+ - `BlockCipherEncBackend`
+ - `BlockCipherDecBackend`
+ - `BlockModeEncBackend`
+ - `BlockModeDecBackend`
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1759])
+- Use `block_buffer::ReadBuffer` in `StreamCipherCoreWrapper` ([#1959])
+- Re-export of `crypto-common` moved to `cipher::common` ([#2237], [#2260])
+- `crypto-common` dependency bumped to v0.2 ([#2276])
+- `blobby` requirement bumped to v0.4 ([#2147])
+- `inout` dependency bumped to v0.2.2 ([#2149])
+
+### Fixed
+- Bugs in `StreamCipherCoreWrapper` trait implementations ([#1421])
+- Seeking implementation in the stream cipher wrapper ([#2052])
+
+### Removed
+- `std` feature ([#1691])
+- `BlockCipherEncrypt::encrypt_padded*` and `BlockCipherDecrypt::decrypt_padded*` methods.
+ Users of the ECB mode should use the `ecb-mode` crate instead. ([#2245])
+- `AsyncStreamCipher` trait ([#2280])
+
+[#1358]: https://github.com/RustCrypto/traits/pull/1358
+[#1421]: https://github.com/RustCrypto/traits/pull/1421
+[#1482]: https://github.com/RustCrypto/traits/pull/1482
+[#1636]: https://github.com/RustCrypto/traits/pull/1636
+[#1691]: https://github.com/RustCrypto/traits/pull/1691
+[#1721]: https://github.com/RustCrypto/traits/pull/1721
+[#1759]: https://github.com/RustCrypto/traits/pull/1759
+[#1907]: https://github.com/RustCrypto/traits/pull/1907
+[#1959]: https://github.com/RustCrypto/traits/pull/1959
+[#2052]: https://github.com/RustCrypto/traits/pull/2052
+[#2147]: https://github.com/RustCrypto/traits/pull/2147
+[#2149]: https://github.com/RustCrypto/traits/pull/2149
+[#2237]: https://github.com/RustCrypto/traits/pull/2237
+[#2245]: https://github.com/RustCrypto/traits/pull/2245
+[#2260]: https://github.com/RustCrypto/traits/pull/2260
+[#2276]: https://github.com/RustCrypto/traits/pull/2276
+[#2280]: https://github.com/RustCrypto/traits/pull/2280
+
## 0.4.4 (2022-03-09)
### Changed
- Move `ParBlocks`/`ParBlocksSizeUser` to the `crypto-common` crate ([#1052])
### external/vendor/cipher/Cargo.lock
@@ -0,0 +1,465 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "bitflags"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
+dependencies = [
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "hex-literal",
+ "inout",
+ "zeroize",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+ "zeroize",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen 0.46.0",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/cipher/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "cipher"
-version = "0.4.4"
+version = "0.5.2"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "Traits for describing block ciphers and stream ciphers"
documentation = "https://docs.rs/cipher"
readme = "README.md"
@@ -33,33 +39,86 @@ repository = "https://github.com/RustCrypto/traits"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = []
+block-padding = ["inout/block-padding"]
+dev = ["blobby"]
+getrandom = ["common/getrandom"]
+rand_core = ["common/rand_core"]
+stream-wrapper = ["block-buffer"]
+zeroize = [
+ "dep:zeroize",
+ "common/zeroize",
+ "block-buffer?/zeroize",
]
+[lib]
+name = "cipher"
+path = "src/lib.rs"
+
+[[test]]
+name = "stream"
+path = "tests/stream.rs"
+
[dependencies.blobby]
-version = "0.3"
+version = "0.4"
optional = true
-[dependencies.crypto-common]
-version = "0.1.6"
+[dependencies.block-buffer]
+version = "0.12"
+optional = true
+
+[dependencies.common]
+version = "0.2.2"
+package = "crypto-common"
[dependencies.inout]
-version = "0.1"
+version = "0.2.2"
[dependencies.zeroize]
-version = "1.5"
+version = "1.8"
optional = true
default-features = false
-[features]
-alloc = []
-block-padding = ["inout/block-padding"]
-dev = ["blobby"]
-rand_core = ["crypto-common/rand_core"]
-std = [
- "alloc",
- "crypto-common/std",
- "inout/std",
-]
+[dev-dependencies.hex-literal]
+version = "1"
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/cipher/Cargo.toml.orig
@@ -1,32 +1,40 @@
[package]
name = "cipher"
-description = "Traits for describing block ciphers and stream ciphers"
-version = "0.4.4"
+version = "0.5.2"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-readme = "README.md"
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/cipher"
+readme = "README.md"
repository = "https://github.com/RustCrypto/traits"
+license = "MIT OR Apache-2.0"
keywords = ["crypto", "block-cipher", "stream-cipher", "trait"]
categories = ["cryptography", "no-std"]
+description = "Traits for describing block ciphers and stream ciphers"
[dependencies]
-crypto-common = "0.1.6"
-inout = "0.1"
+common = { version = "0.2.2", package = "crypto-common" }
+inout = "0.2.2"
# optional dependencies
-blobby = { version = "0.3", optional = true }
-zeroize = { version = "1.5", optional = true, default-features = false }
+blobby = { version = "0.4", optional = true }
+block-buffer = { version = "0.12", optional = true }
+zeroize = { version = "1.8", optional = true, default-features = false }
+
+[dev-dependencies]
+hex-literal = "1"
[features]
alloc = []
-std = ["alloc", "crypto-common/std", "inout/std"]
block-padding = ["inout/block-padding"]
-rand_core = ["crypto-common/rand_core"] # Enable random key and IV generation methods
+stream-wrapper = ["block-buffer"]
+getrandom = ["common/getrandom"]
+rand_core = ["common/rand_core"]
dev = ["blobby"]
+zeroize = ["dep:zeroize", "common/zeroize", "block-buffer?/zeroize"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/cipher/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2016-2020 RustCrypto Developers
+Copyright (c) 2016-2025 RustCrypto Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/cipher/README.md
@@ -7,19 +7,10 @@
[![Project Chat][chat-image]][chat-link]
[![Build Status][build-image]][build-link]
-Traits which define the functionality of [block ciphers] and [stream ciphers].
+Traits which define the functionality of [block ciphers], [block modes] and [stream ciphers].
-See [RustCrypto/block-ciphers] and [RustCrypto/stream-ciphers] for algorithm
-implementations which use these traits.
-
-[Documentation][docs-link]
-
-## Minimum Supported Rust Version
-
-Rust **1.56** or higher.
-
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+See [RustCrypto/block-ciphers] and [RustCrypto/stream-ciphers] for algorithm implementations which
+use these traits.
## SemVer Policy
@@ -48,15 +39,16 @@ dual licensed as above, without any additional terms or conditions.
[docs-image]: https://docs.rs/cipher/badge.svg
[docs-link]: https://docs.rs/cipher/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260050-traits
-[build-image]: https://github.com/RustCrypto/traits/workflows/cipher/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/traits/actions?query=workflow:cipher
+[build-image]: https://github.com/RustCrypto/traits/actions/workflows/cipher.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/traits/actions/workflows/cipher.yml?query=branch:master
[//]: # (general links)
[block ciphers]: https://en.wikipedia.org/wiki/Block_cipher
+[block modes]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
[stream ciphers]: https://en.wikipedia.org/wiki/Stream_cipher
[RustCrypto/block-ciphers]: https://github.com/RustCrypto/block-ciphers
[RustCrypto/stream-ciphers]: https://github.com/RustCrypto/stream-ciphers
### external/vendor/cipher/src/block.rs
@@ -10,76 +10,30 @@
//! [2]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
//! [3]: https://en.wikipedia.org/wiki/Symmetric-key_algorithm
-use crate::{ParBlocks, ParBlocksSizeUser};
#[cfg(all(feature = "block-padding", feature = "alloc"))]
use alloc::{vec, vec::Vec};
+use common::{Block, BlockSizeUser};
+use inout::{InOut, InOutBuf, NotEqualError};
#[cfg(feature = "block-padding")]
use inout::{
- block_padding::{Padding, UnpadError},
InOutBufReserved, PadError,
+ block_padding::{self, Padding},
};
-use inout::{InOut, InOutBuf, NotEqualError};
-
-pub use crypto_common::{generic_array::ArrayLength, typenum::Unsigned, Block, BlockSizeUser};
-
-/// Marker trait for block ciphers.
-pub trait BlockCipher: BlockSizeUser {}
-
-/// Trait implemented by block cipher encryption and decryption backends.
-pub trait BlockBackend: ParBlocksSizeUser {
- /// Process single inout block.
- fn proc_block(&mut self, block: InOut<'_, '_, Block<Self>>);
-
- /// Process inout blocks in parallel.
- #[inline(always)]
- fn proc_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
- for i in 0..Self::ParBlocksSize::USIZE {
- self.proc_block(blocks.get(i));
- }
- }
- /// Process buffer of inout blocks. Length of the buffer MUST be smaller
- /// than `Self::ParBlocksSize`.
- #[inline(always)]
- fn proc_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- assert!(blocks.len() < Self::ParBlocksSize::USIZE);
- for block in blocks {
- self.proc_block(block);
- }
- }
+mod backends;
+mod ctx;
- /// Process single block in-place.
- #[inline(always)]
- fn proc_block_inplace(&mut self, block: &mut Block<Self>) {
- self.proc_block(block.into());
- }
+use ctx::{BlockCtx, BlocksCtx};
- /// Process blocks in parallel in-place.
- #[inline(always)]
- fn proc_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
- self.proc_par_blocks(blocks.into());
- }
-
- /// Process buffer of blocks in-place. Length of the buffer MUST be smaller
- /// than `Self::ParBlocksSize`.
- #[inline(always)]
- fn proc_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
- self.proc_tail_blocks(blocks.into());
- }
-}
-
-/// Trait for [`BlockBackend`] users.
-///
-/// This trait is used to define rank-2 closures.
-pub trait BlockClosure: BlockSizeUser {
- /// Execute closure with the provided block cipher backend.
- fn call<B: BlockBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
-}
+pub use backends::{
+ BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherEncBackend, BlockCipherEncClosure,
+ BlockModeDecBackend, BlockModeDecClosure, BlockModeEncBackend, BlockModeEncClosure,
+};
/// Encrypt-only functionality for block ciphers.
-pub trait BlockEncrypt: BlockSizeUser + Sized {
+pub trait BlockCipherEncrypt: BlockSizeUser + Sized {
/// Encrypt data using backend provided to the rank-2 closure.
- fn encrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>);
/// Encrypt single `inout` block.
#[inline]
@@ -116,6 +70,7 @@ pub trait BlockEncrypt: BlockSizeUser + Sized {
/// Encrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
@@ -127,74 +82,12 @@ pub trait BlockEncrypt: BlockSizeUser + Sized {
InOutBuf::new(in_blocks, out_blocks)
.map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
}
-
- /// Pad input and encrypt. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded_inout<'inp, 'out, P: Padding<Self::BlockSize>>(
- &self,
- data: InOutBufReserved<'inp, 'out, u8>,
- ) -> Result<&'out [u8], PadError> {
- let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
- self.encrypt_blocks_inout(buf.get_blocks());
- if let Some(block) = buf.get_tail_block() {
- self.encrypt_block_inout(block);
- }
- Ok(buf.into_out())
- }
-
- /// Pad input and encrypt in-place. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded<'a, P: Padding<Self::BlockSize>>(
- &self,
- buf: &'a mut [u8],
- msg_len: usize,
- ) -> Result<&'a [u8], PadError> {
- let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
- self.encrypt_padded_inout::<P>(buf)
- }
-
- /// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
- &self,
- msg: &[u8],
- out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], PadError> {
- let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
- self.encrypt_padded_inout::<P>(buf)
- }
-
- /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
- #[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
- #[inline]
- fn encrypt_padded_vec<P: Padding<Self::BlockSize>>(&self, msg: &[u8]) -> Vec<u8> {
- let mut out = allocate_out_vec::<Self>(msg.len());
- let len = self
- .encrypt_padded_b2b::<P>(msg, &mut out)
- .expect("enough space for encrypting is allocated")
- .len();
- out.truncate(len);
- out
- }
}
/// Decrypt-only functionality for block ciphers.
-pub trait BlockDecrypt: BlockSizeUser {
+pub trait BlockCipherDecrypt: BlockSizeUser {
/// Decrypt data using backend provided to the rank-2 closure.
- fn decrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>);
/// Decrypt single `inout` block.
#[inline]
@@ -231,6 +124,7 @@ pub trait BlockDecrypt: BlockSizeUser {
/// Decrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
@@ -242,78 +136,17 @@ pub trait BlockDecrypt: BlockSizeUser {
InOutBuf::new(in_blocks, out_blocks)
.map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
}
+}
- /// Decrypt input and unpad it. Returns resulting ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded_inout<'inp, 'out, P: Padding<Self::BlockSize>>(
- &self,
- data: InOutBuf<'inp, 'out, u8>,
- ) -> Result<&'out [u8], UnpadError> {
- let (mut blocks, tail) = data.into_chunks();
- if !tail.is_empty() {
- return Err(UnpadError);
- }
- self.decrypt_blocks_inout(blocks.reborrow());
- P::unpad_blocks(blocks.into_out())
- }
-
- /// Decrypt input and unpad it in-place. Returns resulting ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded<'a, P: Padding<Self::BlockSize>>(
- &self,
- buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
- self.decrypt_padded_inout::<P>(buf.into())
- }
-
- /// Decrypt input and unpad it buffer-to-buffer. Returns resulting
- /// ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
- &self,
- in_buf: &[u8],
- out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
- if out_buf.len() < in_buf.len() {
- return Err(UnpadError);
- }
- let n = in_buf.len();
- // note: `new` always returns `Ok` here
- let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
- self.decrypt_padded_inout::<P>(buf)
+impl<Alg: BlockCipherEncrypt> BlockCipherEncrypt for &Alg {
+ fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>) {
+ Alg::encrypt_with_backend(self, f);
}
+}
- /// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
- /// ciphertext Vec.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
- #[inline]
- fn decrypt_padded_vec<P: Padding<Self::BlockSize>>(
- &self,
- buf: &[u8],
- ) -> Result<Vec<u8>, UnpadError> {
- let mut out = vec![0; buf.len()];
- let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
- out.truncate(len);
- Ok(out)
+impl<Alg: BlockCipherDecrypt> BlockCipherDecrypt for &Alg {
+ fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>) {
+ Alg::decrypt_with_backend(self, f);
}
}
@@ -322,117 +155,138 @@ pub trait BlockDecrypt: BlockSizeUser {
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
-pub trait BlockEncryptMut: BlockSizeUser + Sized {
+pub trait BlockModeEncrypt: BlockSizeUser + Sized {
/// Encrypt data using backend provided to the rank-2 closure.
- fn encrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn encrypt_with_backend(&mut self, f: impl BlockModeEncClosure<BlockSize = Self::BlockSize>);
/// Encrypt single `inout` block.
#[inline]
- fn encrypt_block_inout_mut(&mut self, block: InOut<'_, '_, Block<Self>>) {
- self.encrypt_with_backend_mut(BlockCtx { block });
+ fn encrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt `inout` blocks.
#[inline]
- fn encrypt_blocks_inout_mut(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- self.encrypt_with_backend_mut(BlocksCtx { blocks });
+ fn encrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ self.encrypt_with_backend(BlocksCtx { blocks });
}
/// Encrypt single block in-place.
#[inline]
- fn encrypt_block_mut(&mut self, block: &mut Block<Self>) {
+ fn encrypt_block(&mut self, block: &mut Block<Self>) {
let block = block.into();
- self.encrypt_with_backend_mut(BlockCtx { block });
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt `in_block` and write result to `out_block`.
#[inline]
- fn encrypt_block_b2b_mut(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
+ fn encrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
let block = (in_block, out_block).into();
- self.encrypt_with_backend_mut(BlockCtx { block });
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt blocks in-place.
#[inline]
- fn encrypt_blocks_mut(&mut self, blocks: &mut [Block<Self>]) {
+ fn encrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
let blocks = blocks.into();
- self.encrypt_with_backend_mut(BlocksCtx { blocks });
+ self.encrypt_with_backend(BlocksCtx { blocks });
}
/// Encrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
- fn encrypt_blocks_b2b_mut(
+ fn encrypt_blocks_b2b(
&mut self,
in_blocks: &[Block<Self>],
out_blocks: &mut [Block<Self>],
) -> Result<(), NotEqualError> {
InOutBuf::new(in_blocks, out_blocks)
- .map(|blocks| self.encrypt_with_backend_mut(BlocksCtx { blocks }))
+ .map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
}
/// Pad input and encrypt. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_inout_mut<'inp, 'out, P: Padding<Self::BlockSize>>(
+ fn encrypt_padded_inout<'out, P: Padding>(
mut self,
- data: InOutBufReserved<'inp, 'out, u8>,
+ data: InOutBufReserved<'_, 'out, u8>,
) -> Result<&'out [u8], PadError> {
let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
- self.encrypt_blocks_inout_mut(buf.get_blocks());
+ self.encrypt_blocks_inout(buf.get_blocks());
if let Some(block) = buf.get_tail_block() {
- self.encrypt_block_inout_mut(block);
+ self.encrypt_block_inout(block);
}
Ok(buf.into_out())
}
/// Pad input and encrypt in-place. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &mut [u8],
- msg_len: usize,
- ) -> Result<&[u8], PadError> {
+ fn encrypt_padded<P: Padding>(self, buf: &mut [u8], msg_len: usize) -> Result<&[u8], PadError> {
let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
- self.encrypt_padded_inout_mut::<P>(buf)
+ self.encrypt_padded_inout::<P>(buf)
}
/// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_b2b_mut<'a, P: Padding<Self::BlockSize>>(
+ fn encrypt_padded_b2b<'a, P: Padding>(
self,
msg: &[u8],
out_buf: &'a mut [u8],
) -> Result<&'a [u8], PadError> {
let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
- self.encrypt_padded_inout_mut::<P>(buf)
+ self.encrypt_padded_inout::<P>(buf)
}
- /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
+ /// Pad `msg` with padding algorithm `P`, encrypt it into a newly allocated `Vec`,
+ /// and return the resulting ciphertext vector.
+ ///
+ /// # Panics
+ /// If `NoPadding` is used with a message size that is not a multiple of the cipher block size.
#[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
#[inline]
- fn encrypt_padded_vec_mut<P: Padding<Self::BlockSize>>(self, msg: &[u8]) -> Vec<u8> {
- let mut out = allocate_out_vec::<Self>(msg.len());
- let len = self
- .encrypt_padded_b2b_mut::<P>(msg, &mut out)
- .expect("enough space for encrypting is allocated")
+ fn encrypt_padded_vec<P: Padding>(self, msg: &[u8]) -> Vec<u8> {
+ use block_padding::{NoPadding, ZeroPadding};
+ use common::typenum::Unsigned;
+ use core::any::TypeId;
+
+ let bs = Self::BlockSize::USIZE;
+ let msg_len = msg.len();
+
+ let pad_type_id = TypeId::of::<P>();
+ let buf_blocks_len = if pad_type_id == TypeId::of::<NoPadding>() {
+ assert!(
+ msg_len % bs == 0,
+ "NoPadding is used with a {msg_len}‑byte message,
+ which is not a multiple of the {bs}‑byte cipher block size"
+ );
+ msg_len / bs
+ } else if pad_type_id == TypeId::of::<ZeroPadding>() {
+ msg_len.div_ceil(bs)
+ } else {
+ 1 + msg_len / bs
+ };
+
+ let mut buf = vec![0; bs * buf_blocks_len];
+ let res_len = self
+ .encrypt_padded_b2b::<P>(msg, &mut buf)
+ .expect("`buf` has enough space for encryption")
.len();
- out.truncate(len);
- out
+ buf.truncate(res_len);
+ buf
}
}
@@ -441,281 +295,122 @@ pub trait BlockEncryptMut: BlockSizeUser + Sized {
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
-pub trait BlockDecryptMut: BlockSizeUser + Sized {
+pub trait BlockModeDecrypt: BlockSizeUser + Sized {
/// Decrypt data using backend provided to the rank-2 closure.
- fn decrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn decrypt_with_backend(&mut self, f: impl BlockModeDecClosure<BlockSize = Self::BlockSize>);
/// Decrypt single `inout` block.
#[inline]
- fn decrypt_block_inout_mut(&mut self, block: InOut<'_, '_, Block<Self>>) {
- self.decrypt_with_backend_mut(BlockCtx { block });
+ fn decrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt `inout` blocks.
#[inline]
- fn decrypt_blocks_inout_mut(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- self.decrypt_with_backend_mut(BlocksCtx { blocks });
+ fn decrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ self.decrypt_with_backend(BlocksCtx { blocks });
}
/// Decrypt single block in-place.
#[inline]
- fn decrypt_block_mut(&mut self, block: &mut Block<Self>) {
+ fn decrypt_block(&mut self, block: &mut Block<Self>) {
let block = block.into();
- self.decrypt_with_backend_mut(BlockCtx { block });
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt `in_block` and write result to `out_block`.
#[inline]
- fn decrypt_block_b2b_mut(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
+ fn decrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
let block = (in_block, out_block).into();
- self.decrypt_with_backend_mut(BlockCtx { block });
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt blocks in-place.
#[inline]
- fn decrypt_blocks_mut(&mut self, blocks: &mut [Block<Self>]) {
+ fn decrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
let blocks = blocks.into();
- self.decrypt_with_backend_mut(BlocksCtx { blocks });
+ self.decrypt_with_backend(BlocksCtx { blocks });
}
/// Decrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
- fn decrypt_blocks_b2b_mut(
+ fn decrypt_blocks_b2b(
&mut self,
in_blocks: &[Block<Self>],
out_blocks: &mut [Block<Self>],
) -> Result<(), NotEqualError> {
InOutBuf::new(in_blocks, out_blocks)
- .map(|blocks| self.decrypt_with_backend_mut(BlocksCtx { blocks }))
+ .map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
}
- /// Decrypt input and unpad it. Returns resulting ciphertext slice.
+ /// Decrypt input and unpad it. Returns resulting plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_inout_mut<'inp, 'out, P: Padding<Self::BlockSize>>(
+ fn decrypt_padded_inout<'out, P: Padding>(
mut self,
- data: InOutBuf<'inp, 'out, u8>,
- ) -> Result<&'out [u8], UnpadError> {
+ data: InOutBuf<'_, 'out, u8>,
+ ) -> Result<&'out [u8], block_padding::Error> {
let (mut blocks, tail) = data.into_chunks();
if !tail.is_empty() {
- return Err(UnpadError);
+ return Err(block_padding::Error);
}
- self.decrypt_blocks_inout_mut(blocks.reborrow());
- P::unpad_blocks(blocks.into_out())
+ self.decrypt_blocks_inout(blocks.reborrow());
+ P::unpad_blocks::<Self::BlockSize>(blocks.into_out())
}
- /// Decrypt input and unpad it in-place. Returns resulting ciphertext slice.
+ /// Decrypt input and unpad it in-place. Returns resulting plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &mut [u8],
- ) -> Result<&[u8], UnpadError> {
- self.decrypt_padded_inout_mut::<P>(buf.into())
+ fn decrypt_padded<P: Padding>(self, buf: &mut [u8]) -> Result<&[u8], block_padding::Error> {
+ self.decrypt_padded_inout::<P>(buf.into())
}
/// Decrypt input and unpad it buffer-to-buffer. Returns resulting
- /// ciphertext slice.
+ /// plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_b2b_mut<'a, P: Padding<Self::BlockSize>>(
+ fn decrypt_padded_b2b<'a, P: Padding>(
self,
in_buf: &[u8],
out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
+ ) -> Result<&'a [u8], block_padding::Error> {
if out_buf.len() < in_buf.len() {
- return Err(UnpadError);
+ return Err(block_padding::Error);
}
let n = in_buf.len();
// note: `new` always returns `Ok` here
- let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
- self.decrypt_padded_inout_mut::<P>(buf)
+ let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| block_padding::Error)?;
+ self.decrypt_padded_inout::<P>(buf)
}
/// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
- /// ciphertext Vec.
+ /// plaintext `Vec`.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
#[inline]
- fn decrypt_padded_vec_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &[u8],
- ) -> Result<Vec<u8>, UnpadError> {
+ fn decrypt_padded_vec<P: Padding>(self, buf: &[u8]) -> Result<Vec<u8>, block_padding::Error> {
let mut out = vec![0; buf.len()];
- let len = self.decrypt_padded_b2b_mut::<P>(buf, &mut out)?.len();
+ let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
out.truncate(len);
Ok(out)
}
}
-
-impl<Alg: BlockEncrypt> BlockEncryptMut for Alg {
- fn encrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- self.encrypt_with_backend(f);
- }
-}
-
-impl<Alg: BlockDecrypt> BlockDecryptMut for Alg {
- fn decrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- self.decrypt_with_backend(f);
- }
-}
-
-impl<Alg: BlockCipher> BlockCipher for &Alg {}
-
-impl<Alg: BlockEncrypt> BlockEncrypt for &Alg {
- fn encrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- Alg::encrypt_with_backend(self, f);
- }
-}
-
-impl<Alg: BlockDecrypt> BlockDecrypt for &Alg {
- fn decrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- Alg::decrypt_with_backend(self, f);
- }
-}
-
-/// Closure used in methods which operate over separate blocks.
-struct BlockCtx<'inp, 'out, BS: ArrayLength<u8>> {
- block: InOut<'inp, 'out, Block<Self>>,
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for BlockCtx<'inp, 'out, BS> {
- type BlockSize = BS;
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockClosure for BlockCtx<'inp, 'out, BS> {
- #[inline(always)]
- fn call<B: BlockBackend<BlockSize = BS>>(self, backend: &mut B) {
- backend.proc_block(self.block);
- }
-}
-
-/// Closure used in methods which operate over slice of blocks.
-struct BlocksCtx<'inp, 'out, BS: ArrayLength<u8>> {
- blocks: InOutBuf<'inp, 'out, Block<Self>>,
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for BlocksCtx<'inp, 'out, BS> {
- type BlockSize = BS;
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockClosure for BlocksCtx<'inp, 'out, BS> {
- #[inline(always)]
- fn call<B: BlockBackend<BlockSize = BS>>(self, backend: &mut B) {
- if B::ParBlocksSize::USIZE > 1 {
- let (chunks, tail) = self.blocks.into_chunks();
- for chunk in chunks {
- backend.proc_par_blocks(chunk);
- }
- backend.proc_tail_blocks(tail);
- } else {
- for block in self.blocks {
- backend.proc_block(block);
- }
- }
- }
-}
-
-#[cfg(all(feature = "block-padding", feature = "alloc"))]
-fn allocate_out_vec<BS: BlockSizeUser>(len: usize) -> Vec<u8> {
- let bs = BS::BlockSize::USIZE;
- vec![0; bs * (len / bs + 1)]
-}
-
-/// Implement simple block backend
-#[macro_export]
-macro_rules! impl_simple_block_encdec {
- (
- <$($N:ident$(:$b0:ident$(+$b:ident)*)?),*>
- $cipher:ident, $block_size:ty, $state:ident, $block:ident,
- encrypt: $enc_block:block
- decrypt: $dec_block:block
- ) => {
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockSizeUser for $cipher<$($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockEncrypt for $cipher<$($N),*> {
- fn encrypt_with_backend(&self, f: impl $crate::BlockClosure<BlockSize = $block_size>) {
- struct EncBack<'a, $($N$(:$b0$(+$b)*)?),* >(&'a $cipher<$($N),*>);
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockSizeUser for EncBack<'a, $($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::ParBlocksSizeUser for EncBack<'a, $($N),*> {
- type ParBlocksSize = $crate::consts::U1;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockBackend for EncBack<'a, $($N),*> {
- #[inline(always)]
- fn proc_block(
- &mut self,
- mut $block: $crate::inout::InOut<'_, '_, $crate::Block<Self>>
- ) {
- let $state: &$cipher<$($N),*> = self.0;
- $enc_block
- }
- }
-
- f.call(&mut EncBack(self))
- }
- }
-
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockDecrypt for $cipher<$($N),*> {
- fn decrypt_with_backend(&self, f: impl $crate::BlockClosure<BlockSize = $block_size>) {
- struct DecBack<'a, $($N$(:$b0$(+$b)*)?),* >(&'a $cipher<$($N),*>);
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockSizeUser for DecBack<'a, $($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::ParBlocksSizeUser for DecBack<'a, $($N),*> {
- type ParBlocksSize = $crate::consts::U1;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockBackend for DecBack<'a, $($N),*> {
- #[inline(always)]
- fn proc_block(
- &mut self,
- mut $block: $crate::inout::InOut<'_, '_, $crate::Block<Self>>
- ) {
- let $state: &$cipher<$($N),*> = self.0;
- $dec_block
- }
- }
-
- f.call(&mut DecBack(self))
- }
- }
- };
- (
- $cipher:ident, $block_size:ty, $state:ident, $block:ident,
- encrypt: $enc_block:block
- decrypt: $dec_block:block
- ) => {
- $crate::impl_simple_block_encdec!(
- <> $cipher, $block_size, $state, $block,
- encrypt: $enc_block
- decrypt: $dec_block
- );
- };
-}
### external/vendor/cipher/src/block/backends.rs
@@ -0,0 +1,206 @@
+use common::{Block, BlockSizeUser, ParBlocks, ParBlocksSizeUser, typenum::Unsigned};
+use inout::{InOut, InOutBuf};
+
+/// Trait implemented by block cipher mode encryption backends.
+pub trait BlockCipherEncBackend: ParBlocksSizeUser {
+ /// Encrypt single inout block.
+ fn encrypt_block(&self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Encrypt inout blocks in parallel.
+ #[inline(always)]
+ fn encrypt_par_blocks(&self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.encrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Encrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.encrypt_block(block);
+ }
+ }
+
+ /// Encrypt single block in-place.
+ #[inline(always)]
+ fn encrypt_block_inplace(&self, block: &mut Block<Self>) {
+ self.encrypt_block(block.into());
+ }
+
+ /// Encrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn encrypt_par_blocks_inplace(&self, blocks: &mut ParBlocks<Self>) {
+ self.encrypt_par_blocks(blocks.into());
+ }
+
+ /// Encrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks_inplace(&self, blocks: &mut [Block<Self>]) {
+ self.encrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockCipherEncBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockCipherEncClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockCipherEncBackend<BlockSize = Self::BlockSize>>(self, backend: &B);
+}
+
+/// Trait implemented by block cipher decryption backends.
+pub trait BlockCipherDecBackend: ParBlocksSizeUser {
+ /// Decrypt single inout block.
+ fn decrypt_block(&self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Decrypt inout blocks in parallel.
+ #[inline(always)]
+ fn decrypt_par_blocks(&self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.decrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Decrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.decrypt_block(block);
+ }
+ }
+
+ /// Decrypt single block in-place.
+ #[inline(always)]
+ fn decrypt_block_inplace(&self, block: &mut Block<Self>) {
+ self.decrypt_block(block.into());
+ }
+
+ /// Decrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn decrypt_par_blocks_inplace(&self, blocks: &mut ParBlocks<Self>) {
+ self.decrypt_par_blocks(blocks.into());
+ }
+
+ /// Decrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks_inplace(&self, blocks: &mut [Block<Self>]) {
+ self.decrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockCipherDecBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockCipherDecClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockCipherDecBackend<BlockSize = Self::BlockSize>>(self, backend: &B);
+}
+
+/// Trait implemented by block cipher mode encryption backends.
+pub trait BlockModeEncBackend: ParBlocksSizeUser {
+ /// Encrypt single inout block.
+ fn encrypt_block(&mut self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Encrypt inout blocks in parallel.
+ #[inline(always)]
+ fn encrypt_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.encrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Encrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.encrypt_block(block);
+ }
+ }
+
+ /// Encrypt single block in-place.
+ #[inline(always)]
+ fn encrypt_block_inplace(&mut self, block: &mut Block<Self>) {
+ self.encrypt_block(block.into());
+ }
+
+ /// Encrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn encrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
+ self.encrypt_par_blocks(blocks.into());
+ }
+
+ /// Encrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
+ self.encrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockModeEncBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockModeEncClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockModeEncBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
+}
+
+/// Trait implemented by block cipher mode decryption backends.
+pub trait BlockModeDecBackend: ParBlocksSizeUser {
+ /// Decrypt single inout block.
+ fn decrypt_block(&mut self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Decrypt inout blocks in parallel.
+ #[inline(always)]
+ fn decrypt_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.decrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Decrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.decrypt_block(block);
+ }
+ }
+
+ /// Decrypt single block in-place.
+ #[inline(always)]
+ fn decrypt_block_inplace(&mut self, block: &mut Block<Self>) {
+ self.decrypt_block(block.into());
+ }
+
+ /// Decrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn decrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
+ self.decrypt_par_blocks(blocks.into());
+ }
+
+ /// Decrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
+ self.decrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockModeDecBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockModeDecClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockModeDecBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
+}
### external/vendor/cipher/src/block/ctx.rs
@@ -0,0 +1,120 @@
+use common::{Block, BlockSizeUser, array::ArraySize, typenum::Unsigned};
+use inout::{InOut, InOutBuf};
+
+use super::{
+ BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherEncBackend, BlockCipherEncClosure,
+ BlockModeDecBackend, BlockModeDecClosure, BlockModeEncBackend, BlockModeEncClosure,
+};
+
+/// Closure used in methods which operate over separate blocks.
+pub(super) struct BlockCtx<'inp, 'out, BS: ArraySize> {
+ pub block: InOut<'inp, 'out, Block<Self>>,
+}
+
+impl<BS: ArraySize> BlockSizeUser for BlockCtx<'_, '_, BS> {
+ type BlockSize = BS;
+}
+
+impl<BS: ArraySize> BlockCipherEncClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherEncBackend<BlockSize = BS>>(self, backend: &B) {
+ backend.encrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockCipherDecClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherDecBackend<BlockSize = BS>>(self, backend: &B) {
+ backend.decrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockModeEncClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeEncBackend<BlockSize = BS>>(self, backend: &mut B) {
+ backend.encrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockModeDecClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeDecBackend<BlockSize = BS>>(self, backend: &mut B) {
+ backend.decrypt_block(self.block);
+ }
+}
+/// Closure used in methods which operate over slice of blocks.
+pub(super) struct BlocksCtx<'inp, 'out, BS: ArraySize> {
+ pub blocks: InOutBuf<'inp, 'out, Block<Self>>,
+}
+
+impl<BS: ArraySize> BlockSizeUser for BlocksCtx<'_, '_, BS> {
+ type BlockSize = BS;
+}
+
+impl<BS: ArraySize> BlockCipherEncClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherEncBackend<BlockSize = BS>>(self, backend: &B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.encrypt_par_blocks(chunk);
+ }
+ backend.encrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.encrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockCipherDecClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherDecBackend<BlockSize = BS>>(self, backend: &B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.decrypt_par_blocks(chunk);
+ }
+ backend.decrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.decrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockModeEncClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeEncBackend<BlockSize = BS>>(self, backend: &mut B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.encrypt_par_blocks(chunk);
+ }
+ backend.encrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.encrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockModeDecClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeDecBackend<BlockSize = BS>>(self, backend: &mut B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.decrypt_par_blocks(chunk);
+ }
+ backend.decrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.decrypt_block(block);
+ }
+ }
+ }
+}
### external/vendor/cipher/src/dev.rs
@@ -1,2 +1,7 @@
-mod block;
-mod stream;
+//! Development-related functionality
+mod block_bench;
+pub mod block_cipher;
+pub mod block_mode;
+pub mod stream;
+
+pub use blobby;
### external/vendor/cipher/src/dev/block.rs
@@ -1,389 +0,0 @@
-//! Development-related functionality
-
-pub use blobby;
-
-/// Define block cipher test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_cipher_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob3Iterator, generic_array::GenericArray, typenum::Unsigned,
- BlockDecryptMut, BlockEncryptMut, BlockSizeUser, KeyInit,
- };
-
- fn run_test(key: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- let mut state = <$cipher as KeyInit>::new_from_slice(key).unwrap();
-
- let mut block = GenericArray::clone_from_slice(pt);
- state.encrypt_block_mut(&mut block);
- if ct != block.as_slice() {
- return false;
- }
-
- state.decrypt_block_mut(&mut block);
- if pt != block.as_slice() {
- return false;
- }
-
- true
- }
-
- fn run_par_test(key: &[u8], pt: &[u8]) -> bool {
- type Block = cipher::Block<$cipher>;
-
- let mut state = <$cipher as KeyInit>::new_from_slice(key).unwrap();
-
- let block = Block::clone_from_slice(pt);
- let mut blocks1 = vec![block; 101];
- for (i, b) in blocks1.iter_mut().enumerate() {
- *b = block;
- b[0] = b[0].wrapping_add(i as u8);
- }
- let mut blocks2 = blocks1.clone();
-
- // check that `encrypt_blocks` and `encrypt_block`
- // result in the same ciphertext
- state.encrypt_blocks_mut(&mut blocks1);
- for b in blocks2.iter_mut() {
- state.encrypt_block_mut(b);
- }
- if blocks1 != blocks2 {
- return false;
- }
-
- // check that `encrypt_blocks` and `encrypt_block`
- // result in the same plaintext
- state.decrypt_blocks_mut(&mut blocks1);
- for b in blocks2.iter_mut() {
- state.decrypt_block_mut(b);
- }
- if blocks1 != blocks2 {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob3Iterator::new(data).unwrap().enumerate() {
- let [key, pt, ct] = row.unwrap();
- if !run_test(key, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, pt, ct,
- );
- }
-
- // test parallel blocks encryption/decryption
- if !run_par_test(key, pt) {
- panic!(
- "\n\
- Failed parallel test №{}\n\
- key:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define block mode encryption test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_mode_enc_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob4Iterator, generic_array::GenericArray, inout::InOutBuf,
- typenum::Unsigned, BlockEncryptMut, BlockSizeUser, KeyIvInit,
- };
-
- fn run_test(key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- assert_eq!(pt.len(), ct.len());
- // test block-by-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
-
- let mut out = vec![0u8; ct.len()];
- let mut buf = InOutBuf::new(pt, &mut out).unwrap();
- let (blocks, tail) = buf.reborrow().into_chunks();
- assert_eq!(tail.len(), 0);
- for block in blocks {
- state.encrypt_block_inout_mut(block);
- }
- if buf.get_out() != ct {
- return false;
- }
-
- // test multi-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
- buf.get_out().iter_mut().for_each(|b| *b = 0);
- let (blocks, _) = buf.reborrow().into_chunks();
- state.encrypt_blocks_inout_mut(blocks);
- if buf.get_out() != ct {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() {
- let [key, iv, pt, ct] = row.unwrap();
- if !run_test(key, iv, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- iv:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, iv, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define block mode decryption test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_mode_dec_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob4Iterator, generic_array::GenericArray, inout::InOutBuf,
- typenum::Unsigned, BlockDecryptMut, BlockSizeUser, KeyIvInit,
- };
-
- fn run_test(key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- assert_eq!(pt.len(), ct.len());
- // test block-by-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
-
- let mut out = vec![0u8; pt.len()];
- let mut buf = InOutBuf::new(ct, &mut out).unwrap();
- let (blocks, tail) = buf.reborrow().into_chunks();
- assert_eq!(tail.len(), 0);
- for block in blocks {
- state.decrypt_block_inout_mut(block);
- }
- if buf.get_out() != pt {
- return false;
- }
-
- // test multi-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
- buf.get_out().iter_mut().for_each(|b| *b = 0);
- let (blocks, _) = buf.reborrow().into_chunks();
- state.decrypt_blocks_inout_mut(blocks);
- if buf.get_out() != pt {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() {
- let [key, iv, pt, ct] = row.unwrap();
- if !run_test(key, iv, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- iv:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, iv, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define `IvState` test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! iv_state_test {
- ($name:ident, $cipher:ty, encrypt $(,)?) => {
- $crate::iv_state_test!($name, $cipher, encrypt_blocks_mut);
- };
- ($name:ident, $cipher:ty, decrypt $(,)?) => {
- $crate::iv_state_test!($name, $cipher, decrypt_blocks_mut);
- };
- ($name:ident, $cipher:ty, apply_ks $(,)?) => {
- $crate::iv_state_test!($name, $cipher, apply_keystream_blocks);
- };
- ($name:ident, $cipher:ty, $method:ident $(,)?) => {
- #[test]
- fn $name() {
- use cipher::*;
-
- let mut blocks = [Block::<$cipher>::default(); 32];
-
- for (i, block) in blocks.iter_mut().enumerate() {
- for (j, b) in block.iter_mut().enumerate() {
- *b = (i + j) as u8;
- }
- }
-
- let mut key = Key::<$cipher>::default();
- let mut iv = Iv::<$cipher>::default();
- key.iter_mut().for_each(|b| *b = 0x42);
- iv.iter_mut().for_each(|b| *b = 0x24);
-
- let mut cipher = <$cipher>::new(&key, &iv);
- let mut target = blocks.clone();
- cipher.$method(&mut target);
-
- for i in 0..32 {
- let mut blocks = blocks.clone();
- let (b1, b2) = blocks.split_at_mut(i);
- let mut cipher1 = <$cipher>::new(&key, &iv);
- cipher1.$method(b1);
- let temp_iv = cipher1.iv_state();
- let mut cipher2 = <$cipher>::new(&key, &temp_iv);
- cipher2.$method(b2);
- assert_eq!(blocks, target);
- }
- }
- };
-}
-
-/// Define block encryptor benchmark
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_encryptor_bench {
- (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_encryptor_bench!(
- {
- use $crate::KeyInit;
- let key = test::black_box(Default::default());
- <$cipher>::new(&key)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_encryptor_bench!(
- {
- use $crate::KeyIvInit;
- let key = test::black_box(Default::default());
- let iv = test::black_box(Default::default());
- <$cipher>::new(&key, &iv)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- #[bench]
- pub fn $block_name(bh: &mut test::Bencher) {
- use cipher::BlockEncryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- for block in blocks.iter_mut() {
- cipher.encrypt_block_mut(block);
- }
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
-
- #[bench]
- pub fn $blocks_name(bh: &mut test::Bencher) {
- use cipher::BlockEncryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- cipher.encrypt_blocks_mut(&mut blocks);
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
- };
-}
-
-/// Define block decryptor benchmark
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_decryptor_bench {
- (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_decryptor_bench!(
- {
- use $crate::KeyInit;
- let key = test::black_box(Default::default());
- <$cipher>::new(&key)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_decryptor_bench!(
- {
- use $crate::KeyIvInit;
- let key = test::black_box(Default::default());
- let iv = test::black_box(Default::default());
- <$cipher>::new(&key, &iv)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- #[bench]
- pub fn $block_name(bh: &mut test::Bencher) {
- use cipher::BlockDecryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- for block in blocks.iter_mut() {
- cipher.decrypt_block_mut(block);
- }
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
-
- #[bench]
- pub fn $blocks_name(bh: &mut test::Bencher) {
- use cipher::BlockDecryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- cipher.decrypt_blocks_mut(&mut blocks);
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
- };
-}
### external/vendor/cipher/src/dev/block_bench.rs
@@ -0,0 +1,125 @@
+/// Define block encryptor benchmark
+#[macro_export]
+macro_rules! block_encryptor_bench {
+ (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ $crate::block_encryptor_bench!(
+ {
+ use $crate::KeyInit;
+ let key = test::black_box(Default::default());
+ <$cipher>::new(&key)
+ },
+ $cipher,
+ $block_name,
+ $blocks_name,
+ );
+ };
+ (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ $crate::block_encryptor_bench!(
+ {
+ use $crate::KeyIvInit;
+ let key = test::black_box(Default::default());
+ let iv = test::black_box(Default::default());
+ <$cipher>::new(&key, &iv)
+ },
+ $cipher,
+ $block_name,
+ $blocks_name,
+ );
+ };
+ ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ #[bench]
+ pub fn $block_name(bh: &mut test::Bencher) {
+ #[allow(unused)]
+ use $crate::{BlockCipherEncrypt, BlockModeEncrypt};
+
+ let mut cipher = $init;
+ let mut blocks = vec![Default::default(); 1024];
+
+ bh.iter(|| {
+ for block in blocks.iter_mut() {
+ cipher.encrypt_block(block);
+ }
+ test::black_box(&blocks);
+ });
+ bh.bytes = (blocks.len() * blocks[0].len()) as u64;
+ }
+
+ #[bench]
+ pub fn $blocks_name(bh: &mut test::Bencher) {
+ #[allow(unused)]
+ use $crate::{BlockCipherEncrypt, BlockModeEncrypt};
+
+ let mut cipher = $init;
+ let mut blocks = vec![Default::default(); 1024];
+
+ bh.iter(|| {
+ cipher.encrypt_blocks(&mut blocks);
+ test::black_box(&blocks);
+ });
+ bh.bytes = (blocks.len() * blocks[0].len()) as u64;
+ }
+ };
+}
+
+/// Define block decryptor benchmark
+#[macro_export]
+macro_rules! block_decryptor_bench {
+ (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ $crate::block_decryptor_bench!(
+ {
+ use $crate::KeyInit;
+ let key = test::black_box(Default::default());
+ <$cipher>::new(&key)
+ },
+ $cipher,
+ $block_name,
+ $blocks_name,
+ );
+ };
+ (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ $crate::block_decryptor_bench!(
+ {
+ use $crate::KeyIvInit;
+ let key = test::black_box(Default::default());
+ let iv = test::black_box(Default::default());
+ <$cipher>::new(&key, &iv)
+ },
+ $cipher,
+ $block_name,
+ $blocks_name,
+ );
+ };
+ ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
+ #[bench]
+ pub fn $block_name(bh: &mut test::Bencher) {
+ #[allow(unused)]
+ use $crate::{BlockCipherDecrypt, BlockModeDecrypt};
+
+ let mut cipher = $init;
+ let mut blocks = vec![Default::default(); 1024];
+
+ bh.iter(|| {
+ for block in blocks.iter_mut() {
+ cipher.decrypt_block(block);
+ }
+ test::black_box(&blocks);
+ });
+ bh.bytes = (blocks.len() * blocks[0].len()) as u64;
+ }
+
+ #[bench]
+ pub fn $blocks_name(bh: &mut test::Bencher) {
+ #[allow(unused)]
+ use $crate::{BlockCipherDecrypt, BlockModeDecrypt};
+
+ let mut cipher = $init;
+ let mut blocks = vec![Default::default(); 1024];
+
+ bh.iter(|| {
+ cipher.decrypt_blocks(&mut blocks);
+ test::black_box(&blocks);
+ });
+ bh.bytes = (blocks.len() * blocks[0].len()) as u64;
+ }
+ };
+}
### external/vendor/cipher/src/dev/block_cipher.rs
@@ -0,0 +1,168 @@
+//! Development-related functionality for block ciphers
+
+#![allow(clippy::missing_errors_doc)]
+
+use crate::{Block, BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};
+
+/// Block cipher test vector
+#[derive(Debug, Clone, Copy)]
+pub struct TestVector {
+ /// Initialization key
+ pub key: &'static [u8],
+ /// Plaintext block
+ pub plaintext: &'static [u8],
+ /// Ciphertext block
+ pub ciphertext: &'static [u8],
+}
+
+fn encrypt_test_inner<C: BlockCipherEncrypt>(
+ cipher: &C,
+ pt: Block<C>,
+ ct: Block<C>,
+) -> Result<(), &'static str> {
+ let mut block = pt.clone();
+ cipher.encrypt_block(&mut block);
+ if block != ct {
+ return Err("single block encryption failure");
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ let mut blocks1: [Block<C>; 101] = core::array::from_fn(|i| {
+ let mut block = pt.clone();
+ block[0] ^= i as u8;
+ block
+ });
+ let mut blocks2 = blocks1.clone();
+
+ // Check that `encrypt_blocks` and `encrypt_block` result in the same ciphertext
+ cipher.encrypt_blocks(&mut blocks1);
+ for b in blocks2.iter_mut() {
+ cipher.encrypt_block(b);
+ }
+ if blocks1 != blocks2 {
+ return Err("multi-block encryption failure");
+ }
+
+ Ok(())
+}
+
+fn decrypt_test_inner<C: BlockCipherDecrypt>(
+ cipher: &C,
+ pt: Block<C>,
+ ct: Block<C>,
+) -> Result<(), &'static str> {
+ let mut block = ct.clone();
+ cipher.decrypt_block(&mut block);
+ if block != pt {
+ return Err("single block decryption failure");
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ let mut blocks1: [Block<C>; 101] = core::array::from_fn(|i| {
+ let mut block = ct.clone();
+ block[0] ^= i as u8;
+ block
+ });
+ let mut blocks2 = blocks1.clone();
+
+ // Check that `encrypt_blocks` and `encrypt_block` result in the same ciphertext
+ cipher.decrypt_blocks(&mut blocks1);
+ for b in blocks2.iter_mut() {
+ cipher.decrypt_block(b);
+ }
+ if blocks1 != blocks2 {
+ return Err("multi-block decryption failure");
+ }
+ Ok(())
+}
+
+/// Block cipher encryption and decryption test
+pub fn encrypt_decrypt_test<C: BlockCipherEncrypt + BlockCipherDecrypt + KeyInit>(
+ tv: &TestVector,
+) -> Result<(), &'static str> {
+ let Ok(cipher) = C::new_from_slice(tv.key) else {
+ return Err("cipher initialization failure");
+ };
+
+ let Ok(pt) = Block::<C>::try_from(tv.plaintext) else {
+ return Err("unexpected size of plaintext block");
+ };
+ let Ok(ct) = Block::<C>::try_from(tv.ciphertext) else {
+ return Err("unexpected size of ciphertext block");
+ };
+
+ encrypt_test_inner(&cipher, pt.clone(), ct.clone())?;
+ decrypt_test_inner(&cipher, pt, ct)
+}
+
+/// Block cipher encryption test
+pub fn encrypt_test<C: BlockCipherEncrypt + KeyInit>(tv: &TestVector) -> Result<(), &'static str> {
+ let Ok(cipher) = C::new_from_slice(tv.key) else {
+ return Err("cipher initialization failure");
+ };
+
+ let Ok(pt) = Block::<C>::try_from(tv.plaintext) else {
+ return Err("unexpected size of plaintext block");
+ };
+ let Ok(ct) = Block::<C>::try_from(tv.ciphertext) else {
+ return Err("unexpected size of ciphertext block");
+ };
+
+ encrypt_test_inner(&cipher, pt, ct)
+}
+
+/// Block cipher encryption test
+pub fn decrypt_test<C: BlockCipherDecrypt + KeyInit>(tv: &TestVector) -> Result<(), &'static str> {
+ let Ok(cipher) = C::new_from_slice(tv.key) else {
+ return Err("cipher initialization failure");
+ };
+ let Ok(pt) = Block::<C>::try_from(tv.plaintext) else {
+ return Err("unexpected size of plaintext block");
+ };
+ let Ok(ct) = Block::<C>::try_from(tv.ciphertext) else {
+ return Err("unexpected size of ciphertext block");
+ };
+ decrypt_test_inner(&cipher, pt, ct)
+}
+
+/// Define block cipher test
+#[macro_export]
+macro_rules! block_cipher_test {
+ // Encrypt/decrypt test with matching test and file names
+ ($name:ident, $cipher:ty $(,)?) => {
+ $crate::block_cipher_test!($name, stringify!($name), $cipher);
+ };
+ // Encrypt/decrypt test with custom test name
+ ($test_name:ident, $file_name:expr, $cipher:ty $(,)?) => {
+ $crate::block_cipher_test!($test_name, $file_name, $cipher, encrypt_decrypt_test);
+ };
+ // Test with custom test function and matching test and file names
+ ($name:ident, $cipher:ty, $test_fn:ident $(,)?) => {
+ $crate::block_cipher_test!($name, stringify!($name), $cipher, $test_fn);
+ };
+ // Test with custom test function and test name
+ ($test_name:ident, $file_name:expr, $cipher:ty, $test_fn:ident $(,)?) => {
+ #[test]
+ fn $test_name() {
+ use $crate::dev::block_cipher::TestVector;
+
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $file_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ if let Err(reason) = $crate::dev::block_cipher::$test_fn::<$cipher>(tv) {
+ panic!(
+ "\n\
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n",
+ );
+ }
+ }
+ }
+ };
+}
### external/vendor/cipher/src/dev/block_mode.rs
@@ -0,0 +1,176 @@
+//! Development-related functionality for block modes
+
+#![allow(clippy::missing_errors_doc)]
+
+use crate::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit, inout::InOutBuf};
+
+const MAX_MSG_LEN: usize = 1 << 12;
+
+/// Block mode test vector
+#[derive(Debug, Clone, Copy)]
+pub struct TestVector {
+ /// Initialization key
+ pub key: &'static [u8],
+ /// Initialization vector
+ pub iv: &'static [u8],
+ /// Plaintext block
+ pub plaintext: &'static [u8],
+ /// Ciphertext block
+ pub ciphertext: &'static [u8],
+}
+
+/// Block mode encryption test
+pub fn encrypt<C: BlockModeEncrypt + KeyIvInit>(tv: &TestVector) -> Result<(), &'static str> {
+ let mut buf = [0u8; MAX_MSG_LEN];
+ let Some(out) = buf.get_mut(..tv.ciphertext.len()) else {
+ return Err("ciphertext is bigger than MAX_MSG_LEN bytes");
+ };
+ let Ok(mut buf) = InOutBuf::new(tv.plaintext, out) else {
+ return Err("plaintext/ciphertext length mismatch");
+ };
+ let (blocks, tail) = buf.reborrow().into_chunks();
+ if !tail.is_empty() {
+ return Err("plaintext/ciphertext length is not multiple of block size");
+ }
+
+ let Ok(mut cipher) = C::new_from_slices(tv.key, tv.iv) else {
+ return Err("cipher initialization failure");
+ };
+ for block in blocks {
+ cipher.encrypt_block_inout(block);
+ }
+ if buf.get_out() != tv.ciphertext {
+ return Err("single block encryption failure");
+ }
+
+ // test multi-block processing
+ let Ok(mut cipher) = C::new_from_slices(tv.key, tv.iv) else {
+ return Err("cipher initialization failure");
+ };
+ buf.get_out().fill(0);
+ let (blocks, _) = buf.reborrow().into_chunks();
+ cipher.encrypt_blocks_inout(blocks);
+ if buf.get_out() != tv.ciphertext {
+ return Err("multi-block encryption failure");
+ }
+ Ok(())
+}
+
+/// Block mode decryption test
+pub fn decrypt<C: BlockModeDecrypt + KeyIvInit>(tv: &TestVector) -> Result<(), &'static str> {
+ let mut buf = [0u8; MAX_MSG_LEN];
+ let Some(out) = buf.get_mut(..tv.plaintext.len()) else {
+ return Err("plaintext is bigger than MAX_MSG_LEN bytes");
+ };
+ let Ok(mut buf) = InOutBuf::new(tv.ciphertext, out) else {
+ return Err("plaintext/ciphertext length mismatch");
+ };
+ let (blocks, tail) = buf.reborrow().into_chunks();
+ if !tail.is_empty() {
+ return Err("plaintext/ciphertext length is not multiple of block size");
+ }
+
+ let Ok(mut cipher) = C::new_from_slices(tv.key, tv.iv) else {
+ return Err("cipher initialization failure");
+ };
+ for block in blocks {
+ cipher.decrypt_block_inout(block);
+ }
+ if buf.get_out() != tv.plaintext {
+ return Err("single block decryption failure");
+ }
+
+ // test multi-block processing
+ let Ok(mut cipher) = C::new_from_slices(tv.key, tv.iv) else {
+ return Err("cipher initialization failure");
+ };
+ buf.get_out().fill(0);
+ let (blocks, _) = buf.reborrow().into_chunks();
+ cipher.decrypt_blocks_inout(blocks);
+ if buf.get_out() != tv.plaintext {
+ return Err("multi-block decryption failure");
+ }
+ Ok(())
+}
+
+/// Define block mode test
+#[macro_export]
+macro_rules! block_mode_test {
+ // Test with matching test and file names
+ ($name:ident, $cipher:ty, $test_fn:ident $(,)?) => {
+ $crate::block_cipher_test!($name, stringify!($name), $cipher);
+ };
+ // Test with custom test function and test name
+ ($test_name:ident, $file_name:expr, $cipher:ty, $test_fn:ident $(,)?) => {
+ #[test]
+ fn $test_name() {
+ use $crate::dev::block_mode::TestVector;
+
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $file_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, iv, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ if let Err(reason) = $crate::dev::block_mode::$test_fn::<$cipher>(tv) {
+ panic!(
+ "\n\
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n",
+ );
+ }
+ }
+ }
+ };
+}
+
+/// Define `IvState` test
+#[macro_export]
+macro_rules! iv_state_test {
+ ($name:ident, $cipher:ty, encrypt $(,)?) => {
+ $crate::iv_state_test!($name, $cipher, encrypt_blocks);
+ };
+ ($name:ident, $cipher:ty, decrypt $(,)?) => {
+ $crate::iv_state_test!($name, $cipher, decrypt_blocks);
+ };
+ ($name:ident, $cipher:ty, apply_ks $(,)?) => {
+ $crate::iv_state_test!($name, $cipher, apply_keystream_blocks);
+ };
+ ($name:ident, $cipher:ty, $method:ident $(,)?) => {
+ #[test]
+ fn $name() {
+ use cipher::*;
+
+ let mut blocks = [Block::<$cipher>::default(); 32];
+
+ for (i, block) in blocks.iter_mut().enumerate() {
+ for (j, b) in block.iter_mut().enumerate() {
+ *b = (i + j) as u8;
+ }
+ }
+
+ let mut key = Key::<$cipher>::default();
+ let mut iv = Iv::<$cipher>::default();
+ key.iter_mut().for_each(|b| *b = 0x42);
+ iv.iter_mut().for_each(|b| *b = 0x24);
+
+ let mut cipher = <$cipher>::new(&key, &iv);
+ let mut target = blocks.clone();
+ cipher.$method(&mut target);
+
+ for i in 0..32 {
+ let mut blocks = blocks.clone();
+ let (b1, b2) = blocks.split_at_mut(i);
+ let mut cipher1 = <$cipher>::new(&key, &iv);
+ cipher1.$method(b1);
+ let temp_iv = cipher1.iv_state();
+ let mut cipher2 = <$cipher>::new(&key, &temp_iv);
+ cipher2.$method(b2);
+ assert_eq!(blocks, target);
+ }
+ }
+ };
+}
### external/vendor/cipher/src/dev/stream.rs
@@ -1,35 +1,73 @@
-//! Development-related functionality
+//! Development-related functionality for stream ciphers
+
+#![allow(clippy::missing_errors_doc)]
+
+use crate::{KeyIvInit, StreamCipher};
+
+/// Stream cipher test vector
+#[derive(Clone, Copy, Debug)]
+pub struct TestVector {
+ /// Initialization key
+ pub key: &'static [u8],
+ /// Initialization vector
+ pub iv: &'static [u8],
+ /// Plaintext
+ pub plaintext: &'static [u8],
+ /// Ciphertext
+ pub ciphertext: &'static [u8],
+}
+
+/// Run stream cipher test
+pub fn stream_cipher_test<C: KeyIvInit + StreamCipher>(
+ tv: &TestVector,
+) -> Result<(), &'static str> {
+ if tv.plaintext.len() != tv.ciphertext.len() {
+ return Err("mismatch of plaintext and ciphertext lengths");
+ }
+ let mut buf = [0u8; 256];
+ for chunk_len in 1..256 {
+ let Ok(mut mode) = C::new_from_slices(tv.key, tv.iv) else {
+ return Err("cipher initialization failure");
+ };
+ let pt_chunks = tv.plaintext.chunks(chunk_len);
+ let ct_chunks = tv.ciphertext.chunks(chunk_len);
+ for (pt_chunk, ct_chunk) in pt_chunks.zip(ct_chunks) {
+ let buf = &mut buf[..pt_chunk.len()];
+ buf.copy_from_slice(pt_chunk);
+ mode.apply_keystream(buf);
+
+ if buf != ct_chunk {
+ return Err("ciphertext mismatch");
+ }
+ }
+ }
+ Ok(())
+}
/// Test core functionality of synchronous stream cipher
#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
macro_rules! stream_cipher_test {
($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
#[test]
fn $name() {
- use cipher::generic_array::GenericArray;
- use cipher::{blobby::Blob4Iterator, KeyIvInit, StreamCipher};
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() {
- let [key, iv, pt, ct] = row.unwrap();
-
- for chunk_n in 1..256 {
- let mut mode = <$cipher>::new_from_slices(key, iv).unwrap();
- let mut pt = pt.to_vec();
- for chunk in pt.chunks_mut(chunk_n) {
- mode.apply_keystream(chunk);
- }
- if pt != &ct[..] {
- panic!(
- "Failed main test №{}, chunk size: {}\n\
- key:\t{:?}\n\
- iv:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, chunk_n, key, iv, pt, ct,
- );
- }
+ use $crate::dev::stream::TestVector;
+
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $test_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, iv, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ let res = $crate::dev::stream::stream_cipher_test::<$cipher>(tv);
+ if let Err(reason) = res {
+ panic!(
+ "\n\
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n"
+ );
}
}
}
@@ -38,12 +76,11 @@ macro_rules! stream_cipher_test {
/// Test stream synchronous stream cipher seeking capabilities
#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
macro_rules! stream_cipher_seek_test {
($name:ident, $cipher:ty) => {
#[test]
fn $name() {
- use cipher::generic_array::GenericArray;
+ use cipher::array::Array;
use cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
fn get_cipher() -> $cipher {
@@ -91,7 +128,6 @@ macro_rules! stream_cipher_seek_test {
/// Create stream cipher benchmarks
#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
macro_rules! stream_cipher_bench {
(
$cipher:ty;
@@ -115,8 +151,7 @@ macro_rules! stream_cipher_bench {
Init: {
use $crate::KeyInit;
let key = test::black_box(Default::default());
- let iv = test::black_box(Default::default());
- <$cipher>::new(&key, &iv)
+ <$cipher>::new(&key)
};
$($name $bs;)*
);
### external/vendor/cipher/src/lib.rs
@@ -1,60 +1,40 @@
-//! This crate defines a set of traits which describe the functionality of
-//! [block ciphers][1], [block modes][2], and [stream ciphers][3].
-//!
-//! [1]: https://en.wikipedia.org/wiki/Block_cipher
-//! [2]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
-//! [3]: https://en.wikipedia.org/wiki/Stream_cipher
-
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
-
-pub use crypto_common;
-pub use inout;
+#![forbid(unsafe_code)]
-#[cfg(all(feature = "block-padding", feature = "alloc"))]
+#[cfg(feature = "alloc")]
extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
-
+#[cfg(feature = "dev")]
+pub use blobby;
+pub use common;
#[cfg(feature = "rand_core")]
-#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
-pub use crypto_common::rand_core;
-
+pub use common::rand_core;
+pub use inout;
#[cfg(feature = "block-padding")]
-#[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
pub use inout::block_padding;
-
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
pub use zeroize;
+pub mod block;
#[cfg(feature = "dev")]
-pub use blobby;
-
-mod block;
-#[cfg(feature = "dev")]
-mod dev;
-mod errors;
-mod stream;
-mod stream_core;
-mod stream_wrapper;
-
-pub use crate::{block::*, errors::*, stream::*, stream_core::*, stream_wrapper::*};
-pub use crypto_common::{
- generic_array,
+pub mod dev;
+pub mod stream;
+pub mod tweak;
+
+pub use block::*;
+pub use stream::*;
+pub use tweak::*;
+
+pub use common::{
+ AlgorithmName, Block, BlockSizeUser, InnerIvInit, InvalidLength, Iv, IvSizeUser, IvState, Key,
+ KeyInit, KeyIvInit, KeySizeUser, ParBlocks, ParBlocksSizeUser, SetIvState,
+ array::{self, Array},
typenum::{self, consts},
- AlgorithmName, Block, InnerIvInit, InvalidLength, Iv, IvSizeUser, Key, KeyInit, KeyIvInit,
- KeySizeUser, ParBlocks, ParBlocksSizeUser,
};
-
-/// Trait for loading current IV state.
-pub trait IvState: IvSizeUser {
- /// Returns current IV state.
- fn iv_state(&self) -> Iv<Self>;
-}
+pub use inout::{InOut, InOutBuf};
### external/vendor/cipher/src/stream.rs
@@ -1,110 +1,177 @@
//! Traits which define functionality of stream ciphers.
//!
-//! See [RustCrypto/stream-ciphers](https://github.com/RustCrypto/stream-ciphers)
+//! See the [RustCrypto/stream-ciphers](https://github.com/RustCrypto/stream-ciphers) repository
//! for ciphers implementation.
-use crate::errors::{OverflowError, StreamCipherError};
-use crate::stream_core::Counter;
-use crate::{Block, BlockDecryptMut, BlockEncryptMut};
use inout::{InOutBuf, NotEqualError};
-/// Marker trait for block-level asynchronous stream ciphers
-pub trait AsyncStreamCipher: Sized {
- /// Encrypt data using `InOutBuf`.
- fn encrypt_inout(mut self, data: InOutBuf<'_, '_, u8>)
- where
- Self: BlockEncryptMut,
- {
- let (blocks, mut tail) = data.into_chunks();
- self.encrypt_blocks_inout_mut(blocks);
- let n = tail.len();
- if n != 0 {
- let mut block = Block::<Self>::default();
- block[..n].copy_from_slice(tail.get_in());
- self.encrypt_block_mut(&mut block);
- tail.get_out().copy_from_slice(&block[..n]);
- }
- }
+mod core_api;
+mod errors;
+#[cfg(feature = "stream-wrapper")]
+mod wrapper;
- /// Decrypt data using `InOutBuf`.
- fn decrypt_inout(mut self, data: InOutBuf<'_, '_, u8>)
- where
- Self: BlockDecryptMut,
- {
- let (blocks, mut tail) = data.into_chunks();
- self.decrypt_blocks_inout_mut(blocks);
- let n = tail.len();
- if n != 0 {
- let mut block = Block::<Self>::default();
- block[..n].copy_from_slice(tail.get_in());
- self.decrypt_block_mut(&mut block);
- tail.get_out().copy_from_slice(&block[..n]);
- }
- }
- /// Encrypt data in place.
- fn encrypt(self, buf: &mut [u8])
- where
- Self: BlockEncryptMut,
- {
- self.encrypt_inout(buf.into());
- }
+pub use core_api::{
+ StreamCipherBackend, StreamCipherClosure, StreamCipherCore, StreamCipherCounter,
+ StreamCipherSeekCore,
+};
+pub use errors::{OverflowError, StreamCipherError};
+#[cfg(feature = "stream-wrapper")]
+pub use wrapper::StreamCipherCoreWrapper;
- /// Decrypt data in place.
- fn decrypt(self, buf: &mut [u8])
- where
- Self: BlockDecryptMut,
- {
- self.decrypt_inout(buf.into());
- }
+/// Stream cipher trait.
+///
+/// This trait applies only to synchronous stream ciphers, which generate a keystream and
+/// XOR data with it during both encryption and decryption. Therefore, instead of separate methods
+/// for encryption and decryption, this trait provides methods for keystream application.
+///
+/// # Notes on Keystream Repetition
+/// All stream ciphers have a finite state, so the generated keystream inevitably repeats itself,
+/// making the cipher vulnerable to chosen plaintext attack. Typically, the repetition period is
+/// astronomically large, rendering keystream repetition impossible to encounter in practice.
+///
+/// However, counter-based stream ciphers allow seeking across the keystream, and some also use
+/// small counters (e.g. 32 bits). This can result in triggering keystream repetition in practice.
+///
+/// To guard against this, methods either panic (e.g. [`StreamCipher::apply_keystream`]) or
+/// return [`StreamCipherError`] (e.g. [`StreamCipher::try_apply_keystream`]) when
+/// keystream repetition occurs. We also provide a number of "unchecked" methods
+/// (e.g. [`StreamCipher::unchecked_apply_keystream`]), but they should be used with extreme care.
+///
+/// For efficiency reasons, the check for keystream repetition is typically implemented by
+/// forbidding the generation of the last keystream block in both the keystream application methods
+/// and the seeking methods defined in the [`StreamCipherSeek`] trait.
+pub trait StreamCipher {
+ /// Check that the cipher can generate a keystream with a length of `data_len` bytes.
+ ///
+ /// # Errors
+ /// Returns [`StreamCipherError`] in the event it cannot.
+ fn check_remaining(&self, data_len: usize) -> Result<(), StreamCipherError>;
+
+ /// Apply keystream to `inout` without checking for keystream repetition.
+ ///
+ /// <div><class = "warning">
+ /// <b>WARNING<b>
+ ///
+ /// This method should be used with extreme caution! Triggering keystream repetition can expose
+ /// the stream cipher to chosen plaintext attacks.
+ /// </div>
+ fn unchecked_apply_keystream_inout(&mut self, buf: InOutBuf<'_, '_, u8>);
+
+ /// Apply keystream to `buf` without checking for keystream repetition.
+ ///
+ /// <div><class = "warning">
+ /// <b>WARNING<b>
+ ///
+ /// This method should be used with extreme caution! Triggering keystream repetition can expose
+ /// the stream cipher to chosen plaintext attacks.
+ /// </div>
+ fn unchecked_write_keystream(&mut self, buf: &mut [u8]);
- /// Encrypt data from buffer to buffer.
- fn encrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), NotEqualError>
- where
- Self: BlockEncryptMut,
- {
- InOutBuf::new(in_buf, out_buf).map(|b| self.encrypt_inout(b))
+ /// Apply keystream to data behind `buf` without checking for keystream repetition.
+ ///
+ /// <div><class = "warning">
+ /// <b>WARNING<b>
+ ///
+ /// This method should be used with extreme caution! Triggering keystream repetition can expose
+ /// the stream cipher to chosen plaintext attacks.
+ /// </div>
+ #[inline]
+ fn unchecked_apply_keystream(&mut self, buf: &mut [u8]) {
+ self.unchecked_apply_keystream_inout(buf.into());
}
- /// Decrypt data from buffer to buffer.
- fn decrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), NotEqualError>
- where
- Self: BlockDecryptMut,
- {
- InOutBuf::new(in_buf, out_buf).map(|b| self.decrypt_inout(b))
+ /// Apply keystream to data buffer-to-buffer without checking for keystream repetition.
+ ///
+ /// It will XOR generated keystream with data from the `input` buffer
+ /// and will write result to the `output` buffer.
+ ///
+ /// # Errors
+ /// Returns [`NotEqualError`] if the `input` and `output` buffers have different lengths.
+ ///
+ /// <div><class = "warning">
+ /// <b>WARNING<b>
+ ///
+ /// This method should be used with extreme caution! Triggering keystream repetition can expose
+ /// the stream cipher to chosen plaintext attacks.
+ /// </div>
+ #[inline]
+ fn unchecked_apply_keystream_b2b(
+ &mut self,
+ input: &[u8],
+ output: &mut [u8],
+ ) -> Result<(), NotEqualError> {
+ let buf = InOutBuf::new(input, output)?;
+ self.unchecked_apply_keystream_inout(buf);
+ Ok(())
}
-}
-/// Synchronous stream cipher core trait.
-pub trait StreamCipher {
/// Apply keystream to `inout` data.
///
- /// If end of the keystream will be achieved with the given data length,
- /// method will return [`StreamCipherError`] without modifying provided `data`.
+ /// # Errors
+ /// If the end of the keystream is reached with the given buffer length,
+ /// the method will return [`StreamCipherError`] without modifying `buf`.
fn try_apply_keystream_inout(
&mut self,
buf: InOutBuf<'_, '_, u8>,
- ) -> Result<(), StreamCipherError>;
+ ) -> Result<(), StreamCipherError> {
+ self.check_remaining(buf.len())?;
+ self.unchecked_apply_keystream_inout(buf);
+ Ok(())
+ }
/// Apply keystream to data behind `buf`.
///
- /// If end of the keystream will be achieved with the given data length,
- /// method will return [`StreamCipherError`] without modifying provided `data`.
+ /// # Errors
+ /// If the end of the keystream is reached with the given buffer length,
+ /// the method will return [`StreamCipherError`] without modifying `buf`.
#[inline]
fn try_apply_keystream(&mut self, buf: &mut [u8]) -> Result<(), StreamCipherError> {
self.try_apply_keystream_inout(buf.into())
}
+ /// Apply keystream to data buffer-to-buffer.
+ ///
+ /// It will XOR generated keystream with data from the `input` buffer
+ /// and will write result to the `output` buffer.
+ ///
+ /// # Errors
+ /// Returns [`StreamCipherError`] without modifying the buffers if the `input` and `output`
+ /// buffers have different lengths, or if the end of the keystream is reached with
+ /// the given data length.
+ #[inline]
+ fn try_apply_keystream_b2b(
+ &mut self,
+ input: &[u8],
+ output: &mut [u8],
+ ) -> Result<(), StreamCipherError> {
+ InOutBuf::new(input, output)
+ .map_err(|_| StreamCipherError)
+ .and_then(|buf| self.try_apply_keystream_inout(buf))
+ }
+
+ /// Write keystream to `buf`.
+ ///
+ /// # Errors
+ /// If the end of the keystream is reached with the given buffer length,
+ /// the method will return [`StreamCipherError`] without modifying `buf`.
+ #[inline]
+ fn try_write_keystream(&mut self, buf: &mut [u8]) -> Result<(), StreamCipherError> {
+ self.check_remaining(buf.len())?;
+ self.unchecked_write_keystream(buf);
+ Ok(())
+ }
+
/// Apply keystream to `inout` data.
///
/// It will XOR generated keystream with the data behind `in` pointer
/// and will write result to `out` pointer.
///
/// # Panics
- /// If end of the keystream will be reached with the given data length,
- /// method will panic without modifying the provided `data`.
+ /// If the end of the keystream is reached with the given buffer length.
#[inline]
fn apply_keystream_inout(&mut self, buf: InOutBuf<'_, '_, u8>) {
- self.try_apply_keystream_inout(buf).unwrap();
+ self.try_apply_keystream_inout(buf)
+ .expect("end of keystream reached");
}
/// Apply keystream to data in-place.
@@ -113,74 +180,90 @@ pub trait StreamCipher {
/// to the same buffer.
///
/// # Panics
- /// If end of the keystream will be reached with the given data length,
- /// method will panic without modifying the provided `data`.
+ /// If the end of the keystream is reached with the given buffer length.
#[inline]
fn apply_keystream(&mut self, buf: &mut [u8]) {
- self.try_apply_keystream(buf).unwrap();
+ self.try_apply_keystream(buf)
+ .expect("end of keystream reached");
}
/// Apply keystream to data buffer-to-buffer.
///
/// It will XOR generated keystream with data from the `input` buffer
/// and will write result to the `output` buffer.
///
- /// Returns [`StreamCipherError`] if provided `in_blocks` and `out_blocks`
- /// have different lengths or if end of the keystream will be reached with
- /// the given input data length.
+ /// # Panics
+ /// If the end of the keystream is reached with the given buffer length,
+ /// of if the `input` and `output` buffers have different lengths.
#[inline]
- fn apply_keystream_b2b(
- &mut self,
- input: &[u8],
- output: &mut [u8],
- ) -> Result<(), StreamCipherError> {
- InOutBuf::new(input, output)
- .map_err(|_| StreamCipherError)
- .and_then(|buf| self.try_apply_keystream_inout(buf))
+ fn apply_keystream_b2b(&mut self, input: &[u8], output: &mut [u8]) {
+ let Ok(buf) = InOutBuf::new(input, output) else {
+ panic!("Lengths of input and output buffers are not equal to each other!");
+ };
+ self.apply_keystream_inout(buf);
+ }
+
+ /// Write keystream to `buf`.
+ ///
+ /// # Panics
+ /// If the end of the keystream is reached with the given buffer length.
+ #[inline]
+ fn write_keystream(&mut self, buf: &mut [u8]) {
+ self.try_write_keystream(buf)
+ .expect("end of keystream reached");
}
}
/// Trait for seekable stream ciphers.
///
-/// Methods of this trait are generic over the [`SeekNum`] trait, which is
-/// implemented for primitive numeric types, i.e.: `i32`, `u32`, `u64`,
-/// `u128`, and `usize`.
+/// Methods of this trait are generic over the [`SeekNum`] trait,
+/// i.e. they can be used with `i32`, `u32`, `u64`, `u128`, and `usize`.
pub trait StreamCipherSeek {
- /// Try to get current keystream position
+ /// Try to get current keystream position in bytes.
///
- /// Returns [`OverflowError`] if position can not be represented by type `T`
+ /// # Errors
+ /// Returns [`OverflowError`] if the position value can not be represented by type `T`.
fn try_current_pos<T: SeekNum>(&self) -> Result<T, OverflowError>;
- /// Try to seek to the given position
+ /// Try to seek to the provided position in bytes.
///
- /// Returns [`StreamCipherError`] if provided position value is bigger than
- /// keystream length.
+ /// # Errors
+ /// Returns [`StreamCipherError`] if the position value is bigger than keystream length.
fn try_seek<T: SeekNum>(&mut self, pos: T) -> Result<(), StreamCipherError>;
- /// Get current keystream position
+ /// Get current keystream position in bytes.
///
/// # Panics
- /// If position can not be represented by type `T`
+ /// If the position value can not be represented by type `T`.
fn current_pos<T: SeekNum>(&self) -> T {
- self.try_current_pos().unwrap()
+ self.try_current_pos()
+ .expect("position cannot be represented by `T`")
}
- /// Seek to the given position
+ /// Seek to the provided keystream position in bytes.
///
/// # Panics
- /// If provided position value is bigger than keystream length
+ /// If the position value is bigger than keystream length.
fn seek<T: SeekNum>(&mut self, pos: T) {
- self.try_seek(pos).unwrap()
+ self.try_seek(pos)
+ .expect("position value bigger than keystream length");
}
}
impl<C: StreamCipher> StreamCipher for &mut C {
#[inline]
- fn try_apply_keystream_inout(
- &mut self,
- buf: InOutBuf<'_, '_, u8>,
- ) -> Result<(), StreamCipherError> {
- C::try_apply_keystream_inout(self, buf)
+ fn check_remaining(&self, data_len: usize) -> Result<(), StreamCipherError> {
+ C::check_remaining(self, data_len)
+ }
+
+ #[inline]
+ fn unchecked_apply_keystream_inout(&mut self, buf: InOutBuf<'_, '_, u8>) {
+ C::unchecked_apply_keystream_inout(self, buf);
+ }
+
+ #[inline]
+ fn unchecked_write_keystream(&mut self, buf: &mut [u8]) {
+ C::unchecked_write_keystream(self, buf);
}
}
@@ -192,31 +275,41 @@ impl<C: StreamCipher> StreamCipher for &mut C {
pub trait SeekNum: Sized {
/// Try to get position for block number `block`, byte position inside
/// block `byte`, and block size `bs`.
- fn from_block_byte<T: Counter>(block: T, byte: u8, bs: u8) -> Result<Self, OverflowError>;
+ ///
+ /// # Errors
+ /// Returns [`OverflowError`] in the event of a counter overflow.
+ fn from_block_byte<T: StreamCipherCounter>(
+ block: T,
+ byte: u8,
+ bs: u8,
+ ) -> Result<Self, OverflowError>;
/// Try to get block number and bytes position for given block size `bs`.
- fn into_block_byte<T: Counter>(self, bs: u8) -> Result<(T, u8), OverflowError>;
+ ///
+ /// # Errors
+ /// Returns [`OverflowError`] in the event of a counter overflow.
+ fn into_block_byte<T: StreamCipherCounter>(self, bs: u8) -> Result<(T, u8), OverflowError>;
}
macro_rules! impl_seek_num {
{$($t:ty )*} => {
$(
impl SeekNum for $t {
- fn from_block_byte<T: Counter>(block: T, byte: u8, bs: u8) -> Result<Self, OverflowError> {
- debug_assert!(byte < bs);
- let mut block: Self = block.try_into().map_err(|_| OverflowError)?;
- if byte != 0 {
- block -= 1;
- }
- let pos = block.checked_mul(bs as Self).ok_or(OverflowError)? + (byte as Self);
- Ok(pos)
+ fn from_block_byte<T: StreamCipherCounter>(block: T, byte: u8, block_size: u8) -> Result<Self, OverflowError> {
+ debug_assert!(byte != 0);
+ let rem = block_size.checked_sub(byte).ok_or(OverflowError)?;
+ let block: Self = block.try_into().map_err(|_| OverflowError)?;
+ block
+ .checked_mul(block_size.into())
+ .and_then(|v| v.checked_sub(rem.into()))
+ .ok_or(OverflowError)
}
- fn into_block_byte<T: Counter>(self, bs: u8) -> Result<(T, u8), OverflowError> {
- let bs = bs as Self;
- let byte = self % bs;
- let block = T::try_from(self/bs).map_err(|_| OverflowError)?;
- Ok((block, byte as u8))
+ fn into_block_byte<T: StreamCipherCounter>(self, block_size: u8) -> Result<(T, u8), OverflowError> {
+ let bs = Self::from(block_size);
+ let byte = u8::try_from(self % bs).expect("bs fits into u8");
+ let block = T::try_from(self / bs).map_err(|_| OverflowError)?;
+ Ok((block, byte))
}
}
)*
### external/vendor/cipher/src/stream/core_api.rs
@@ -1,13 +1,13 @@
-use crate::{ParBlocks, ParBlocksSizeUser, StreamCipherError};
-use crypto_common::{
- generic_array::{ArrayLength, GenericArray},
+use super::StreamCipherError;
+use crate::{
+ array::{Array, ArraySize},
typenum::Unsigned,
- Block, BlockSizeUser,
};
+use common::{Block, BlockSizeUser, ParBlocks, ParBlocksSizeUser};
use inout::{InOut, InOutBuf};
/// Trait implemented by stream cipher backends.
-pub trait StreamBackend: ParBlocksSizeUser {
+pub trait StreamCipherBackend: ParBlocksSizeUser {
/// Generate keystream block.
fn gen_ks_block(&mut self, block: &mut Block<Self>);
@@ -30,25 +30,24 @@ pub trait StreamBackend: ParBlocksSizeUser {
}
}
-/// Trait for [`StreamBackend`] users.
+/// Trait for [`StreamCipherBackend`] users.
///
/// This trait is used to define rank-2 closures.
-pub trait StreamClosure: BlockSizeUser {
+pub trait StreamCipherClosure: BlockSizeUser {
/// Execute closure with the provided stream cipher backend.
- fn call<B: StreamBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
+ fn call<B: StreamCipherBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
}
/// Block-level synchronous stream ciphers.
pub trait StreamCipherCore: BlockSizeUser + Sized {
- /// Return number of remaining blocks before cipher wraps around.
+ /// Return number of remaining blocks before the cipher wraps around.
///
/// Returns `None` if number of remaining blocks can not be computed
- /// (e.g. in ciphers based on the sponge construction) or it's too big
- /// to fit into `usize`.
+ /// (e.g. in the case of sponge-based stream ciphers) or it’s too big to fit into `usize`.
fn remaining_blocks(&self) -> Option<usize>;
/// Process data using backend provided to the rank-2 closure.
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>);
+ fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = Self::BlockSize>);
/// Write keystream block.
///
@@ -94,23 +93,24 @@ pub trait StreamCipherCore: BlockSizeUser + Sized {
/// Try to apply keystream to data not divided into blocks.
///
- /// Consumes cipher since it may consume final keystream block only
- /// partially.
+ /// Consumes cipher since it may consume the final keystream block only partially.
///
- /// Returns an error if number of remaining blocks is not sufficient
- /// for processing the input data.
+ /// # Errors
+ /// Returns [`StreamCipherError`] if the number of remaining blocks is not sufficient
+ /// for processing of the input data.
#[inline]
fn try_apply_keystream_partial(
mut self,
mut buf: InOutBuf<'_, '_, u8>,
) -> Result<(), StreamCipherError> {
- if let Some(rem) = self.remaining_blocks() {
- let blocks = if buf.len() % Self::BlockSize::USIZE == 0 {
- buf.len() % Self::BlockSize::USIZE
- } else {
- buf.len() % Self::BlockSize::USIZE + 1
- };
- if blocks > rem {
+ if let Some(rem_blocks) = self.remaining_blocks() {
+ // Note that if `rem_blocks` is equal to zero, it means that
+ // the next generated block will be the last in the keystream and
+ // the cipher core will wrap to its initial state.
+ // Since we consume `self`, it's fine to generate the last keystream block,
+ // so we can use division instead of `div_ceil` to compute `req_blocks`.
+ let req_blocks = buf.len() / Self::BlockSize::USIZE;
+ if req_blocks > rem_blocks {
return Err(StreamCipherError);
}
}
@@ -142,7 +142,8 @@ pub trait StreamCipherCore: BlockSizeUser + Sized {
/// input data.
#[inline]
fn apply_keystream_partial(self, buf: InOutBuf<'_, '_, u8>) {
- self.try_apply_keystream_partial(buf).unwrap()
+ self.try_apply_keystream_partial(buf)
+ .expect("number of remaining blocks insufficient");
}
}
@@ -156,7 +157,7 @@ pub trait StreamCipherCore: BlockSizeUser + Sized {
/// This trait is implemented for `i32`, `u32`, `u64`, `u128`, and `usize`.
/// It's not intended to be implemented in third-party crates, but doing so
/// is not forbidden.
-pub trait Counter:
+pub trait StreamCipherCounter:
TryFrom<i32>
+ TryFrom<u32>
+ TryFrom<u64>
@@ -167,13 +168,16 @@ pub trait Counter:
+ TryInto<u64>
+ TryInto<u128>
+ TryInto<usize>
+ + Copy
{
+ /// Returns `true` if `self` is equal to the max counter value.
+ fn is_max(&self) -> bool;
}
/// Block-level seeking trait for stream ciphers.
pub trait StreamCipherSeekCore: StreamCipherCore {
/// Counter type used inside stream cipher.
- type Counter: Counter;
+ type Counter: StreamCipherCounter;
/// Get current block position.
fn get_block_pos(&self) -> Self::Counter;
@@ -184,57 +188,44 @@ pub trait StreamCipherSeekCore: StreamCipherCore {
macro_rules! impl_counter {
{$($t:ty )*} => {
- $( impl Counter for $t { } )*
+ $(
+ impl StreamCipherCounter for $t {
+ fn is_max(&self) -> bool {
+ *self == <$t>::MAX
+ }
+ }
+ )*
};
}
impl_counter! { u32 u64 u128 }
-/// Partition buffer into 2 parts: buffer of arrays and tail.
-///
-/// In case if `N` is less or equal to 1, buffer of arrays has length
-/// of zero and tail is equal to `self`.
-#[inline]
-fn into_chunks<T, N: ArrayLength<T>>(buf: &mut [T]) -> (&mut [GenericArray<T, N>], &mut [T]) {
- use core::slice;
- if N::USIZE <= 1 {
- return (&mut [], buf);
- }
- let chunks_len = buf.len() / N::USIZE;
- let tail_pos = N::USIZE * chunks_len;
- let tail_len = buf.len() - tail_pos;
- unsafe {
- let ptr = buf.as_mut_ptr();
- let chunks = slice::from_raw_parts_mut(ptr as *mut GenericArray<T, N>, chunks_len);
- let tail = slice::from_raw_parts_mut(ptr.add(tail_pos), tail_len);
- (chunks, tail)
- }
-}
-
-struct WriteBlockCtx<'a, BS: ArrayLength<u8>> {
+struct WriteBlockCtx<'a, BS: ArraySize> {
block: &'a mut Block<Self>,
}
-impl<'a, BS: ArrayLength<u8>> BlockSizeUser for WriteBlockCtx<'a, BS> {
+impl<BS: ArraySize> BlockSizeUser for WriteBlockCtx<'_, BS> {
type BlockSize = BS;
}
-impl<'a, BS: ArrayLength<u8>> StreamClosure for WriteBlockCtx<'a, BS> {
+impl<BS: ArraySize> StreamCipherClosure for WriteBlockCtx<'_, BS> {
#[inline(always)]
- fn call<B: StreamBackend<BlockSize = BS>>(self, backend: &mut B) {
+ fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
backend.gen_ks_block(self.block);
}
}
-struct WriteBlocksCtx<'a, BS: ArrayLength<u8>> {
+struct WriteBlocksCtx<'a, BS: ArraySize> {
blocks: &'a mut [Block<Self>],
}
-impl<'a, BS: ArrayLength<u8>> BlockSizeUser for WriteBlocksCtx<'a, BS> {
+
+impl<BS: ArraySize> BlockSizeUser for WriteBlocksCtx<'_, BS> {
type BlockSize = BS;
}
-impl<'a, BS: ArrayLength<u8>> StreamClosure for WriteBlocksCtx<'a, BS> {
+
+impl<BS: ArraySize> StreamCipherClosure for WriteBlocksCtx<'_, BS> {
#[inline(always)]
- fn call<B: StreamBackend<BlockSize = BS>>(self, backend: &mut B) {
+ fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
if B::ParBlocksSize::USIZE > 1 {
- let (chunks, tail) = into_chunks::<_, B::ParBlocksSize>(self.blocks);
+ let (chunks, tail) = Array::slice_as_chunks_mut(self.blocks);
for chunk in chunks {
backend.gen_par_ks_blocks(chunk);
}
@@ -247,35 +238,35 @@ impl<'a, BS: ArrayLength<u8>> StreamClosure for WriteBlocksCtx<'a, BS> {
}
}
-struct ApplyBlockCtx<'inp, 'out, BS: ArrayLength<u8>> {
+struct ApplyBlockCtx<'inp, 'out, BS: ArraySize> {
block: InOut<'inp, 'out, Block<Self>>,
}
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for ApplyBlockCtx<'inp, 'out, BS> {
+impl<BS: ArraySize> BlockSizeUser for ApplyBlockCtx<'_, '_, BS> {
type BlockSize = BS;
}
-impl<'inp, 'out, BS: ArrayLength<u8>> StreamClosure for ApplyBlockCtx<'inp, 'out, BS> {
+impl<BS: ArraySize> StreamCipherClosure for ApplyBlockCtx<'_, '_, BS> {
#[inline(always)]
- fn call<B: StreamBackend<BlockSize = BS>>(mut self, backend: &mut B) {
+ fn call<B: StreamCipherBackend<BlockSize = BS>>(mut self, backend: &mut B) {
let mut t = Default::default();
backend.gen_ks_block(&mut t);
self.block.xor_in2out(&t);
}
}
-struct ApplyBlocksCtx<'inp, 'out, BS: ArrayLength<u8>> {
+struct ApplyBlocksCtx<'inp, 'out, BS: ArraySize> {
blocks: InOutBuf<'inp, 'out, Block<Self>>,
}
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for ApplyBlocksCtx<'inp, 'out, BS> {
+impl<BS: ArraySize> BlockSizeUser for ApplyBlocksCtx<'_, '_, BS> {
type BlockSize = BS;
}
-impl<'inp, 'out, BS: ArrayLength<u8>> StreamClosure for ApplyBlocksCtx<'inp, 'out, BS> {
+impl<BS: ArraySize> StreamCipherClosure for ApplyBlocksCtx<'_, '_, BS> {
#[inline(always)]
#[allow(clippy::needless_range_loop)]
- fn call<B: StreamBackend<BlockSize = BS>>(self, backend: &mut B) {
+ fn call<B: StreamCipherBackend<BlockSize = BS>>(self, backend: &mut B) {
if B::ParBlocksSize::USIZE > 1 {
let (chunks, mut tail) = self.blocks.into_chunks::<B::ParBlocksSize>();
for mut chunk in chunks {
@@ -284,7 +275,7 @@ impl<'inp, 'out, BS: ArrayLength<u8>> StreamClosure for ApplyBlocksCtx<'inp, 'ou
chunk.xor_in2out(&tmp);
}
let n = tail.len();
- let mut buf = GenericArray::<_, B::ParBlocksSize>::default();
+ let mut buf = Array::<_, B::ParBlocksSize>::default();
let ks = &mut buf[..n];
backend.gen_tail_blocks(ks);
for i in 0..n {
### external/vendor/cipher/src/stream/errors.rs
@@ -17,9 +17,7 @@ impl fmt::Display for StreamCipherError {
}
}
-#[cfg(feature = "std")]
-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
-impl std::error::Error for StreamCipherError {}
+impl core::error::Error for StreamCipherError {}
/// The error type returned when a cipher position can not be represented
/// by the requested type.
@@ -38,6 +36,4 @@ impl From<OverflowError> for StreamCipherError {
}
}
-#[cfg(feature = "std")]
-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
-impl std::error::Error for OverflowError {}
+impl core::error::Error for OverflowError {}
### external/vendor/cipher/src/stream/wrapper.rs
@@ -0,0 +1,228 @@
+use crate::StreamCipherCounter;
+
+use super::{
+ OverflowError, SeekNum, StreamCipher, StreamCipherCore, StreamCipherSeek, StreamCipherSeekCore,
+ errors::StreamCipherError,
+};
+use block_buffer::{BlockSizes, ReadBuffer};
+use common::{
+ Iv, IvSizeUser, Key, KeyInit, KeyIvInit, KeySizeUser, array::Array, typenum::Unsigned,
+};
+use core::fmt;
+use inout::InOutBuf;
+#[cfg(feature = "zeroize")]
+use zeroize::ZeroizeOnDrop;
+
+/// Buffering wrapper around a [`StreamCipherCore`] implementation.
+///
+/// It handles data buffering and implements the slice-based traits.
+pub struct StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ core: T,
+ buffer: ReadBuffer<T::BlockSize>,
+}
+
+impl<T> Clone for StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore + Clone,
+ T::BlockSize: BlockSizes,
+{
+ #[inline]
+ fn clone(&self) -> Self {
+ Self {
+ core: self.core.clone(),
+ buffer: self.buffer.clone(),
+ }
+ }
+}
+
+impl<T> fmt::Debug for StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore + fmt::Debug,
+ T::BlockSize: BlockSizes,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("StreamCipherCoreWrapper")
+ .finish_non_exhaustive()
+ }
+}
+
+impl<T> StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ /// Initialize from a [`StreamCipherCore`] instance.
+ pub fn from_core(core: T) -> Self {
+ Self {
+ core,
+ buffer: Default::default(),
+ }
+ }
+
+ /// Get reference to the wrapped [`StreamCipherCore`] instance.
+ pub fn get_core(&self) -> &T {
+ &self.core
+ }
+}
+
+impl<T> StreamCipher for StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ #[inline]
+ fn check_remaining(&self, data_len: usize) -> Result<(), StreamCipherError> {
+ let Some(rem_blocks) = self.core.remaining_blocks() else {
+ return Ok(());
+ };
+ let Some(data_len) = data_len.checked_sub(self.buffer.remaining()) else {
+ return Ok(());
+ };
+ let req_blocks = data_len.div_ceil(T::BlockSize::USIZE);
+ if req_blocks > rem_blocks {
+ Err(StreamCipherError)
+ } else {
+ Ok(())
+ }
+ }
+
+ #[inline]
+ fn unchecked_apply_keystream_inout(&mut self, data: InOutBuf<'_, '_, u8>) {
+ let head_ks = self.buffer.read_cached(data.len());
+
+ let (mut head, data) = data.split_at(head_ks.len());
+ let (blocks, mut tail) = data.into_chunks();
+
+ head.xor_in2out(head_ks);
+ self.core.apply_keystream_blocks_inout(blocks);
+
+ self.buffer.write_block(
+ tail.len(),
+ |b| self.core.write_keystream_block(b),
+ |tail_ks| {
+ tail.xor_in2out(tail_ks);
+ },
+ );
+ }
+
+ #[inline]
+ fn unchecked_write_keystream(&mut self, data: &mut [u8]) {
+ let head_ks = self.buffer.read_cached(data.len());
+
+ let (head, data) = data.split_at_mut(head_ks.len());
+ let (blocks, tail) = Array::slice_as_chunks_mut(data);
+
+ head.copy_from_slice(head_ks);
+ self.core.write_keystream_blocks(blocks);
+
+ self.buffer.write_block(
+ tail.len(),
+ |b| self.core.write_keystream_block(b),
+ |tail_ks| tail.copy_from_slice(tail_ks),
+ );
+ }
+}
+
+impl<T> StreamCipherSeek for StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherSeekCore,
+ T::BlockSize: BlockSizes,
+{
+ #[allow(clippy::unwrap_in_result)]
+ fn try_current_pos<SN: SeekNum>(&self) -> Result<SN, OverflowError> {
+ let pos = u8::try_from(self.buffer.get_pos())
+ .expect("buffer position is always smaller than 256");
+ SN::from_block_byte(self.core.get_block_pos(), pos, T::BlockSize::U8)
+ }
+
+ fn try_seek<SN: SeekNum>(&mut self, new_pos: SN) -> Result<(), StreamCipherError> {
+ let (block_pos, byte_pos) = new_pos.into_block_byte::<T::Counter>(T::BlockSize::U8)?;
+ if byte_pos != 0 && block_pos.is_max() {
+ return Err(StreamCipherError);
+ }
+ // For correct implementations of `SeekNum` the compiler should be able to
+ // eliminate this assert
+ assert!(byte_pos < T::BlockSize::U8);
+
+ self.core.set_block_pos(block_pos);
+
+ self.buffer.reset();
+
+ self.buffer.write_block(
+ usize::from(byte_pos),
+ |b| self.core.write_keystream_block(b),
+ |_| {},
+ );
+ Ok(())
+ }
+}
+
+// Note: ideally we would only implement the InitInner trait and everything
+// else would be handled by blanket impls, but, unfortunately, it will
+// not work properly without mutually exclusive traits, see:
+// https://github.com/rust-lang/rfcs/issues/1053
+
+impl<T> KeySizeUser for StreamCipherCoreWrapper<T>
+where
+ T: KeySizeUser + StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ type KeySize = T::KeySize;
+}
+
+impl<T> IvSizeUser for StreamCipherCoreWrapper<T>
+where
+ T: IvSizeUser + StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ type IvSize = T::IvSize;
+}
+
+impl<T> KeyIvInit for StreamCipherCoreWrapper<T>
+where
+ T: KeyIvInit + StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ #[inline]
+ fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
+ Self {
+ core: T::new(key, iv),
+ buffer: Default::default(),
+ }
+ }
+}
+
+impl<T> KeyInit for StreamCipherCoreWrapper<T>
+where
+ T: KeyInit + StreamCipherCore,
+ T::BlockSize: BlockSizes,
+{
+ #[inline]
+ fn new(key: &Key<Self>) -> Self {
+ Self {
+ core: T::new(key),
+ buffer: Default::default(),
+ }
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<T> ZeroizeOnDrop for StreamCipherCoreWrapper<T>
+where
+ T: StreamCipherCore + ZeroizeOnDrop,
+ T::BlockSize: BlockSizes,
+{
+}
+
+// Assert that `ReadBuffer` implements `ZeroizeOnDrop`
+#[cfg(feature = "zeroize")]
+const _: () = {
+ #[allow(dead_code, trivial_casts)]
+ fn check_buffer<BS: BlockSizes>(v: &ReadBuffer<BS>) {
+ let _ = v as &dyn ZeroizeOnDrop;
+ }
+};
### external/vendor/cipher/src/stream_wrapper.rs
@@ -1,242 +0,0 @@
-use crate::{
- errors::StreamCipherError, Block, OverflowError, SeekNum, StreamCipher, StreamCipherCore,
- StreamCipherSeek, StreamCipherSeekCore,
-};
-use crypto_common::{
- typenum::{IsLess, Le, NonZero, Unsigned, U256},
- BlockSizeUser, Iv, IvSizeUser, Key, KeyInit, KeyIvInit, KeySizeUser,
-};
-use inout::InOutBuf;
-#[cfg(feature = "zeroize")]
-use zeroize::{Zeroize, ZeroizeOnDrop};
-
-/// Wrapper around [`StreamCipherCore`] implementations.
-///
-/// It handles data buffering and implements the slice-based traits.
-#[derive(Clone, Default)]
-pub struct StreamCipherCoreWrapper<T: BlockSizeUser>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- core: T,
- buffer: Block<T>,
- pos: u8,
-}
-
-impl<T: StreamCipherCore> StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- /// Return reference to the core type.
- pub fn get_core(&self) -> &T {
- &self.core
- }
-
- /// Return reference to the core type.
- pub fn from_core(core: T) -> Self {
- Self {
- core,
- buffer: Default::default(),
- pos: 0,
- }
- }
-
- /// Return current cursor position.
- #[inline]
- fn get_pos(&self) -> usize {
- let pos = self.pos as usize;
- if T::BlockSize::USIZE == 0 {
- panic!("Block size can not be equal to zero");
- }
- if pos >= T::BlockSize::USIZE {
- debug_assert!(false);
- // SAFETY: `pos` is set only to values smaller than block size
- unsafe { core::hint::unreachable_unchecked() }
- }
- self.pos as usize
- }
-
- /// Return size of the internal buffer in bytes.
- #[inline]
- fn size(&self) -> usize {
- T::BlockSize::USIZE
- }
-
- #[inline]
- fn set_pos_unchecked(&mut self, pos: usize) {
- debug_assert!(pos < T::BlockSize::USIZE);
- self.pos = pos as u8;
- }
-
- /// Return number of remaining bytes in the internal buffer.
- #[inline]
- fn remaining(&self) -> usize {
- self.size() - self.get_pos()
- }
-
- fn check_remaining(&self, dlen: usize) -> Result<(), StreamCipherError> {
- let rem_blocks = match self.core.remaining_blocks() {
- Some(v) => v,
- None => return Ok(()),
- };
-
- let bytes = if self.pos == 0 {
- dlen
- } else {
- let rem = self.remaining();
- if dlen > rem {
- dlen - rem
- } else {
- return Ok(());
- }
- };
- let bs = T::BlockSize::USIZE;
- let blocks = if bytes % bs == 0 {
- bytes / bs
- } else {
- bytes / bs + 1
- };
- if blocks > rem_blocks {
- Err(StreamCipherError)
- } else {
- Ok(())
- }
- }
-}
-
-impl<T: StreamCipherCore> StreamCipher for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- #[inline]
- fn try_apply_keystream_inout(
- &mut self,
- mut data: InOutBuf<'_, '_, u8>,
- ) -> Result<(), StreamCipherError> {
- self.check_remaining(data.len())?;
-
- let pos = self.get_pos();
- if pos != 0 {
- let rem = &self.buffer[pos..];
- let n = data.len();
- if n < rem.len() {
- data.xor_in2out(&rem[..n]);
- self.set_pos_unchecked(pos + n);
- return Ok(());
- }
- let (mut left, right) = data.split_at(rem.len());
- data = right;
- left.xor_in2out(rem);
- }
-
- let (blocks, mut leftover) = data.into_chunks();
- self.core.apply_keystream_blocks_inout(blocks);
-
- let n = leftover.len();
- if n != 0 {
- self.core.write_keystream_block(&mut self.buffer);
- leftover.xor_in2out(&self.buffer[..n]);
- }
- self.set_pos_unchecked(n);
-
- Ok(())
- }
-}
-
-impl<T: StreamCipherSeekCore> StreamCipherSeek for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- fn try_current_pos<SN: SeekNum>(&self) -> Result<SN, OverflowError> {
- let Self { core, pos, .. } = self;
- SN::from_block_byte(core.get_block_pos(), *pos, T::BlockSize::U8)
- }
-
- fn try_seek<SN: SeekNum>(&mut self, new_pos: SN) -> Result<(), StreamCipherError> {
- let Self { core, buffer, pos } = self;
- let (block_pos, byte_pos) = new_pos.into_block_byte(T::BlockSize::U8)?;
- core.set_block_pos(block_pos);
- if byte_pos != 0 {
- self.core.write_keystream_block(buffer);
- }
- *pos = byte_pos;
- Ok(())
- }
-}
-
-// Note: ideally we would only implement the InitInner trait and everything
-// else would be handled by blanket impls, but unfortunately it will
-// not work properly without mutually exclusive traits, see:
-// https://github.com/rust-lang/rfcs/issues/1053
-
-impl<T: KeySizeUser + BlockSizeUser> KeySizeUser for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- type KeySize = T::KeySize;
-}
-
-impl<T: IvSizeUser + BlockSizeUser> IvSizeUser for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- type IvSize = T::IvSize;
-}
-
-impl<T: KeyIvInit + BlockSizeUser> KeyIvInit for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- #[inline]
- fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
- Self {
- core: T::new(key, iv),
- buffer: Default::default(),
- pos: 0,
- }
- }
-}
-
-impl<T: KeyInit + BlockSizeUser> KeyInit for StreamCipherCoreWrapper<T>
-where
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- #[inline]
- fn new(key: &Key<Self>) -> Self {
- Self {
- core: T::new(key),
- buffer: Default::default(),
- pos: 0,
- }
- }
-}
-
-#[cfg(feature = "zeroize")]
-impl<T> Drop for StreamCipherCoreWrapper<T>
-where
- T: BlockSizeUser,
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
- fn drop(&mut self) {
- self.buffer.zeroize();
- self.pos.zeroize();
- }
-}
-
-#[cfg(feature = "zeroize")]
-impl<T> ZeroizeOnDrop for StreamCipherCoreWrapper<T>
-where
- T: BlockSizeUser + ZeroizeOnDrop,
- T::BlockSize: IsLess<U256>,
- Le<T::BlockSize, U256>: NonZero,
-{
-}
### external/vendor/cipher/src/tweak.rs
@@ -0,0 +1,152 @@
+//! Traits used to define functionality of [tweakable block ciphers][1].
+//!
+//! [1]: https://people.eecs.berkeley.edu/~daw/papers/tweak-crypto02.pdf
+use common::{
+ Block, BlockSizeUser,
+ array::{Array, ArraySize},
+};
+use inout::InOut;
+
+mod ctx;
+mod zero;
+
+pub use zero::ZeroTweak;
+
+/// Tweak used by a [`TweakSizeUser`] implementor.
+pub type Tweak<C> = Array<u8, <C as TweakSizeUser>::TweakSize>;
+
+/// Trait which contains tweak size used by the tweak cipher traits.
+pub trait TweakSizeUser {
+ /// Size of the tweak in bytes.
+ type TweakSize: ArraySize;
+}
+
+/// Encrypt-only functionality for tweakable block ciphers.
+pub trait TweakBlockCipherEncrypt: BlockSizeUser + TweakSizeUser + Sized {
+ /// Encrypt data using backend provided to the rank-2 closure.
+ fn encrypt_with_backend(
+ &self,
+ f: impl TweakBlockCipherEncClosure<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>,
+ );
+
+ /// Encrypt single `inout` block.
+ #[inline]
+ fn encrypt_block_inout(&self, tweak: &Tweak<Self>, block: InOut<'_, '_, Block<Self>>) {
+ self.encrypt_with_backend(ctx::BlockCtx { tweak, block });
+ }
+
+ /// Encrypt single block in-place.
+ #[inline]
+ fn encrypt_block(&self, tweak: &Tweak<Self>, block: &mut Block<Self>) {
+ self.encrypt_block_inout(tweak, block.into());
+ }
+
+ /// Encrypt `in_block` and write result to `out_block`.
+ #[inline]
+ fn encrypt_block_b2b(
+ &self,
+ tweak: &Tweak<Self>,
+ in_block: &Block<Self>,
+ out_block: &mut Block<Self>,
+ ) {
+ self.encrypt_block_inout(tweak, (in_block, out_block).into());
+ }
+}
+
+/// Decrypt-only functionality for tweakable block ciphers.
+pub trait TweakBlockCipherDecrypt: BlockSizeUser + TweakSizeUser + Sized {
+ /// Decrypt data using backend provided to the rank-2 closure.
+ fn decrypt_with_backend(
+ &self,
+ f: impl TweakBlockCipherDecClosure<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>,
+ );
+
+ /// Decrypt single `inout` block.
+ #[inline]
+ fn decrypt_block_inout(&self, tweak: &Tweak<Self>, block: InOut<'_, '_, Block<Self>>) {
+ self.decrypt_with_backend(ctx::BlockCtx { tweak, block });
+ }
+
+ /// Decrypt single block in-place.
+ #[inline]
+ fn decrypt_block(&self, tweak: &Tweak<Self>, block: &mut Block<Self>) {
+ self.decrypt_block_inout(tweak, block.into());
+ }
+
+ /// Decrypt `in_block` and write result to `out_block`.
+ #[inline]
+ fn decrypt_block_b2b(
+ &self,
+ tweak: &Tweak<Self>,
+ in_block: &Block<Self>,
+ out_block: &mut Block<Self>,
+ ) {
+ self.decrypt_block_inout(tweak, (in_block, out_block).into());
+ }
+}
+
+/// Trait for [`TweakBlockCipherEncBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait TweakBlockCipherEncClosure: BlockSizeUser + TweakSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B>(self, backend: &B)
+ where
+ B: TweakBlockCipherEncBackend<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>;
+}
+
+/// Trait for [`TweakBlockCipherDecBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait TweakBlockCipherDecClosure: BlockSizeUser + TweakSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B>(self, backend: &B)
+ where
+ B: TweakBlockCipherDecBackend<BlockSize = Self::BlockSize, TweakSize = Self::TweakSize>;
+}
+
+/// Trait implemented by block cipher mode encryption backends.
+pub trait TweakBlockCipherEncBackend: BlockSizeUser + TweakSizeUser {
+ /// Encrypt single inout block.
+ fn encrypt_block_inout(&self, tweak: &Tweak<Self>, block: InOut<'_, '_, Block<Self>>);
+
+ /// Encrypt single block in-place.
+ #[inline]
+ fn encrypt_block(&self, tweak: &Tweak<Self>, block: &mut Block<Self>) {
+ self.encrypt_block_inout(tweak, block.into());
+ }
+
+ /// Encrypt `in_block` and write result to `out_block`.
+ #[inline]
+ fn encrypt_block_b2b(
+ &self,
+ tweak: &Tweak<Self>,
+ in_block: &Block<Self>,
+ out_block: &mut Block<Self>,
+ ) {
+ self.encrypt_block_inout(tweak, (in_block, out_block).into());
+ }
+}
+
+/// Trait implemented by block cipher mode decryption backends.
+pub trait TweakBlockCipherDecBackend: BlockSizeUser + TweakSizeUser {
+ /// Decrypt single inout block.
+ fn decrypt_block_inout(&self, tweak: &Tweak<Self>, block: InOut<'_, '_, Block<Self>>);
+
+ /// Decrypt single block in-place.
+ #[inline]
+ fn decrypt_block(&self, tweak: &Tweak<Self>, block: &mut Block<Self>) {
+ self.decrypt_block_inout(tweak, block.into());
+ }
+
+ /// Decrypt `in_block` and write result to `out_block`.
+ #[inline]
+ fn decrypt_block_b2b(
+ &self,
+ tweak: &Tweak<Self>,
+ in_block: &Block<Self>,
+ out_block: &mut Block<Self>,
+ ) {
+ self.decrypt_block_inout(tweak, (in_block, out_block).into());
+ }
+}
### external/vendor/cipher/src/tweak/ctx.rs
@@ -0,0 +1,41 @@
+use common::{Block, BlockSizeUser, array::ArraySize};
+use inout::InOut;
+
+use super::{
+ Tweak, TweakBlockCipherDecBackend, TweakBlockCipherDecClosure, TweakBlockCipherEncBackend,
+ TweakBlockCipherEncClosure, TweakSizeUser,
+};
+
+/// Closure used in methods which operate over separate blocks.
+pub(super) struct BlockCtx<'a, TS: ArraySize, BS: ArraySize> {
+ pub tweak: &'a Tweak<Self>,
+ pub block: InOut<'a, 'a, Block<Self>>,
+}
+
+impl<TS: ArraySize, BS: ArraySize> BlockSizeUser for BlockCtx<'_, TS, BS> {
+ type BlockSize = BS;
+}
+
+impl<TS: ArraySize, BS: ArraySize> TweakSizeUser for BlockCtx<'_, TS, BS> {
+ type TweakSize = TS;
+}
+
+impl<TS: ArraySize, BS: ArraySize> TweakBlockCipherEncClosure for BlockCtx<'_, TS, BS> {
+ #[inline]
+ fn call<B>(self, backend: &B)
+ where
+ B: TweakBlockCipherEncBackend<BlockSize = BS, TweakSize = TS>,
+ {
+ backend.encrypt_block_inout(self.tweak, self.block);
+ }
+}
+
+impl<TS: ArraySize, BS: ArraySize> TweakBlockCipherDecClosure for BlockCtx<'_, TS, BS> {
+ #[inline]
+ fn call<B>(self, backend: &B)
+ where
+ B: TweakBlockCipherDecBackend<BlockSize = BS, TweakSize = TS>,
+ {
+ backend.decrypt_block_inout(self.tweak, self.block);
+ }
+}
### external/vendor/cipher/src/tweak/zero.rs
@@ -0,0 +1,118 @@
+use core::marker::PhantomData;
+
+use common::{Block, ParBlocksSizeUser, array::ArraySize};
+
+use super::{
+ TweakBlockCipherDecBackend, TweakBlockCipherDecClosure, TweakBlockCipherDecrypt,
+ TweakBlockCipherEncBackend, TweakBlockCipherEncrypt, TweakSizeUser,
+};
+use crate::{
+ BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherDecrypt, BlockCipherEncBackend,
+ BlockCipherEncClosure, BlockCipherEncrypt, BlockSizeUser, consts::U1,
+ tweak::TweakBlockCipherEncClosure,
+};
+
+/// Wrapper around tweakable block cipher which implements
+/// the [common block cipher traits][crate::block] using zero tweak.
+#[derive(Debug, Clone)]
+pub struct ZeroTweak<C: TweakSizeUser + BlockSizeUser>(pub C);
+
+impl<C: TweakSizeUser + BlockSizeUser> BlockSizeUser for ZeroTweak<C> {
+ type BlockSize = C::BlockSize;
+}
+
+impl<C: TweakBlockCipherEncrypt> BlockCipherEncrypt for ZeroTweak<C> {
+ #[inline]
+ fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>) {
+ self.0.encrypt_with_backend(ClosureWrapper {
+ f,
+ _pd: PhantomData,
+ });
+ }
+}
+
+impl<C: TweakBlockCipherDecrypt> BlockCipherDecrypt for ZeroTweak<C> {
+ #[inline]
+ fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>) {
+ self.0.decrypt_with_backend(ClosureWrapper {
+ f,
+ _pd: PhantomData,
+ });
+ }
+}
+
+/// Wrapper around non-tweakble block cipher closures which implements the tweakable
+/// block cipher closure traits using zero tweak.
+struct ClosureWrapper<TS: ArraySize, BS: ArraySize, F> {
+ f: F,
+ _pd: PhantomData<(TS, BS)>,
+}
+
+impl<TS: ArraySize, BS: ArraySize, F> BlockSizeUser for ClosureWrapper<TS, BS, F> {
+ type BlockSize = BS;
+}
+
+impl<TS: ArraySize, BS: ArraySize, F> TweakSizeUser for ClosureWrapper<TS, BS, F> {
+ type TweakSize = TS;
+}
+
+impl<TS: ArraySize, BS: ArraySize, F> TweakBlockCipherEncClosure for ClosureWrapper<TS, BS, F>
+where
+ F: BlockCipherEncClosure<BlockSize = BS>,
+{
+ #[inline]
+ fn call<B: TweakBlockCipherEncBackend<BlockSize = BS, TweakSize = TS>>(self, backend: &B) {
+ self.f.call(&BackendWrapper {
+ backend,
+ _pd: PhantomData,
+ });
+ }
+}
+
+impl<TS: ArraySize, BS: ArraySize, F> TweakBlockCipherDecClosure for ClosureWrapper<TS, BS, F>
+where
+ F: BlockCipherDecClosure<BlockSize = BS>,
+{
+ #[inline]
+ fn call<B: TweakBlockCipherDecBackend<BlockSize = BS, TweakSize = TS>>(self, backend: &B) {
+ self.f.call(&BackendWrapper {
+ backend,
+ _pd: PhantomData,
+ });
+ }
+}
+
+/// Wrapper around tweakable block cipher backend which implements non-tweakable
+/// block cipher backend traits using zero tweak.
+struct BackendWrapper<'a, BS: ArraySize, B> {
+ backend: &'a B,
+ _pd: PhantomData<BS>,
+}
+
+impl<BS: ArraySize, B> BlockSizeUser for BackendWrapper<'_, BS, B> {
+ type BlockSize = BS;
+}
+
+impl<BS: ArraySize, B> ParBlocksSizeUser for BackendWrapper<'_, BS, B> {
+ type ParBlocksSize = U1;
+}
+
+impl<BS: ArraySize, B> BlockCipherEncBackend for BackendWrapper<'_, BS, B>
+where
+ B: TweakBlockCipherEncBackend<BlockSize = BS>,
+{
+ #[inline]
+ fn encrypt_block(&self, block: inout::InOut<'_, '_, Block<Self>>) {
+ self.backend.encrypt_block_inout(&Default::default(), block);
+ }
+}
+
+impl<BS: ArraySize, B> BlockCipherDecBackend for BackendWrapper<'_, BS, B>
+where
+ B: TweakBlockCipherDecBackend<BlockSize = BS>,
+{
+ #[inline]
+ fn decrypt_block(&self, block: inout::InOut<'_, '_, Block<Self>>) {
+ self.backend.decrypt_block_inout(&Default::default(), block);
+ }
+}
### external/vendor/cipher/tests/data/dummy_stream_cipher.blb
[binary or diff unavailable]
### external/vendor/cipher/tests/stream.rs
@@ -0,0 +1,177 @@
+//! Stream cipher tests.
+
+use cipher::{
+ BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, ParBlocksSizeUser, StreamCipherBackend,
+ StreamCipherClosure, StreamCipherCore, StreamCipherSeekCore,
+ consts::{U1, U4, U16},
+};
+use hex_literal::hex;
+
+const KEY: [u8; 4] = hex!("00010203");
+const IV: [u8; 4] = hex!("04050607");
+
+/// Core of dummy insecure stream cipher.
+#[derive(Debug)]
+#[allow(missing_copy_implementations)]
+pub struct DummyStreamCipherCore {
+ key_iv: u64,
+ pos: u64,
+}
+
+impl KeySizeUser for DummyStreamCipherCore {
+ type KeySize = U4;
+}
+
+impl IvSizeUser for DummyStreamCipherCore {
+ type IvSize = U4;
+}
+
+impl KeyIvInit for DummyStreamCipherCore {
+ fn new(key: &cipher::Key<Self>, iv: &cipher::Iv<Self>) -> Self {
+ let mut key_iv = [0u8; 8];
+ key_iv[..4].copy_from_slice(key);
+ key_iv[4..].copy_from_slice(iv);
+ Self {
+ key_iv: u64::from_le_bytes(key_iv),
+ pos: 0,
+ }
+ }
+}
+
+impl BlockSizeUser for DummyStreamCipherCore {
+ type BlockSize = U16;
+}
+
+impl StreamCipherCore for DummyStreamCipherCore {
+ fn remaining_blocks(&self) -> Option<usize> {
+ let rem = u64::MAX - self.pos;
+ usize::try_from(rem).ok()
+ }
+
+ fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = U16>) {
+ f.call(self);
+ }
+}
+
+impl ParBlocksSizeUser for DummyStreamCipherCore {
+ type ParBlocksSize = U1;
+}
+
+impl StreamCipherBackend for DummyStreamCipherCore {
+ fn gen_ks_block(&mut self, block: &mut cipher::Block<Self>) {
+ const C1: u64 = 0x87c3_7b91_1142_53d5;
+ const C2: u64 = 0x4cf5_ad43_2745_937f;
+
+ let a = self.key_iv ^ C1;
+ let b = self.pos ^ C2;
+ let a = a.rotate_left(13).wrapping_mul(b);
+ let b = b.rotate_left(13).wrapping_mul(a);
+
+ block[..8].copy_from_slice(&a.to_le_bytes());
+ block[8..].copy_from_slice(&b.to_le_bytes());
+ self.pos = self.pos.wrapping_add(1);
+ }
+}
+
+impl StreamCipherSeekCore for DummyStreamCipherCore {
+ type Counter = u64;
+
+ fn get_block_pos(&self) -> Self::Counter {
+ self.pos
+ }
+
+ fn set_block_pos(&mut self, pos: Self::Counter) {
+ self.pos = pos;
+ }
+}
+
+#[test]
+fn dummy_stream_cipher_core() {
+ let mut cipher = DummyStreamCipherCore::new(&KEY.into(), &IV.into());
+ assert_eq!(cipher.get_block_pos(), 0);
+
+ let mut block = [0u8; 16].into();
+ cipher.write_keystream_block(&mut block);
+ assert_eq!(block, hex!("e82393543cc96089305116003a417acc"));
+ assert_eq!(cipher.get_block_pos(), 1);
+
+ cipher.set_block_pos(200);
+ assert_eq!(cipher.get_block_pos(), 200);
+
+ cipher.write_keystream_block(&mut block);
+ assert_eq!(block, hex!("28a96998fe4874ffb0ce9b046c6a9ddb"));
+ assert_eq!(cipher.get_block_pos(), 201);
+}
+
+#[cfg(feature = "stream-wrapper")]
+mod wrapper {
+ use core::panic;
+
+ use super::*;
+ use cipher::{StreamCipher, StreamCipherCoreWrapper, StreamCipherSeek};
+
+ /// Dummy insecure stream cipher.
+ pub type DummyStreamCipher = StreamCipherCoreWrapper<DummyStreamCipherCore>;
+
+ #[test]
+ fn dummy_stream_cipher_basic() {
+ let mut cipher = DummyStreamCipher::new(&KEY.into(), &IV.into());
+ assert_eq!(cipher.current_pos::<u64>(), 0);
+
+ let mut buf = [0u8; 20];
+ cipher.apply_keystream(&mut buf);
+ assert_eq!(buf, hex!("e82393543cc96089305116003a417accd073384a"));
+ assert_eq!(cipher.current_pos::<usize>(), buf.len());
+
+ const SEEK_POS: usize = 500;
+ cipher.seek(SEEK_POS);
+ cipher.apply_keystream(&mut buf);
+ assert_eq!(buf, hex!("6b014c6a3c376b13c4720590d26147c5ebf334c5"));
+ assert_eq!(cipher.current_pos::<usize>(), SEEK_POS + buf.len());
+ }
+
+ #[test]
+ fn dummy_stream_cipher_seek_limit() {
+ let mut cipher = DummyStreamCipher::new(&KEY.into(), &IV.into());
+ let mut buf = [0u8; 64];
+
+ let block_size = DummyStreamCipherCore::block_size();
+ let block_size_u128 = u128::try_from(block_size).unwrap();
+ let keystream_end = 1u128 << 68;
+ let last_block_pos = keystream_end - block_size_u128;
+
+ // Seeking to the last block or past it should return error
+ for offset in 0..block_size_u128 {
+ let res = cipher.try_seek(keystream_end - offset);
+ assert!(res.is_err());
+ let res = cipher.try_seek(keystream_end + offset);
+ assert!(res.is_err());
+ }
+
+ // Trying to apply the last keystream block should return error
+ for offset in block_size..buf.len() {
+ for len in 0..buf.len() {
+ let pos = keystream_end - u128::try_from(offset).unwrap();
+ let res = cipher.try_seek(pos);
+ assert!(res.is_ok());
+ let res = cipher.try_apply_keystream(&mut buf[..len]);
+ let expected_pos = pos + u128::try_from(len).unwrap();
+ if expected_pos > last_block_pos {
+ assert!(res.is_err());
+ } else {
+ assert!(res.is_ok());
+ assert_eq!(cipher.current_pos::<u128>(), expected_pos);
+ }
+ }
+ }
+ }
+
+ #[cfg(feature = "dev")]
+ cipher::stream_cipher_test!(
+ dummy_stream_cipher,
+ "dummy_stream_cipher",
+ DummyStreamCipher,
+ );
+ #[cfg(feature = "dev")]
+ cipher::stream_cipher_seek_test!(dummy_stream_cipher_seek, DummyStreamCipher);
+}
### external/vendor/cmov/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"f7f0e23dda2cd5bc0af34a840db6217f9c403f0da076001246625d3f50109b24","CHANGELOG.md":"3b6296d1f27c66fe4d6c433588dc1fd1c7295638c31f5191e30fdb3823759cf9","Cargo.lock":"5db82bc06e5e331233578c5ea763396da0cc121bdd37f2bb38d708736e55c72d","Cargo.toml":"3f91a59940445ae78e4155fc6bd53efaf277f8369a0c6385f0033d986a3455ad","Cargo.toml.orig":"627071b9f7ba7dda204a1394c002386ee14fb5753f1b061183108b97f05fa2ca","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"70c9d40f1f9545c3f133b8a67206e89da850f6468eed072281bb3701514114a9","README.md":"f9bde8c28c8756efe81311f0ab28c5aee02f44b92994e808f01cde0ba0f277f2","src/array.rs":"0aa216d6ee64543ea47f4992a24ad9148ce4d6092c81bba3f2df606d533ee978","src/backends.rs":"bdd03fdd6bff16ee428200bf7eae586e220a88bf58eff5b27b57f396379e12d3","src/backends/aarch64.rs":"85bb0412d6d387b9ff7112a9969a3e4432fd517db4b263e9a5ad8b43fb32d0e7","src/backends/soft.rs":"6d2dacbc9307dd6386f351778ad329b93a9b03a3de0ebd85f9ab18b34791753a","src/backends/x86.rs":"db21dfca86f27d4c333e521ead6309fde8f27d2e4319047cbc8a3e9be8975ead","src/lib.rs":"7a4205a03b64b6d1f162fe9a9a5c56d542e67819ad5ececda815566af435564c","src/macros.rs":"04b99d6c2a24da7e23e1490d15073a7868aada995446be831ca55b3c665b1390","src/slice.rs":"9321be8948d1995b0f536e5316e454cc2c7d555a8dc2113b4e2765407de9d2b3","tests/core_impls.rs":"4fe53bbf598621d9cbda5768221ee6f681c1d18f624e09b2f1b9dcdb0e197e9f","tests/proptests.rs":"bccd67b861302408d7904963ce7461ee32a9be0cfa14aaadfb9bbe801a557699","tests/regression.rs":"fcd71ea8d7992fa89846cedc0b4db6f5e4aed1167e28f2ec0e7f943319911339"},"package":"0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"}
\ No newline at end of file
### external/vendor/cmov/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "5c7e4f9bb31af81bf766360e836b6d633b84dbff"
+ },
+ "path_in_vcs": "cmov"
+}
\ No newline at end of file
### external/vendor/cmov/CHANGELOG.md
@@ -0,0 +1,162 @@
+# Changelog
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## 0.5.4 (2026-05-28)
+### Security
+- Fix [GHSA-3rjw-m598-pq24]: `Cmov`/`CmovEq` on `aarch64` can produce wrong results if high-bits of registers are set ([dba6c355])
+
+[GHSA-3rjw-m598-pq24]: https://github.com/RustCrypto/utils/security/advisories/GHSA-3rjw-m598-pq24
+[dba6c355]: https://github.com/RustCrypto/utils/commit/dba6c355c9f241e3726d5ec2a68f9f3b519f6063
+
+## 0.5.3 (2026-04-02)
+### Added
+- Impl `Cmov`/`CmovEq` for `NonZeroUsize`/`NonZeroIsize` ([#1415])
+
+### Changed
+- Avoid using `asm!` under `cfg(miri)` ([#1436])
+
+[#1415]: https://github.com/RustCrypto/utils/pull/1415
+[#1436]: https://github.com/RustCrypto/utils/pull/1436
+
+## 0.5.2 (2026-01-20)
+### Fixed
+- `Cmov` impl for `isize`/`usize` ([#1412])
+
+[#1412]: https://github.com/RustCrypto/utils/pull/1412
+
+## 0.5.1 (2026-01-18)
+### Added
+- `riscv32` optimised mask generation ([#1396])
+- `riscv64` optimised mask generation ([#1397])
+- Support for `core::num::NonZero*` and `core::cmp::Ordering` ([#1404])
+
+[#1396]: https://github.com/RustCrypto/utils/pull/1396
+[#1397]: https://github.com/RustCrypto/utils/pull/1397
+[#1404]: https://github.com/RustCrypto/utils/pull/1404
+
+## 0.5.0 (2026-01-17)
+### Added
+- Optimized `CmovEq` for `[u8]` ([#1356])
+- Optimized `CmovEq` for `[u16]` ([#1370])
+- Impl `Cmov`/`CmovEq` for slices of unsigned integers ([#1370], [#1372])
+- Impl `Cmov`/`CmovEq` for slices of signed integers ([#1373])
+- Impl `Cmov`/`CmovEq` for `isize`/`usize` ([#1375])
+
+### Changed
+- Impls of `Cmov`/`CmovEq` for `[T; N]` are now bounded on `[T]: Cmov(Eq)` ([#1372])
+
+### Removed
+- Generic impl of `CmovEq` for `[T]` where `T: CmovEq` in favor of specialized impls ([#1356])
+
+[#1356]: https://github.com/RustCrypto/utils/pull/1356
+[#1370]: https://github.com/RustCrypto/utils/pull/1370
+[#1372]: https://github.com/RustCrypto/utils/pull/1372
+[#1373]: https://github.com/RustCrypto/utils/pull/1373
+[#1375]: https://github.com/RustCrypto/utils/pull/1375
+
+## 0.4.6 (2026-01-16)
+### Added
+- Optimized `Cmov` for `[u8; N]` ([#1350])
+- Optimized `CmovEq` for `[u8; N]` ([#1353])
+- Optimized `Cmov` for `[u8]` ([#1354])
+
+### Fixed
+- Provided `Cmov::cmovz` impl ([#1351])
+
+[#1350]: https://github.com/RustCrypto/utils/pull/1350
+[#1351]: https://github.com/RustCrypto/utils/pull/1351
+[#1353]: https://github.com/RustCrypto/utils/pull/1353
+[#1354]: https://github.com/RustCrypto/utils/pull/1354
+
+## 0.4.5 (2026-01-15)
+### Changed
+- Introduce small ARM32 `asm!` optimization which also guarantees constant-time operation ([#1336], [#1346])
+
+[#1336]: https://github.com/RustCrypto/utils/pull/1336
+[#1346]: https://github.com/RustCrypto/utils/pull/1346
+
+## 0.4.4 (2026-01-14)
+### Security
+- Fix non-constant-time assembly being emitted from portable backend on `thumbv6m-none-eabi` ([#1332])
+
+[#1332]: https://github.com/RustCrypto/utils/pull/1332
+
+## 0.4.3 (2025-12-27)
+### Fixed
+- `aarch64` ASM bug ([#1299])
+- Truncation bug in portable implementation ([#1300])
+
+[#1299]: https://github.com/RustCrypto/utils/pull/1299
+[#1300]: https://github.com/RustCrypto/utils/pull/1300
+
+## 0.4.2 (2025-12-26)
+### Added
+- Signed integer support ([#1280])
+
+[#1280]: https://github.com/RustCrypto/utils/pull/1280
+
+## 0.4.1 (2025-12-19)
+### Changed
+- Use `black_box` in portable impl ([#1255])
+
+[#1255]: https://github.com/RustCrypto/utils/pull/1255
+
+## 0.4.0 (2025-09-10)
+### Changed
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1149])
+
+[#1149]: https://github.com/RustCrypto/utils/pull/1149
+
+## 0.3.1 (2023-10-14)
+### Added
+- `CmovEq` impl for slices ([#954])
+
+### Changed
+- Use `#[inline]` instead of `#[inline(always)]` ([#924])
+- `CmovEq` now invokes XOR within the ASM block ([#925])
+
+[#924]: https://github.com/RustCrypto/utils/pull/924
+[#925]: https://github.com/RustCrypto/utils/pull/925
+[#954]: https://github.com/RustCrypto/utils/pull/954
+
+## 0.3.0 (2023-04-02)
+### Added
+- `miri` support by forcing the `portable` backend ([#864])
+- Constant-time equality comparisons ([#873])
+
+### Changed
+- Make `Cmov::cmovz` a provided method ([#871])
+
+### Fixed
+- Builds on `x86` (32-bit) targets ([#863])
+
+[#863]: https://github.com/RustCrypto/utils/pull/863
+[#864]: https://github.com/RustCrypto/utils/pull/864
+[#871]: https://github.com/RustCrypto/utils/pull/871
+[#873]: https://github.com/RustCrypto/utils/pull/873
+
+## 0.2.0 (2023-02-26)
+### Added
+- `Condition` alias for `u8` ([#830])
+
+### Changed
+- Redesigned trait-based API ([#830])
+ - Built around a `Cmov` trait
+ - Trait is impl'd for `u8`, `u16`, `u32`, `u64`, `u128`
+ - Accepts a `Condition` (i.e. `u8`) as a predicate
+- MSRV 1.60 ([#839])
+
+[#830]: https://github.com/RustCrypto/utils/pull/830
+[#839]: https://github.com/RustCrypto/utils/pull/839
+
+## 0.1.1 (2022-03-02)
+### Added
+- `cmovz`/`cmovnz`-alike support for AArch64 targets ([#744])
+
+[#744]: https://github.com/RustCrypto/utils/pull/744
+
+## 0.1.0 (2022-02-27)
+- Initial release
### external/vendor/cmov/Cargo.lock
@@ -0,0 +1,621 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
+[[package]]
+name = "bitflags"
+version = "2.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+dependencies = [
+ "proptest",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.182"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "proptest"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
+dependencies = [
+ "bit-set",
+ "bit-vec",
+ "bitflags",
+ "num-traits",
+ "rand",
+ "rand_chacha",
+ "rand_xorshift",
+ "regex-syntax",
+ "rusty-fork",
+ "tempfile",
+ "unarray",
+]
+
+[[package]]
+name = "quick-error"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
+
+[[package]]
+name = "quote"
+version = "1.0.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "rand_xorshift"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "rusty-fork"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
+dependencies = [
+ "fnv",
+ "quick-error",
+ "tempfile",
+ "wait-timeout",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.1",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "unarray"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wait-timeout"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen 0.46.0",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/cmov/Cargo.toml
@@ -0,0 +1,105 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+rust-version = "1.85"
+name = "cmov"
+version = "0.5.4"
+authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = """
+Conditional move CPU intrinsics which are guaranteed on major platforms (ARM32/ARM64, x86/x86_64,
+RISC-V) to execute in constant-time and not be rewritten as branches by the compiler. Provides
+wrappers for the CMOV family of instructions on x86/x86_64 and CSEL on AArch64, along with a
+portable "best-effort" pure Rust fallback implementation.
+"""
+documentation = "https://docs.rs/cmov"
+readme = "README.md"
+keywords = [
+ "constant-time",
+ "crypto",
+ "intrinsics",
+]
+categories = [
+ "cryptography",
+ "hardware-support",
+ "no-std",
+]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/RustCrypto/utils"
+
+[package.metadata.docs.rs]
+all-features = true
+
+[lib]
+name = "cmov"
+path = "src/lib.rs"
+
+[[test]]
+name = "core_impls"
+path = "tests/core_impls.rs"
+
+[[test]]
+name = "proptests"
+path = "tests/proptests.rs"
+
+[[test]]
+name = "regression"
+path = "tests/regression.rs"
+
+[target."cfg(any(unix, windows))".dev-dependencies.proptest]
+version = "1.11"
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+doc_markdown = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/cmov/Cargo.toml.orig
@@ -0,0 +1,27 @@
+[package]
+name = "cmov"
+version = "0.5.4"
+authors = ["RustCrypto Developers"]
+edition = "2024"
+rust-version = "1.85"
+documentation = "https://docs.rs/cmov"
+readme = "README.md"
+repository = "https://github.com/RustCrypto/utils"
+license = "Apache-2.0 OR MIT"
+keywords = ["constant-time", "crypto", "intrinsics"]
+categories = ["cryptography", "hardware-support", "no-std"]
+description = """
+Conditional move CPU intrinsics which are guaranteed on major platforms (ARM32/ARM64, x86/x86_64,
+RISC-V) to execute in constant-time and not be rewritten as branches by the compiler. Provides
+wrappers for the CMOV family of instructions on x86/x86_64 and CSEL on AArch64, along with a
+portable "best-effort" pure Rust fallback implementation.
+"""
+
+[target.'cfg(any(unix, windows))'.dev-dependencies]
+proptest = "1.11"
+
+[lints]
+workspace = true
+
+[package.metadata.docs.rs]
+all-features = true
### external/vendor/cmov/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ 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
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
### external/vendor/cmov/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2018-2019 The RustCrypto Project Developers
+Copyright (c) 2022-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/cmov/README.md
@@ -0,0 +1,124 @@
+# [RustCrypto]: CMOV (Conditional Move)
+
+[![Crate][crate-image]][crate-link]
+[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
+![Apache 2.0/MIT Licensed][license-image]
+![MSRV][msrv-image]
+[![Project Chat][chat-image]][chat-link]
+
+Conditional move CPU intrinsics which are guaranteed on major platforms to execute in constant-time
+and not be rewritten as branches by the compiler.
+
+Provides wrappers for the [CMOV family] of instructions on `x86`/`x86_64` and the [CSEL]
+instruction on `aarch64` CPUs, along with a portable fallback implementation for other CPU
+architectures.
+
+## About
+
+Conditional move intrinsics provide [predication] which allows selection
+of one or more values without using branch instructions, thus making the
+selection constant-time with respect to the values, and not subject to CPU
+execution features which might introduce timing or other microarchitectural
+sidechannels introduced by branch prediction or other speculative execution
+features.
+
+This crate provides wrappers for the CMOV/CSEL instructions implemented using
+inline `asm!`, which means the implementation is a black box that will not be
+rewritten by e.g. LLVM's architecture-specific lowerings, such as the
+[x86-cmov-conversion] pass.
+
+This is a *low level crate* who's API is designed to make it easy to build
+portable abstractions across various CPU architectures and is not intended for
+general purpose use.
+
+See the [`ctutils`] crate for a higher-level API build on top of `cmov`.
+
+## Supported target architectures
+
+This crate provides guaranteed constant-time operation using inline `asm!`
+on the following CPU architectures:
+
+- [x] `x86`/`x86_64` (`CMOVZ`, `CMOVNZ`)
+- [x] `arm` (mask generation only)
+- [x] `aarch64` (`CSEL`)
+- [x] `riscv32` (mask generation only)
+- [x] `riscv64` (mask generation only)
+
+On other target architectures, a "best effort" portable fallback implementation
+based on bitwise arithmetic is used instead, augmented with tactical usage of
+`core::hint::black_box` based on past analysis of the generated assembly.
+However, we cannot guarantee that this implementation generates branch-free
+code, especially on hypothetical future rustc versions which introduce new
+optimizations.
+
+Please [open an issue] if you notice non-constant-time CPU instructions
+(e.g. branches, secret-dependent address calculations) being generated and we
+will treat it as a security issue and do our best to find a solution.
+
+You can also open an issue to request first-class support for native
+predication instructions on other architectures we don't currently support.
+
+### `x86` / `x86_64` notes
+
+Intel has confirmed that all extant CPUs implement the CMOV family of
+instructions in constant-time, and that this property will hold for future
+Intel CPUs as well.
+
+## ⚠️ Security Warning
+
+The implementation contained in this crate has never been independently audited!
+USE AT YOUR OWN RISK!
+
+Below are security issues this crate has experienced in the past:
+
+- [RUSTSEC-2026-0003]: Non-constant-time code generation on ARM32 targets
+- [GHSA-3rjw-m598-pq24]: `Cmov`/`CmovEq` on ARM64 can produce wrong results if high-bits of registers are set
+
+## Minimum Supported Rust Version (MSRV) Policy
+
+MSRV increases are not considered breaking changes and can happen in patch
+releases.
+
+The crate MSRV accounts for all supported targets and crate feature
+combinations, excluding explicitly unstable features.
+
+## License
+
+Licensed under either of:
+
+* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
+* [MIT license](http://opensource.org/licenses/MIT)
+
+at your option.
+
+### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
+dual licensed as above, without any additional terms or conditions.
+
+[//]: # (badges)
+
+[crate-image]: https://img.shields.io/crates/v/cmov.svg
+[crate-link]: https://crates.io/crates/cmov
+[docs-image]: https://docs.rs/cmov/badge.svg
+[docs-link]: https://docs.rs/cmov/
+[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
+[msrv-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
+[build-image]: https://github.com/RustCrypto/utils/actions/workflows/cmov.yml/badge.svg
+[build-link]: https://github.com/RustCrypto/utils/actions/workflows/cmov.yml
+[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
+[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260052-utils
+
+[//]: # (links)
+
+[RustCrypto]: https://github.com/RustCrypto
+[CMOV family]: https://www.jaist.ac.jp/iscenter-new/mpc/altix/altixdata/opt/intel/vtune/doc/users_guide/mergedProjects/analyzer_ec/mergedProjects/reference_olh/mergedProjects/instructions/instruct32_hh/vc35.htm
+[CSEL]: https://developer.arm.com/documentation/dui0802/b/CSEL
+[predication]: https://en.wikipedia.org/wiki/Predication_(computer_architecture)
+[x86-cmov-conversion]: https://dsprenkels.com/cmov-conversion.html
+[`ctutils`]: https://docs.rs/ctutils
+[open an issue]: https://github.com/RustCrypto/utils/issues
+[RUSTSEC-2026-0003]: https://rustsec.org/advisories/RUSTSEC-2026-0003.html
+[GHSA-3rjw-m598-pq24]: https://github.com/RustCrypto/utils/security/advisories/GHSA-3rjw-m598-pq24
### external/vendor/cmov/src/array.rs
@@ -0,0 +1,29 @@
+//! Trait impls for core arrays.
+//!
+//! Implemented generically, delegating to the slice impls.
+
+use crate::{Cmov, CmovEq, Condition};
+
+// Optimized implementation for arrays which coalesces them into word-sized chunks first,
+// then performs [`Cmov`] at the word-level to cut down on the total number of instructions.
+impl<T, const N: usize> Cmov for [T; N]
+where
+ [T]: Cmov,
+{
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ self.as_mut_slice().cmovnz(value, condition);
+ }
+}
+
+// Optimized implementation for arrays which coalesces them into word-sized chunks first,
+// then performs [`CmovEq`] at the word-level to cut down on the total number of instructions.
+impl<T, const N: usize> CmovEq for [T; N]
+where
+ [T]: CmovEq,
+{
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ self.as_slice().cmovne(rhs, input, output);
+ }
+}
### external/vendor/cmov/src/backends.rs
@@ -0,0 +1,17 @@
+//! Backends for `cmov`, only one of which will be selected at compile-time.
+
+// Architecture-specific backends for target architectures with native predication instructions
+#[cfg(not(miri))]
+#[cfg(target_arch = "aarch64")]
+mod aarch64;
+#[cfg(not(miri))]
+#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+mod x86;
+
+// Fallback portable implementation for targets which don't have native predication instructions
+// (or if they do, aren't currently supported)
+#[cfg(any(
+ not(any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")),
+ miri
+))]
+mod soft;
### external/vendor/cmov/src/backends/aarch64.rs
@@ -0,0 +1,181 @@
+use crate::{Cmov, CmovEq, Condition};
+use core::arch::asm;
+
+/// Conditional select
+macro_rules! csel {
+ ($tst:expr, $csel:expr, $dst:expr, $src:expr, $condition:expr) => {
+ unsafe {
+ asm! {
+ $tst,
+ $csel,
+ in(reg) $condition,
+ inlateout(reg) *$dst,
+ in(reg) *$src,
+ in(reg) *$dst,
+ options(pure, nomem, nostack),
+ };
+ }
+ };
+}
+
+/// Conditional select-based equality test
+macro_rules! cseleq {
+ ($eor:expr, $cmp:expr, $instruction:expr, $lhs:expr, $rhs:expr, $condition:expr, $dst:expr) => {
+ let mut tmp = u16::from(*$dst);
+ let condition = u16::from($condition);
+ unsafe {
+ asm! {
+ $eor,
+ $cmp,
+ $instruction,
+ out(reg) _,
+ in(reg) *$lhs,
+ in(reg) *$rhs,
+ inlateout(reg) tmp,
+ in(reg) condition,
+ in(reg) tmp,
+ options(pure, nomem, nostack),
+ };
+ };
+
+ *$dst = (tmp & 0xFF) as u8;
+ };
+}
+
+/// Conditional select using 32-bit `:w` registers
+macro_rules! csel32 {
+ ($csel:expr, $dst:expr, $src:expr, $condition:expr) => {
+ csel!("tst {0:w}, 0xff", $csel, $dst, $src, $condition)
+ };
+}
+
+/// Conditional select using 64-bit `:x` registers
+macro_rules! csel64 {
+ ($csel:expr, $dst:expr, $src:expr, $condition:expr) => {
+ csel!("tst {0:x}, 0xff", $csel, $dst, $src, $condition)
+ };
+}
+
+/// Conditional select equality test using 32-bit `:w` registers and
+/// correctly handling unspecified upper bits of 16 bit inputs
+macro_rules! cseleq16 {
+ ($instruction:expr, $lhs:expr, $rhs:expr, $condition:expr, $dst:expr) => {
+ cseleq!(
+ "eor {0:w}, {1:w}, {2:w}",
+ "tst {0:w}, 0xffff",
+ $instruction,
+ $lhs,
+ $rhs,
+ $condition,
+ $dst
+ )
+ };
+}
+
+/// Conditional select equality test using 32-bit `:w` registers
+macro_rules! cseleq32 {
+ ($instruction:expr, $lhs:expr, $rhs:expr, $condition:expr, $dst:expr) => {
+ cseleq!(
+ "eor {0:w}, {1:w}, {2:w}",
+ "cmp {0:w}, 0",
+ $instruction,
+ $lhs,
+ $rhs,
+ $condition,
+ $dst
+ )
+ };
+}
+
+/// Conditional select equality test using 64-bit `:w` registers
+macro_rules! cseleq64 {
+ ($instruction:expr, $lhs:expr, $rhs:expr, $condition:expr, $dst:expr) => {
+ cseleq!(
+ "eor {0:x}, {1:x}, {2:x}",
+ "cmp {0:x}, 0",
+ $instruction,
+ $lhs,
+ $rhs,
+ $condition,
+ $dst
+ )
+ };
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u16 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ csel32!("csel {1:w}, {2:w}, {3:w}, NE", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ csel32!("csel {1:w}, {2:w}, {3:w}, EQ", self, value, condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u32 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ csel32!("csel {1:w}, {2:w}, {3:w}, NE", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ csel32!("csel {1:w}, {2:w}, {3:w}, EQ", self, value, condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u64 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ csel64!("csel {1:x}, {2:x}, {3:x}, NE", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ csel64!("csel {1:x}, {2:x}, {3:x}, EQ", self, value, condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u16 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq16!("csel {3:w}, {4:w}, {5:w}, NE", self, rhs, input, output);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq16!("csel {3:w}, {4:w}, {5:w}, EQ", self, rhs, input, output);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u32 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq32!("csel {3:w}, {4:w}, {5:w}, NE", self, rhs, input, output);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq32!("csel {3:w}, {4:w}, {5:w}, EQ", self, rhs, input, output);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u64 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq64!("csel {3:x}, {4:x}, {5:x}, NE", self, rhs, input, output);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cseleq64!("csel {3:x}, {4:x}, {5:x}, EQ", self, rhs, input, output);
+ }
+}
### external/vendor/cmov/src/backends/soft.rs
@@ -0,0 +1,308 @@
+//! Portable "best effort" implementation of `Cmov`/`CmovEq`.
+//!
+//! This implementation is based on portable arithmetic operations augmented with tactical usage of
+//! `core::hint::black_box` based on past observations of where the optimizer has inserted branches
+//! (see CVE-2026-23519), but the fully portable implementation cannot guarantee that the resulting
+//! generated assembly is free of branch instructions.
+//!
+//! For select platforms using this backend (currently limited to ARM32) we use `asm!` for mask
+//! generation which should largely mitigate the optimizer potentially inserting branches.
+
+use crate::{Cmov, CmovEq, Condition};
+use core::ops::{BitAnd, BitOr, Not};
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u16 {
+ #[inline]
+ fn cmovnz(&mut self, value: &u16, condition: Condition) {
+ *self = masksel(*self, *value, (masknz32(condition.into()) & 0xFFFF) as u16);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &u16, condition: Condition) {
+ *self = masksel(*self, *value, (!masknz32(condition.into()) & 0xFFFF) as u16);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u32 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ *self = masksel(*self, *value, masknz32(condition.into()));
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ *self = masksel(*self, *value, !masknz32(condition.into()));
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u64 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ *self = masksel(*self, *value, masknz64(condition.into()));
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ *self = masksel(*self, *value, !masknz64(condition.into()));
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u16 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(
+ *output,
+ input,
+ (masknz32((*self ^ *rhs).into()) & 0xFF) as Condition,
+ );
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(
+ *output,
+ input,
+ (!masknz32((*self ^ *rhs).into()) & 0xFF) as Condition,
+ );
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u32 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(*output, input, (maskne32(*self, *rhs) & 0xFF) as Condition);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(*output, input, (maskeq32(*self, *rhs) & 0xFF) as Condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u64 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(*output, input, (maskne64(*self, *rhs) & 0xFF) as Condition);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ *output = masksel(*output, input, (maskeq64(*self, *rhs) & 0xFF) as Condition);
+ }
+}
+
+/// Returns `u32::MAX` if `x` is equal to `y`, otherwise returns `0` (32-bit version)
+#[inline]
+fn maskeq32(x: u32, y: u32) -> u32 {
+ !maskne32(x, y)
+}
+
+/// Returns `u64::MAX` if `x` is equal to `y`, otherwise returns `0` (64-bit version)
+#[inline]
+fn maskeq64(x: u64, y: u64) -> u64 {
+ !maskne64(x, y)
+}
+
+/// Returns `0` if `x` is equal to `y`, otherwise returns `u32::MAX` (32-bit version)
+#[inline]
+fn maskne32(x: u32, y: u32) -> u32 {
+ masknz32(x ^ y)
+}
+
+/// Returns `0` if `x` is equal to `y`, otherwise returns `u64::MAX` (64-bit version)
+#[inline]
+fn maskne64(x: u64, y: u64) -> u64 {
+ masknz64(x ^ y)
+}
+
+/// Return a `u32::MAX` mask if `condition` is non-zero, otherwise return zero for a zero input.
+#[cfg(any(
+ miri,
+ not(any(target_arch = "arm", target_arch = "riscv32", target_arch = "riscv64"))
+))]
+fn masknz32(condition: u32) -> u32 {
+ masknz!(condition: u32)
+}
+
+/// Return a `u64::MAX` mask if `condition` is non-zero, otherwise return zero for a zero input.
+#[cfg(any(
+ miri,
+ not(any(target_arch = "arm", target_arch = "riscv32", target_arch = "riscv64"))
+))]
+fn masknz64(condition: u64) -> u64 {
+ masknz!(condition: u64)
+}
+
+/// Optimized mask generation for ARM32 targets.
+///
+/// This is written in assembly both for performance and because we've had problematic code
+/// generation in this routine in the past which lead to the insertion of a branch, which using
+/// assembly should guarantee won't happen again in the future (CVE-2026-23519).
+#[cfg(all(target_arch = "arm", not(miri)))]
+fn masknz32(condition: u32) -> u32 {
+ let mut mask: u32;
+ unsafe {
+ core::arch::asm!(
+ "rsbs {0}, {1}, #0", // Reverse subtract
+ "sbcs {0}, {0}, {0}", // Subtract with carry, setting flags
+ lateout(reg) mask,
+ in(reg) condition,
+ options(nostack, nomem),
+ );
+ }
+ mask
+}
+
+/// Optimized mask generation for riscv32 targets.
+#[cfg(all(target_arch = "riscv32", not(miri)))]
+fn masknz32(condition: u32) -> u32 {
+ let mut mask: u32;
+ unsafe {
+ core::arch::asm!(
+ "seqz {0}, {1}", // Set-if-not-zero pseudo-instruction
+ "addi {0}, {0}, -1", // Subtract 1, to have either full ones or full zeroes mask
+ lateout(reg) mask,
+ in(reg) condition,
+ options(nostack, nomem),
+ );
+ }
+ mask
+}
+
+/// Optimized mask generation for riscv32 targets.
+#[cfg(all(target_arch = "riscv64", not(miri)))]
+fn masknz32(condition: u32) -> u32 {
+ (masknz64(condition.into()) & 0xFFFF_FFFF) as u32
+}
+
+/// Optimized mask generation for riscv64 targets.
+#[cfg(all(target_arch = "riscv64", not(miri)))]
+fn masknz64(condition: u64) -> u64 {
+ let mut mask: u64;
+ unsafe {
+ core::arch::asm!(
+ "seqz {0}, {1}", // Set-if-not-zero pseudo-instruction
+ "addi {0}, {0}, -1", // Subtract 1, to have either full ones or full zeroes mask
+ lateout(reg) mask,
+ in(reg) condition,
+ options(nostack, nomem),
+ );
+ }
+ mask
+}
+
+/// 64-bit wrapper for targets that implement 32-bit mask generation in assembly.
+#[cfg(all(any(target_arch = "arm", target_arch = "riscv32"), not(miri)))]
+fn masknz64(condition: u64) -> u64 {
+ let lo = masknz32((condition & 0xFFFF_FFFF) as u32);
+ let hi = masknz32((condition >> 32) as u32);
+ let mask = u64::from(lo | hi);
+ mask | mask << 32
+}
+
+/// Given a supplied mask of `0` or all 1-bits (i.e. `u*::MAX`), select `a` if the mask is all-zeros
+/// and `b` if the mask is all-ones.
+///
+/// This function shouldn't be used with a mask that isn't `0` or `u*::MAX`.
+#[inline]
+fn masksel<T>(a: T, b: T, mask: T) -> T
+where
+ T: BitAnd<Output = T> + BitOr<Output = T> + Copy + Not<Output = T>,
+{
+ (a & !mask) | (b & mask)
+}
+
+#[cfg(test)]
+mod tests {
+ // Spot check up to a given limit
+ const TEST_LIMIT: u32 = 65536;
+
+ #[test]
+ fn maskeq32() {
+ assert_eq!(super::maskeq32(0, 0), u32::MAX);
+ assert_eq!(super::maskeq32(1, 0), 0);
+ assert_eq!(super::maskeq32(0, 1), 0);
+ assert_eq!(super::maskeq32(1, 1), u32::MAX);
+ assert_eq!(super::maskeq32(u32::MAX, 1), 0);
+ assert_eq!(super::maskeq32(1, u32::MAX), 0);
+ assert_eq!(super::maskeq32(u32::MAX, u32::MAX), u32::MAX);
+ }
+
+ #[test]
+ fn maskeq64() {
+ assert_eq!(super::maskeq64(0, 0), u64::MAX);
+ assert_eq!(super::maskeq64(1, 0), 0);
+ assert_eq!(super::maskeq64(0, 1), 0);
+ assert_eq!(super::maskeq64(1, 1), u64::MAX);
+ assert_eq!(super::maskeq64(u64::MAX, 1), 0);
+ assert_eq!(super::maskeq64(1, u64::MAX), 0);
+ assert_eq!(super::maskeq64(u64::MAX, u64::MAX), u64::MAX);
+ }
+
+ #[test]
+ fn maskne32() {
+ assert_eq!(super::maskne32(0, 0), 0);
+ assert_eq!(super::maskne32(1, 0), u32::MAX);
+ assert_eq!(super::maskne32(0, 1), u32::MAX);
+ assert_eq!(super::maskne32(1, 1), 0);
+ assert_eq!(super::maskne32(u32::MAX, 1), u32::MAX);
+ assert_eq!(super::maskne32(1, u32::MAX), u32::MAX);
+ assert_eq!(super::maskne32(u32::MAX, u32::MAX), 0);
+ }
+
+ #[test]
+ fn maskne64() {
+ assert_eq!(super::maskne64(0, 0), 0);
+ assert_eq!(super::maskne64(1, 0), u64::MAX);
+ assert_eq!(super::maskne64(0, 1), u64::MAX);
+ assert_eq!(super::maskne64(1, 1), 0);
+ assert_eq!(super::maskne64(u64::MAX, 1), u64::MAX);
+ assert_eq!(super::maskne64(1, u64::MAX), u64::MAX);
+ assert_eq!(super::maskne64(u64::MAX, u64::MAX), 0);
+ }
+
+ #[test]
+ fn masknz32() {
+ assert_eq!(super::masknz32(0), 0);
+ for i in 1..=TEST_LIMIT {
+ assert_eq!(super::masknz32(i), u32::MAX);
+ }
+
+ for i in (u32::MAX - TEST_LIMIT)..=u32::MAX {
+ assert_eq!(super::masknz32(i), u32::MAX);
+ }
+ }
+
+ #[test]
+ fn masknz64() {
+ assert_eq!(super::masknz64(0), 0);
+ for i in 1..=(TEST_LIMIT as u64) {
+ assert_eq!(super::masknz64(i), u64::MAX);
+ }
+
+ for i in (u64::MAX - TEST_LIMIT as u64)..=u64::MAX {
+ assert_eq!(super::masknz64(i), u64::MAX);
+ }
+ }
+
+ #[test]
+ fn masksel() {
+ assert_eq!(super::masksel(23u8, 42u8, 0u8), 23u8);
+ assert_eq!(super::masksel(23u8, 42u8, u8::MAX), 42u8);
+
+ assert_eq!(super::masksel(17u32, 101077u32, 0u32), 17u32);
+ assert_eq!(super::masksel(17u32, 101077u32, u32::MAX), 101077u32);
+
+ assert_eq!(super::masksel(129u64, 0xFFEEDDCCBBAA9988u64, 0u64), 129u64);
+ assert_eq!(
+ super::masksel(129u64, 0xFFEEDDCCBBAA9988u64, u64::MAX),
+ 0xFFEEDDCCBBAA9988u64
+ );
+ }
+}
### external/vendor/cmov/src/backends/x86.rs
@@ -0,0 +1,220 @@
+//! From "AMD64 Architecture Programmer’s Manual, Volume 1: Application Programming"
+//! (Rev. 3.23 - October 2020) page 46:
+//!
+//! <https://www.amd.com/system/files/TechDocs/24592.pdf>
+//!
+//! > The CMOVcc instructions conditionally copy a word, doubleword, or
+//! > quadword from a register or memory location to a register location.
+//! > The source and destination must be of the same size.
+
+use crate::{Cmov, CmovEq, Condition};
+use core::arch::asm;
+
+macro_rules! cmov {
+ ($instruction:expr, $dst:expr, $src:expr, $condition:expr) => {
+ unsafe {
+ asm! {
+ "test {0}, {0}",
+ $instruction,
+ in(reg_byte) $condition,
+ inlateout(reg) *$dst,
+ in(reg) *$src,
+ options(pure, nomem, nostack),
+ };
+ }
+ };
+}
+
+macro_rules! cmov_eq {
+ ($xor:expr, $instruction:expr, $lhs:expr, $rhs:expr, $condition:expr, $dst:expr) => {
+ let mut tmp = u16::from(*$dst);
+ let condition = u16::from($condition);
+ unsafe {
+ asm! {
+ $xor,
+ $instruction,
+ inout(reg) *$lhs => _,
+ in(reg) *$rhs,
+ inlateout(reg) tmp,
+ in(reg) condition,
+ options(pure, nomem, nostack),
+ };
+ }
+
+ *$dst = (tmp & 0xFF) as u8;
+ };
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u16 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovnz {1:e}, {2:e}", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovz {1:e}, {2:e}", self, value, condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u32 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovnz {1:e}, {2:e}", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovz {1:e}, {2:e}", self, value, condition);
+ }
+}
+
+#[cfg(target_arch = "x86")]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u64 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ let mut lo = (*self & u32::MAX as u64) as u32;
+ let mut hi = (*self >> 32) as u32;
+
+ lo.cmovnz(&((*value & u32::MAX as u64) as u32), condition);
+ hi.cmovnz(&((*value >> 32) as u32), condition);
+
+ *self = (lo as u64) | (hi as u64) << 32;
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ let mut lo = (*self & u32::MAX as u64) as u32;
+ let mut hi = (*self >> 32) as u32;
+
+ lo.cmovz(&((*value & u32::MAX as u64) as u32), condition);
+ hi.cmovz(&((*value >> 32) as u32), condition);
+
+ *self = (lo as u64) | (hi as u64) << 32;
+ }
+}
+
+#[cfg(target_arch = "x86_64")]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for u64 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovnz {1:r}, {2:r}", self, value, condition);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ cmov!("cmovz {1:r}, {2:r}", self, value, condition);
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u16 {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:x}, {1:x}",
+ "cmovz {2:e}, {3:e}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:x}, {1:x}",
+ "cmovnz {2:e}, {3:e}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+}
+
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u32 {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:e}, {1:e}",
+ "cmovz {2:e}, {3:e}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:e}, {1:e}",
+ "cmovnz {2:e}, {3:e}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+}
+
+#[cfg(target_arch = "x86")]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u64 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let lo = (*self & u32::MAX as u64) as u32;
+ let hi = (*self >> 32) as u32;
+
+ let mut tmp = 1u8;
+ lo.cmovne(&((*rhs & u32::MAX as u64) as u32), 0, &mut tmp);
+ hi.cmovne(&((*rhs >> 32) as u32), 0, &mut tmp);
+ tmp.cmoveq(&0, input, output);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let lo = (*self & u32::MAX as u64) as u32;
+ let hi = (*self >> 32) as u32;
+
+ let mut tmp = 1u8;
+ lo.cmovne(&((*rhs & u32::MAX as u64) as u32), 0, &mut tmp);
+ hi.cmovne(&((*rhs >> 32) as u32), 0, &mut tmp);
+ tmp.cmoveq(&1, input, output);
+ }
+}
+
+#[cfg(target_arch = "x86_64")]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl CmovEq for u64 {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:r}, {1:r}",
+ "cmovz {2:r}, {3:r}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ cmov_eq!(
+ "xor {0:r}, {1:r}",
+ "cmovnz {2:r}, {3:r}",
+ self,
+ rhs,
+ input,
+ output
+ );
+ }
+}
### external/vendor/cmov/src/lib.rs
@@ -0,0 +1,337 @@
+#![no_std]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
+#![doc(
+ html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
+ html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
+)]
+#![allow(clippy::undocumented_unsafe_blocks)] // TODO(tarcieri): document all unsafe blocks
+#![warn(
+ clippy::arithmetic_side_effects,
+ clippy::integer_division_remainder_used,
+ clippy::panic
+)]
+
+#[macro_use]
+mod macros;
+
+mod array;
+mod backends;
+mod slice;
+
+use core::{
+ cmp,
+ num::{
+ NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
+ NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
+ },
+};
+
+/// Condition: the argument given to [`Cmov`] and [`CmovEq`] representing an effective boolean
+/// condition by virtue of being zero or non-zero.
+///
+/// Using a `u8` for this type helps prevent rustc optimizers from speculating about it as if it
+/// were a boolean value.
+pub type Condition = u8;
+
+/// Conditional move
+pub trait Cmov {
+ /// Move if non-zero.
+ ///
+ /// Moves `value` to `self` in constant-time if `condition` is non-zero.
+ fn cmovnz(&mut self, value: &Self, condition: Condition);
+
+ /// Move if zero.
+ ///
+ /// Moves `value` to `self` in constant-time if `condition` is equal to zero.
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ let nz = masknz!(condition: Condition);
+ self.cmovnz(value, !nz);
+ }
+}
+
+/// Conditional move with equality comparison
+pub trait CmovEq {
+ /// Move if both inputs are not equal.
+ ///
+ /// Moves `input` to `output` in constant-time if `self` and `rhs` are NOT equal.
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let mut tmp = 1u8;
+ self.cmoveq(rhs, 0u8, &mut tmp);
+ tmp.cmoveq(&1u8, input, output);
+ }
+
+ /// Move if both inputs are equal.
+ ///
+ /// Moves `input` to `output` in constant-time if `self` and `rhs` are equal.
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let mut tmp = 1u8;
+ self.cmovne(rhs, 0u8, &mut tmp);
+ tmp.cmoveq(&1, input, output);
+ }
+}
+
+impl Cmov for u8 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ let mut tmp = u16::from(*self);
+ tmp.cmovnz(&u16::from(*value), condition);
+ debug_assert!(u8::try_from(tmp).is_ok());
+ *self = (tmp & 0xFF) as u8;
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ let mut tmp = u16::from(*self);
+ tmp.cmovz(&u16::from(*value), condition);
+ debug_assert!(u8::try_from(tmp).is_ok());
+ *self = (tmp & 0xFF) as u8;
+ }
+}
+
+impl Cmov for u128 {
+ #[inline]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ let mut lo = (*self & 0xFFFF_FFFF_FFFF_FFFF) as u64;
+ let mut hi = (*self >> 64) as u64;
+
+ lo.cmovnz(&((*value & 0xFFFF_FFFF_FFFF_FFFF) as u64), condition);
+ hi.cmovnz(&((*value >> 64) as u64), condition);
+
+ *self = u128::from(lo) | (u128::from(hi) << 64);
+ }
+
+ #[inline]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ let mut lo = (*self & 0xFFFF_FFFF_FFFF_FFFF) as u64;
+ let mut hi = (*self >> 64) as u64;
+
+ lo.cmovz(&((*value & 0xFFFF_FFFF_FFFF_FFFF) as u64), condition);
+ hi.cmovz(&((*value >> 64) as u64), condition);
+
+ *self = u128::from(lo) | (u128::from(hi) << 64);
+ }
+}
+
+impl CmovEq for u8 {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ u16::from(*self).cmoveq(&u16::from(*rhs), input, output);
+ }
+
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ u16::from(*self).cmovne(&u16::from(*rhs), input, output);
+ }
+}
+
+impl CmovEq for u128 {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let lo = (*self & 0xFFFF_FFFF_FFFF_FFFF) as u64;
+ let hi = (*self >> 64) as u64;
+
+ let mut tmp = 1u8;
+ lo.cmovne(&((*rhs & 0xFFFF_FFFF_FFFF_FFFF) as u64), 0, &mut tmp);
+ hi.cmovne(&((*rhs >> 64) as u64), 0, &mut tmp);
+ tmp.cmoveq(&0, input, output);
+ }
+
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ let lo = (*self & 0xFFFF_FFFF_FFFF_FFFF) as u64;
+ let hi = (*self >> 64) as u64;
+
+ let mut tmp = 1u8;
+ lo.cmovne(&((*rhs & 0xFFFF_FFFF_FFFF_FFFF) as u64), 0, &mut tmp);
+ hi.cmovne(&((*rhs >> 64) as u64), 0, &mut tmp);
+ tmp.cmoveq(&1, input, output);
+ }
+}
+
+/// Impl `Cmov*` by first casting to unsigned then using the unsigned `Cmov` impls
+// TODO(tarcieri): use `cast_unsigned`/`cast_signed` to get rid of the `=> u*`
+macro_rules! impl_cmov_traits_for_signed_ints {
+ ( $($int:ty => $uint:ty),+ ) => {
+ $(
+ impl Cmov for $int {
+ #[inline]
+ #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ let mut tmp = *self as $uint;
+ tmp.cmovnz(&(*value as $uint), condition);
+ *self = tmp as $int;
+ }
+
+ #[inline]
+ #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
+ fn cmovz(&mut self, value: &Self, condition: Condition) {
+ let mut tmp = *self as $uint;
+ tmp.cmovz(&(*value as $uint), condition);
+ *self = tmp as $int;
+ }
+ }
+
+ impl CmovEq for $int {
+ #[inline]
+ #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as $uint).cmoveq(&(*rhs as $uint), input, output);
+ }
+
+ #[inline]
+ #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as $uint).cmovne(&(*rhs as $uint), input, output);
+ }
+ }
+ )+
+ };
+}
+
+impl_cmov_traits_for_signed_ints!(
+ i8 => u8,
+ i16 => u16,
+ i32 => u32,
+ i64 => u64,
+ i128 => u128
+);
+
+macro_rules! impl_cmov_traits_for_size_int {
+ ($size:ty, $int16:ty, $int32:ty, $int64:ty) => {
+ #[cfg(any(
+ target_pointer_width = "16",
+ target_pointer_width = "32",
+ target_pointer_width = "64"
+ ))]
+ #[cfg_attr(docsrs, doc(cfg(true)))]
+ #[allow(clippy::cast_possible_truncation)]
+ impl Cmov for $size {
+ #[cfg(target_pointer_width = "16")]
+ #[inline]
+ fn cmovnz(&mut self, other: &Self, condition: Condition) {
+ let mut tmp = *self as $int16;
+ tmp.cmovnz(&(*other as $int16), condition);
+ *self = tmp as $size;
+ }
+
+ #[cfg(target_pointer_width = "32")]
+ #[inline]
+ fn cmovnz(&mut self, other: &Self, condition: Condition) {
+ let mut tmp = *self as $int32;
+ tmp.cmovnz(&(*other as $int32), condition);
+ *self = tmp as $size;
+ }
+
+ #[cfg(target_pointer_width = "64")]
+ #[inline]
+ fn cmovnz(&mut self, other: &Self, condition: Condition) {
+ let mut tmp = *self as $int64;
+ tmp.cmovnz(&(*other as $int64), condition);
+ *self = tmp as $size;
+ }
+ }
+
+ #[cfg(any(
+ target_pointer_width = "16",
+ target_pointer_width = "32",
+ target_pointer_width = "64"
+ ))]
+ #[cfg_attr(docsrs, doc(cfg(true)))]
+ #[allow(clippy::cast_possible_truncation)]
+ impl CmovEq for $size {
+ #[cfg(target_pointer_width = "16")]
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as $int16).cmovne(&(*rhs as $int16), input, output);
+ }
+
+ #[cfg(target_pointer_width = "32")]
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as $int32).cmovne(&(*rhs as $int32), input, output);
+ }
+
+ #[cfg(target_pointer_width = "64")]
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as $int64).cmovne(&(*rhs as $int64), input, output);
+ }
+ }
+ };
+}
+
+impl_cmov_traits_for_size_int!(isize, i16, i32, i64);
+impl_cmov_traits_for_size_int!(usize, u16, u32, u64);
+
+/// Impl `Cmov` for `NonZero<T>` by calling the `Cmov` impl for `T`.
+macro_rules! impl_cmov_traits_for_nonzero_integers {
+ ( $($nzint:ident),+ ) => {
+ $(
+ impl Cmov for $nzint {
+ #[inline]
+ fn cmovnz(&mut self, src: &Self, condition: Condition) {
+ let mut n = self.get();
+ n.cmovnz(&src.get(), condition);
+
+ // SAFETY: we are constructing `NonZero` from a value we obtained from
+ // `NonZero::get`, which ensures it's non-zero.
+ #[allow(unsafe_code)]
+ unsafe { *self = $nzint::new_unchecked(n) }
+ }
+ }
+
+ impl CmovEq for $nzint {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ self.get().cmoveq(&rhs.get(), input, output);
+ }
+ }
+ )+
+ };
+}
+
+impl_cmov_traits_for_nonzero_integers!(
+ NonZeroI8,
+ NonZeroI16,
+ NonZeroI32,
+ NonZeroI64,
+ NonZeroI128,
+ NonZeroIsize,
+ NonZeroU8,
+ NonZeroU16,
+ NonZeroU32,
+ NonZeroU64,
+ NonZeroU128,
+ NonZeroUsize
+);
+
+impl Cmov for cmp::Ordering {
+ #[inline]
+ fn cmovnz(&mut self, src: &Self, condition: Condition) {
+ // `Ordering` is `#[repr(i8)]` where:
+ //
+ // - `Less` => -1
+ // - `Equal` => 0
+ // - `Greater` => 1
+ //
+ // Given this, it's possible to operate on orderings as if they're `i8`, which allows us to
+ // use the `CtSelect` impl on `i8` to select between them.
+ let mut n = *self as i8;
+ n.cmovnz(&(*src as i8), condition);
+
+ // SAFETY: `Ordering` is `#[repr(i8)]` and `ret` has been assigned to
+ // a value which was originally a valid `Ordering` then cast to `i8`
+ #[allow(trivial_casts, unsafe_code)]
+ unsafe {
+ *self = *(&raw const n).cast::<Self>();
+ }
+ }
+}
+
+impl CmovEq for cmp::Ordering {
+ #[inline]
+ fn cmoveq(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ (*self as i8).cmoveq(&(*rhs as i8), input, output);
+ }
+}
### external/vendor/cmov/src/macros.rs
@@ -0,0 +1,63 @@
+//! Macro definitions.
+
+/// Generates a mask the width of the given unsigned integer type `$uint` if the input value is
+/// non-zero.
+///
+/// Uses `core::hint::black_box` to coerce our desired codegen based on real-world observations
+/// of the assembly generated by Rust/LLVM.
+///
+/// Implemented as a macro instead of a generic function because it uses functionality for which
+/// there aren't available `core` traits, e.g. `wrapping_neg`.
+///
+/// See also:
+/// - CVE-2026-23519
+/// - RustCrypto/utils#1332
+macro_rules! masknz {
+ ($value:tt : $uint:ident) => {{
+ let mut value: $uint = $value;
+ value |= value.wrapping_neg(); // has MSB `1` if non-zero, `0` if zero
+
+ // use `black_box` to obscure we're computing a 1-bit value
+ core::hint::black_box(
+ value >> ($uint::BITS - 1), // Extract MSB
+ )
+ .wrapping_neg() // Generate $uint::MAX mask if `black_box` outputs `1`
+ }};
+}
+
+#[cfg(test)]
+mod tests {
+ // Spot check up to a given limit
+ const TEST_LIMIT: u8 = 128;
+
+ macro_rules! masknz_test {
+ ( $($name:ident : $uint:ident),+ ) => {
+ $(
+ #[test]
+ fn $name() {
+ assert_eq!(masknz!(0: $uint), 0);
+
+ // Test lower values
+ for i in 1..=$uint::from(TEST_LIMIT) {
+ assert_eq!(masknz!(i: $uint), $uint::MAX);
+ }
+
+ // Test upper values
+ for i in ($uint::MAX - $uint::from(TEST_LIMIT))..=$uint::MAX {
+ assert_eq!(masknz!(i: $uint), $uint::MAX);
+ }
+ }
+ )+
+ }
+ }
+
+ // Ensure the macro works with any types we might use it with (we only use u8, u32, and u64)
+ masknz_test!(
+ masknz_u8: u8,
+ masknz_u16: u16,
+ masknz_u32: u32,
+ masknz_u64: u64,
+ masknz_u128: u128,
+ masknz_usize: usize
+ );
+}
### external/vendor/cmov/src/slice.rs
@@ -0,0 +1,547 @@
+//! Trait impls for core slices.
+
+use crate::{Cmov, CmovEq, Condition};
+use core::{
+ cmp,
+ num::{
+ NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, NonZeroU8,
+ NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize,
+ },
+ ops::{BitOrAssign, Shl},
+ ptr, slice,
+};
+
+// Uses 64-bit words on 64-bit targets, 32-bit everywhere else
+#[cfg(not(target_pointer_width = "64"))]
+type Word = u32;
+#[cfg(target_pointer_width = "64")]
+type Word = u64;
+const WORD_SIZE: usize = size_of::<Word>();
+
+/// Assert the lengths of the two slices are equal.
+macro_rules! assert_lengths_eq {
+ ($a:expr, $b:expr) => {
+ assert_eq!(
+ $a, $b,
+ "source slice length ({}) does not match destination slice length ({})",
+ $b, $a
+ );
+ };
+}
+
+//
+// `Cmov` trait impls
+//
+
+// Optimized implementation for byte slices which coalesces them into word-sized chunks first,
+// then performs [`Cmov`] at the word-level to cut down on the total number of instructions.
+impl Cmov for [u8] {
+ #[inline]
+ #[track_caller]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ assert_lengths_eq!(self.len(), value.len());
+
+ let (dst_chunks, dst_remainder) = slice_as_chunks_mut::<u8, WORD_SIZE>(self);
+ let (src_chunks, src_remainder) = slice_as_chunks::<u8, WORD_SIZE>(value);
+
+ for (dst_chunk, src_chunk) in dst_chunks.iter_mut().zip(src_chunks.iter()) {
+ let mut a = Word::from_ne_bytes(*dst_chunk);
+ let b = Word::from_ne_bytes(*src_chunk);
+ a.cmovnz(&b, condition);
+ dst_chunk.copy_from_slice(&a.to_ne_bytes());
+ }
+
+ cmovnz_remainder(dst_remainder, src_remainder, condition);
+ }
+}
+
+// Optimized implementation for slices of `u16` which coalesces them into word-sized chunks first,
+// then performs [`Cmov`] at the word-level to cut down on the total number of instructions.
+#[cfg(not(target_pointer_width = "64"))]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for [u16] {
+ #[inline]
+ #[track_caller]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ assert_lengths_eq!(self.len(), value.len());
+
+ let (dst_chunks, dst_remainder) = slice_as_chunks_mut::<u16, 2>(self);
+ let (src_chunks, src_remainder) = slice_as_chunks::<u16, 2>(value);
+
+ for (dst_chunk, src_chunk) in dst_chunks.iter_mut().zip(src_chunks.iter()) {
+ let mut a = Word::from(dst_chunk[0]) | (Word::from(dst_chunk[1]) << 16);
+ let b = Word::from(src_chunk[0]) | (Word::from(src_chunk[1]) << 16);
+ a.cmovnz(&b, condition);
+ dst_chunk[0] = (a & 0xFFFF) as u16;
+ dst_chunk[1] = (a >> 16) as u16;
+ }
+
+ cmovnz_remainder(dst_remainder, src_remainder, condition);
+ }
+}
+
+// Optimized implementation for slices of `u16` which coalesces them into word-sized chunks first,
+// then performs [`Cmov`] at the word-level to cut down on the total number of instructions.
+#[cfg(target_pointer_width = "64")]
+#[cfg_attr(docsrs, doc(cfg(true)))]
+impl Cmov for [u16] {
+ #[inline]
+ #[track_caller]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ assert_lengths_eq!(self.len(), value.len());
+
+ #[inline(always)]
+ fn u16x4_to_u64(input: &[u16; 4]) -> u64 {
+ Word::from(input[0])
+ | (Word::from(input[1]) << 16)
+ | (Word::from(input[2]) << 32)
+ | (Word::from(input[3]) << 48)
+ }
+
+ let (dst_chunks, dst_remainder) = slice_as_chunks_mut::<u16, 4>(self);
+ let (src_chunks, src_remainder) = slice_as_chunks::<u16, 4>(value);
+
+ for (dst_chunk, src_chunk) in dst_chunks.iter_mut().zip(src_chunks.iter()) {
+ let mut a = u16x4_to_u64(dst_chunk);
+ let b = u16x4_to_u64(src_chunk);
+ a.cmovnz(&b, condition);
+ dst_chunk[0] = (a & 0xFFFF) as u16;
+ dst_chunk[1] = ((a >> 16) & 0xFFFF) as u16;
+ dst_chunk[2] = ((a >> 32) & 0xFFFF) as u16;
+ dst_chunk[3] = ((a >> 48) & 0xFFFF) as u16;
+ }
+
+ cmovnz_remainder(dst_remainder, src_remainder, condition);
+ }
+}
+
+/// Implement [`Cmov`] using a simple loop.
+macro_rules! impl_cmov_with_loop {
+ ( $($int:ty),+ ) => {
+ $(
+ impl Cmov for [$int] {
+ #[inline]
+ #[track_caller]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ assert_lengths_eq!(self.len(), value.len());
+ for (a, b) in self.iter_mut().zip(value.iter()) {
+ a.cmovnz(b, condition);
+ }
+ }
+ }
+ )+
+ };
+}
+
+// These types are large enough we don't need to use anything more complex than a simple loop
+impl_cmov_with_loop!(u32, u64, u128, usize);
+
+/// Ensure the two provided types have the same size and alignment.
+macro_rules! assert_size_and_alignment_eq {
+ ($int:ty, $uint:ty) => {
+ const {
+ assert!(
+ size_of::<$int>() == size_of::<$uint>(),
+ "integers are of unequal size"
+ );
+
+ assert!(
+ align_of::<$int>() == align_of::<$uint>(),
+ "integers have unequal alignment"
+ );
+ }
+ };
+}
+
+/// Implement [`Cmov`] and [`CmovEq`] traits by casting to a different type that impls the traits.
+macro_rules! impl_cmov_with_cast {
+ ( $($src:ty => $dst:ty),+ ) => {
+ $(
+ impl Cmov for [$src] {
+ #[inline]
+ #[track_caller]
+ #[allow(unsafe_code)]
+ fn cmovnz(&mut self, value: &Self, condition: Condition) {
+ assert_size_and_alignment_eq!($src, $dst);
+
+ // SAFETY:
+ // - Slices being constructed are of same-sized integers as asserted above.
+ // - We source the slice length directly from the other valid slice.
+ let self_unsigned = unsafe { cast_slice_mut::<$src, $dst>(self) };
+ let value_unsigned = unsafe { cast_slice::<$src, $dst>(value) };
+ self_unsigned.cmovnz(value_unsigned, condition);
+ }
+ }
+ )+
+ };
+}
+
+// These types are all safe to cast between each other
+impl_cmov_with_cast!(
+ i8 => u8,
+ i16 => u16,
+ i32 => u32,
+ i64 => u64,
+ i128 => u128,
+ isize => usize,
+ NonZeroI8 => i8,
+ NonZeroI16 => i16,
+ NonZeroI32 => i32,
+ NonZeroI64 => i64,
+ NonZeroI128 => i128,
+ NonZeroIsize => isize,
+ NonZeroU8 => u8,
+ NonZeroU16 => u16,
+ NonZeroU32 => u32,
+ NonZeroU64 => u64,
+ NonZeroU128 => u128,
+ NonZeroUsize => usize,
+ cmp::Ordering => i8 // #[repr(i8)]
+);
+
+//
+// `CmovEq` impls
+//
+
+// Optimized implementation for byte slices which coalesces them into word-sized chunks first,
+// then performs [`CmovEq`] at the word-level to cut down on the total number of instructions.
+impl CmovEq for [u8] {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ // Short-circuit the comparison if the slices are of different lengths, and set the output
+ // condition to the input condition.
+ if self.len() != rhs.len() {
+ *output = input;
+ return;
+ }
+
+ let (self_chunks, self_remainder) = slice_as_chunks::<u8, WORD_SIZE>(self);
+ let (rhs_chunks, rhs_remainder) = slice_as_chunks::<u8, WORD_SIZE>(rhs);
+
+ for (self_chunk, rhs_chunk) in self_chunks.iter().zip(rhs_chunks.iter()) {
+ let a = Word::from_ne_bytes(*self_chunk);
+ let b = Word::from_ne_bytes(*rhs_chunk);
+ a.cmovne(&b, input, output);
+ }
+
+ cmovne_remainder(self_remainder, rhs_remainder, input, output);
+ }
+}
+
+/// Implement [`CmovEq`] using a simple loop.
+macro_rules! impl_cmoveq_with_loop {
+ ( $($int:ty),+ ) => {
+ $(
+ impl CmovEq for [$int] {
+ #[inline]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ // Short-circuit the comparison if the slices are of different lengths, and set the output
+ // condition to the input condition.
+ if self.len() != rhs.len() {
+ *output = input;
+ return;
+ }
+
+ for (a, b) in self.iter().zip(rhs.iter()) {
+ a.cmovne(b, input, output);
+ }
+ }
+ }
+ )+
+ };
+}
+
+// TODO(tarcieri): investigate word-coalescing impls
+impl_cmoveq_with_loop!(u16, u32, u64, u128, usize);
+
+/// Implement [`CmovEq`] traits by casting to a different type that impls the traits.
+macro_rules! impl_cmoveq_with_cast {
+ ( $($src:ty => $dst:ty),+ ) => {
+ $(
+ impl CmovEq for [$src] {
+ #[inline]
+ #[allow(unsafe_code)]
+ fn cmovne(&self, rhs: &Self, input: Condition, output: &mut Condition) {
+ assert_size_and_alignment_eq!($src, $dst);
+
+ // SAFETY:
+ // - Slices being constructed are of same-sized types as asserted above.
+ // - We source the slice length directly from the other valid slice.
+ let self_unsigned = unsafe { cast_slice::<$src, $dst>(self) };
+ let rhs_unsigned = unsafe { cast_slice::<$src, $dst>(rhs) };
+ self_unsigned.cmovne(rhs_unsigned, input, output);
+ }
+ }
+ )+
+ };
+}
+
+// These types are all safe to cast between each other
+impl_cmoveq_with_cast!(
+ i8 => u8,
+ i16 => u16,
+ i32 => u32,
+ i64 => u64,
+ i128 => u128,
+ isize => usize,
+ NonZeroI8 => i8,
+ NonZeroI16 => i16,
+ NonZeroI32 => i32,
+ NonZeroI64 => i64,
+ NonZeroI128 => i128,
+ NonZeroIsize => isize,
+ NonZeroU8 => u8,
+ NonZeroU16 => u16,
+ NonZeroU32 => u32,
+ NonZeroU64 => u64,
+ NonZeroU128 => u128,
+ NonZeroUsize => usize,
+ cmp::Ordering => i8 // #[repr(i8)]
+);
+
+//
+// Helper functions
+//
+
+/// Performs an unsafe pointer cast from one slice type to the other.
+///
+/// # Compile-time panics
+/// - If `T` and `U` differ in size
+/// - If `T` and `U` differ in alignment
+unsafe fn cast_slice<T, U>(slice: &[T]) -> &[U] {
+ const {
+ assert!(size_of::<T>() == size_of::<U>(), "T/U size differs");
+ assert!(align_of::<T>() == align_of::<U>(), "T/U alignment differs");
+ }
+
+ // SAFETY:
+ // - Slices are of same-sized/aligned types as asserted above.
+ // - It's up to the caller to ensure the pointer cast from `T` to `U` itself is valid.
+ #[allow(unsafe_code)]
+ unsafe {
+ &*(ptr::from_ref::<[T]>(slice) as *const [U])
+ }
+}
+
+/// Performs an unsafe pointer cast from one mutable slice type to the other.
+///
+/// # Compile-time panics
+/// - If `T` and `U` differ in size
+/// - If `T` and `U` differ in alignment
+unsafe fn cast_slice_mut<T, U>(slice: &mut [T]) -> &mut [U] {
+ const {
+ assert!(size_of::<T>() == size_of::<U>(), "T/U size differs");
+ assert!(align_of::<T>() == align_of::<U>(), "T/U alignment differs");
+ }
+
+ // SAFETY:
+ // - Slices are of same-sized/aligned types as asserted above.
+ // - It's up to the caller to ensure the pointer cast from `T` to `U` itself is valid.
+ #[allow(unsafe_code)]
+ unsafe {
+ &mut *(ptr::from_mut::<[T]>(slice) as *mut [U])
+ }
+}
+
+/// Compare the two remainder slices by loading a `Word` then performing `cmovne`.
+#[inline]
+fn cmovne_remainder<T>(
+ a_remainder: &[T],
+ b_remainder: &[T],
+ input: Condition,
+ output: &mut Condition,
+) where
+ T: Copy,
+ Word: From<T>,
+{
+ let a = slice_to_word(a_remainder);
+ let b = slice_to_word(b_remainder);
+ a.cmovne(&b, input, output);
+}
+
+/// Load the remainder from chunking the slice into a single `Word`, perform `cmovnz`, then write
+/// the result back out to `dst_remainder`.
+#[inline]
+fn cmovnz_remainder<T>(dst_remainder: &mut [T], src_remainder: &[T], condition: Condition)
+where
+ T: BitOrAssign + Copy + From<u8> + Shl<usize, Output = T>,
+ Word: From<T>,
+{
+ let mut remainder = slice_to_word(dst_remainder);
+ remainder.cmovnz(&slice_to_word(src_remainder), condition);
+ word_to_slice(remainder, dst_remainder);
+}
+
+/// Create a [`Word`] from the given input slice.
+#[inline]
+fn slice_to_word<T>(slice: &[T]) -> Word
+where
+ T: Copy,
+ Word: From<T>,
+{
+ debug_assert!(size_of_val(slice) <= WORD_SIZE, "slice too large");
+ slice.iter().rev().copied().fold(0, |acc, n| {
+ (acc << (const { size_of::<T>() * 8 })) | Word::from(n)
+ })
+}
+
+/// Serialize [`Word`] as bytes using the same byte ordering as `slice_to_word`.
+#[inline]
+#[allow(clippy::arithmetic_side_effects)]
+fn word_to_slice<T>(word: Word, out: &mut [T])
+where
+ T: BitOrAssign + Copy + From<u8> + Shl<usize, Output = T>,
+{
+ debug_assert!(size_of::<T>() > 0, "can't be used with ZSTs");
+ debug_assert!(out.len() <= WORD_SIZE, "slice too large");
+
+ let bytes = word.to_le_bytes();
+ for (o, chunk) in out.iter_mut().zip(bytes.chunks(size_of::<T>())) {
+ *o = T::from(0u8);
+ for (i, &byte) in chunk.iter().enumerate() {
+ *o |= T::from(byte) << (i * 8);
+ }
+ }
+}
+
+//
+// Vendored `core` functions to allow a 1.85 MSRV
+//
+
+/// Rust core `[T]::as_chunks` vendored because of its 1.88 MSRV.
+/// TODO(tarcieri): use upstream function when we bump MSRV
+#[inline]
+#[track_caller]
+#[must_use]
+#[allow(
+ clippy::arithmetic_side_effects,
+ clippy::integer_division_remainder_used
+)]
+fn slice_as_chunks<T, const N: usize>(slice: &[T]) -> (&[[T; N]], &[T]) {
+ assert!(N != 0, "chunk size must be non-zero");
+ let len_rounded_down = slice.len() / N * N;
+ // SAFETY: The rounded-down value is always the same or smaller than the
+ // original length, and thus must be in-bounds of the slice.
+ let (multiple_of_n, remainder) = unsafe { slice.split_at_unchecked(len_rounded_down) };
+ // SAFETY: We already panicked for zero, and ensured by construction
+ // that the length of the subslice is a multiple of N.
+ let array_slice = unsafe { slice_as_chunks_unchecked(multiple_of_n) };
+ (array_slice, remainder)
+}
+
+/// Rust core `[T]::as_chunks_mut` vendored because of its 1.88 MSRV.
+/// TODO(tarcieri): use upstream function when we bump MSRV
+#[inline]
+#[track_caller]
+#[must_use]
+#[allow(
+ clippy::arithmetic_side_effects,
+ clippy::integer_division_remainder_used
+)]
+fn slice_as_chunks_mut<T, const N: usize>(slice: &mut [T]) -> (&mut [[T; N]], &mut [T]) {
+ assert!(N != 0, "chunk size must be non-zero");
+ let len_rounded_down = slice.len() / N * N;
+ // SAFETY: The rounded-down value is always the same or smaller than the
+ // original length, and thus must be in-bounds of the slice.
+ let (multiple_of_n, remainder) = unsafe { slice.split_at_mut_unchecked(len_rounded_down) };
+ // SAFETY: We already panicked for zero, and ensured by construction
+ // that the length of the subslice is a multiple of N.
+ let array_slice = unsafe { slice_as_chunks_unchecked_mut(multiple_of_n) };
+ (array_slice, remainder)
+}
+
+/// Rust core `[T]::as_chunks_unchecked` vendored because of its 1.88 MSRV.
+/// TODO(tarcieri): use upstream function when we bump MSRV
+#[inline]
+#[must_use]
+#[track_caller]
+#[allow(
+ clippy::arithmetic_side_effects,
+ clippy::integer_division_remainder_used
+)]
+unsafe fn slice_as_chunks_unchecked<T, const N: usize>(slice: &[T]) -> &[[T; N]] {
+ // Caller must guarantee that `N` is nonzero and exactly divides the slice length
+ const { debug_assert!(N != 0) };
+ debug_assert_eq!(slice.len() % N, 0);
+ let new_len = slice.len() / N;
+
+ // SAFETY: We cast a slice of `new_len * N` elements into
+ // a slice of `new_len` many `N` elements chunks.
+ unsafe { slice::from_raw_parts(slice.as_ptr().cast(), new_len) }
+}
+
+/// Rust core `[T]::as_chunks_unchecked_mut` vendored because of its 1.88 MSRV.
+/// TODO(tarcieri): use upstream function when we bump MSRV
+#[inline]
+#[must_use]
+#[track_caller]
+#[allow(
+ clippy::arithmetic_side_effects,
+ clippy::integer_division_remainder_used
+)]
+unsafe fn slice_as_chunks_unchecked_mut<T, const N: usize>(slice: &mut [T]) -> &mut [[T; N]] {
+ // Caller must guarantee that `N` is nonzero and exactly divides the slice length
+ const { debug_assert!(N != 0) };
+ debug_assert_eq!(slice.len() % N, 0);
+ let new_len = slice.len() / N;
+
+ // SAFETY: We cast a slice of `new_len * N` elements into
+ // a slice of `new_len` many `N` elements chunks.
+ unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), new_len) }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn cmovnz_remainder() {
+ // - Test endianness handling on non-64-bit platforms
+ // - Test handling of odd length slices on 64-bit platforms
+ #[cfg(not(target_pointer_width = "64"))]
+ const A_U16: [u16; 2] = [0xAAAA, 0xBBBB];
+ #[cfg(target_pointer_width = "64")]
+ const A_U16: [u16; 3] = [0xAAAA, 0xBBBB, 0xCCCC];
+
+ #[cfg(not(target_pointer_width = "64"))]
+ const B_U16: [u16; 2] = [0x10, 0xFFFF];
+ #[cfg(target_pointer_width = "64")]
+ const B_U16: [u16; 3] = [0x10, 0x10, 0xFFFF];
+
+ let mut out = A_U16;
+
+ super::cmovnz_remainder(&mut out, &B_U16, 0);
+ assert_eq!(A_U16, out);
+
+ super::cmovnz_remainder(&mut out, &B_U16, 1);
+ assert_eq!(B_U16, out);
+ }
+
+ #[test]
+ fn slice_to_word() {
+ assert_eq!(0xAABBCC, super::slice_to_word(&[0xCCu8, 0xBB, 0xAA]));
+ assert_eq!(0xAAAABBBB, super::slice_to_word(&[0xBBBBu16, 0xAAAA]));
+
+ #[cfg(target_pointer_width = "64")]
+ assert_eq!(
+ 0xAAAABBBBCCCC,
+ super::slice_to_word(&[0xCCCCu16, 0xBBBB, 0xAAAA])
+ );
+ }
+
+ #[test]
+ fn word_to_slice() {
+ let mut out = [0u8; 3];
+ super::word_to_slice(0xAABBCC, &mut out);
+ assert_eq!(&[0xCC, 0xBB, 0xAA], &out);
+
+ let mut out = [0u16; 2];
+ super::word_to_slice(0xAAAABBBB, &mut out);
+ assert_eq!(&[0xBBBB, 0xAAAA], &out);
+
+ #[cfg(target_pointer_width = "64")]
+ {
+ let mut out = [0u16; 3];
+ super::word_to_slice(0xAAAABBBBCCCC, &mut out);
+ assert_eq!(&[0xCCCC, 0xBBBB, 0xAAAA], &out);
+ }
+ }
+}
### external/vendor/cmov/tests/core_impls.rs
@@ -0,0 +1,379 @@
+//! Tests for `Cmov`/`CmovEq` impls on `core` types.
+
+/// Write the tests for an integer type, given two unequal integers
+macro_rules! int_tests {
+ ($int:ident, $a:expr, $b:expr) => {
+ mod $int {
+ use cmov::{Cmov, CmovEq};
+
+ #[test]
+ fn cmovz_works() {
+ let mut n: $int = $a;
+
+ for cond in 1..0xFF {
+ n.cmovz(&$b, cond);
+ assert_eq!(n, $a);
+ }
+
+ n.cmovz(&$b, 0);
+ assert_eq!(n, $b);
+
+ n.cmovz(&<$int>::MAX, 0);
+ assert_eq!(n, <$int>::MAX);
+ }
+
+ #[test]
+ fn cmovnz_works() {
+ let mut n = $a;
+ n.cmovnz(&$b, 0);
+ assert_eq!(n, $a);
+
+ for cond in 1..0xFF {
+ let mut n = $a;
+ n.cmovnz(&$b, cond);
+ assert_eq!(n, $b);
+ }
+ }
+
+ #[test]
+ #[allow(
+ trivial_numeric_casts,
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss
+ )]
+ fn cmoveq_works() {
+ let mut o = 0u8;
+
+ // compare to zero (a and b should be non-zero)
+ $a.cmoveq(&0, 1, &mut o);
+ assert_eq!(o, 0);
+ 0.cmoveq(&$a, 1, &mut o);
+ assert_eq!(o, 0);
+
+ for cond in 1..(0x7F as $int) {
+ cond.cmoveq(&cond, cond as u8, &mut o);
+ assert_eq!(o, cond as u8);
+ cond.cmoveq(&0, 0, &mut o);
+ assert_eq!(o, cond as u8);
+ }
+
+ // equal so we move
+ $a.cmoveq(&$a, 43u8, &mut o);
+ assert_eq!(o, 43u8);
+
+ // non-equal so we don't move
+ $a.cmoveq(&$b, 55u8, &mut o);
+ assert_eq!(o, 43u8);
+ <$int>::MAX.cmoveq(&$a, 55u8, &mut o);
+ assert_eq!(o, 43u8);
+
+ // equal so we move
+ <$int>::MAX.cmoveq(&<$int>::MAX, 55u8, &mut o);
+ assert_eq!(o, 55u8);
+ }
+
+ #[test]
+ #[allow(
+ trivial_numeric_casts,
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss
+ )]
+ fn cmovne_works() {
+ let mut o = 0u8;
+
+ // compare to zero (a and b should be non-zero)
+ $a.cmovne(&0, 1, &mut o);
+ assert_eq!(o, 1);
+ o = 0;
+ 0.cmovne(&$a, 1, &mut o);
+ assert_eq!(o, 1);
+ o = 0;
+
+ for cond in 1..(0x7F as $int) {
+ cond.cmovne(&0, cond as u8, &mut o);
+ assert_eq!(o, cond as u8);
+ cond.cmovne(&cond, 0, &mut o);
+ assert_eq!(o, cond as u8);
+ }
+
+ // non-equal so we move
+ o = 0;
+ $a.cmovne(&$b, 55u8, &mut o);
+ assert_eq!(o, 55u8);
+
+ // equal so we don't move
+ $a.cmovne(&$a, 66u8, &mut o);
+ assert_eq!(o, 55u8);
+ <$int>::MAX.cmovne(&<$int>::MAX, 66u8, &mut o);
+ assert_eq!(o, 55u8);
+
+ // non-equal so we move
+ <$int>::MAX.cmovne(&$a, 66u8, &mut o);
+ assert_eq!(o, 66u8);
+ }
+ }
+ };
+}
+
+int_tests!(i8, 0x11i8, -0x22i8);
+int_tests!(i16, 0x1111i16, -0x2222i16);
+int_tests!(i32, 0x1111_1111i32, -0x2222_2222i32);
+int_tests!(i64, 0x1111_1111_1111_1111i64, -0x2222_2222_2222_2222i64);
+int_tests!(
+ i128,
+ 0x1111_1111_1111_1111_1111_1111_1111_1111i128,
+ -0x2222_2222_2222_2222_2222_2222_2222_2222i128
+);
+int_tests!(isize, 0x1111isize, -0x2222isize);
+int_tests!(u8, 0x11u8, 0x22u8);
+int_tests!(u16, 0x1111u16, 0x2222u16);
+int_tests!(u32, 0x1111_1111u32, 0x2222_2222u32);
+int_tests!(u64, 0x1111_1111_1111_1111u64, 0x2222_2222_2222_2222u64);
+int_tests!(
+ u128,
+ 0x1111_1111_1111_1111_2222_2222_2222_2222u128,
+ 0x2222_2222_2222_2222_3333_3333_3333_3333u128
+);
+int_tests!(usize, 0x1111usize, 0x2222usize);
+
+mod ordering {
+ use cmov::{Cmov, CmovEq};
+ use core::cmp::Ordering;
+
+ #[test]
+ fn cmovz_works() {
+ let mut n: Ordering = Ordering::Less;
+
+ n.cmovz(&Ordering::Equal, 0);
+ assert_eq!(n, Ordering::Equal);
+
+ for cond in 1..0xFF {
+ n.cmovz(&Ordering::Greater, cond);
+ assert_eq!(n, Ordering::Equal);
+ }
+ }
+
+ #[test]
+ fn cmovnz_works() {
+ let mut n = Ordering::Less;
+ n.cmovnz(&Ordering::Equal, 0);
+ assert_eq!(n, Ordering::Less);
+
+ for cond in 1..0xFF {
+ let mut n = Ordering::Less;
+ n.cmovnz(&Ordering::Greater, cond);
+ assert_eq!(n, Ordering::Greater);
+ }
+ }
+
+ #[test]
+ fn cmoveq_works() {
+ let mut o = 0u8;
+
+ // equal so we move
+ Ordering::Equal.cmoveq(&Ordering::Equal, 43u8, &mut o);
+ assert_eq!(o, 43u8);
+
+ // non-equal so we don't move
+ Ordering::Less.cmoveq(&Ordering::Equal, 1, &mut o);
+ assert_eq!(o, 43u8);
+ Ordering::Less.cmoveq(&Ordering::Greater, 1, &mut o);
+ assert_eq!(o, 43u8);
+ }
+}
+
+mod arrays {
+ use cmov::{Cmov, CmovEq};
+
+ // 127-elements: large enough to test the chunk loop, odd-sized to test remainder handling,
+ // and with each element different to ensure the operations actually work
+ const EXAMPLE_A: [u8; 127] = [
+ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11,
+ 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
+ 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
+ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+ 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d,
+ 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c,
+ 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b,
+ 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+ 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
+ ];
+
+ // Completely different
+ const EXAMPLE_B: [u8; 127] = [
+ 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1,
+ 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2,
+ 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3,
+ 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4,
+ 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5,
+ 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6,
+ 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97,
+ 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88,
+ 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81,
+ ];
+
+ // Same as `EXAMPLE_A` except for the last byte
+ const EXAMPLE_C: [u8; 127] = [
+ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11,
+ 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
+ 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
+ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
+ 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d,
+ 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c,
+ 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b,
+ 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+ 0x7b, 0x7c, 0x7d, 0x7e, 0x7e,
+ ];
+
+ /// Note: we only provide this impl for `[u8; N]` so we have some optimized way of operating
+ /// over byte arrays. Unfortunately without specialization we can't also provide a generalized
+ /// impl, but having good codegen for byte arrays is important.
+ #[test]
+ fn u8_cmovnz_works() {
+ let mut x = EXAMPLE_A;
+ x.cmovnz(&EXAMPLE_B, 0);
+ assert_eq!(x, EXAMPLE_A);
+
+ for cond in 1..u8::MAX {
+ let mut x = EXAMPLE_A;
+ x.cmovnz(&EXAMPLE_B, cond);
+ assert_eq!(x, EXAMPLE_B);
+ }
+ }
+
+ #[test]
+ fn u8_cmovz_works() {
+ let mut x = EXAMPLE_A;
+ x.cmovz(&EXAMPLE_B, 0);
+ assert_eq!(x, EXAMPLE_B);
+
+ for cond in 1..u8::MAX {
+ let mut x = EXAMPLE_A;
+ x.cmovz(&EXAMPLE_B, cond);
+ assert_eq!(x, EXAMPLE_A);
+ }
+ }
+
+ #[test]
+ fn u8_cmoveq_works() {
+ let mut o = 0u8;
+
+ // Same contents.
+ EXAMPLE_A.cmoveq(&EXAMPLE_A, 43, &mut o);
+ assert_eq!(o, 43);
+
+ // Different contents.
+ EXAMPLE_A.cmoveq(&EXAMPLE_B, 45, &mut o);
+ EXAMPLE_A.cmoveq(&EXAMPLE_C, 45, &mut o);
+ assert_ne!(o, 45);
+ }
+
+ #[test]
+ fn u8_cmovne_works() {
+ let mut o = 0u8;
+
+ // Same contents.
+ EXAMPLE_A.cmovne(&EXAMPLE_A, 43, &mut o);
+ assert_ne!(o, 43);
+
+ // Different contents.
+ EXAMPLE_A.cmovne(&EXAMPLE_B, 45, &mut o);
+ assert_eq!(o, 45);
+
+ EXAMPLE_A.cmovne(&EXAMPLE_C, 47, &mut o);
+ assert_eq!(o, 47);
+ }
+}
+
+mod slices {
+ macro_rules! int_slice_test {
+ ($int:ident, $a:expr, $b:expr) => {
+ mod $int {
+ use cmov::{Cmov, CmovEq};
+
+ const EXAMPLE_A: &[$int] = &[$a, $a, $b];
+ const EXAMPLE_B: &[$int] = &[$b, $a, $a]; // different contents
+ const EXAMPLE_C: &[$int] = &[$a, $a]; // different length
+
+ #[test]
+ fn cmovnz_works() {
+ let mut x: [$int; 3] = [0; 3];
+ x.as_mut_slice().cmovnz(EXAMPLE_A, 0);
+ assert_eq!(x, [0; 3]);
+
+ for cond in 1..u8::MAX {
+ let mut x: [$int; 3] = [0; 3];
+ x.as_mut_slice().cmovnz(EXAMPLE_A, cond);
+ assert_eq!(x, EXAMPLE_A);
+ }
+ }
+
+ #[test]
+ fn cmovz_works() {
+ let mut x: [$int; 3] = [0; 3];
+ x.as_mut_slice().cmovz(EXAMPLE_A, 0);
+ assert_eq!(x, EXAMPLE_A);
+
+ for cond in 1..u8::MAX {
+ let mut x: [$int; 3] = [0; 3];
+ x.as_mut_slice().cmovz(EXAMPLE_A, cond);
+ assert_eq!(x, [0; 3]);
+ }
+ }
+
+ #[test]
+ #[should_panic]
+ fn cmovnz_length_mismatch_panics() {
+ let mut x: [$int; 3] = [0; 3];
+ x.as_mut_slice().cmovnz(EXAMPLE_C, 1);
+ }
+
+ #[test]
+ fn cmoveq_works() {
+ let mut o = 0u8;
+
+ // Same slices.
+ EXAMPLE_A.cmoveq(EXAMPLE_A, 43, &mut o);
+ assert_eq!(o, 43);
+
+ // Different contents.
+ EXAMPLE_A.cmoveq(EXAMPLE_B, 45, &mut o);
+ assert_ne!(o, 45);
+
+ // Different lengths.
+ EXAMPLE_A.cmoveq(EXAMPLE_C, 44, &mut o);
+ assert_ne!(o, 44);
+ }
+
+ #[test]
+ fn cmovne_works() {
+ let mut o = 0u8;
+
+ // Same slices.
+ EXAMPLE_A.cmovne(EXAMPLE_A, 43, &mut o);
+ assert_ne!(o, 43);
+
+ // Different contents.
+ EXAMPLE_A.cmovne(EXAMPLE_B, 45, &mut o);
+ assert_eq!(o, 45);
+
+ // Different lengths.
+ EXAMPLE_A.cmovne(EXAMPLE_C, 44, &mut o);
+ assert_eq!(o, 44);
+ }
+ }
+ };
+ }
+
+ int_slice_test!(i8, i8::MIN, i8::MAX);
+ int_slice_test!(i16, i16::MIN, i16::MAX);
+ int_slice_test!(i32, i32::MIN, i32::MAX);
+ int_slice_test!(i64, i64::MIN, i64::MAX);
+ int_slice_test!(i128, i128::MIN, i128::MAX);
+
+ int_slice_test!(u8, 7, u8::MAX);
+ int_slice_test!(u16, 11, u16::MAX);
+ int_slice_test!(u32, 13, u32::MAX);
+ int_slice_test!(u64, 17, u64::MAX);
+ int_slice_test!(u128, 23, u128::MAX);
+}
### external/vendor/cmov/tests/proptests.rs
[binary or diff unavailable]
### external/vendor/cmov/tests/regression.rs
[binary or diff unavailable]
### external/vendor/const-oid/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/const-oid/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/const-oid/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.lock
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.toml
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/const-oid/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/const-oid/README.md
[binary or diff unavailable]
### external/vendor/const-oid/src/arcs.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/buffer.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/checked.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/db.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/db/generated.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/encoder.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/error.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/lib.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/parser.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/traits.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/lib.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/oid.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/oid_ref.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/proptests.proptest-regressions
[binary or diff unavailable]
### external/vendor/const-oid/tests/proptests.rs
[binary or diff unavailable]
### external/vendor/cpubits/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/cpubits/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/cpubits/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.lock
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.toml
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/cpubits/LICENSE-APACHE
[binary or diff unavailable]
### external/vendor/cpubits/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/cpubits/README.md
[binary or diff unavailable]
### external/vendor/cpubits/src/lib.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/cpufeatures/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/cpufeatures/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.lock
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.toml
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/cpufeatures/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/cpufeatures/README.md
[binary or diff unavailable]
### external/vendor/cpufeatures/src/aarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/lib.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/loongarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/miri.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/x86.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/aarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/loongarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/x86.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/crypto-bigint/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/crypto-bigint/.github/workflows/crypto-bigint.yml
[binary or diff unavailable]
### external/vendor/crypto-bigint/.github/workflows/security-audit.yml
[binary or diff unavailable]
### external/vendor/crypto-bigint/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.lock
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.toml
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/crypto-bigint/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/crypto-bigint/README.md
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/bench.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/boxed_monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/boxed_uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/const_monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/int.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/limb.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/array.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/bitlen.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint/cmp.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/checked.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/ct_choice.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/encoding.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/bit_and.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/bit_not.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/bit_or.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/bit_xor.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/cmp.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/ct.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/div.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/div_unsigned.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/encoding.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/from.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/gcd.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/invert_mod.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/mod_symbol.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/mul.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/mul_unsigned.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/neg.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/rand.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/resize.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/shl.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/shr.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/sign.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/sqrt.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/sub.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/types.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/jacobi.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/lib.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/bit_and.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/bit_not.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/bit_or.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/bit_xor.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/bits.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/cmp.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/ct.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/div.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/encoding.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/from.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/gcd.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/invert_mod.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/mul.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/neg.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/rand.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/shl.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/shr.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/sqrt.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/limb/sub.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/macros.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/modular.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/modular/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/modular/bingcd.rs
[binary or diff unavailable]Why this scored 38/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.