【问题标题】:How to store large numbers?如何存储大数?
【发布时间】:2016-08-24 12:49:03
【问题描述】:

我必须在 32 位板上的 C 中制作 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

这似乎很难使用。如何简化?

【问题讨论】:

  • 如果您不能使用现有的库(GMP、MPFI、...),您可能需要检查它们如何表示长整数。它通常是与平台对齐的无符号数组。
  • 我不能使用任何库,我想我会用 uint32 尝试一下,谢谢!
  • “我不能将小数存储在向量或类似的东西中” - 为什么?有什么限制?有具体的尺寸吗?
  • 我有一个 RH850 板(renesas.com/en-us/products/microcontrollers-microprocessors/…),这就是为什么内存是有限的,并且孔算法将在状态机上构建,这就是为什么我应该更加注意不丢失数据的原因.
  • 我做了这个这个结构你有什么更好的想法吗? if (CPU_TYPE == CPU_TYPE_32) typedef uint32_t 字; #define word_length 32 typedef struct BigNumber { word words[64]; } 大数; #elif (CPU_TYPE == CPU_TYPE_16) typedef uint16_t word; #define word_length 16 typedef struct BigNumber { word words[128]; } 大数; #else #error 不支持的 CPU_TYPE #endif

标签: c bytearray


【解决方案1】:

您可以简单地使用 OpenSSL 的 BigNumber API。你可以找到完整的 API here

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

#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;
}

编译:

#> gcc -Wall -Wextra -g -o sample sample.c -lcrypto

执行时你应该得到类似的东西:

18446744073709551616 + 36893488147419103232 = 55340232221128654848

【讨论】:

  • 谢谢,但由于内存限制,我不能使用任何库,我使用了我发布的那个方法,但我仍然没有回答这个问题,如果有更好的解决方案,这会帮助别人。
  • 你也可以看看mbed TLS是一个与OpenSSL非常相似的库,专门用于嵌入式系统。你的“内存限制”的问题是你从来没有准确地告诉过他们有多严格。
猜你喜欢
  • 2016-08-08
  • 1970-01-01
  • 2019-07-19
  • 2013-08-06
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多