I would like to call a python function to realize the encryption in SHA256 from a C program. Can someone help me in this work? Or can someone give me an example of calling Python function in C?
Thank you!
Shelling out to a Python script, while it can be made to work, is very hacky and not recommended. As @JohnBollinger mentioned in the comments, your Python interpreter almost certainly utilizes a C library for its hashing. Therefore, you'd have a C program call a Python function which calls a C function. Very roundabout.
You'd be better off using one of the standard TLS libraries available for C, such as openssl and mbedTLS. Documentation for them is available online (see here).
Here's an example using mbedTLS:
#include <stdio.h>
#include <sys/types.h>
#include <mbedtls/md.h>
int hashMe(const unsigned char *data, size_t size) {
int ret;
mbedtls_md_context_t ctx;
unsigned char output[32];
mbedtls_md_init(&ctx);
ret=mbedtls_md_setup(
&ctx,
mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
0 // Indicates that we're doing simple hashing and not an HMAC
);
if ( ret != 0 ) {
return ret;
}
mbedtls_md_starts(&ctx);
mbedtls_md_update(&ctx,data,size); // Call this multiple times for each chunk of data you want to hash.
mbedtls_md_finish(&ctx,output);
mbedtls_md_free(&ctx);
printf("The hash is: ");
for (unsigned int k=0; k<sizeof(output); k++) {
printf("%02x ", output[k]);
}
printf("\n");
return 0;
}