C 算法避免 RSA 期间 pow 和 mod 溢出

C algorithm to avoid overflow of pow and mod during RSA

我在做RSA加解密,运行尝试pow(ascii, e) % c时遇到溢出的问题。

我尝试了另一种方法,即 ascii 乘以自身 e 次,每次乘以 mod c。这应该给我一些 intlong 可以容纳的东西。但是,我没有得到正确的加密数字。

我正在尝试加密字符串 Hello。预期输出应为

1148 326 1145 1145 1780 

但我得到

1343 1450 379 379 855 

这就是我的

int main(int argc, const char *argv[]) {
   char buff[128];
   strncpy(buff, "Hello\n",6);

   int n = 0;
   while(buff[n] != '\n') {
      int i;
      int ascii = (int)buff[n];
      int en = ascii;

      int e = 451; // example
      int c = 2623; // example
      // instead of raising to power of e, multiply by itself e times
      // then mod c each time
      for (i = 0; i < e; i++) {
         en = (en * ascii) % c;
      }
      fprintf(stdout, "%d ", en);

      n++;
   }
   fprintf(stdout, "\n");

   return 0;
}

循环应该 运行 e-1 次。因为在第一次迭代中你会得到正方形等等....

int en = ascii; //这里有一个错误,en = 1