



#include <string.h>
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/evp.h>



int demonstrate_digest(BIO *input)
{
    OSSL_LIB_CTX *library_context = NULL;
    int ret = 0;
    const char *option_properties = NULL;
    EVP_MD *message_digest = NULL;
    EVP_MD_CTX *digest_context = NULL;
    int digest_length;
    unsigned char *digest_value = NULL;
    unsigned char buffer[512];
    int ii;

    library_context = OSSL_LIB_CTX_new();
    if (library_context == NULL) {
        fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n");
        goto cleanup;
    }

    
    message_digest = EVP_MD_fetch(library_context,
                                  "SHA3-512", option_properties);
    if (message_digest == NULL) {
        fprintf(stderr, "EVP_MD_fetch could not find SHA3-512.");
        ERR_print_errors_fp(stderr);
        OSSL_LIB_CTX_free(library_context);
        return 0;
    }
    
    digest_length = EVP_MD_get_size(message_digest);
    if (digest_length <= 0) {
        fprintf(stderr, "EVP_MD_get_size returned invalid size.\n");
        goto cleanup;
    }

    digest_value = OPENSSL_malloc(digest_length);
    if (digest_value == NULL) {
        fprintf(stderr, "No memory.\n");
        goto cleanup;
    }
    
    digest_context = EVP_MD_CTX_new();
    if (digest_context == NULL) {
        fprintf(stderr, "EVP_MD_CTX_new failed.\n");
        ERR_print_errors_fp(stderr);
        goto cleanup;
    }
    
    if (EVP_DigestInit(digest_context, message_digest) != 1) {
        fprintf(stderr, "EVP_DigestInit failed.\n");
        ERR_print_errors_fp(stderr);
        goto cleanup;
    }
    while ((ii = BIO_read(input, buffer, sizeof(buffer))) > 0) {
        if (EVP_DigestUpdate(digest_context, buffer, ii) != 1) {
            fprintf(stderr, "EVP_DigestUpdate() failed.\n");
            goto cleanup;
        }
    }
    if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) {
        fprintf(stderr, "EVP_DigestFinal() failed.\n");
        goto cleanup;
    }
    ret = 1;
    for (ii=0; ii<digest_length; ii++) {
        fprintf(stdout, "%02x", digest_value[ii]);
    }
    fprintf(stdout, "\n");

cleanup:
    if (ret != 1)
        ERR_print_errors_fp(stderr);
    
    EVP_MD_CTX_free(digest_context);
    OPENSSL_free(digest_value);
    EVP_MD_free(message_digest);

    OSSL_LIB_CTX_free(library_context);
    return ret;
}

int main(void)
{
    int ret = EXIT_FAILURE;
    BIO *input = BIO_new_fd(fileno(stdin), 1);

    if (input != NULL) {
        ret = (demonstrate_digest(input) ? EXIT_SUCCESS : EXIT_FAILURE);
        BIO_free(input);
    }
    if (ret != EXIT_SUCCESS)
        ERR_print_errors_fp(stderr);
    return ret;
}
