Skip to content

SHA-256

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

SHA-256 is a hash function from the SHA-2 family, specified in FIPS 180-4 and one of NIST’s approved hash functions. TLS 1.3, for example, defines the cipher suite TLS_AES_128_GCM_SHA256, which uses SHA-256 with HKDF.

Quick Example

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

int main() {
    using namespace CryptoPP;

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

    StringSource(message, true,
        new HashFilter(hash,
            new StringSink(digest)
        )
    );

    // Convert to hex
    StringSource(digest, true,
        new HexEncoder(new StringSink(hexOutput))
    );

    std::cout << "SHA-256: " << hexOutput << std::endl;
    // Expected: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f

    return 0;
}

Usage Guidelines

Do:

  • Use SHA-256 for general-purpose hashing (file integrity, checksums)
  • Use for digital signatures and certificates
  • Use with HMAC for message authentication
  • Use as the underlying hash in PBKDF2 (PBKDF2-HMAC-SHA256)
  • Use as a fast follow-on KDF after Argon2 (once you already have a high-entropy key)

Avoid:

  • Hashing passwords directly with plain SHA-256 (we recommend Argon2id for password hashing)
  • Using SHA-1 for new applications; its collision strength is below 80 bits
  • Assuming collision resistance means preimage resistance

Class: SHA256

Cryptographic hash function producing 256-bit (32-byte) digests.

Constants

static const int DIGESTSIZE = 32;   // 32 bytes (256 bits)
static const int BLOCKSIZE = 64;    // 64 bytes (512 bits)

Constructors

Default Constructor

SHA256();

Create SHA-256 hash object in initial state.

Example:

SHA256 hash;

Methods

Update()

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

Add data to the hash computation.

Parameters:

  • input - Data to hash
  • length - Length of data in bytes

Can be called multiple times to hash data incrementally.

Example:

SHA256 hash;
hash.Update((const byte*)"Hello, ", 7);
hash.Update((const byte*)"World!", 6);
// Equivalent to hashing "Hello, World!"

Final()

void Final(byte* digest);

Finalize hash and get result.

Parameters:

  • digest - Output buffer (must be 32 bytes)

Note: Automatically calls Restart() after completion.

Example:

SHA256 hash;
std::string message = "Hello, World!";
hash.Update((const byte*)message.data(), message.size());

byte digest[SHA256::DIGESTSIZE];
hash.Final(digest);

TruncatedFinal()

void TruncatedFinal(byte* digest, size_t digestSize);

Get truncated hash (first digestSize bytes).

Parameters:

  • digest - Output buffer
  • digestSize - Number of bytes to output (at most 32; a larger value throws InvalidArgument)

Use case: Some protocols require shorter hashes (e.g., 128-bit).

Example:

SHA256 hash;
hash.Update(data, dataLen);  // const byte* data, size_t dataLen

byte shortHash[16];  // 128-bit hash
hash.TruncatedFinal(shortHash, 16);

Restart()

void Restart();

Reset hash to initial state. Keeps object for reuse.

Example:

SHA256 hash;

// Hash first message
hash.Update((const byte*)msg1.data(), msg1.size());
byte digest1[32];
hash.Final(digest1);

// Reuse for second message
hash.Update((const byte*)msg2.data(), msg2.size());
byte digest2[32];
hash.Final(digest2);

CalculateDigest()

void CalculateDigest(byte* digest,
                     const byte* input,
                     size_t length);

One-shot hash computation: Update() followed by Final().

Parameters:

  • digest - Output buffer (32 bytes)
  • input - Data to hash
  • length - Length of data

Example:

std::string message = "Hello, World!";
byte digest[SHA256::DIGESTSIZE];

SHA256 hash;
hash.CalculateDigest(digest,
    (const byte*)message.data(),
    message.size()
);

VerifyDigest()

bool VerifyDigest(const byte* digest,
                  const byte* input,
                  size_t length);

Verify a hash digest (constant-time comparison).

Parameters:

  • digest - Expected hash (32 bytes)
  • input - Data to verify
  • length - Length of data

Returns: true if hash matches, false otherwise

Important: The comparison uses VerifyBufsEqual, which does not stop at the first differing byte.

Example:

byte expectedHash[32] = { /* ... */ };
std::string data = "Test data";

SHA256 hash;
bool valid = hash.VerifyDigest(
    expectedHash,
    reinterpret_cast<const byte*>(data.data()),
    data.size()
);

if (valid) {
    std::cout << "Hash verified!" << std::endl;
}

DigestSize()

unsigned int DigestSize() const;

Get hash output size.

Returns: 32 (bytes)

AlgorithmName()

std::string AlgorithmName() const;

Get algorithm name.

Returns: “SHA-256”

AlgorithmProvider()

std::string AlgorithmProvider() const;

Get implementation provider (hardware acceleration info).

Returns: the first match, in this order:

  • “SHANI” - Intel SHA extensions
  • “SSE2” - SSE2 assembly
  • “NEON” or “ARMv7” - Cryptogams ARM assembly
  • “ARMv8” - ARMv8 SHA-2 instructions
  • “Power8” - POWER8 SHA instructions
  • “C++” - Portable implementation

Example:

SHA256 hash;
std::cout << "Provider: " << hash.AlgorithmProvider() << std::endl;
// Prints "SHANI" on x86 CPUs with the SHA extensions

Complete Example: File Hashing

#include <cryptopp/sha.h>
#include <cryptopp/files.h>
#include <cryptopp/hex.h>
#include <iostream>

using namespace CryptoPP;

std::string hashFile(const std::string& filename) {
    SHA256 hash;
    std::string digest, hexDigest;

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

    StringSource(digest, true,
        new HexEncoder(new StringSink(hexDigest))
    );

    return hexDigest;
}

int main() {
    try {
        std::string hash = hashFile("document.pdf");
        std::cout << "SHA-256: " << hash << std::endl;
    } catch (const Exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

A digest stored next to the file detects corruption, not tampering: anyone who can change the file can change the digest. Keep the digest where the file’s writer cannot reach it, or sign it.

Complete Example: Incremental Hashing

#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <vector>

using namespace CryptoPP;

std::string hashLargeFile(const std::string& filename) {
    SHA256 hash;
    std::ifstream file(filename, std::ios::binary);

    if (!file) {
        throw std::runtime_error("Cannot open file");
    }

    // Process in 64 KiB chunks
    std::vector<byte> buffer(65536);

    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 file");
    }

    byte digest[SHA256::DIGESTSIZE];
    hash.Final(digest);

    // Convert to hex
    std::string hexDigest;
    StringSource(digest, sizeof(digest), true,
        new HexEncoder(new StringSink(hexDigest))
    );

    return hexDigest;
}

int main() {
    try {
        std::string hash = hashLargeFile("large_video.mp4");
        std::cout << "SHA-256: " << hash << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

Complete Example: HMAC-SHA256

#include <cryptopp/sha.h>
#include <cryptopp/hmac.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <iostream>

using namespace CryptoPP;

std::string hmacSHA256(const SecByteBlock& key, const std::string& message) {
    HMAC<SHA256> hmac(key, key.size());

    std::string mac, hexMAC;
    StringSource(message, true,
        new HashFilter(hmac,
            new StringSink(mac)
        )
    );

    StringSource(mac, true,
        new HexEncoder(new StringSink(hexMAC))
    );

    return hexMAC;
}

int main() {
    // Key: 32 random bytes, as long as the SHA-256 output (see the HMAC page for key guidance)
    AutoSeededRandomPool rng;
    SecByteBlock key(32);
    rng.GenerateBlock(key, key.size());
    std::string message = "Important message";

    std::string mac = hmacSHA256(key, message);
    std::cout << "HMAC-SHA256: " << mac << std::endl;

    return 0;
}

Performance

Hardware Acceleration

The library has SHA-256 code paths for these instruction sets:

PlatformInstructionsProvider string
x86 and x86-64Intel SHA extensions“SHANI”
ARMv8SHA-2 instructions“ARMv8”
POWER8 and laterSHA instructions“Power8”
OtherPortable C++“C++”

Checking Hardware Support

SHA256 hash;
std::string provider = hash.AlgorithmProvider();

if (provider == "SHANI" || provider == "ARMv8" || provider == "Power8") {
    std::cout << "Hardware acceleration available!" << std::endl;
} else {
    std::cout << "Using software implementation" << std::endl;
}

Security

Security Properties

  • Collision resistance: 128 bits
  • Preimage resistance: 256 bits
  • Second preimage: 256 - L(M) bits, where L(M) is the base-2 logarithm of the message length in 512-bit blocks
  • Output size: 256 bits (32 bytes)
  • Block size: 512 bits (64 bytes)
  • Standard: FIPS 180-4, NIST approved

Security Level

SHA-256 provides 128-bit collision resistance and 256-bit preimage resistance.

Comparison:

  • SHA-256: 128-bit collision / 256-bit preimage
  • SHA-512: 256-bit collision / 512-bit preimage
  • BLAKE3: the specification targets 128-bit security for every goal; the implementation documentation states 128-bit collision and 256-bit preimage resistance for the default output

Important Security Notes

  1. Not for Password Hashing: SHA-256 is a fast general-purpose hash. We recommend Argon2id for passwords; see Argon2.

  2. Collision Resistance vs Preimage:

    • Collision: Finding two messages with same hash (128-bit security)
    • Preimage: Finding message for given hash (256-bit security)
  3. SHA-1 is Broken: SHA-1 has a collision strength below 80 bits; see SHA-1.

    // Use SHA-256 for new applications, not SHA1
    SHA256 secure;

Test Vectors

The empty-string digest is the Len = 0 case of the NIST CAVP byte-oriented test vectors, which the library’s FIPS 180 vector file also carries. The “abc” digest is the one-block example from NIST’s SHA-256 example document.

// Test Vector 1: Empty string
// Input: ""
// SHA-256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

SHA256 hash;
byte digest[32];
hash.Final(digest);

byte expected[] = {
    0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
    0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
    0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
    0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
};

assert(std::memcmp(digest, expected, 32) == 0);
// Test Vector 2: "abc"
// Input: "abc"
// SHA-256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

std::string message = "abc";
SHA256 hash;
hash.Update((const byte*)message.data(), message.size());

byte digest[32];
hash.Final(digest);

byte expected[] = {
    0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
    0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
    0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
    0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad
};

assert(std::memcmp(digest, expected, 32) == 0);

Common Use Cases

1. File Integrity Verification

// Generate checksum
std::string originalHash = hashFile("software.zip");

// Later: verify file hasn't been modified
std::string currentHash = hashFile("software.zip");

if (originalHash == currentHash) {
    std::cout << "File integrity verified" << std::endl;
} else {
    std::cout << "WARNING: File has been modified!" << std::endl;
}

2. Content-Addressed Storage

// Store content under its SHA-256 hash
SHA256 hash;
std::string hexHash;
StringSource(content, true,
    new HashFilter(hash, new HexEncoder(new StringSink(hexHash))));

// For "abc": storage/BA/7816BF8F.../content
std::string path = "storage/" + hexHash.substr(0, 2) + "/" +
                   hexHash.substr(2) + "/content";

3. Digital Signatures (with RSA/ECDSA)

The signature scheme hashes the message itself, so pass the whole document to the signer rather than a digest you computed:

// privateKey is an RSA::PrivateKey, rng an AutoSeededRandomPool
RSASS<PSS, SHA256>::Signer signer(privateKey);

std::string signature;
StringSource(document, true,
    new SignerFilter(rng, signer, new StringSink(signature)));

4. Merkle Trees

// Build Merkle tree leaves from transaction hashes
std::vector<std::string> transactions;
std::vector<SecByteBlock> leafHashes;

SHA256 hash;
for (const auto& tx : transactions) {
    SecByteBlock leaf(SHA256::DIGESTSIZE);
    hash.CalculateDigest(leaf,
        reinterpret_cast<const byte*>(tx.data()), tx.size());
    leafHashes.push_back(leaf);
}

// Combine hashes pairwise
// ...

Thread Safety

Not thread-safe. Use separate instances per thread.

// WRONG - sharing between threads
SHA256 global_hash;
void thread1() { global_hash.Update(...); }  // RACE CONDITION
void thread2() { global_hash.Update(...); }

// CORRECT - per-thread instances
void threadFunc(const std::string& data) {
    SHA256 hash;  // Thread-local
    hash.Update((const byte*)data.data(), data.size());
    byte digest[32];
    hash.Final(digest);
}

When to Use SHA-256

Use SHA-256 for:

  1. File Integrity - Checksums, downloads verification
  2. Digital Signatures - As the hash in a signature scheme
  3. Certificates - TLS certificates
  4. HMAC - Message authentication (HMAC-SHA256)
  5. General Hashing - When you need a standard hash

Don’t use SHA-256 for:

  1. Password Hashing - We recommend Argon2id
  2. Throughput-critical hashing without SHA extensions - Consider BLAKE3

SHA-256 vs Alternatives

AlgorithmCollision securitySpecificationUse Case
SHA-256128 bitsFIPS 180-4General purpose
BLAKE3128 bitsBLAKE3 specificationHigh performance
SHA-512256 bitsFIPS 180-4Larger digest
SHA3-256128 bitsFIPS 202Algorithm diversity
SHA-1Below 80 bitsFIPS 180-4Legacy only

Exceptions

TruncatedFinal(), TruncatedVerify() and VerifyTruncatedDigest() throw InvalidArgument when the requested size is larger than 32 bytes. Memory allocation failures may throw std::bad_alloc.

See Also

References

  1. FIPS 180-4: Secure Hash Standard (SHS)
  2. NIST: Hash Functions
  3. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3
  4. NIST CAVP: Secure Hashing
  5. NIST: SHA-256 example with intermediate values