# Schnorr signature using discrete logarithm / problem with python implementation [closed]

For educational purposes (by purpose with small values for the prime order q), I tried to write a small Python implementation of the Schnorr signature described in the Wikipedia article https://en.wikipedia.org/wiki/Schnorr_signature

I implemented the following in python (Python 3.6)

from hashlib import sha256
from random import randint

def hashThis(r, M):
hash=sha256();
hash.update(str(r).encode());
hash.update(M.encode());
return int(hash.hexdigest(),16);

## Notation
# generator g
g = 2

# Prime q (for educational purpose I use explicitly a small prime number - for cryptographic purposes this would have to be much larger)
q = 2695139

## Key generation
#Private signing key x
x = 32991
# calculate public verification key y
y = pow(g, x, q)

## Signing
M = "This is the message"
k = randint(1, q - 1)
r = pow(g, k, q)
e = hashThis(r, M) % q # part 1 of signature
s = (k - (x * e)) % q # part 2 of signature

## Verification

rv = (pow(g, s, q) * pow (y, e, q)) % q
ev = hashThis(rv, M) % q

print ("e " + str(e) + " should equal ev " + str(ev))
# e 2241534 should equal ev 2462540



As you can see, e and ev should be equal - however, they are clarly not.

I don't know where the problem lies - do you have any ideas what I am doing wrong

Beware, notice the $s$ is computed modulo $(q-1)$ (due to Fermat's little theorem). You have to write $s = (k - (x * e)) \mod{ (q-1)}$.
• It is related to the fact that for any $a$, $a^{q-1}=1 \mod{q}$ holds (if $q$ is prime). That means that for any field element $a$, for any exponent $e$ and for any integer $r$, one has $a^{e} = a^{e+r \times (q-1)} = a^e \times a^{r\times(q-1)} = a^{e} \times (a^{(q-1)})^r = a^e \times 1^r = a^e \times 1 = a^e \mod{q}$. Actually, when thinking about field element, you have to think "$\mod{q}$", when thinking about exponent, you have to think about "$\mod{(q-1)}$". Since $s$ is used as an exponent, you have to think $\mod{q-1}$ ;-) – Jérémy Métairie Apr 11 '18 at 18:38
• What I mean is that $g^s = g^{(s+r \times (q-1))}$. Somehow, $s$ is not affected by multiples of $(q-1)$. Of course, exponentiation is performed over $\mod{q}$. If you consider $s \mod{q}$ (meaning you can add multiple of $q$ to $s$) you would have something like $g^{s+r \times q} = g^{s} \times (g^q)^r$. Notice that because $g^{q-1} = 1$ then $g^q=g$. Since then $g^{s} \times (g^q)^r = g^s \times g^r$ which differs from $g^s$. – Jérémy Métairie Apr 12 '18 at 6:13