Skip to content

Commit 96eaa5e

Browse files
committed
Implemented __hash__ function for key objects.
Overriding __eq__ blocks inheritance of __hash__ in Python 3. Fixes issue sybrenstuvel#55
1 parent 5e08c91 commit 96eaa5e

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

rsa/key.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,9 @@ def __eq__(self, other):
228228
def __ne__(self, other):
229229
return not (self == other)
230230

231+
def __hash__(self):
232+
return hash((self.n, self.e))
233+
231234
@classmethod
232235
def _load_pkcs1_der(cls, keyfile):
233236
"""Loads a key in PKCS#1 DER format.
@@ -430,6 +433,9 @@ def __eq__(self, other):
430433
def __ne__(self, other):
431434
return not (self == other)
432435

436+
def __hash__(self):
437+
return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef))
438+
433439
def blinded_decrypt(self, encrypted):
434440
"""Decrypts the message using blinding to prevent side-channel attacks.
435441

tests/test_key.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,14 @@ def getprime(_):
5959
exponent=exponent)
6060
self.assertEqual(39317, p)
6161
self.assertEqual(33107, q)
62+
63+
64+
class HashTest(unittest.TestCase):
65+
"""Test hashing of keys"""
66+
67+
def test_hash_possible(self):
68+
priv, pub = rsa.key.newkeys(16)
69+
70+
# This raises a TypeError when hashing isn't possible.
71+
hash(priv)
72+
hash(pub)

0 commit comments

Comments
 (0)