Calculating pow(a,b) mod n

后端 未结 14 1147
执念已碎
执念已碎 2020-11-22 16:25

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

unsigned long i         


        
14条回答
  •  抹茶落季
    2020-11-22 17:14

    The only actual logic error that I see is this line:

    if (b % n == 1)
    

    which should be this:

    if (b % 2 == 1)
    

    But your overall design is problematic: your function performs O(b) multiplications and modulus operations, but your use of b / 2 and a * a implies that you were aiming to perform O(log b) operations (which is usually how modular exponentiation is done).

提交回复
热议问题