Calculate sha256 with OpenSSL and C

To compile the following code you have to link OpenSSL libeay32.lib with your project. To build OpenSSL for Windows please read this post.

Includes and Definitions

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <openssl/evp.h>
 
int HashSHA256(unsigned char *hashed, const unsigned char *plain, size_t plen);

Hash function

int HashSHA256(unsigned char *hashed, const unsigned char *plain, size_t plen){
 
	EVP_MD_CTX *mdctx;
	int md_len = 0;
 
	if (!(mdctx = EVP_MD_CTX_create())) return 0;
 
	if (1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) {
		if (mdctx) EVP_MD_CTX_destroy(mdctx);
		return 0;
	}
 
	if (1 != EVP_DigestUpdate(mdctx, plain, plen)) {
		if (mdctx) EVP_MD_CTX_destroy(mdctx);
		return 0;
	}
 
	if (1 != EVP_DigestFinal_ex(mdctx, hashed, &md_len)) {
		if (mdctx) EVP_MD_CTX_destroy(mdctx);
		return 0;
	}
 
	if (mdctx) EVP_MD_CTX_destroy(mdctx);
 
	return md_len;
}

Usage

int main(void){
	unsigned char *text = "Hello, World!\0";
	unsigned char hashed[EVP_MAX_MD_SIZE];
	int i = 0, len = 0;
 
	if ((len = HashSHA256(hashed, text, strlen(text))) > 0){
		printf("Hash value: ");
		for (i = 0; i < len; i++)
			printf("%02x", hashed[i]);
		printf("\n");
	}
	return EXIT_SUCCESS;
}
Categories: C Tags: , , ,
%d bloggers like this: