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

Commit ae1a906

Browse files
and-semakinsybrenstuvel
authored andcommitted
Add more type hints
1 parent 1473cb8 commit ae1a906

File tree

9 files changed

+31
-26
lines changed

9 files changed

+31
-26
lines changed

rsa/_compat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from struct import pack
1818

1919

20-
def byte(num: int):
20+
def byte(num: int) -> bytes:
2121
"""
2222
Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)
2323
representation.

rsa/cli.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def __init__(self) -> None:
110110

111111
@abc.abstractmethod
112112
def perform_operation(self, indata: bytes, key: rsa.key.AbstractKey,
113-
cli_args: Indexable):
113+
cli_args: Indexable) -> typing.Any:
114114
"""Performs the program's operation.
115115
116116
Implement in a subclass.
@@ -201,7 +201,7 @@ class EncryptOperation(CryptoOperation):
201201
operation_progressive = 'encrypting'
202202

203203
def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
204-
cli_args: Indexable = ()):
204+
cli_args: Indexable = ()) -> bytes:
205205
"""Encrypts files."""
206206
assert isinstance(pub_key, rsa.key.PublicKey)
207207
return rsa.encrypt(indata, pub_key)
@@ -219,7 +219,7 @@ class DecryptOperation(CryptoOperation):
219219
key_class = rsa.PrivateKey
220220

221221
def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
222-
cli_args: Indexable = ()):
222+
cli_args: Indexable = ()) -> bytes:
223223
"""Decrypts files."""
224224
assert isinstance(priv_key, rsa.key.PrivateKey)
225225
return rsa.decrypt(indata, priv_key)
@@ -242,7 +242,7 @@ class SignOperation(CryptoOperation):
242242
'to stdout if this option is not present.')
243243

244244
def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
245-
cli_args: Indexable):
245+
cli_args: Indexable) -> bytes:
246246
"""Signs files."""
247247
assert isinstance(priv_key, rsa.key.PrivateKey)
248248

@@ -269,7 +269,7 @@ class VerifyOperation(CryptoOperation):
269269
has_output = False
270270

271271
def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
272-
cli_args: Indexable):
272+
cli_args: Indexable) -> None:
273273
"""Verifies files."""
274274
assert isinstance(pub_key, rsa.key.PublicKey)
275275

rsa/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919

2020
class NotRelativePrimeError(ValueError):
21-
def __init__(self, a, b, d, msg=''):
21+
def __init__(self, a: int, b: int, d: int, msg: str = '') -> None:
2222
super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d))
2323
self.a = a
2424
self.b = b

rsa/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"""
2020

2121

22-
def assert_int(var: int, name: str):
22+
def assert_int(var: int, name: str) -> None:
2323
if isinstance(var, int):
2424
return
2525

rsa/key.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def _save_pkcs1_der(self) -> bytes:
9494
"""
9595

9696
@classmethod
97-
def load_pkcs1(cls, keyfile: bytes, format='PEM') -> 'AbstractKey':
97+
def load_pkcs1(cls, keyfile: bytes, format: str = 'PEM') -> 'AbstractKey':
9898
"""Loads a key in PKCS#1 DER or PEM format.
9999
100100
:param keyfile: contents of a DER- or PEM-encoded file that contains
@@ -128,7 +128,7 @@ def _assert_format_exists(file_format: str, methods: typing.Mapping[str, typing.
128128
raise ValueError('Unsupported format: %r, try one of %s' % (file_format,
129129
formats))
130130

131-
def save_pkcs1(self, format='PEM') -> bytes:
131+
def save_pkcs1(self, format: str = 'PEM') -> bytes:
132132
"""Saves the key in PKCS#1 DER or PEM format.
133133
134134
:param format: the format to save; 'PEM' or 'DER'
@@ -203,7 +203,7 @@ class PublicKey(AbstractKey):
203203

204204
__slots__ = ('n', 'e')
205205

206-
def __getitem__(self, key):
206+
def __getitem__(self, key: str) -> int:
207207
return getattr(self, key)
208208

209209
def __repr__(self) -> str:
@@ -378,7 +378,7 @@ def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None:
378378
self.exp2 = int(d % (q - 1))
379379
self.coef = rsa.common.inverse(q, p)
380380

381-
def __getitem__(self, key):
381+
def __getitem__(self, key: str) -> int:
382382
return getattr(self, key)
383383

384384
def __repr__(self) -> str:
@@ -388,7 +388,7 @@ def __getstate__(self) -> typing.Tuple[int, int, int, int, int, int, int, int]:
388388
"""Returns the key as tuple for pickling."""
389389
return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef
390390

391-
def __setstate__(self, state: typing.Tuple[int, int, int, int, int, int, int, int]):
391+
def __setstate__(self, state: typing.Tuple[int, int, int, int, int, int, int, int]) -> None:
392392
"""Sets the key from tuple."""
393393
self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state
394394

@@ -574,7 +574,9 @@ def _save_pkcs1_pem(self) -> bytes:
574574
return rsa.pem.save_pem(der, b'RSA PRIVATE KEY')
575575

576576

577-
def find_p_q(nbits: int, getprime_func=rsa.prime.getprime, accurate=True) -> typing.Tuple[int, int]:
577+
def find_p_q(nbits: int,
578+
getprime_func: typing.Callable[[int], int] = rsa.prime.getprime,
579+
accurate: bool = True) -> typing.Tuple[int, int]:
578580
"""Returns a tuple of two different primes of nbits bits each.
579581
580582
The resulting p * q has exacty 2 * nbits bits, and the returned p and q
@@ -619,7 +621,7 @@ def find_p_q(nbits: int, getprime_func=rsa.prime.getprime, accurate=True) -> typ
619621
log.debug('find_p_q(%i): Finding q', nbits)
620622
q = getprime_func(qbits)
621623

622-
def is_acceptable(p, q):
624+
def is_acceptable(p: int, q: int) -> bool:
623625
"""Returns True iff p and q are acceptable:
624626
625627
- p and q differ
@@ -697,8 +699,8 @@ def calculate_keys(p: int, q: int) -> typing.Tuple[int, int]:
697699

698700
def gen_keys(nbits: int,
699701
getprime_func: typing.Callable[[int], int],
700-
accurate=True,
701-
exponent=DEFAULT_EXPONENT) -> typing.Tuple[int, int, int, int]:
702+
accurate: bool = True,
703+
exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[int, int, int, int]:
702704
"""Generate RSA keys of nbits bits. Returns (p, q, e, d).
703705
704706
Note: this can take a long time, depending on the key size.
@@ -726,8 +728,10 @@ def gen_keys(nbits: int,
726728
return p, q, e, d
727729

728730

729-
def newkeys(nbits: int, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT) \
730-
-> typing.Tuple[PublicKey, PrivateKey]:
731+
def newkeys(nbits: int,
732+
accurate: bool = True,
733+
poolsize: int = 1,
734+
exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[PublicKey, PrivateKey]:
731735
"""Generates public and private keys, and returns them as (pub, priv).
732736
733737
The public key is also known as the 'encryption key', and is a
@@ -763,7 +767,7 @@ def newkeys(nbits: int, accurate=True, poolsize=1, exponent=DEFAULT_EXPONENT) \
763767
if poolsize > 1:
764768
from rsa import parallel
765769

766-
def getprime_func(nbits):
770+
def getprime_func(nbits: int) -> int:
767771
return parallel.getprime(nbits, poolsize=poolsize)
768772
else:
769773
getprime_func = rsa.prime.getprime

rsa/parallel.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,13 @@
2323
"""
2424

2525
import multiprocessing as mp
26+
from multiprocessing.connection import Connection
2627

2728
import rsa.prime
2829
import rsa.randnum
2930

3031

31-
def _find_prime(nbits: int, pipe) -> None:
32+
def _find_prime(nbits: int, pipe: Connection) -> None:
3233
while True:
3334
integer = rsa.randnum.read_random_odd_int(nbits)
3435

rsa/pem.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iter
4949
# Handle start marker
5050
if line == pem_start:
5151
if in_pem_part:
52-
raise ValueError('Seen start marker "%s" twice' % pem_start)
52+
raise ValueError('Seen start marker "%r" twice' % pem_start)
5353

5454
in_pem_part = True
5555
seen_pem_start = True
@@ -72,10 +72,10 @@ def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iter
7272

7373
# Do some sanity checks
7474
if not seen_pem_start:
75-
raise ValueError('No PEM start marker "%s" found' % pem_start)
75+
raise ValueError('No PEM start marker "%r" found' % pem_start)
7676

7777
if in_pem_part:
78-
raise ValueError('No PEM end marker "%s" found' % pem_end)
78+
raise ValueError('No PEM end marker "%r" found' % pem_end)
7979

8080

8181
def load_pem(contents: FlexiText, pem_marker: FlexiText) -> bytes:

rsa/pkcs1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def _pad_for_signing(message: bytes, target_length: int) -> bytes:
157157
message])
158158

159159

160-
def encrypt(message: bytes, pub_key: key.PublicKey):
160+
def encrypt(message: bytes, pub_key: key.PublicKey) -> bytes:
161161
"""Encrypts the given message using PKCS#1 v1.5
162162
163163
:param message: the message to encrypt. Must be a byte string no longer than

rsa/pkcs1_v2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
)
2626

2727

28-
def mgf1(seed: bytes, length: int, hasher='SHA-1') -> bytes:
28+
def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:
2929
"""
3030
MGF1 is a Mask Generation Function based on a hash function.
3131

0 commit comments

Comments
 (0)