如何存储大数字?

Pop*_*ebi 5 c bytearray

我必须C在32位电路板上制作RSA签名(在状态机上).我的内存有限,所以我不能将小数存储在矢量或类似的东西中.

最好的办法是,如果我可以存储位并轻松访问它们; 什么存储方法最好?

我做了这个:

#if (CPU_TYPE == CPU_TYPE_32)

typedef uint32_t word;
#define word_length 32
typedef struct BigNumber {
    word words[64];
} BigNumber;

#elif (CPU_TYPE == CPU_TYPE_16)

typedef uint16_t word;
#define word_length 16
typedef struct BigNumber {
    word words[128];
} BigNumber;

#else  
#error Unsupported CPU_TYPE  
#endif
Run Code Online (Sandbox Code Playgroud)

这似乎很难使用.我该如何简化它?

per*_*ror 4

您可以简单地使用 OpenSSL 的 BigNumber API。您可以在此处找到完整的 API 。

并且,您可以使用此代码示例作为开始:

#include <stdio.h>

#include <openssl/crypto.h>
#include <openssl/bn.h>

int main(int argc, char *argv[])
{
  static const char num1[] = "18446744073709551616";
  static const char num2[] = "36893488147419103232";

  BIGNUM *bn1 = NULL;
  BIGNUM *bn2 = NULL;
  BN_CTX *ctx = BN_CTX_new();

  BN_dec2bn(&bn1, num1); // convert the string to BIGNUM
  BN_dec2bn(&bn2, num2);

  BN_add(bn1, bn1, bn2); // bn1 = bn1 + bn2

  char *result_str = BN_bn2dec(bn1);  // convert the BIGNUM back to string
  printf("%s + %s = %s\n", num1, num2, result_str);
  OPENSSL_free(result_str);

  BN_free(bn1);
  BN_free(bn2);
  BN_CTX_free(ctx);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译它:

#> gcc -Wall -Wextra -g -o sample sample.c -lcrypto
Run Code Online (Sandbox Code Playgroud)

执行时你应该得到类似这样的结果:

18446744073709551616 + 36893488147419103232 = 55340232221128654848
Run Code Online (Sandbox Code Playgroud)