I'm trying to implement the mongomery-ladder method for modular exponentiation for RSA (so N=p•q, p,q are primes) in python, as followed in this paper:
My code looks like this:
# uses montgomery-ladder method for modular exponentiation
def montgomery_ladder(x, k, N):
x %= N
k %= N
# getting the binary representation of k
bin_k = list(map(int, bin(k)[2:]))
# Initialize two variables to hold the intermediate results
r0 = 1
r1 = x
# Loop through each bit of the binary exponent from most significant to the least significant
for i in range(len(bin_k)):
if bin_k[i] == 0:
r1 = (r1 * r0) % N
r0 = (r0 ** 2) % N
else:
r0 = (r0 * r1) % N
r1 = (r1 ** 2) % N
# The final result is in r0
return r0
it doesn't work well for very large numbers, for example the following test:
def main():
x = 412432421343242134234233
k = 62243535235312321213254235
N = 10423451524353243462
print(montgomery_ladder(x, k, N))
print(pow(x, k, N))
if __name__ == '__main__':
main()
yields:
7564492758006795519
179467895766154563
pow(x, k, n) returns the correct answer, but my function doesn't. Have any ideas?
Remove the k %= N
at the start.