Skip to content

Commit

Permalink
Apply nonce bit-length mitigation to stop timing leakage.
Browse files Browse the repository at this point in the history
 - See https://minerva.crocs.fi.muni.cz for more info.
  • Loading branch information
J08nY committed Oct 6, 2019
1 parent 1bcdd87 commit 3bd6f10
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 10 additions & 1 deletion src/ecdsa/ecdsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from six import int2byte, b
from . import ellipticcurve
from . import numbertheory
from . import rfc6979


class RSZeroError(RuntimeError):
Expand Down Expand Up @@ -171,7 +172,15 @@ def sign(self, hash, random_k):
G = self.public_key.generator
n = G.order()
k = random_k % n
p1 = k * G
# Fix the bit-length of the random nonce,
# so that it doesn't leak via timing.
# This does not change that ks = k mod n
ks = k + n
kt = ks + n
if rfc6979.bit_length(ks) == rfc6979.bit_length(n):
p1 = kt * G
else:
p1 = ks * G
r = p1.x() % n
if r == 0:
raise RSZeroError("amazingly unlucky random number r")
Expand Down
10 changes: 6 additions & 4 deletions src/ecdsa/ellipticcurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ def __eq__(self, other):
else:
return False

def __neg__(self):
return Point(self.__curve, self.__x, self.__curve.p() - self.__y)

def __add__(self, other):
"""Add one point to another point."""

Expand Down Expand Up @@ -123,13 +126,12 @@ def leftmost_bit(x):
return result // 2

e = other
if self.__order:
e = e % self.__order
if e == 0:
if e == 0 or (self.__order and e % self.__order == 0):
return INFINITY
if self == INFINITY:
return INFINITY
assert e > 0
if e < 0:
return (-self) * (-e)

# From X9.62 D.3.2:

Expand Down

0 comments on commit 3bd6f10

Please sign in to comment.