BLAKE3
Header: #include <cryptopp/blake3.h> | Namespace: CryptoPP
Since: cryptopp-modern 2025.11.0 (runtime input validation: 2026.8.0)
Thread Safety: Not thread-safe per instance; use separate instances per thread
BLAKE3 is a cryptographic hash function based on BLAKE2 and the original Bao tree mode. It supports parallel tree hashing, keyed hashing (MAC), key derivation and extendable output. The cryptopp-modern implementation selects AVX-512, AVX2, SSE4.1 or portable C++ code at run time from the CPU features it detects.
Quick Example
#include <cryptopp/blake3.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>
#include <string>
int main() {
using namespace CryptoPP;
BLAKE3 hash;
std::string message = "abc";
std::string digest, hexOutput;
hash.Update(reinterpret_cast<const byte*>(message.data()), message.size());
digest.resize(hash.DigestSize());
hash.Final(reinterpret_cast<byte*>(&digest[0]));
StringSource(digest, true, new HexEncoder(new StringSink(hexOutput)));
std::cout << "BLAKE3: " << hexOutput << std::endl;
// Expected: 6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85
return 0;
}Overview
BLAKE3 is a single algorithm with no variants, designed for consistent high performance in software. Its designers describe it as much faster than MD5, SHA-1, SHA-2, SHA-3 and BLAKE2. It can be used as a general-purpose hash function, a keyed hash (MAC), or a key derivation function (KDF).
Key features:
- SIMD paths - AVX-512 (16 chunks at a time), AVX2 (8), SSE4.1 (4), or portable C++, chosen at run time
- Parallelisable - Input is split into 1 KiB chunks that form the leaves of a binary tree, so chunks can be compressed independently
- Variable output - Output lengths from 1 to 1,024 bytes in this library, configured at construction; the specification allows any length below 2^64 bytes
- Multiple modes - Standard hash, keyed hash (MAC), or KDF
- No length extension - The ROOT flag is set only on the final compression, so a hash output is never an intermediate state that can be extended; CHUNK_END marks the last block of each chunk
Usage Guidelines
Do:
- Use BLAKE3 for general-purpose hashing, file integrity, and content addressing
- Use keyed mode (MAC) for message authentication with a secret key
- Use KDF mode for deriving keys from high-entropy secrets or existing keys (for example, the output of Argon2)
- Reuse the same instance for multiple messages;
Final()andTruncatedFinal()restart it automatically - Check
AlgorithmProvider()for the highest SIMD capability the build detected
Avoid:
- Using BLAKE3 for password hashing; it is designed to be fast, and its designers recommend Argon2 for passwords (see Argon2)
- Using keyed mode as a replacement for digital signatures (use Ed25519 instead)
- Reusing the same key for multiple purposes (use different keys or context strings)
- Using user-supplied strings directly as KDF context (use fixed, application-specific strings)
Constants
DIGESTSIZE = 32- Default output size in bytesBLOCKSIZE = 64- Internal block size in bytesCHUNKSIZE = 1024- Chunk size for tree hashingDEFAULT_KEYLENGTH = 32- Recommended key length for keyed hashingMIN_KEYLENGTH = 32- Keyed mode requires exactly 32 bytes of key materialMAX_KEYLENGTH = 32- Maximum supported key length in bytes
Constructors
Default Constructor
BLAKE3(unsigned int digestSize = DIGESTSIZE)Constructs a BLAKE3 hash object with the specified output size. The implementation supports output lengths from 1 to 1,024 bytes.
Parameters:
digestSize- Desired hash output size in bytes (default: 32)
Exceptions:
- Throws
InvalidArgumentifdigestSizeis 0 or larger than 1,024
Example:
BLAKE3 hash; // 32-byte output
BLAKE3 hash256(32); // Explicit 32-byte output
BLAKE3 hashXOF(128); // 128-byte extended output
Keyed Constructor (MAC Mode)
BLAKE3(const byte* key, size_t keyLength, unsigned int digestSize = DIGESTSIZE)Constructs a BLAKE3 object for keyed hashing (MAC mode). Use this for message authentication with a secret key.
Parameters:
key- Pointer to key bytes (must not be null)keyLength- Length of key in bytes. Keyed BLAKE3 requires exactly 32 bytes of key material; use the default constructor for unkeyed hashingdigestSize- Desired hash output size in bytes (default: 32)
Exceptions:
- Throws
InvalidKeyLengthifkeyLengthis not 32 - Throws
InvalidArgumentifkeyis null, or ifdigestSizeis 0 or larger than 1,024
When to use: Message authentication where both parties share a secret key (similar to HMAC).
Example:
SecByteBlock key(32);
AutoSeededRandomPool rng;
rng.GenerateBlock(key, key.size());
BLAKE3 mac(key, key.size()); // Create MAC with 32-byte key
KDF Constructor (Key Derivation Mode)
BLAKE3(const char* context, unsigned int digestSize = DIGESTSIZE)Constructs a BLAKE3 object for key derivation (KDF mode) with a context string for domain separation.
Parameters:
context- Context string for domain separation; a fixed, globally unique application stringdigestSize- Desired output size in bytes (default: 32)
Exceptions:
- Throws
InvalidArgumentifcontextis null, or ifdigestSizeis 0 or larger than 1,024
When to use: Deriving multiple keys from a single secret, or creating domain-separated hashes. The specification says the context string should be hardcoded, globally unique and application-specific, and suggests the format “[application] [commit timestamp] [purpose]”. The constructor rejects only a null context, so an empty context is accepted. The mode flags still separate a key derived with an empty context from hash and keyed-hash outputs, but it is not separated from any other application that also derives with an empty context.
Example:
BLAKE3 kdf("MyApp 2025-11-25 Encryption Key", 32);
BLAKE3 kdf2("MyApp 2025-11-25 MAC Key", 32); // Different context = different output
Public Methods
StaticAlgorithmName()
static const char* StaticAlgorithmName()Returns the algorithm name as a static string: "BLAKE3".
Thread Safety: Thread-safe (static method).
AlgorithmName()
std::string AlgorithmName() constReturns the algorithm name with digest size, e.g. "BLAKE3-256" for 32-byte output.
Thread Safety: Thread-safe (const method, read-only).
AlgorithmProvider()
std::string AlgorithmProvider() constReturns the highest SIMD capability the runtime detection found. This is not necessarily the path used for every input: a parallel path runs only when a single Update() call starts on a chunk boundary and supplies more than 16 (AVX-512), 8 (AVX2) or 4 (SSE4.1) chunks of 1,024 bytes, so smaller inputs use the single-block SSE4.1 or portable C++ compression even when this returns "AVX2" or "AVX512". ARM builds use the portable path and report "C++".
Returns: One of "C++", "SSE4.1", "AVX2", or "AVX512".
Thread Safety: Thread-safe (const method).
Example:
BLAKE3 hash;
std::cout << "Using: " << hash.AlgorithmProvider() << std::endl;
// Might print "AVX2" on modern x86 CPUs
DigestSize()
unsigned int DigestSize() constReturns the configured output size in bytes.
Thread Safety: Thread-safe (const method).
BlockSize()
unsigned int BlockSize() constReturns the internal block size (64 bytes).
Thread Safety: Thread-safe (const method).
Update()
void Update(const byte* input, size_t length)Updates the hash with additional input data. Can be called multiple times for incremental hashing.
Parameters:
input- Pointer to input datalength- Length of input data in bytes
Exceptions:
- None (a call with
length = 0does nothing)
Thread Safety: Not thread-safe. Do not call from multiple threads on the same instance.
TruncatedFinal()
void TruncatedFinal(byte* hash, size_t size)Finalizes the hash and writes the output. After calling this, the object is reset and can be reused.
Parameters:
hash- Buffer to receive hash output (must be allocated by caller)size- Number of bytes to write, up to the digest size configured at construction
Exceptions:
- Throws
InvalidArgumentifsizeexceeds the configured digest size. Safe to call withsize = 0
Thread Safety: Not thread-safe.
Note: Calling TruncatedFinal() automatically restarts the instance, so it can be immediately reused. This is not a seekable XOF reader like the official implementation’s OutputReader: producing a different output length requires hashing the input again.
Final()
void Final(byte* hash)Finalises the hash and writes the configured digest size to the output buffer. Equivalent to TruncatedFinal(hash, DigestSize()).
Parameters:
hash- Buffer to receive hash output (must be at leastDigestSize()bytes, which may be up to 1,024)
Exceptions: None
Thread Safety: Not thread-safe.
Note: For the default 32-byte output, Final() is simpler than TruncatedFinal(). Use TruncatedFinal() when you need a different output size (XOF mode).
Restart()
void Restart()Resets the hash to its initial state, allowing reuse of the object. Preserves the mode (standard, keyed, or KDF) and configuration.
Exceptions: None
Thread Safety: Not thread-safe.
Reserve explicit Restart() for abandoning a partially hashed message; Final() and TruncatedFinal() already restart the object.
Example:
BLAKE3 hash;
hash.Update(...);
hash.Final(...); // The object restarts automatically
// Can immediately reuse:
hash.Update(...);
hash.Final(...);Usage Modes
Basic Hash Mode
When to use: General-purpose hashing, file integrity verification, content addressing.
#include <cryptopp/blake3.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <iostream>
int main() {
CryptoPP::BLAKE3 hash;
std::string message = "The quick brown fox jumps over the lazy dog";
std::string digest;
hash.Update(reinterpret_cast<const CryptoPP::byte*>(message.data()), message.size());
digest.resize(hash.DigestSize());
hash.Final(reinterpret_cast<CryptoPP::byte*>(&digest[0]));
std::string hexOutput;
CryptoPP::StringSource(digest, true,
new CryptoPP::HexEncoder(new CryptoPP::StringSink(hexOutput))
);
std::cout << "BLAKE3: " << hexOutput << std::endl;
return 0;
}File hashing example:
BLAKE3 hash;
std::string digest;
FileSource("document.pdf", true,
new HashFilter(hash,
new StringSink(digest)
)
);
// digest now contains the BLAKE3 hash of the file
Keyed Hash Mode (MAC)
When to use: Message authentication when both parties share a secret key.
#include <cryptopp/blake3.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <iostream>
int main() {
using namespace CryptoPP;
// Generate a random 32-byte key (do this once, store securely)
AutoSeededRandomPool rng;
SecByteBlock key(32);
rng.GenerateBlock(key, key.size());
// Create keyed BLAKE3 (MAC)
BLAKE3 mac(key, key.size());
std::string message = "Authenticate this message";
std::string tag;
mac.Update(reinterpret_cast<const byte*>(message.data()), message.size());
tag.resize(mac.DigestSize());
mac.Final(reinterpret_cast<byte*>(&tag[0]));
// Send message + tag to recipient
// Recipient verifies by recomputing MAC with same key
std::string hexTag;
StringSource(tag, true, new HexEncoder(new StringSink(hexTag)));
std::cout << "MAC: " << hexTag << std::endl;
return 0;
}Verification example:
// Receiver side:
BLAKE3 verifyMac(key, key.size());
verifyMac.Update(reinterpret_cast<const byte*>(receivedMessage.data()), receivedMessage.size());
std::string computedTag(32, '\0');
verifyMac.Final(reinterpret_cast<byte*>(&computedTag[0]));
// Check the length first (tag length is not secret), then compare in
// constant time. Comparing a fixed 32 bytes against a shorter received
// tag would read out of bounds.
const size_t tagSize = computedTag.size();
if (receivedTag.size() == tagSize &&
VerifyBufsEqual(
reinterpret_cast<const byte*>(computedTag.data()),
reinterpret_cast<const byte*>(receivedTag.data()),
tagSize))
{
std::cout << "Message is authentic!" << std::endl;
} else {
std::cout << "WARNING: Message has been tampered with!" << std::endl;
}Key Derivation Mode (KDF)
When to use: Deriving multiple keys from a single secret, creating domain-separated keys.
#include <cryptopp/blake3.h>
#include <cryptopp/osrng.h>
#include <cryptopp/secblock.h>
#include <iostream>
#include <string>
int main() {
using namespace CryptoPP;
// Input key material must be high-entropy: a randomly generated key,
// Argon2 output, or a secret loaded from protected key storage.
SecByteBlock inputKeyMaterial(32);
AutoSeededRandomPool rng;
rng.GenerateBlock(inputKeyMaterial, inputKeyMaterial.size());
// Derive encryption key
BLAKE3 kdfEncrypt("MyApplication 2025-11-25 Encryption Key", 32);
kdfEncrypt.Update(inputKeyMaterial.data(), inputKeyMaterial.size());
SecByteBlock encryptionKey(32);
kdfEncrypt.Final(encryptionKey);
// Derive MAC key (different context = different output)
BLAKE3 kdfMac("MyApplication 2025-11-25 MAC Key", 32);
kdfMac.Update(inputKeyMaterial.data(), inputKeyMaterial.size());
SecByteBlock macKey(32);
kdfMac.Final(macKey);
// encryptionKey and macKey are now independent, derived keys
std::cout << "Derived two independent keys from one secret" << std::endl;
return 0;
}For password hashing, use Argon2 instead!
BLAKE3 KDF is fast, which is good for key derivation but bad for password hashing. Argon2 is deliberately memory-hard and slow, making it resistant to brute-force attacks.
Extendable Output (XOF)
When to use: Protocols that need output longer than 32 bytes.
The implementation supports variable output lengths from 1 to 1,024 bytes. Configure the maximum output size in the constructor; TruncatedFinal() may emit up to that configured size. This is not a seekable XOF reader like the official implementation’s OutputReader: finalisation restarts the object, so producing another length means hashing the input again. BLAKE3 does not domain-separate output lengths, so a shorter output is a prefix of a longer one.
#include <cryptopp/blake3.h>
#include <iostream>
#include <string>
int main() {
using namespace CryptoPP;
BLAKE3 hash(128); // configure the maximum output size up front
std::string message = "Generate extended output";
hash.Update(
reinterpret_cast<const byte*>(message.data()),
message.size());
std::string output(128, '\0');
hash.TruncatedFinal(
reinterpret_cast<byte*>(&output[0]),
output.size());
std::cout << "Generated " << output.size() << "-byte hash output" << std::endl;
// A different length requires hashing the input again:
BLAKE3 short16(16);
short16.Update(
reinterpret_cast<const byte*>(message.data()),
message.size());
std::string small(16, '\0');
short16.TruncatedFinal(reinterpret_cast<byte*>(&small[0]), small.size());
return 0;
}Performance
SIMD Paths
| SIMD level | Chunks per batch | A single Update() call must supply more than |
|---|---|---|
| AVX-512 (AVX-512F and AVX-512VL) | 16 | 16 KiB |
| AVX2 | 8 | 8 KiB |
| SSE4.1 | 4 | 4 KiB |
| C++ | 1 | Any length |
Performance Tips
- Use large buffers: pass more than 16 KiB per
Update()call (8 KiB for AVX2, 4 KiB for SSE4.1) so the parallel chunk paths can run - Check your provider: Use
AlgorithmProvider()to inspect the highest detected SIMD capability - Small data is fine: small inputs produce the same digest through the single-block compression path
#include <fstream>
#include <stdexcept>
#include <vector>
// Large buffers enable the parallel SIMD paths
BLAKE3 hash;
const size_t BUFFER_SIZE = 65536; // 64 KiB
std::vector<byte> buffer(BUFFER_SIZE);
std::ifstream file("largefile.bin", std::ios::binary);
if (!file)
throw std::runtime_error("Could not open largefile.bin");
while (file) {
file.read(
reinterpret_cast<char*>(buffer.data()),
static_cast<std::streamsize>(buffer.size()));
const std::streamsize count = file.gcount();
if (count > 0)
hash.Update(buffer.data(), static_cast<size_t>(count));
}
if (!file.eof())
throw std::runtime_error("Error reading largefile.bin");A while (file.read(...)) loop silently drops the final partial block: the last short read sets the stream failure state before its bytes are hashed.
Security
Security properties
- Security strength: The specification targets 128-bit security for preimage, second-preimage and collision attacks. The implementation documentation states that an N-bit output is intended to give N-bit first- and second-preimage resistance and N/2-bit collision resistance for N up to 256, so the default 256-bit output is intended to give 256-bit preimage and 128-bit collision resistance.
- Output length: The default 32-byte output is recommended for general use. Outputs shorter than 32 bytes provide less security, and longer outputs do not provide any additional security.
- Length-extension resistance: The specification’s subtree-freeness argument rules out length-extension attacks. The ROOT flag is set only on the last compression, so a hash output cannot be continued as if it were a chaining value, and the CHUNK_END flag marks the final block of each chunk, so a chunk’s chaining value cannot be confused with a partial state.
- Keyed mode (MAC / PRF): The keyed_hash mode takes a 256-bit key and removes the need for a separate construction like HMAC. Its security target is the specification’s 128 bits. It is not a drop-in replacement for HMAC at the API, protocol or interoperability level.
- KDF mode: derive_key takes a context string and key material; the context string should be hardcoded, globally unique and application-specific, and should not contain variable data such as salts, IDs or the current time.
- Side-channel behaviour: The portable compression function uses only additions, XORs and fixed rotations, and indexes its message schedule by round number, not by secret data. No independent constant-time guarantee is made for every platform and compiler.
Security notes
- Use at least 32 bytes of output for cryptographic purposes. A 16-byte output is intended to provide 64-bit collision resistance; use it only where that bound is acceptable.
- For quantum attack estimates, see Security Levels Explained.
- Do not use BLAKE3 directly for password hashing or deriving keys from low-entropy passwords; it is designed to be fast, and its designers recommend Argon2. Treat BLAKE3 KDF as a fast, follow-on KDF once you already have high-entropy key material.
- In keyed mode, treat BLAKE3 as a MAC/PRF, not as a digital signature. Use Ed25519/RSA/etc. where you need non-repudiation.
- When deriving multiple keys from the same input (e.g. encryption key + MAC key), always use distinct, fixed context strings to enforce domain separation between outputs.
Thread Safety
- Per-instance: Not thread-safe. Do not use the same
BLAKE3instance from multiple threads simultaneously. - Multi-instance: Thread-safe. You can safely use different
BLAKE3instances in different threads. - Static methods: Thread-safe (
StaticAlgorithmName()).
Example (safe):
// Each thread has its own instance
void workerThread(const std::vector<std::string>& messages) {
BLAKE3 hash; // Thread-local instance
for (const auto& msg : messages) {
hash.Update(...);
hash.TruncatedFinal(...); // restarts the object for the next message
}
}Use Cases
- File integrity - Checksums and file verification
- Signature prehashing - Only in protocols that explicitly specify BLAKE3 as their prehash; Ed25519 and the other signature schemes hash internally
- Content addressing - IPFS is among the adopters the BLAKE3 project lists
- Deduplication - Fast hash for identifying duplicate data
- Message authentication - Use keyed mode for MAC
- Key derivation - Derive multiple keys from one secret (use KDF mode)
- Hash tables - Keyed hashing for identifiers and keys
Test Vectors
Use these to verify your BLAKE3 implementation:
| Mode | Input | Output (hex) |
|---|---|---|
| Basic | empty (0 bytes) | af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262 |
| Basic | 3 bytes 00 01 02 | e1be4d7a8ab5560aa4199eea339849ba8e293d55ca0a81006726d184519e647f |
Both are the first 32 bytes of cases in the official BLAKE3 test vectors, which also cover the keyed and derive-key modes with extended output. The library’s known-answer tests use the same vectors in TestVectors/blake3.txt.
See Also
- BLAKE3 Guide - Detailed guide with more examples
- Hash Functions Guide - Overview of all hash functions
- Algorithm Selection Guide - Choosing between the commonly used algorithms
- Argon2 - Use this for password hashing, not BLAKE3
- HMAC - Alternative MAC construction
- BLAKE3 Specification - Official specification