Skip to content

Commit

Permalink
Fix exception causes all over the codebase
Browse files Browse the repository at this point in the history
The mistake is this: In some parts of the code, an exception is being
caught and replaced with a more user-friendly error. In these cases the
syntax `raise new_error from old_error` needs to be used.

Python's exception chaining means it shows not only the traceback of the
current exception, but that of the original exception (and possibly
more.) This is regardless of `raise from`. The usage of `raise from`
tells Python to put a more accurate message between the tracebacks.
Instead of this:

    During handling of the above exception, another exception occurred:

You'll get this:

    The above exception was the direct cause of the following exception:

The first is inaccurate, because it signifies a bug in the
exception-handling code itself, which is a separate situation than
wrapping an exception.
  • Loading branch information
cool-RR authored and sybrenstuvel committed Feb 24, 2021
1 parent b8ac79f commit 1a5b2d1
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 9 deletions.
8 changes: 4 additions & 4 deletions rsa/cli.py
Expand Up @@ -58,10 +58,10 @@ def keygen() -> None:

try:
keysize = int(cli_args[0])
except ValueError:
except ValueError as ex:
parser.print_help()
print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
raise SystemExit(1)
raise SystemExit(1) from ex

print('Generating %i-bit key' % keysize, file=sys.stderr)
(pub_key, priv_key) = rsa.newkeys(keysize)
Expand Down Expand Up @@ -280,8 +280,8 @@ def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,

try:
rsa.verify(indata, signature, pub_key)
except rsa.VerificationError:
raise SystemExit('Verification failed.')
except rsa.VerificationError as ex:
raise SystemExit('Verification failed.') from ex

print('Verification OK', file=sys.stderr)

Expand Down
6 changes: 3 additions & 3 deletions rsa/key.py
Expand Up @@ -131,10 +131,10 @@ def _assert_format_exists(file_format: str, methods: typing.Mapping[str, typing.

try:
return methods[file_format]
except KeyError:
except KeyError as ex:
formats = ', '.join(sorted(methods.keys()))
raise ValueError('Unsupported format: %r, try one of %s' % (file_format,
formats))
formats)) from ex

def save_pkcs1(self, format: str = 'PEM') -> bytes:
"""Saves the key in PKCS#1 DER or PEM format.
Expand Down Expand Up @@ -703,7 +703,7 @@ def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tupl
raise rsa.common.NotRelativePrimeError(
exponent, phi_n, ex.d,
msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" %
(exponent, phi_n, ex.d))
(exponent, phi_n, ex.d)) from ex

if (exponent * d) % phi_n != 1:
raise ValueError("e (%d) and d (%d) are not mult. inv. modulo "
Expand Down
4 changes: 2 additions & 2 deletions rsa/pkcs1_v2.py
Expand Up @@ -49,12 +49,12 @@ def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:

try:
hash_length = pkcs1.HASH_METHODS[hasher]().digest_size
except KeyError:
except KeyError as ex:
raise ValueError(
'Invalid `hasher` specified. Please select one of: {hash_list}'.format(
hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys()))
)
)
) from ex

# If l > 2^32(hLen), output "mask too long" and stop.
if length > (2**32 * hash_length):
Expand Down

0 comments on commit 1a5b2d1

Please sign in to comment.