#include <stdio.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
static const char message[] = "This is a test message.";
static const unsigned char known_answer[] = {
0x52, 0x97, 0x93, 0x78, 0x27, 0x58, 0x7d, 0x62,
0x8b, 0x00, 0x25, 0xb5, 0xec, 0x39, 0x5e, 0x2d,
0x7f, 0x3e, 0xd4, 0x19
};
static const char *propq = NULL;
int main(int argc, char **argv)
{
int ret = EXIT_FAILURE;
OSSL_LIB_CTX *libctx = NULL;
EVP_MD *md = NULL;
EVP_MD_CTX *ctx = NULL;
unsigned int digest_len = 20;
int digest_len_i;
unsigned char *digest = NULL;
if (argc > 1) {
digest_len_i = atoi(argv[1]);
if (digest_len_i <= 0) {
fprintf(stderr, "Specify a non-negative digest length\n");
goto end;
}
digest_len = (unsigned int)digest_len_i;
}
md = EVP_MD_fetch(libctx, "SHAKE256", propq);
if (md == NULL) {
fprintf(stderr, "Failed to retrieve SHAKE256 algorithm\n");
goto end;
}
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
fprintf(stderr, "Failed to create digest context\n");
goto end;
}
if (EVP_DigestInit(ctx, md) == 0) {
fprintf(stderr, "Failed to initialize digest\n");
goto end;
}
if (EVP_DigestUpdate(ctx, message, sizeof(message)) == 0) {
fprintf(stderr, "Failed to hash input message\n");
goto end;
}
digest = OPENSSL_malloc(digest_len);
if (digest == NULL) {
fprintf(stderr, "Failed to allocate memory for digest\n");
goto end;
}
if (EVP_DigestFinalXOF(ctx, digest, digest_len) == 0) {
fprintf(stderr, "Failed to finalize hash\n");
goto end;
}
printf("Output digest:\n");
BIO_dump_indent_fp(stdout, digest, digest_len, 2);
if (digest_len == 20) {
if (CRYPTO_memcmp(digest, known_answer, sizeof(known_answer)) != 0) {
fprintf(stderr, "Output does not match expected result\n");
goto end;
}
}
ret = EXIT_SUCCESS;
end:
OPENSSL_free(digest);
EVP_MD_CTX_free(ctx);
EVP_MD_free(md);
OSSL_LIB_CTX_free(libctx);
return ret;
}