Ad
Calling Python Functions In C Program
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!
Ad
Answer
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;
}
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad