SHA-256 Hash (sha256)
SHA-256 secure hash algorithm, 256-bit digest computation. Supports one-shot and streaming interfaces.
Constants and Data Structure
#define SHA256_DIGEST_SIZE (32)
struct sha256_ctx_t {
uint64_t count;
uint8_t buf[64];
uint32_t state[8];
};
API
One-shot
const uint8_t * sha256_hash(const void * data, int len, uint8_t * digest);
data— Input datalen— Data lengthdigest— Output 32-byte digest
Returns digest pointer.
Streaming
void sha256_init(struct sha256_ctx_t * ctx);
void sha256_update(struct sha256_ctx_t * ctx, const void * data, int len);
const uint8_t * sha256_final(struct sha256_ctx_t * ctx);
sha256_init— Initialize contextsha256_update— Feed data, may be called multiple timessha256_final— Finalize and return digest pointer (points to internal context buffer)
Example
One-shot
uint8_t msg[] = { 'x', 'b', 'o', 'o', 't' };
uint8_t digest[SHA256_DIGEST_SIZE];
sha256_hash(msg, sizeof(msg), digest);
/* digest = 0xa81a87bd a68abf88 8b64aa20 c6cf204b
91889afa 1a8506b1 e4125acb 372edb0d */
Streaming
struct sha256_ctx_t ctx;
uint8_t digest[SHA256_DIGEST_SIZE];
sha256_init(&ctx);
sha256_update(&ctx, chunk1, len1);
sha256_update(&ctx, chunk2, len2);
sha256_final(&ctx);