Skip to content
This repository was archived by the owner on Apr 20, 2025. It is now read-only.

Add range checks to decrypt_int and decrypt_int_fast #241

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions rsa/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,22 @@ def assert_int(var: int, name: str) -> None:
raise TypeError("{} should be an integer, not {}".format(name, var.__class__))


def assert_length(message: int, n: int) -> None:
if message < 0:
raise ValueError("Only non-negative numbers are supported")

if message >= n:
raise OverflowError("The message %i is too long for n=%i" % (message, n))


def encrypt_int(message: int, ekey: int, n: int) -> int:
"""Encrypts a message using encryption key 'ekey', working modulo n"""

assert_int(message, "message")
assert_int(ekey, "ekey")
assert_int(n, "n")

if message < 0:
raise ValueError("Only non-negative numbers are supported")

if message >= n:
raise OverflowError("The message %i is too long for n=%i" % (message, n))
assert_length(message, n)

return pow(message, ekey, n)

Expand All @@ -51,6 +55,8 @@ def decrypt_int(cyphertext: int, dkey: int, n: int) -> int:
assert_int(dkey, "dkey")
assert_int(n, "n")

assert_length(cyphertext, n)

message = pow(cyphertext, dkey, n)
return message

Expand All @@ -60,6 +66,7 @@ def decrypt_int_fast(
rs: typing.List[int],
ds: typing.List[int],
ts: typing.List[int],
n: int,
) -> int:
"""Decrypts a cypher text more quickly using the Chinese Remainder Theorem."""

Expand All @@ -70,6 +77,8 @@ def decrypt_int_fast(
assert_int(d, "d")
for t in ts:
assert_int(t, "t")

assert_length(cyphertext, n)

p, q, rs = rs[0], rs[1], rs[2:]
exp1, exp2, ds = ds[0], ds[1], ds[2:]
Expand Down
1 change: 1 addition & 0 deletions rsa/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ def blinded_decrypt(self, encrypted: int) -> int:
[self.p, self.q] + self.rs,
[self.exp1, self.exp2] + self.ds,
[self.coef] + self.ts,
self.n,
)
return self.unblind(decrypted, blindfac_inverse)

Expand Down
Loading