I've implemented Pollard's Rho for logarithms using Sage, as the following program stored in pollardrho.py
.
def pollardrho(g, h, G):
k, m = 1, 0
t = g**k * h**m
i, j = 1, 0
r = g**i * h**j
def step(t, k, m):
if lift(t) % 3 == 0:
return (t * g, k+1, m)
if lift(t) % 3 == 1:
return (t * h, k, m+1)
if lift(t) % 3 == 2:
return (t ** 2, 2*k, 2*m)
while True:
t, k, m = step(t, k, m)
r, i, j = step(*step(r, i, j))
if t == r:
print("Found a cycle")
print("g^%s h^%s == g^%s h^%s" % (k, m, i, j))
print("g^(%s - %s) == h^(%s - %s)" % (i, k, m, j))
l = g.multiplicative_order()
print("(%s - %s) / (%s - %s) %% %s" % (i, k, m, j, l))
return (i - k) / (m - j) % l # this is where everything goes wrong.
Running this with G = GF(1013), g = G(3), h = G(245)
gives the following output:
sage: pollardrho(g, h, G)
Found a cycle
g^262 h^14 == g^16870 h^1006
g^(16870 - 262) == h^(14 - 1006)
(16870 - 262) / (14 - 1006) % 1012
995
However:
sage: (16870 - 262) / (14 - 1006) % 1012
375
Note that this is a completely different result!
If I check the types of i, j, k, m
, they are all of type int
...
It turns out that typing an integer in the sage shell gives a different result than doing the same inside a python program that uses Sage libraries:
sage: type(1234)
<type 'sage.rings.integer.Integer'>
This isn't the same as the <type 'int'>
I got inside of my own program!
Using k, m = Integer(1), Integer(0)
solved my problem and I now get the correct discrete log.