#include #include #include "log.h" EVP_MD_CTX * md_ctx = NULL; EVP_MD * md = NULL; static int hasher_initialized = 0; int init_hasher(void){ if(hasher_initialized){ printf("hasher already initialized"); return 1; } else{ md = EVP_MD_fetch(NULL, "SHA256", NULL); if(md == NULL){ ERR_print_errors_fp(stderr); return 0; } md_ctx = EVP_MD_CTX_new(); /*TODO: see whether EVP_MD_CTX_new() ever fails?*/ if(md_ctx == NULL){ ERR_print_errors_fp(stderr); return 0; } } return 1; } int deinit_hasher(void){ if(md != NULL){ EVP_MD_free(md); } if(md_ctx != NULL){ EVP_MD_CTX_free(md_ctx); } return 0; } int rounduptoblocksize(int a){ return a; } unsigned char * digest(const unsigned char *in, size_t inlen, unsigned int * outlen){ if(!EVP_DigestInit_ex(md_ctx, md, NULL)){ log(LOG_INFO, "Problem encountered while initializing digest"); ERR_print_errors_fp(stderr); return NULL; } if(!EVP_DigestUpdate(md_ctx, in, inlen)){ log(LOG_INFO, "Problem encountered while adding data to digest"); ERR_print_errors_fp(stderr); return NULL; } unsigned char *out = OPENSSL_malloc(EVP_MD_get_size(md)); if(!EVP_DigestFinal_ex(md_ctx, out, outlen)){ log(LOG_INFO, "Problem encountered while retrieving digest"); ERR_print_errors_fp(stderr); return NULL; } return out; } int begin_digest(){ if(!EVP_DigestInit_ex(md_ctx, md, NULL)){ log(LOG_INFO, "Problem encountered while initializing digest"); ERR_print_errors_fp(stderr); return 0; } return 1; } int digest_part(const unsigned char *in, size_t inlen){ if(!EVP_DigestUpdate(md_ctx, in, inlen)){ log(LOG_INFO, "Problem encountered while adding data to digest"); ERR_print_errors_fp(stderr); return 0; } return 1; } unsigned char * get_digest(unsigned int * outlen){ unsigned char *out = OPENSSL_malloc(EVP_MD_get_size(md)); if(!EVP_DigestFinal_ex(md_ctx, out, outlen)){ log(LOG_INFO, "Problem encountered while retrieving digest"); ERR_print_errors_fp(stderr); return NULL; } return out; }