\brief Hashes a generic message using a hash/digest algorithm. It uses the EVP API in the OpenSSL library to generate the hash. The type of the hash is defined by the \b hash_type \b parameter.
| 28 | /// the hash. The type of the hash is defined by the |
| 29 | /// \b hash_type \b parameter. |
| 30 | const char* gdv_hash_using_openssl(int64_t context, const void* message, |
| 31 | size_t message_length, const EVP_MD* hash_type, |
| 32 | uint32_t result_buf_size, int32_t* out_length) { |
| 33 | EVP_MD_CTX* md_ctx = EVP_MD_CTX_new(); |
| 34 | |
| 35 | if (md_ctx == nullptr) { |
| 36 | gdv_fn_context_set_error_msg(context, |
| 37 | "Could not create the context for SHA processing."); |
| 38 | *out_length = 0; |
| 39 | return ""; |
| 40 | } |
| 41 | |
| 42 | int evp_success_status = 1; |
| 43 | |
| 44 | if (EVP_DigestInit_ex(md_ctx, hash_type, nullptr) != evp_success_status || |
| 45 | EVP_DigestUpdate(md_ctx, message, message_length) != evp_success_status) { |
| 46 | gdv_fn_context_set_error_msg(context, |
| 47 | "Could not obtain the hash for the defined value."); |
| 48 | EVP_MD_CTX_free(md_ctx); |
| 49 | |
| 50 | *out_length = 0; |
| 51 | return ""; |
| 52 | } |
| 53 | |
| 54 | // Create the temporary buffer used by the EVP to generate the hash |
| 55 | unsigned int hash_digest_size = EVP_MD_size(hash_type); |
| 56 | auto* result = static_cast<unsigned char*>(OPENSSL_malloc(hash_digest_size)); |
| 57 | |
| 58 | if (result == nullptr) { |
| 59 | gdv_fn_context_set_error_msg(context, "Could not allocate memory for SHA processing"); |
| 60 | EVP_MD_CTX_free(md_ctx); |
| 61 | *out_length = 0; |
| 62 | return ""; |
| 63 | } |
| 64 | |
| 65 | unsigned int result_length; |
| 66 | int evp_result = EVP_DigestFinal_ex(md_ctx, result, &result_length); |
| 67 | |
| 68 | if (evp_result != evp_success_status || result_length != hash_digest_size || |
| 69 | result_buf_size != (2 * hash_digest_size)) { |
| 70 | gdv_fn_context_set_error_msg(context, |
| 71 | "Could not obtain the hash for the defined value"); |
| 72 | EVP_MD_CTX_free(md_ctx); |
| 73 | OPENSSL_free(result); |
| 74 | |
| 75 | *out_length = 0; |
| 76 | return ""; |
| 77 | } |
| 78 | |
| 79 | // Allocate one extra byte beyond result_buf_size so that the null terminator |
| 80 | // written by the final snprintf call does not land past the end of the buffer. |
| 81 | auto result_buffer = |
| 82 | reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, result_buf_size + 1)); |
| 83 | |
| 84 | if (result_buffer == nullptr) { |
| 85 | gdv_fn_context_set_error_msg(context, |
| 86 | "Could not allocate memory for the result buffer"); |
| 87 | // Free the resources used by the EVP |
no test coverage detected