Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating pow(a,b) mod n

Tags:

c++

c

algorithm

I want to calculate abmod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?

unsigned long int decrypt2(int a,int b,int n) {     unsigned long int res = 1;      for (int i = 0; i < (b / 2); i++)     {         res *= ((a * a) % n);         res %= n;     }      if (b % n == 1)         res *=a;      res %=n;     return res; } 
like image 602
Moein Hosseini Avatar asked Dec 13 '11 21:12

Moein Hosseini


People also ask

How do you calculate POW?

The most basic way to calculate the nth power of a number is to multiply that number exactly n-times. In this case, we could just find the inverse of its positive power i.e. pow(2,-3) = 1/(2^3).

How do you calculate AB mod?

As we said, a mod b is simply an expression representing the remainder when we divide a by b. Therefore, if a / b = q remainder r, then a mod b = r.


1 Answers

You can try this C++ code. I've used it with 32 and 64-bit integers. I'm sure I got this from SO.

template <typename T> T modpow(T base, T exp, T modulus) {   base %= modulus;   T result = 1;   while (exp > 0) {     if (exp & 1) result = (result * base) % modulus;     base = (base * base) % modulus;     exp >>= 1;   }   return result; } 

You can find this algorithm and related discussion in the literature on p. 244 of

Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C, Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4.


Note that the multiplications result * base and base * base are subject to overflow in this simplified version. If the modulus is more than half the width of T (i.e. more than the square root of the maximum T value), then one should use a suitable modular multiplication algorithm instead - see the answers to Ways to do modulo multiplication with primitive types.

like image 83
Blastfurnace Avatar answered Oct 04 '22 04:10

Blastfurnace