### Bash: BLAKE3 Command-Line Usage (b3sum) Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Provides examples of using the `b3sum` command-line utility for BLAKE3 hashing. It covers hashing single or multiple files, reading from standard input, verifying checksums, keyed hashing, and output customization. Install with `cargo install b3sum`. ```bash # Install b3sum cargo install b3sum # Hash a single file b3sum /path/to/file.txt # Output: a1b2c3d4... /path/to/file.txt # Hash multiple files b3sum file1.txt file2.txt file3.txt # Hash from stdin echo "hello world" | b3sum cat large_file.bin | b3sum # Check mode (verify checksums) b3sum file.txt > checksums.txt b3sum --check checksums.txt # Keyed hashing mode b3sum --keyed --key-file secret.key data.bin # Derive key mode b3sum --derive-key "MyApp 2024-01-01 encryption" < key-material.bin # Extended output length b3sum --length 512 file.txt # 512 bits = 64 bytes # Raw binary output b3sum --raw file.bin > hash.bin # No filename in output b3sum --no-names file.txt # Benchmark performance dd if=/dev/zero bs=1M count=1000 | b3sum # Hash 1GB of zeros ``` -------------------------------- ### Install BLAKE3 Crate and b3sum Utility Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Instructions for adding the BLAKE3 crate to a Rust project using Cargo.toml or the `cargo add` command, and how to install the `b3sum` command-line utility for hashing files. ```toml # Cargo.toml [dependencies] blake3 = "1.8.2" # With optional features [dependencies.blake3] version = "1.8.2" features = ["rayon", "mmap", "digest", "serde", "zeroize"] ``` ```bash # Or using cargo add command cargo add blake3 # Install the b3sum command-line utility cargo install b3sum ``` -------------------------------- ### Install b3sum command-line utility using Cargo Source: https://crates.io/crates/blake3/1 This command installs the `b3sum` utility, which provides a command-line interface for calculating BLAKE3 hashes. It requires Rust and Cargo to be installed on your system. ```rust cargo install b3sum ``` -------------------------------- ### Benchmark BLAKE3 against SHA-256 using command-line utilities Source: https://crates.io/crates/blake3/1 This example demonstrates how to benchmark the performance of BLAKE3 against SHA-256. It involves creating a large file, hashing it with `openssl sha256`, and then hashing it with `b3sum`. The `time` command is used to measure the execution time of each operation. ```bash # Create a 1 GB file. head -c 1000000000 /dev/zero > /tmp/bigfile # Hash it with SHA-256. time openssl sha256 /tmp/bigfile # Hash it with BLAKE3. time b3sum /tmp/bigfile ``` -------------------------------- ### Install b3sum CLI using Cargo Source: https://crates.io/crates/blake3/index Installs the `b3sum` command-line utility, which provides a BLAKE3 hashing functionality, using the Rust package manager, Cargo. Ensure Rust and Cargo are installed and configured in your system's PATH. ```bash cargo install b3sum ``` -------------------------------- ### Incremental BLAKE3 Hashing in Rust Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Illustrates how to compute a BLAKE3 hash by feeding data in chunks using the `blake3::Hasher` API. Includes an example of hashing a file incrementally. ```rust use blake3::Hasher; fn main() { // Create a new hasher let mut hasher = Hasher::new(); // Feed data incrementally hasher.update(b"foo"); hasher.update(b"bar"); hasher.update(b"baz"); // Finalize to get the hash let hash = hasher.finalize(); // Verify it matches one-shot hash let direct_hash = blake3::hash(b"foobarbaz"); assert_eq!(hash, direct_hash); println!("Incremental hash: {}", hash); } // Hash a file incrementally use std::fs::File; use std::io::{self, Read}; fn hash_file(path: &str) -> io::Result { let mut hasher = Hasher::new(); let mut file = File::open(path)?; let mut buffer = [0; 8192]; loop { let bytes_read = file.read(&mut buffer)?; if bytes_read == 0 { break; } hasher.update(&buffer[..bytes_read]); } Ok(hasher.finalize()) } ``` -------------------------------- ### Benchmark BLAKE3 against SHA-256 using b3sum and openssl Source: https://crates.io/crates/blake3/index Compares the performance of BLAKE3 hashing against SHA-256 by hashing a large file. This requires the `b3sum` utility to be installed and the `openssl` command-line tool. The `time` command measures the execution duration. ```bash # Create a 1 GB file. head -c 1000000000 /dev/zero > /tmp/bigfile # Hash it with SHA-256. time openssl sha256 /tmp/bigfile # Hash it with BLAKE3. time b3sum /tmp/bigfile ``` -------------------------------- ### Basic BLAKE3 Hashing in Rust Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Demonstrates how to compute a BLAKE3 hash from a byte slice or string in a single function call using the `blake3::hash()` function. Shows how to get the raw bytes of the hash. ```rust use blake3; fn main() { // Simple one-shot hashing let hash = blake3::hash(b"foobarbaz"); println!("Hash: {}", hash); // Output: Hash: a8e89f3e1bd08... (32 bytes as hex) // Hash from string let text = "Hello, BLAKE3!"; let hash = blake3::hash(text.as_bytes()); assert_eq!(hash.as_bytes().len(), 32); // Always 32 bytes (256 bits) // Get raw bytes let hash_bytes: [u8; 32] = *hash.as_bytes(); println!("First byte: {}", hash_bytes[0]); } ``` -------------------------------- ### BLAKE3 Extended Output (XOF) in Rust Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Shows how to use BLAKE3 as an extendable output function (XOF) to generate arbitrary-length output. Includes examples for reading extended output and deterministic key generation from a seed. ```rust use blake3::Hasher; fn main() { let mut hasher = Hasher::new(); hasher.update(b"input data"); // Get extended output reader let mut output_reader = hasher.finalize_xof(); // Read any amount of output let mut output_1kb = [0u8; 1000]; output_reader.fill(&mut output_1kb); // First 32 bytes match the standard hash let standard_hash = blake3::hash(b"input data"); assert_eq!(standard_hash.as_bytes(), &output_1kb[..32]); // OutputReader implements Read and Seek let mut more_output = vec![0u8; 500]; output_reader.fill(&mut more_output); println!("Generated {} bytes of output", output_1kb.len() + more_output.len()); } // Deterministic key generation from seed fn generate_keys(seed: &[u8], count: usize, key_len: usize) -> Vec> { let mut hasher = Hasher::new(); hasher.update(seed); let mut reader = hasher.finalize_xof(); let mut keys = Vec::new(); for _ in 0..count { let mut key = vec![0u8; key_len]; reader.fill(&mut key); keys.push(key); } keys } ``` -------------------------------- ### Rust: BLAKE3 Performance Benchmarking Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Includes a Rust code snippet to benchmark the performance of the BLAKE3 hash function across different data sizes. It measures throughput in MB/s and demonstrates how to use `std::time::Instant` for timing. This helps in understanding BLAKE3's speed on various hardware. ```rust use blake3; use std::time::Instant; fn benchmark_hash_function() { let data_sizes = vec![ 1024, // 1 KB 1024 * 1024, // 1 MB 100 * 1024 * 1024, // 100 MB ]; for size in data_sizes { let data = vec![0u8; size]; // Benchmark BLAKE3 let start = Instant::now(); let _hash = blake3::hash(&data); let duration = start.elapsed(); let throughput = (size as f64 / 1024.0 / 1024.0) / duration.as_secs_f64(); println!("BLAKE3 - {} bytes: {:.2} MB/s", size, throughput); } } fn main() { benchmark_hash_function(); // Typical output on modern CPU: // BLAKE3 - 1024 bytes: 500 MB/s // BLAKE3 - 1048576 bytes: 3000 MB/s // BLAKE3 - 104857600 bytes: 5000+ MB/s (with parallel) } ``` -------------------------------- ### Rust: Hashing Input with `blake3` Crate Source: https://crates.io/crates/blake3/1 Demonstrates how to hash input bytes using the `blake3` Rust crate. It shows both one-shot hashing and incremental hashing, including features like extended output and hex printing. Dependencies: `blake3` crate. ```rust // Hash an input all at once. let hash1 = blake3::hash(b"foobarbaz"); // Hash an input incrementally. let mut hasher = blake3::Hasher::new(); hasher.update(b"foo"); hasher.update(b"bar"); hasher.update(b"baz"); let hash2 = hasher.finalize(); assert_eq!(hash1, hash2); // Extended output. OutputReader also implements Read and Seek. let mut output = [0; 1000]; let mut output_reader = hasher.finalize_xof(); output_reader.fill(&mut output); assert_eq!(hash1, output[..32]); // Print a hash as hex. println!("{}", hash1); ``` -------------------------------- ### Rust: Keyed Hashing with `blake3` Crate Source: https://crates.io/crates/blake3/1 Illustrates how to perform keyed hashing (Message Authentication Code - MAC) using the `blake3` Rust crate. It covers both one-shot and incremental keyed hashing operations. Dependencies: `blake3` crate. ```rust // MAC an input all at once. let example_key = [42u8; 32]; let mac1 = blake3::keyed_hash(&example_key, b"example input"); // MAC incrementally. let mut hasher = blake3::Hasher::new_keyed(&example_key); hasher.update(b"example input"); let mac2 = hasher.finalize(); assert_eq!(mac1, mac2); ``` -------------------------------- ### Rust: Incremental and One-Shot Hashing with blake3 Source: https://crates.io/crates/blake3/index Demonstrates how to hash input bytes all at once or incrementally using the blake3 crate in Rust. It covers basic hashing, finalization, and extended output functionality. The code also shows how to print the resulting hash in hexadecimal format. Requires the 'blake3' crate as a dependency. ```rust use blake3; // Hash an input all at once. let hash1 = blake3::hash(b"foobarbaz"); // Hash an input incrementally. let mut hasher = blake3::Hasher::new(); hasher.update(b"foo"); hasher.update(b"bar"); hasher.update(b"baz"); let hash2 = hasher.finalize(); assert_eq!(hash1, hash2); // Extended output. OutputReader also implements Read and Seek. let mut output = [0; 1000]; let mut output_reader = hasher.finalize_xof(); output_reader.fill(&mut output); assert_eq!(hash1, output[..32]); // Print a hash as hex. println!("{}", hash1); ``` -------------------------------- ### Rust: Hash Input All at Once and Incrementally with BLAKE3 Source: https://crates.io/crates/blake3/0 Demonstrates how to compute a BLAKE3 hash for input bytes, both by providing all data at once and by updating a hasher incrementally. It also shows how to finalize with extended output and print the hash as a hexadecimal string. This is useful for general-purpose hashing of data. ```rust use blake3; // Hash an input all at once. let hash1 = blake3::hash(b"foobarbaz"); // Hash an input incrementally. let mut hasher = blake3::Hasher::new(); hasher.update(b"foo"); hasher.update(b"bar"); hasher.update(b"baz"); let hash2 = hasher.finalize(); assert_eq!(hash1, hash2); // Extended output. OutputReader also implements Read and Seek. let mut output = [0; 1000]; let mut output_reader = hasher.finalize_xof(); output_reader.fill(&mut output); assert_eq!(&output[..32], hash1.as_bytes()); // Print a hash as hex. println!("{}", hash1.to_hex()); ``` -------------------------------- ### Rust: Deriving Keys with `blake3` Crate Source: https://crates.io/crates/blake3/1 Shows how to use the `derive_key` function from the `blake3` Rust crate to derive unique subkeys from input key material using context strings. This is not for password hashing. Dependencies: `blake3` crate. ```rust // Derive a couple of subkeys for different purposes. const EMAIL_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:10:44 email key"; const API_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:11:21 API key"; let input_key_material = b"usually at least 32 random bytes, not a password"; let email_key = blake3::derive_key(EMAIL_CONTEXT, input_key_material); let api_key = blake3::derive_key(API_CONTEXT, input_key_material); assert_ne!(email_key, api_key); ``` -------------------------------- ### Content-Addressable Storage with BLAKE3 in Rust Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt This Rust code demonstrates a simple content-addressable storage system using the BLAKE3 hash function. It defines a `ContentStore` struct to manage storing and retrieving data based on its BLAKE3 hash. The system shatters data into subdirectories based on the hash for organization and ensures data integrity through hash verification. It uses standard Rust libraries for file system operations and collections. ```rust use blake3; use std::collections::HashMap; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; struct ContentStore { root: PathBuf, index: HashMap, } impl ContentStore { fn new(root: impl AsRef) -> io::Result { let root = root.as_ref().to_path_buf(); fs::create_dir_all(&root)?; Ok(Self { root, index: HashMap::new(), }) } // Store content and return its hash fn store(&mut self, content: &[u8]) -> io::Result { let hash = blake3::hash(content); // Use first 2 chars of hex hash for subdirectory (sharding) let hash_hex = hash.to_hex(); let subdir = &hash_hex.as_str()[..2]; let dir_path = self.root.join(subdir); fs::create_dir_all(&dir_path)?; let file_path = dir_path.join(&hash_hex.as_str()[2..]); // Only write if doesn't exist (content-addressable = deduplication) if !file_path.exists() { let mut file = File::create(&file_path)?; file.write_all(content)?; } self.index.insert(hash, file_path.clone()); Ok(hash) } // Retrieve content by hash fn retrieve(&self, hash: &blake3::Hash) -> io::Result> { let hash_hex = hash.to_hex(); let subdir = &hash_hex.as_str()[..2]; let file_path = self.root.join(subdir).join(&hash_hex.as_str()[2..]); let content = fs::read(&file_path)?; // Verify integrity let computed_hash = blake3::hash(&content); if computed_hash != *hash { return Err(io::Error::new( io::ErrorKind::InvalidData, "Hash mismatch: data corruption detected", )); } Ok(content) } // Check if content exists fn exists(&self, hash: &blake3::Hash) -> bool { let hash_hex = hash.to_hex(); let subdir = &hash_hex.as_str()[..2]; let file_path = self.root.join(subdir).join(&hash_hex.as_str()[2..]); file_path.exists() } } fn main() -> io::Result<()> { let mut store = ContentStore::new("./content_store")?; // Store some content let content1 = b"Hello, BLAKE3!"; let hash1 = store.store(content1)?; println!("Stored content with hash: {}", hash1); // Store duplicate content (will be deduplicated) let hash2 = store.store(content1)?; assert_eq!(hash1, hash2); // Retrieve content let retrieved = store.retrieve(&hash1)?; assert_eq!(retrieved, content1); println!("Retrieved: {}", String::from_utf8_lossy(&retrieved)); // Check existence assert!(store.exists(&hash1)); Ok(()) } ``` -------------------------------- ### Rust: Keyed Hashing (MAC) with BLAKE3 Source: https://crates.io/crates/blake3/0 Shows how to use BLAKE3 for keyed hashing, which acts as a Message Authentication Code (MAC). This involves providing a secret key and input data. It covers both computing the MAC all at once and incrementally. This is essential for verifying data integrity and authenticity. ```rust use blake3; // MAC an input all at once. let example_key = [42u8; 32]; let mac1 = blake3::keyed_hash(&example_key, b"example input"); // MAC incrementally. let mut hasher = blake3::Hasher::new_keyed(&example_key); hasher.update(b"example input"); let mac2 = hasher.finalize(); assert_eq!(mac1, mac2); ``` -------------------------------- ### Rust: Key Derivation with blake3 Source: https://crates.io/crates/blake3/index Demonstrates the key derivation functionality of the blake3 crate in Rust. It shows how to derive unique subkeys for different purposes using a context string and input key material. The context string should be application-specific and globally unique. ```rust use blake3; // Derive a couple of subkeys for different purposes. const EMAIL_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:10:44 email key"; const API_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:11:21 API key"; let input_key_material = b"usually at least 32 random bytes, not a password"; let email_key = blake3::derive_key(EMAIL_CONTEXT, input_key_material); let api_key = blake3::derive_key(API_CONTEXT, input_key_material); assert_ne!(email_key, api_key); ``` -------------------------------- ### Cargo: Add `blake3` Dependency to `Cargo.toml` Source: https://crates.io/crates/blake3/0 Provides instructions on how to add the `blake3` crate as a dependency to a Rust project using Cargo. This involves either using the `cargo add` command or manually editing the `Cargo.toml` file. This is the standard way to include external libraries in Rust projects. ```bash cargo add blake3@=0.3.8 ``` ```toml [dependencies] blake3 = "=0.3.8" ``` -------------------------------- ### Rust: BLAKE3 Serialization with Serde Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Demonstrates how to serialize and deserialize BLAKE3 hashes using the Serde library. This is useful for storing or transmitting data structures that include BLAKE3 checksums. Ensure the `serde` feature is enabled in `Cargo.toml`. ```rust // Enable serde feature in Cargo.toml: // blake3 = { version = "1.8.2", features = ["serde"] } use blake3; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Document { content: String, checksum: blake3::Hash, } fn main() { let content = "Important document content"; let hash = blake3::hash(content.as_bytes()); let doc = Document { content: content.to_string(), checksum: hash, }; // Serialize to JSON let json = serde_json::to_string(&doc).unwrap(); println!("JSON: {}", json); // Output: {"content":"Important document content","checksum":"a1b2c3..."} // Deserialize from JSON let doc2: Document = serde_json::from_str(&json).unwrap(); assert_eq!(doc.checksum, doc2.checksum); // Verify checksum let recomputed = blake3::hash(doc2.content.as_bytes()); assert_eq!(doc2.checksum, recomputed); } ``` -------------------------------- ### Rust: Derive Keys for Different Purposes using BLAKE3 Source: https://crates.io/crates/blake3/0 Illustrates how to use BLAKE3's key derivation mode. This function takes a context string and key material to produce a derived key of a specified length. It's crucial for generating unique keys for various application-specific purposes, ensuring security and separation. ```rust use blake3; // Derive a couple of subkeys for different purposes. const EMAIL_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:10:44 email key"; const API_CONTEXT: &str = "BLAKE3 example 2020-01-07 17:11:21 API key"; let input_key = b"some very secret key material (>'-')> <('-'<) ^('-')^"; let mut email_key = [0; 32]; blake3::derive_key(EMAIL_CONTEXT, input_key, &mut email_key); let mut api_key = [0; 32]; blake3::derive_key(API_CONTEXT, input_key, &mut api_key); assert!(email_key != api_key); ``` -------------------------------- ### Rust: Keyed Hashing with blake3 Source: https://crates.io/crates/blake3/index Illustrates how to perform keyed hashing (Message Authentication Code) using the blake3 crate in Rust. It shows both one-shot keyed hashing and incremental keyed hashing with a specified 256-bit key. This functionality is useful for message authentication. ```rust use blake3; // MAC an input all at once. let example_key = [42u8; 32]; let mac1 = blake3::keyed_hash(&example_key, b"example input"); // MAC incrementally. let mut hasher = blake3::Hasher::new_keyed(&example_key); hasher.update(b"example input"); let mac2 = hasher.finalize(); assert_eq!(mac1, mac2); ``` -------------------------------- ### Key Derivation (KDF Mode) with BLAKE3 Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Derive cryptographic keys from input key material using context strings. This mode is suitable for deriving keys for various purposes, ensuring cryptographic independence between derived keys. It's important to use unique and application-specific context strings. ```rust use blake3; fn main() { // Input key material (NOT a password - use Argon2 for passwords) let ikm = b"master secret key material, at least 32 random bytes"; // Context strings should be hardcoded, unique, and application-specific // Format: "[application] [timestamp] [purpose]" const EMAIL_CONTEXT: &str = "MyApp 2024-04-15 email-encryption"; const API_CONTEXT: &str = "MyApp 2024-04-15 api-authentication"; const DB_CONTEXT: &str = "MyApp 2024-04-15 database-encryption"; // Derive different keys for different purposes let email_key = blake3::derive_key(EMAIL_CONTEXT, ikm); let api_key = blake3::derive_key(API_CONTEXT, ikm); let db_key = blake3::derive_key(DB_CONTEXT, ikm); // Keys are cryptographically independent assert_ne!(email_key, api_key); assert_ne!(api_key, db_key); assert_ne!(email_key, db_key); println!("Email key: {}", email_key); println!("API key: {}", api_key); println!("DB key: {}", db_key); } // Derive subkeys with extended output fn derive_multiple_keys(ikm: &[u8], context: &str, num_keys: usize) -> Vec<[u8; 32]> { let mut hasher = blake3::Hasher::new_derive_key(context); hasher.update(ikm); let mut reader = hasher.finalize_xof(); let mut keys = Vec::new(); for _ in 0..num_keys { let mut key = [0u8; 32]; reader.fill(&mut key); keys.push(key); } keys } ``` -------------------------------- ### Keyed Hashing (MAC Mode) with BLAKE3 Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Compute message authentication codes (MACs) using a 256-bit secret key. Supports both one-shot and incremental hashing for message authentication. Includes functions for verifying message authenticity and signing API requests. ```rust use blake3; fn main() { // 256-bit (32-byte) secret key let secret_key = [42u8; 32]; // One-shot keyed hash (MAC) let mac = blake3::keyed_hash(&secret_key, b"message to authenticate"); println!("MAC: {}", mac); // Incremental keyed hashing let mut hasher = blake3::Hasher::new_keyed(&secret_key); hasher.update(b"message "); hasher.update(b"to authenticate"); let mac2 = hasher.finalize(); assert_eq!(mac, mac2); } // Verify message authenticity fn verify_message(message: &[u8], mac: &blake3::Hash, key: &[u8; 32]) -> bool { let computed_mac = blake3::keyed_hash(key, message); // Use constant-time comparison in production computed_mac == *mac } // Example: API request signing fn sign_api_request(api_key: &[u8; 32], method: &str, path: &str, body: &[u8]) -> blake3::Hash { let mut hasher = blake3::Hasher::new_keyed(api_key); hasher.update(method.as_bytes()); hasher.update(b"\n"); hasher.update(path.as_bytes()); hasher.update(b"\n"); hasher.update(body); hasher.finalize() } ``` -------------------------------- ### Parallel Hashing with Rayon in BLAKE3 Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Enable multithreaded hashing for improved performance on large inputs by enabling the 'rayon' feature in Cargo.toml. Rayon automatically parallelizes hashing operations when the input data is sufficiently large. ```rust // Enable rayon feature in Cargo.toml: // blake3 = { version = "1.8.2", features = ["rayon"] } use blake3::Hasher; use std::fs::File; use std::io::{self, Read}; fn hash_large_file_parallel(path: &str) -> io::Result { let mut file = File::open(path)?; let mut hasher = Hasher::new(); // Rayon automatically parallelizes when data is large enough let mut buffer = Vec::new(); file.read_to_end(&mut buffer)?; hasher.update_rayon(&buffer); Ok(hasher.finalize()) } fn main() { // Standard hashing uses Rayon automatically for large inputs let large_data = vec![0u8; 10_000_000]; // 10 MB let hash = blake3::hash(&large_data); println!("Hash of 10MB: {}", hash); // Explicit parallel update let mut hasher = Hasher::new(); hasher.update_rayon(&large_data); let hash2 = hasher.finalize(); assert_eq!(hash, hash2); } ``` -------------------------------- ### Memory-Mapped File Hashing with BLAKE3 Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Hash large files efficiently using memory mapping by enabling the 'mmap' and 'rayon' features in Cargo.toml. This approach allows the operating system to handle loading file data into memory as needed, reducing the application's memory footprint. ```rust // Enable mmap feature in Cargo.toml: // blake3 = { version = "1.8.2", features = ["mmap", "rayon"] } use blake3::Hasher; use memmap2::Mmap; use std::fs::File; use std::io; fn hash_file_mmap(path: &str) -> io::Result { let file = File::open(path)?; let mmap = unsafe { Mmap::map(&file)? }; let mut hasher = Hasher::new(); hasher.update(&mmap); Ok(hasher.finalize()) } fn hash_file_mmap_parallel(path: &str) -> io::Result { let file = File::open(path)?; let mmap = unsafe { Mmap::map(&file)? }; let mut hasher = Hasher::new(); hasher.update_rayon(&mmap); Ok(hasher.finalize()) } fn main() -> io::Result<()> { let hash = hash_file_mmap_parallel("/path/to/large/file.bin")?; println!("File hash: {}", hash); Ok(()) } ``` -------------------------------- ### Rust: BLAKE3 with Digest Trait Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Integrates BLAKE3 with the RustCrypto `digest` trait ecosystem. This allows using BLAKE3 interchangeably with other hash functions that implement the `Digest` trait. It requires enabling the `digest` feature in the `Cargo.toml` file. ```rust // Enable digest feature in Cargo.toml: // blake3 = { version = "1.8.2", features = ["digest"] } use blake3::Hasher; use digest::{Digest, DynDigest}; fn main() { // Use as a Digest let mut hasher = Hasher::new(); hasher.update(b"hello"); hasher.update(b" world"); let result = hasher.finalize(); // Generic function using Digest trait fn hash_with_digest(data: &[u8]) -> Vec { let mut hasher = D::new(); hasher.update(data); hasher.finalize().to_vec() } let hash = hash_with_digest::(b"test data"); assert_eq!(hash.len(), 32); } // Compare different hash functions use digest::Digest; fn compare_hashes(data: &[u8]) { let blake3_hash = blake3::Hasher::digest(data); println!("BLAKE3: {}", hex::encode(blake3_hash)); // Can easily swap with other digest-compatible hashes // use sha2::Sha256; // let sha256_hash = Sha256::digest(data); // println!("SHA-256: {}", hex::encode(sha256_hash)); } ``` -------------------------------- ### Rust: BLAKE3 Secure Memory Clearing with Zeroize Source: https://context7.com/context7/crates_io_crates_blake3/llms.txt Shows how to securely clear sensitive data from memory after it has been hashed using BLAKE3. This is crucial for security applications to prevent sensitive data from lingering in memory. Requires the `zeroize` feature in `Cargo.toml`. ```rust // Enable zeroize feature in Cargo.toml: // blake3 = { version = "1.8.2", features = ["zeroize"] } use blake3::Hasher; use zeroize::Zeroize; fn hash_sensitive_data(mut secret: Vec) -> blake3::Hash { let mut hasher = Hasher::new(); hasher.update(&secret); let hash = hasher.finalize(); // Securely clear sensitive data from memory secret.zeroize(); hash } fn main() { let mut password = b"super_secret_password".to_vec(); let hash = blake3::hash(&password); // Clear password from memory password.zeroize(); assert_eq!(password, vec![0u8; 21]); println!("Hash: {}", hash); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.