Skip to content

BLAKE2b / BLAKE2s

Header: #include <cryptopp/blake2.h> | Namespace: CryptoPP Since: Crypto++ 5.6.4 Thread Safety: Not thread-safe per instance; use separate instances per thread

Its designers describe BLAKE2 as faster than MD5, SHA-1, SHA-2 and SHA-3, yet at least as secure as SHA-3. It is specified in RFC 7693 and comes in two variants: BLAKE2b, optimised for 64-bit platforms with digests of 1 to 64 bytes, and BLAKE2s, optimised for 8- to 32-bit platforms with digests of 1 to 32 bytes.

Quick Example

#include <cryptopp/blake2.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>
#include <string>

int main() {
    using namespace CryptoPP;

    std::string message = "Hello, World!";
    std::string hash;

    // BLAKE2b (64-byte output by default)
    BLAKE2b blake2b;
    StringSource(message, true,
        new HashFilter(blake2b,
            new HexEncoder(new StringSink(hash))
        )
    );

    std::cout << hash << std::endl;
    // 7DFDB888AF71EAE0E6A6B751E8E3413D767EF4FA52A7993DAA9EF097F7AA3D94
    // 9199C113CAA37C94F80CF3B22F7D9D6E4F5DEF4FF927830CFFE4857C34BE3D89
    return 0;
}

Usage Guidelines

  • Use BLAKE2b on 64-bit platforms and BLAKE2s on 8- to 32-bit platforms, the platforms each is optimised for
  • Use keyed mode for MAC functionality; BLAKE2 has a built-in keying mechanism and does not need HMAC
  • Specify output length if you need less than default
  • Don’t use for password hashing (use Argon2)
  • Don’t pass a key, salt, personalization or digest size outside the ranges in Parameters to the constructors; see Error Handling

BLAKE2b vs BLAKE2s

FeatureBLAKE2bBLAKE2s
Optimised for64-bit platforms8- to 32-bit platforms
Output size1-64 bytes (default 64)1-32 bytes (default 32)
Block size128 bytes64 bytes
Collision security (full-length digest)2^2562^128

Constants

// BLAKE2b
BLAKE2b::DIGESTSIZE      // 64 bytes (default output)
BLAKE2b::BLOCKSIZE       // 128 bytes
BLAKE2b::MIN_KEYLENGTH   // 0 bytes (unkeyed)
BLAKE2b::MAX_KEYLENGTH   // 64 bytes

// BLAKE2s
BLAKE2s::DIGESTSIZE      // 32 bytes (default output)
BLAKE2s::BLOCKSIZE       // 64 bytes
BLAKE2s::MIN_KEYLENGTH   // 0 bytes (unkeyed)
BLAKE2s::MAX_KEYLENGTH   // 32 bytes

SALTSIZE and PERSONALIZATIONSIZE are 16 bytes for BLAKE2b and 8 bytes for BLAKE2s.

Constructors

// Default (full output length, unkeyed)
BLAKE2b(bool treeMode = false, unsigned int digestSize = DIGESTSIZE);
BLAKE2s(bool treeMode = false, unsigned int digestSize = DIGESTSIZE);

// Digest size only (tree mode off)
BLAKE2b(unsigned int digestSize);
BLAKE2s(unsigned int digestSize);

// Keyed mode (MAC); BLAKE2s has the same signature
BLAKE2b(const byte* key, size_t keyLength, const byte* salt = NULLPTR,
        size_t saltLength = 0, const byte* personalization = NULLPTR,
        size_t personalizationLength = 0, bool treeMode = false,
        unsigned int digestSize = DIGESTSIZE);

Parameters

ParameterTypeDescription
treeModeboolSets the last-node flag at finalisation, as tree hashing requires
digestSizeunsigned intOutput length in bytes (1-64 for BLAKE2b, 1-32 for BLAKE2s)
keyconst byte*Key for keyed mode (MAC)
keyLengthsize_tKey length (0-64 for BLAKE2b, 0-32 for BLAKE2s)
saltconst byte*Optional salt, up to 16 bytes for BLAKE2b and 8 for BLAKE2s; a shorter salt is zero-padded
personalizationconst byte*Optional personalization string, up to 16 bytes for BLAKE2b and 8 for BLAKE2s; a shorter string is zero-padded

Methods

Update

void Update(const byte* input, size_t length);

Adds data to the hash computation.

Final

void Final(byte* digest);

Computes the final hash value.

TruncatedFinal

void TruncatedFinal(byte* digest, size_t digestSize);

Computes a truncated hash.

Restart

void Restart();

Resets for new computation (keeps key if set).

DigestSize

unsigned int DigestSize() const;

Returns the configured output size.

Complete Examples

Example 1: Basic BLAKE2b Hashing

#include <cryptopp/blake2.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    std::string message = "The quick brown fox jumps over the lazy dog";

    // Method 1: Pipeline
    std::string hash1;
    BLAKE2b blake2b;
    StringSource(message, true,
        new HashFilter(blake2b,
            new HexEncoder(new StringSink(hash1))
        )
    );

    // Method 2: Direct API
    BLAKE2b hasher;
    hasher.Update((const byte*)message.data(), message.size());
    byte digest[BLAKE2b::DIGESTSIZE];
    hasher.Final(digest);

    std::cout << "BLAKE2b: " << hash1 << std::endl;

    return 0;
}

Example 2: BLAKE2s for Embedded/32-bit

#include <cryptopp/blake2.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    std::string message = "Data for 32-bit system";

    std::string hash;
    BLAKE2s blake2s;
    StringSource(message, true,
        new HashFilter(blake2s,
            new HexEncoder(new StringSink(hash))
        )
    );

    std::cout << "BLAKE2s (32 bytes): " << hash << std::endl;

    return 0;
}

Example 3: Custom Output Length

#include <cryptopp/blake2.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    std::string message = "Hello";

    // 32-byte output (256-bit) instead of default 64
    BLAKE2b blake2b_256(false, 32);

    std::string hash;
    StringSource(message, true,
        new HashFilter(blake2b_256,
            new HexEncoder(new StringSink(hash))
        )
    );

    std::cout << "BLAKE2b-256: " << hash << std::endl;
    // Output: 64 hex characters (32 bytes)

    return 0;
}

Example 4: Keyed BLAKE2 (MAC Mode)

#include <cryptopp/blake2.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/misc.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    // Generate 32-byte key
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    std::string message = "Message to authenticate";

    // Keyed BLAKE2b (acts as MAC)
    BLAKE2b mac(key, key.size());

    std::string tag;
    StringSource(message, true,
        new HashFilter(mac,
            new HexEncoder(new StringSink(tag))
        )
    );

    std::cout << "BLAKE2b-MAC: " << tag << std::endl;

    // Verify
    BLAKE2b verifier(key, key.size());
    verifier.Update((const byte*)message.data(), message.size());

    byte computed[BLAKE2b::DIGESTSIZE];
    verifier.Final(computed);

    // Decode expected tag
    std::string decoded;
    StringSource(tag, true,
        new HexDecoder(new StringSink(decoded))
    );

    // Check the length, then compare in constant time
    if (decoded.size() == sizeof(computed) &&
        VerifyBufsEqual(computed,
                        reinterpret_cast<const byte*>(decoded.data()),
                        sizeof(computed))) {
        std::cout << "MAC verified!" << std::endl;
    } else {
        std::cerr << "MAC verification failed" << std::endl;
        return 1;
    }

    return 0;
}

Example 5: File Hashing

#include <cryptopp/blake2.h>
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

std::string hashFile(const std::string& filename) {
    using namespace CryptoPP;

    std::string hash;
    BLAKE2b blake2b;

    FileSource(filename.c_str(), true,
        new HashFilter(blake2b,
            new HexEncoder(new StringSink(hash))
        )
    );

    return hash;
}

int main() {
    try {
        std::string hash = hashFile("document.pdf");
        std::cout << "BLAKE2b: " << hash << std::endl;
    } catch (const CryptoPP::Exception& e) {
        std::cerr << "Cannot read file: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

Example 6: BLAKE2 with Salt and Personalization

#include <cryptopp/blake2.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>
#include <cstring>

int main() {
    using namespace CryptoPP;

    // Key (optional, can be nullptr for unkeyed)
    AutoSeededRandomPool rng;
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());

    // Salt (16 bytes for BLAKE2b)
    byte salt[16];
    memset(salt, 0x01, sizeof(salt));

    // Personalization (16 bytes for BLAKE2b)
    byte personalization[BLAKE2b::PERSONALIZATIONSIZE];
    std::memcpy(personalization, "MyApp_v1________", sizeof(personalization));

    // Create BLAKE2b with all parameters
    BLAKE2b hasher(key, key.size(), salt, sizeof(salt),
                   personalization, sizeof(personalization));

    std::string message = "Application-specific hash";
    std::string hash;

    hasher.Update((const byte*)message.data(), message.size());
    byte digest[BLAKE2b::DIGESTSIZE];
    hasher.Final(digest);

    StringSource(digest, sizeof(digest), true,
        new HexEncoder(new StringSink(hash))
    );

    std::cout << "Personalized BLAKE2b: " << hash << std::endl;

    return 0;
}

Example 7: Incremental Hashing

#include <cryptopp/blake2.h>
#include <cryptopp/hex.h>
#include <cryptopp/filters.h>
#include <iostream>

int main() {
    using namespace CryptoPP;

    BLAKE2b hasher;

    // Hash data in chunks (streaming)
    std::string chunk1 = "First part of ";
    std::string chunk2 = "the message to ";
    std::string chunk3 = "be hashed";

    hasher.Update((const byte*)chunk1.data(), chunk1.size());
    hasher.Update((const byte*)chunk2.data(), chunk2.size());
    hasher.Update((const byte*)chunk3.data(), chunk3.size());

    byte digest[BLAKE2b::DIGESTSIZE];
    hasher.Final(digest);

    std::string hash;
    StringSource(digest, sizeof(digest), true,
        new HexEncoder(new StringSink(hash))
    );

    std::cout << "BLAKE2b: " << hash << std::endl;

    // Hash again without recreating object
    hasher.Restart();
    std::string newMessage = "Different message";
    hasher.Update((const byte*)newMessage.data(), newMessage.size());
    hasher.Final(digest);

    return 0;
}

BLAKE2 vs Other Hash Functions

FeatureBLAKE2bBLAKE3SHA-256SHA-3
Output size1-64 bytes1-1,024 bytes in this library32 bytes28, 32, 48 or 64 bytes
Keyed modeBuilt-inBuilt-inVia HMACVia HMAC
SpecificationRFC 7693 (Informational)BLAKE3 specificationFIPS 180-4FIPS 202

When to Use BLAKE2

Use BLAKE2b for:

  1. General-purpose hashing on 64-bit platforms
  2. MAC without HMAC (keyed mode)
  3. File integrity verification
  4. Content-addressable storage
  5. Interoperating with RFC 7693 implementations

Use BLAKE2s for:

  1. 8- to 32-bit platforms
  2. When 128-bit collision security is sufficient

Don’t use BLAKE2 for:

  1. Password hashing (use Argon2)
  2. When an approved hash is required: NIST’s approved hash functions are those in FIPS 180-4 and FIPS 202

Security Properties

PropertyBLAKE2b-512BLAKE2s-256
Collision security2^2562^128

Shorter digests have lower collision security; RFC 7693 lists 2^128 for BLAKE2b-256 and 2^64 for BLAKE2s-128. The designers state that BLAKE2 aims for the highest security level against (second) preimage and collision attacks, and that keyed BLAKE2 can be used securely in prefix-MAC mode.

Thread Safety

BLAKE2 objects are not thread-safe:

// WRONG - shared across threads
BLAKE2b sharedHasher;

// CORRECT - per-thread instances
void hashInThread(const std::string& data) {
    BLAKE2b hasher;
    hasher.Update((const byte*)data.data(), data.size());
    byte digest[BLAKE2b::DIGESTSIZE];
    hasher.Final(digest);
}

Error Handling

The constructors validate their arguments. A key longer than MAX_KEYLENGTH throws InvalidKeyLength. A digest size of 0 or larger than DIGESTSIZE, a salt longer than SALTSIZE, a personalization string longer than PERSONALIZATIONSIZE, or a null pointer passed with a non-zero length throws InvalidArgument. SetKey() makes the same checks: it throws InvalidKeyLength for a key longer than MAX_KEYLENGTH and InvalidArgument for an out-of-range DigestSize, Salt or Personalization parameter:

#include <cryptopp/blake2.h>
#include <iostream>
#include <string>

void safeHash(const CryptoPP::SecByteBlock& key, const std::string& message) {
    using namespace CryptoPP;

    try {
        // SetKey() validates the key length (0 to 64 bytes for BLAKE2b)
        BLAKE2b mac;
        mac.SetKey(key, key.size());

        mac.Update(reinterpret_cast<const byte*>(message.data()), message.size());

        byte digest[BLAKE2b::DIGESTSIZE];
        mac.Final(digest);

    } catch (const InvalidKeyLength& e) {
        std::cerr << "Invalid key length: " << e.what() << std::endl;
    }
}

Migration from HMAC

BLAKE2’s keyed mode can replace HMAC for new applications. The tags are not interchangeable: both sides must use the same construction. The tag sizes differ too: HMAC-SHA256 writes 32 bytes and BLAKE2b writes 64 by default, so a buffer sized for the HMAC tag overflows on Final(). Size each buffer from the class’s DIGESTSIZE, or pass a digestSize of 32 to the BLAKE2b constructor to keep the tag length. BLAKE2b keys are at most BLAKE2b::MAX_KEYLENGTH (64) bytes; an HMAC key longer than that must be re-derived to 64 bytes or fewer before migrating.

// Before (HMAC-SHA256): 32-byte tag
HMAC<SHA256> hmac(key, keyLen);
byte hmacTag[HMAC<SHA256>::DIGESTSIZE];   // 32 bytes
hmac.Update(message, messageLen);
hmac.Final(hmacTag);

// After (BLAKE2b keyed): 64-byte tag by default; keyLen must be at most BLAKE2b::MAX_KEYLENGTH (64)
BLAKE2b blake2(key, keyLen);
byte blake2Tag[BLAKE2b::DIGESTSIZE];      // 64 bytes
blake2.Update(message, messageLen);
blake2.Final(blake2Tag);

The designers state that keyed BLAKE2 (prefix-MAC) is faster than HMAC because it saves at least one call to the compression function.

See Also

  • BLAKE3 - Faster parallel hash function
  • SHA-256 - Standard hash function
  • SHA-3 - FIPS 202 hash function
  • HMAC - Hash-based MAC (for SHA family)
  • HashFilter - Pipeline filter for hashing

References

  1. BLAKE2 home page
  2. RFC 7693: The BLAKE2 Cryptographic Hash and Message Authentication Code (MAC)
  3. Aumasson, Neves, Wilcox-O’Hearn and Winnerlein: BLAKE2: simpler, smaller, fast as MD5