Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with massive numbers in C

I am writing an RSA encryption algorithm in C. Im not planning to put it in production anywhere, it is mainly just so I can broaden my understanding of encryption.

How do I deal with the massive numbers that RSA generates? Even when performing decryption with a relatively small private key like 103, I still have the issue of dealing with things like this:

67^103 mod 143 = (1.21816096336830017301951805581 x 10^188) mod 143

What is the best way to store a number of that size? Is there any way to do it using standard libraries? .

like image 660
mstagg Avatar asked Sep 26 '22 09:09

mstagg


1 Answers

Wrong approach. 67^103 mod 143 does not need to first calculate 67^103.

Calculate the modulo in a loop, 1 bit of exponent at a time.

uint32_t powmod(uint32_t base, uint32_t expo, uint32_t mod) {

  // % mod need only for the cases expo==0, mod<=1
  uint32_t y = 1u % mod;

  while (expo) {
    if (expo & 1u) {
      y = ((uint64_t) base * y) % mod;
    }
    expo >>= 1u;
    base = ((uint64_t) base * base) % mod;
  }

  return y;
}

int main(void) {
  printf("%lu",(unsigned long)  powmod(67, 103, 143));
}

Output

89
like image 197
chux - Reinstate Monica Avatar answered Oct 03 '22 01:10

chux - Reinstate Monica