Skip to content

Commit

Permalink
Implemented __hash__ function for key objects.
Browse files Browse the repository at this point in the history
Overriding __eq__ blocks inheritance of __hash__ in Python 3.

Fixes issue #55
  • Loading branch information
sybrenstuvel committed Mar 29, 2016
1 parent 5e08c91 commit 96eaa5e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions rsa/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ def __eq__(self, other):
def __ne__(self, other):
return not (self == other)

def __hash__(self):
return hash((self.n, self.e))

@classmethod
def _load_pkcs1_der(cls, keyfile):
"""Loads a key in PKCS#1 DER format.
Expand Down Expand Up @@ -430,6 +433,9 @@ def __eq__(self, other):
def __ne__(self, other):
return not (self == other)

def __hash__(self):
return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef))

def blinded_decrypt(self, encrypted):
"""Decrypts the message using blinding to prevent side-channel attacks.
Expand Down
11 changes: 11 additions & 0 deletions tests/test_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,14 @@ def getprime(_):
exponent=exponent)
self.assertEqual(39317, p)
self.assertEqual(33107, q)


class HashTest(unittest.TestCase):
"""Test hashing of keys"""

def test_hash_possible(self):
priv, pub = rsa.key.newkeys(16)

# This raises a TypeError when hashing isn't possible.
hash(priv)
hash(pub)

0 comments on commit 96eaa5e

Please sign in to comment.