From 8ed507176f09b9c162cf4f060dab8e219c6b0d77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Tue, 14 Apr 2020 18:55:37 +0200 Subject: [PATCH] Choose blinding factor relatively prime to N This is a requirement for RSA blinding, but wasn't implemented yet. --- CHANGELOG.md | 1 + rsa/key.py | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f67b84..1aae86d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - Added support for SHA3 hashing: SHA3-256, SHA3-384, SHA3-512. This is natively supported by Python 3.6+ and supported via a third-party library on Python 3.5. +- Choose blinding factor relatively prime to N. Thanks Christian Heimes for pointing this out. ## Version 4.0 - released 2018-09-16 diff --git a/rsa/key.py b/rsa/key.py index b4d902b..7da0535 100644 --- a/rsa/key.py +++ b/rsa/key.py @@ -416,6 +416,13 @@ def __ne__(self, other: typing.Any) -> bool: def __hash__(self) -> int: return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) + def _get_blinding_factor(self) -> int: + for _ in range(1000): + blind_r = rsa.randnum.randint(self.n - 1) + if rsa.prime.are_relatively_prime(self.n, blind_r): + return blind_r + raise RuntimeError('unable to find blinding factor') + def blinded_decrypt(self, encrypted: int) -> int: """Decrypts the message using blinding to prevent side-channel attacks. @@ -426,7 +433,7 @@ def blinded_decrypt(self, encrypted: int) -> int: :rtype: int """ - blind_r = rsa.randnum.randint(self.n - 1) + blind_r = self._get_blinding_factor() blinded = self.blind(encrypted, blind_r) # blind before decrypting decrypted = rsa.core.decrypt_int(blinded, self.d, self.n) @@ -442,7 +449,7 @@ def blinded_encrypt(self, message: int) -> int: :rtype: int """ - blind_r = rsa.randnum.randint(self.n - 1) + blind_r = self._get_blinding_factor() blinded = self.blind(message, blind_r) # blind before encrypting encrypted = rsa.core.encrypt_int(blinded, self.d, self.n) return self.unblind(encrypted, blind_r)