/*
* Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#ifndef FIPS_MODULE
# include <openssl/engine.h>
#endif
#include <openssl/params.h>
#include <openssl/core_names.h>
#include "internal/cryptlib.h"
#include "internal/provider.h"
#include "internal/core.h"
#include "crypto/evp.h"
#include "evp_local.h"
static void cleanup_old_md_data(EVP_MD_CTX *ctx, int force)
{
if (ctx->digest != NULL) {
if (ctx->digest->cleanup != NULL
&& !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_CLEANED))
ctx->digest->cleanup(ctx);
if (ctx->md_data != NULL && ctx->digest->ctx_size > 0
&& (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_REUSE)
|| force)) {
OPENSSL_clear_free(ctx->md_data, ctx->digest->ctx_size);
ctx->md_data = NULL;
}
}
}
void evp_md_ctx_clear_digest(EVP_MD_CTX *ctx, int force, int keep_fetched)
{
if (ctx->algctx != NULL) {
if (ctx->digest != NULL && ctx->digest->freectx != NULL)
ctx->digest->freectx(ctx->algctx);
ctx->algctx = NULL;
EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
}
/* Code below to be removed when legacy support is dropped. */
/*
* Don't assume ctx->md_data was cleaned in EVP_Digest_Final, because
* sometimes only copies of the context are ever finalised.
*/
cleanup_old_md_data(ctx, force);
if (force)
ctx->digest = NULL;
#if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE)
ENGINE_finish(ctx->engine);
ctx->engine = NULL;
#endif
/* Non legacy code, this has to be later than the ctx->digest cleaning */
if (!keep_fetched) {
EVP_MD_free(ctx->fetched_digest);
ctx->fetched_digest = NULL;
ctx->reqdigest = NULL;
}
}
static int evp_md_ctx_reset_ex(EVP_MD_CTX *ctx, int keep_fetched)
{
if (ctx == NULL)
return 1;
#ifndef FIPS_MODULE
/*
* pctx should be freed by the user of EVP_MD_CTX
* if EVP_MD_CTX_FLAG_KEEP_PKEY_CTX is set
*/
if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX)) {
EVP_PKEY_CTX_free(ctx->pctx);
ctx->pctx = NULL;
}
#endif
evp_md_ctx_clear_digest(ctx, 0, keep_fetched);
if (!keep_fetched)
OPENSSL_cleanse(ctx, sizeof(*ctx));
return 1;
}
/* This call frees resources associated with the context */
int EVP_MD_CTX_reset(EVP_MD_CTX *ctx)
{
return evp_md_ctx_reset_ex(ctx, 0);
}
#ifndef FIPS_MODULE
EVP_MD_CTX