I was given the following algorithm that computes s, where s = g ^ u mod p in Python:
def modexp ( g, u, p ):
"""computes s = (g ^ u) mod p
args are base, exponent, modulus
(see Bruce Schneier book, _Applied Cryptography_ p. 244)"""
s = 1
while u != 0:
if u & 1:
s = (s * g)%p
u >>= 1
g = (g * g)%p;
return s
However, when I convert the code to Ruby like this:
def modexp ( g, u, p )
s = 1
while u != 0
if u & 1
s = (s * g)%p
end
u >>= 1
g = (g * g)%p
end
return s
end
I get different results. For instance:
Python 2.7 (r27:82500, Oct 6 2010, 12:29:13)
[GCC 4.5.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import modexp
>>> modexp.modexp(96,25,17)
6
What is the correct answer from Python code compared to
>> require './modexp.rb'
=> true
>> modexp(96,25,17)
=> 14
Can anyone explain this? From what I read, Python and Ruby have the same syntax for bit-shifting and bitwise and are used in the code, so I don't think so. Does anyone have any other ideas?