I use the libsrypto openssl library to try to create the sha256 hash of an arbitrary input buffer, however, when I null complete the hash buffer to make it a C string, it fails, but only when using the dynamic memory returned from malloc
but not when I use statically allocated memory, as in this example: generate sha256 using openssl and C ++ . I allocate 65 bytes, as in the example, as shown by the printed value length
. So, why does zero terminate buffer failure when using dynamic memory as opposed to static memory?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/sha.h>
static int sha256(char *in, char **out)
{
int rtrn, i;
SHA256_CTX sha256;
unsigned char hash[SHA256_DIGEST_LENGTH];
rtrn = SHA256_Init(&sha256);
if(rtrn < 0)
{
printf("Sha Init Error\n");
return -1;
}
rtrn = SHA256_Update(&sha256, in, strlen(in));
if(rtrn < 0)
{
printf("Sha Update Error\n");
return -1;
}
rtrn = SHA256_Final(hash, &sha256);
if(rtrn < 0)
{
printf("Sha Final Error\n");
return -1;
}
*out = malloc((SHA256_DIGEST_LENGTH * 2) + 1);
if(*out == NULL)
{
printf("Can't allocate output buf\n");
return -1;
}
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(*out + (i * 2), "%02x", hash[i]);
}
printf("Length: %d\n", (SHA256_DIGEST_LENGTH * 2) + 1);
*out[64] = '\0';
return 0;
}
int main(void)
{
int rtrn;
char *input = "3r98h932hr934hor";
char *output;
rtrn = sha256(input, &output);
if(rtrn < 0)
{
printf("Sha256\n");
return -1;
}
printf("%s\n", output);
return 0;
}