问题描述
我想调用python函数以从C程序实现SHA256中的加密。有人可以帮助我完成这项工作吗?或者有人可以给我一个在C中调用Python函数的示例吗?
谢谢!
解决方法
虽然可以使之工作,但将其封装到Python脚本中却很容易破解,因此不建议这样做。正如@JohnBollinger在评论中提到的那样,您的Python解释器几乎可以肯定地使用C库进行哈希处理。因此,您将拥有一个调用Python函数的C程序,该Python函数将调用C函数。非常环岛。
使用C可用的标准TLS库之一(例如openssl和mbedTLS)会更好。可以在线获得有关它们的文档(请参见here)。
以下是使用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;
}