Digest algorithms
Digest algorithms support MD4, MD5, SHA1, SHA2, SHA3, and BLAKE2. Only BLAKE2 does not support an operator implementation replacement for NanoCrypto. For each digest algorithm, the Crypto Interface provides an API that can perform the digest when the entire message is known at once (i.e., “one shot”), and a set of APIs that can process the message in chunks at a time using an allocated context (i.e., “streaming”).
Examples
One shot (SHA2-256)
For example, for SHA2-256, if the entire message is in one buffer, call:
CRYPTO_INTERFACE_SHA256_completeDigest(pData, dataLen, pResult);
Streaming (SHA-256)
If the message needs to be processed in chunks at a time, make the following series of calls using a context object. A BulkCtx
type (essentially a void *
) is provided for the context object and can be used with any of the supported digest algorithms.
Declare a
BulkCtx
:BulkCtx pCtx = NULL;
Allocate the context to the correct size for the chosen digest algorithm:
CRYPTO_INTERFACE_SHA256_allocDigest(&pCtx);
Initialize the context for the digest algorithm:
CRYPTO_INTERFACE_SHA256_initDigest(pCtx);
Update with the data or portion thereof to be digested. Call as many times as necessary.
dataLen
here is always in bytes.CRYPTO_INTERFACE_SHA256_updateDigest(pCtx, pData, dataLen);
Finalize the hashing operation and write the results to a buffer
pResult
. This buffer must have enough space for the resulting digest.CRYPTO_INTERFACE_SHA256_finalDigest(pCtx, pResult);
Free the context object when finished with it.
CRYPTO_INTERFACE_SHA256_freeDigest(&pCtx);
Other digest sizes
The APIs for the other digest sizes of SHA2, MD4, MD5, SHA1, SHA3, and BLAKE2 are all analogous with the following exceptions:
Unlike SHA2, which has different APIs for each mode (i.e., each digest output size), there are only a single set of SHA3 APIs with the mode being a runtime parameter to its
initDigest
orcompleteDigest
API. The supported modes are SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, and SHAKE256.The SHA3
finalDigest
andcompleteDigest
APIs take in adesiredOutputLen
parameter for use in the extendable output modes SHAKE128 and SHAKE256.The BLAKE2
initDigest
andcompleteDigest
APIs may take in an optional key and its length to use BLAKE2 as a MAC algorithm. Pass inNULL
and0
, respectively, to use BLAKE2 as a digest.
Important
Applications should always use the allocDigest
and freeDigest
APIs rather than allocating themselves or placing a context on the stack. Alternative operator implementations may need these calls to allocate and free internal contexts. Otherwise, memory leaks may occur.
Full examples
A full example for SHA2-256 may be found at:
${MSS_SRC_PKG}/src/crypto_interface/example/crypto_interface_sha2_example.c
A full example for SHA3 may be found at:
${MSS_SRC_PKG}/src/crypto_interface/example/crypto_interface_sha3_example.c