【问题标题】:Calling Python functions in C program [closed]在 C 程序中调用 Python 函数 [关闭]
【发布时间】:2020-12-14 08:10:49
【问题描述】:

我想从一个C程序调用一个python函数来实现SHA256的加密。有人可以帮助我完成这项工作吗?或者有人可以给我一个在 C 中调用 Python 函数的例子吗?

谢谢!

【问题讨论】:

  • 你能解释一下你将如何使用这个函数吗?您需要捕获函数的返回值还是仅捕获输出?如果是后者,那么您应该查看 stdio.h 中的 popen 函数。
  • 另外,您是否有理由不能为 C 使用 openssl 或 mbedtls 之类的库?
  • 我想捕获被调用函数的返回值。我对C编程了解不多。我想我可以使用 openssl,你能给我一些建议吗?很抱歉缺少信息!我需要 Python 程序和 C 程序之间的互操作性,所以我需要使用相同的加密算法。我想用 Python 加密,用 C 解密,反之亦然。
  • 让 Python 参与其中似乎非常迂回。有非常好的 C 库用于计算 SHA256 和其他哈希。事实上,使用其中之一很可能是您打算依赖的任何 Python 模块的方式。
  • 你能给我一些用 C 库加密的例子吗?谢谢!

标签: python c sha


【解决方案1】:

编写一个 Python 脚本,虽然它可以工作,但非常 hacky,不推荐。正如@JohnBollinger 在 cmets 中提到的那样,您的 Python 解释器几乎肯定会使用 C 库进行哈希处理。因此,您将有一个 C 程序调用一个调用 C 函数的 Python 函数。非常迂回。

您最好使用可用于 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;
}

【讨论】:

  • 谢谢你,而不是 AES 和 DES?你有事吗?谢谢!
  • mbedTLS 库也实现了这些。查看文档。
  • @Vaahn69,如果您觉得我的回答有用,请随时点赞。
猜你喜欢
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 2020-06-03
  • 2014-05-02
  • 1970-01-01
  • 2019-03-26
相关资源
最近更新 更多