This weekend I put together a C11 implementation of the following SHA-3 algorithms from FIPS 202 and SP 800-185:
- SHA3-224
- SHA3-256
- SHA3-384
- SHA3-512
- HMAC-SHA3-224
- HMAC-SHA3-256
- HMAC-SHA3-384
- HMAC-SHA3-512
- SHAKE128 and SHAKE128-XOF
- SHAKE256 and SHAKE256-XOF
- cSHAKE128 and cSHAKE128-XOF
- cSHAKE256 and cSHAKE256-XOF
- KMAC128 and KMAC128-XOF
- KMAC256 and KMAC256-XOF
- TupleHash128 and TupleHash128-XOF
- TupleHash256 and TupleHash256-XOF
- ParallelHash128 and ParallelHash128-XOF
- ParallelHash256 and ParallelHash256-XOF
- TurboSHAKE128 and TurboSHAKE256
- KangarooTwelve
The code is available in the Git repository.
Features
- MIT licensed
- Standard C11 with no external dependencies.
- No allocations.
- Easy to embed; drop
sha3.h
andsha3.c
into your application. - Full Doxygen-friendly API documentation.
- Full test suite based on test vectors from the NIST CSRC Examples with Intermediate Values page.
Example
// example.c: print hex-encode sha3-256 hash of each command-line argument
//
// build:
// cc -o example -std=c11 -O3 -W -Wall -Wextra -Werror -pedantic -march=native -mtune=native example.c sha3.c
#include <stdint.h> // uint8_t
#include <stdio.h> // printf()
#include <string.h> // strlen()
#include "sha3.h" // sha3_256()
// print hex-encoded buffer to stdout.
static void print_hex(const uint8_t * const buf, const size_t len) {
for (size_t i = 0; i < len; i++) {
printf("%02x", buf[i]);
}
}
int main(int argc, char *argv[]) {
// loop over command-line arguments
for (int i = 1; i < argc; i++) {
// hash argument
uint8_t buf[32] = { 0 };
sha3_256((uint8_t*) argv[i], strlen(argv[i]), buf);
// print argument and hex-encoded hash
printf("\"%s\",", argv[i]);
print_hex(buf, sizeof(buf));
fputs("\n", stdout);
}
// return success
return 0;
}
Output:
> ./example asdf foo bar
"asdf",dd2781f4c51bccdbe23e4d398b8a82261f585c278dbb4b84989fea70e76723a9
"foo",76d3bc41c9f588f7fcd0d5bf4718f8f84b1c41b20882703100b9eb9413807c01
"bar",cceefd7e0545bcf8b6d19f3b5750c8a3ee8350418877bc6fb12e32de28137355
Update (2023-09-07): Released v0.2 with TurboSHAKE128,
TurboSHAKE256, KangarooTwelve, and an examples/
directory.
Update (2023-09-18): Released v0.3 with AVX-512 support (~3x faster) and miscellaneous small fixes.