summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSybren A. Stüvel <sybren@stuvel.eu>2021-03-29 23:17:55 +0200
committerSybren A. Stüvel <sybren@stuvel.eu>2021-03-29 23:17:55 +0200
commit35e962d9ce424ef5ea35a9787b7b165fc034712d (patch)
treed2f93be0eb8e288ce4c2021527ddd9e57489ca7c
parent7bdbdaa16ee644d00845b94eaa3008061dc5ec79 (diff)
downloadrsa-git-35e962d9ce424ef5ea35a9787b7b165fc034712d.tar.gz
Reformatting with Black
No functional changes.
-rw-r--r--pyproject.toml3
-rw-r--r--rsa/__init__.py34
-rw-r--r--rsa/asn1.py19
-rw-r--r--rsa/cli.py207
-rw-r--r--rsa/common.py9
-rw-r--r--rsa/core.py16
-rw-r--r--rsa/key.py215
-rw-r--r--rsa/parallel.py13
-rw-r--r--rsa/pem.py22
-rw-r--r--rsa/pkcs1.py117
-rw-r--r--rsa/pkcs1_v2.py20
-rw-r--r--rsa/prime.py10
-rw-r--r--rsa/randnum.py5
-rw-r--r--rsa/transform.py8
-rw-r--r--rsa/util.py74
-rw-r--r--tests/test_cli.py127
-rw-r--r--tests/test_common.py18
-rw-r--r--tests/test_compat.py46
-rw-r--r--tests/test_load_save_keys.py72
-rw-r--r--tests/test_mypy.py14
-rw-r--r--tests/test_pem.py39
-rw-r--r--tests/test_pkcs1.py87
-rw-r--r--tests/test_pkcs1_v2.py52
-rw-r--r--tests/test_prime.py54
-rw-r--r--tests/test_strings.py2
-rw-r--r--tests/test_transform.py17
26 files changed, 723 insertions, 577 deletions
diff --git a/pyproject.toml b/pyproject.toml
index 9c4f753..d5fd5ab 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -51,3 +51,6 @@ build-backend = "poetry.core.masonry.api"
"pyrsa-decrypt" = "rsa.cli:decrypt"
"pyrsa-sign" = "rsa.cli:sign"
"pyrsa-verify" = "rsa.cli:verify"
+
+[tool.black]
+line-length = 100
diff --git a/rsa/__init__.py b/rsa/__init__.py
index 4bc164e..8d23986 100644
--- a/rsa/__init__.py
+++ b/rsa/__init__.py
@@ -22,12 +22,21 @@ prevent repetitions, or other common security improvements. Use with care.
"""
from rsa.key import newkeys, PrivateKey, PublicKey
-from rsa.pkcs1 import encrypt, decrypt, sign, verify, DecryptionError, \
- VerificationError, find_signature_hash, sign_hash, compute_hash
+from rsa.pkcs1 import (
+ encrypt,
+ decrypt,
+ sign,
+ verify,
+ DecryptionError,
+ VerificationError,
+ find_signature_hash,
+ sign_hash,
+ compute_hash,
+)
__author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly"
-__date__ = '2021-02-24'
-__version__ = '4.8-dev0'
+__date__ = "2021-02-24"
+__version__ = "4.8-dev0"
# Do doctest if we're run directly
if __name__ == "__main__":
@@ -35,6 +44,17 @@ if __name__ == "__main__":
doctest.testmod()
-__all__ = ["newkeys", "encrypt", "decrypt", "sign", "verify", 'PublicKey',
- 'PrivateKey', 'DecryptionError', 'VerificationError',
- 'find_signature_hash', 'compute_hash', 'sign_hash']
+__all__ = [
+ "newkeys",
+ "encrypt",
+ "decrypt",
+ "sign",
+ "verify",
+ "PublicKey",
+ "PrivateKey",
+ "DecryptionError",
+ "VerificationError",
+ "find_signature_hash",
+ "compute_hash",
+ "sign_hash",
+]
diff --git a/rsa/asn1.py b/rsa/asn1.py
index 32b1eb4..4cc4dd3 100644
--- a/rsa/asn1.py
+++ b/rsa/asn1.py
@@ -22,18 +22,19 @@ from pyasn1.type import univ, namedtype, tag
class PubKeyHeader(univ.Sequence):
componentType = namedtype.NamedTypes(
- namedtype.NamedType('oid', univ.ObjectIdentifier()),
- namedtype.NamedType('parameters', univ.Null()),
+ namedtype.NamedType("oid", univ.ObjectIdentifier()),
+ namedtype.NamedType("parameters", univ.Null()),
)
class OpenSSLPubKey(univ.Sequence):
componentType = namedtype.NamedTypes(
- namedtype.NamedType('header', PubKeyHeader()),
-
- # This little hack (the implicit tag) allows us to get a Bit String as Octet String
- namedtype.NamedType('key', univ.OctetString().subtype(
- implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3))),
+ namedtype.NamedType("header", PubKeyHeader()),
+ # This little hack (the implicit tag) allows us to get a Bit String as Octet String
+ namedtype.NamedType(
+ "key",
+ univ.OctetString().subtype(implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3)),
+ ),
)
@@ -46,6 +47,6 @@ class AsnPubKey(univ.Sequence):
"""
componentType = namedtype.NamedTypes(
- namedtype.NamedType('modulus', univ.Integer()),
- namedtype.NamedType('publicExponent', univ.Integer()),
+ namedtype.NamedType("modulus", univ.Integer()),
+ namedtype.NamedType("publicExponent", univ.Integer()),
)
diff --git a/rsa/cli.py b/rsa/cli.py
index c7a24f4..5a9c797 100644
--- a/rsa/cli.py
+++ b/rsa/cli.py
@@ -34,21 +34,33 @@ def keygen() -> None:
"""Key generator."""
# Parse the CLI options
- parser = optparse.OptionParser(usage='usage: %prog [options] keysize',
- description='Generates a new RSA keypair of "keysize" bits.')
-
- parser.add_option('--pubout', type='string',
- help='Output filename for the public key. The public key is '
- 'not saved if this option is not present. You can use '
- 'pyrsa-priv2pub to create the public key file later.')
-
- parser.add_option('-o', '--out', type='string',
- help='Output filename for the private key. The key is '
- 'written to stdout if this option is not present.')
-
- parser.add_option('--form',
- help='key format of the private and public keys - default PEM',
- choices=('PEM', 'DER'), default='PEM')
+ parser = optparse.OptionParser(
+ usage="usage: %prog [options] keysize",
+ description='Generates a new RSA keypair of "keysize" bits.',
+ )
+
+ parser.add_option(
+ "--pubout",
+ type="string",
+ help="Output filename for the public key. The public key is "
+ "not saved if this option is not present. You can use "
+ "pyrsa-priv2pub to create the public key file later.",
+ )
+
+ parser.add_option(
+ "-o",
+ "--out",
+ type="string",
+ help="Output filename for the private key. The key is "
+ "written to stdout if this option is not present.",
+ )
+
+ parser.add_option(
+ "--form",
+ help="key format of the private and public keys - default PEM",
+ choices=("PEM", "DER"),
+ default="PEM",
+ )
(cli, cli_args) = parser.parse_args(sys.argv[1:])
@@ -60,44 +72,45 @@ def keygen() -> None:
keysize = int(cli_args[0])
except ValueError as ex:
parser.print_help()
- print('Not a valid number: %s' % cli_args[0], file=sys.stderr)
+ print("Not a valid number: %s" % cli_args[0], file=sys.stderr)
raise SystemExit(1) from ex
- print('Generating %i-bit key' % keysize, file=sys.stderr)
+ print("Generating %i-bit key" % keysize, file=sys.stderr)
(pub_key, priv_key) = rsa.newkeys(keysize)
# Save public key
if cli.pubout:
- print('Writing public key to %s' % cli.pubout, file=sys.stderr)
+ print("Writing public key to %s" % cli.pubout, file=sys.stderr)
data = pub_key.save_pkcs1(format=cli.form)
- with open(cli.pubout, 'wb') as outfile:
+ with open(cli.pubout, "wb") as outfile:
outfile.write(data)
# Save private key
data = priv_key.save_pkcs1(format=cli.form)
if cli.out:
- print('Writing private key to %s' % cli.out, file=sys.stderr)
- with open(cli.out, 'wb') as outfile:
+ print("Writing private key to %s" % cli.out, file=sys.stderr)
+ with open(cli.out, "wb") as outfile:
outfile.write(data)
else:
- print('Writing private key to stdout', file=sys.stderr)
+ print("Writing private key to stdout", file=sys.stderr)
sys.stdout.buffer.write(data)
class CryptoOperation(metaclass=abc.ABCMeta):
"""CLI callable that operates with input, output, and a key."""
- keyname = 'public' # or 'private'
- usage = 'usage: %%prog [options] %(keyname)s_key'
- description = ''
- operation = 'decrypt'
- operation_past = 'decrypted'
- operation_progressive = 'decrypting'
- input_help = 'Name of the file to %(operation)s. Reads from stdin if ' \
- 'not specified.'
- output_help = 'Name of the file to write the %(operation_past)s file ' \
- 'to. Written to stdout if this option is not present.'
+ keyname = "public" # or 'private'
+ usage = "usage: %%prog [options] %(keyname)s_key"
+ description = ""
+ operation = "decrypt"
+ operation_past = "decrypted"
+ operation_progressive = "decrypting"
+ input_help = "Name of the file to %(operation)s. Reads from stdin if " "not specified."
+ output_help = (
+ "Name of the file to write the %(operation_past)s file "
+ "to. Written to stdout if this option is not present."
+ )
expected_cli_args = 1
has_output = True
@@ -109,8 +122,9 @@ class CryptoOperation(metaclass=abc.ABCMeta):
self.output_help = self.output_help % self.__class__.__dict__
@abc.abstractmethod
- def perform_operation(self, indata: bytes, key: rsa.key.AbstractKey,
- cli_args: Indexable) -> typing.Any:
+ def perform_operation(
+ self, indata: bytes, key: rsa.key.AbstractKey, cli_args: Indexable
+ ) -> typing.Any:
"""Performs the program's operation.
Implement in a subclass.
@@ -141,14 +155,17 @@ class CryptoOperation(metaclass=abc.ABCMeta):
parser = optparse.OptionParser(usage=self.usage, description=self.description)
- parser.add_option('-i', '--input', type='string', help=self.input_help)
+ parser.add_option("-i", "--input", type="string", help=self.input_help)
if self.has_output:
- parser.add_option('-o', '--output', type='string', help=self.output_help)
+ parser.add_option("-o", "--output", type="string", help=self.output_help)
- parser.add_option('--keyform',
- help='Key format of the %s key - default PEM' % self.keyname,
- choices=('PEM', 'DER'), default='PEM')
+ parser.add_option(
+ "--keyform",
+ help="Key format of the %s key - default PEM" % self.keyname,
+ choices=("PEM", "DER"),
+ default="PEM",
+ )
(cli, cli_args) = parser.parse_args(sys.argv[1:])
@@ -161,8 +178,8 @@ class CryptoOperation(metaclass=abc.ABCMeta):
def read_key(self, filename: str, keyform: str) -> rsa.key.AbstractKey:
"""Reads a public or private key."""
- print('Reading %s key from %s' % (self.keyname, filename), file=sys.stderr)
- with open(filename, 'rb') as keyfile:
+ print("Reading %s key from %s" % (self.keyname, filename), file=sys.stderr)
+ with open(filename, "rb") as keyfile:
keydata = keyfile.read()
return self.key_class.load_pkcs1(keydata, keyform)
@@ -171,37 +188,39 @@ class CryptoOperation(metaclass=abc.ABCMeta):
"""Read the input file"""
if inname:
- print('Reading input from %s' % inname, file=sys.stderr)
- with open(inname, 'rb') as infile:
+ print("Reading input from %s" % inname, file=sys.stderr)
+ with open(inname, "rb") as infile:
return infile.read()
- print('Reading input from stdin', file=sys.stderr)
+ print("Reading input from stdin", file=sys.stderr)
return sys.stdin.buffer.read()
def write_outfile(self, outdata: bytes, outname: str) -> None:
"""Write the output file"""
if outname:
- print('Writing output to %s' % outname, file=sys.stderr)
- with open(outname, 'wb') as outfile:
+ print("Writing output to %s" % outname, file=sys.stderr)
+ with open(outname, "wb") as outfile:
outfile.write(outdata)
else:
- print('Writing output to stdout', file=sys.stderr)
+ print("Writing output to stdout", file=sys.stderr)
sys.stdout.buffer.write(outdata)
class EncryptOperation(CryptoOperation):
"""Encrypts a file."""
- keyname = 'public'
- description = ('Encrypts a file. The file must be shorter than the key '
- 'length in order to be encrypted.')
- operation = 'encrypt'
- operation_past = 'encrypted'
- operation_progressive = 'encrypting'
-
- def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
- cli_args: Indexable = ()) -> bytes:
+ keyname = "public"
+ description = (
+ "Encrypts a file. The file must be shorter than the key " "length in order to be encrypted."
+ )
+ operation = "encrypt"
+ operation_past = "encrypted"
+ operation_progressive = "encrypting"
+
+ def perform_operation(
+ self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable = ()
+ ) -> bytes:
"""Encrypts files."""
assert isinstance(pub_key, rsa.key.PublicKey)
return rsa.encrypt(indata, pub_key)
@@ -210,16 +229,19 @@ class EncryptOperation(CryptoOperation):
class DecryptOperation(CryptoOperation):
"""Decrypts a file."""
- keyname = 'private'
- description = ('Decrypts a file. The original file must be shorter than '
- 'the key length in order to have been encrypted.')
- operation = 'decrypt'
- operation_past = 'decrypted'
- operation_progressive = 'decrypting'
+ keyname = "private"
+ description = (
+ "Decrypts a file. The original file must be shorter than "
+ "the key length in order to have been encrypted."
+ )
+ operation = "decrypt"
+ operation_past = "decrypted"
+ operation_progressive = "decrypting"
key_class = rsa.PrivateKey
- def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
- cli_args: Indexable = ()) -> bytes:
+ def perform_operation(
+ self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable = ()
+ ) -> bytes:
"""Decrypts files."""
assert isinstance(priv_key, rsa.key.PrivateKey)
return rsa.decrypt(indata, priv_key)
@@ -228,28 +250,32 @@ class DecryptOperation(CryptoOperation):
class SignOperation(CryptoOperation):
"""Signs a file."""
- keyname = 'private'
- usage = 'usage: %%prog [options] private_key hash_method'
- description = ('Signs a file, outputs the signature. Choose the hash '
- 'method from %s' % ', '.join(HASH_METHODS))
- operation = 'sign'
- operation_past = 'signature'
- operation_progressive = 'Signing'
+ keyname = "private"
+ usage = "usage: %%prog [options] private_key hash_method"
+ description = (
+ "Signs a file, outputs the signature. Choose the hash "
+ "method from %s" % ", ".join(HASH_METHODS)
+ )
+ operation = "sign"
+ operation_past = "signature"
+ operation_progressive = "Signing"
key_class = rsa.PrivateKey
expected_cli_args = 2
- output_help = ('Name of the file to write the signature to. Written '
- 'to stdout if this option is not present.')
+ output_help = (
+ "Name of the file to write the signature to. Written "
+ "to stdout if this option is not present."
+ )
- def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey,
- cli_args: Indexable) -> bytes:
+ def perform_operation(
+ self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable
+ ) -> bytes:
"""Signs files."""
assert isinstance(priv_key, rsa.key.PrivateKey)
hash_method = cli_args[1]
if hash_method not in HASH_METHODS:
- raise SystemExit('Invalid hash method, choose one of %s' %
- ', '.join(HASH_METHODS))
+ raise SystemExit("Invalid hash method, choose one of %s" % ", ".join(HASH_METHODS))
return rsa.sign(indata, priv_key, hash_method)
@@ -257,33 +283,36 @@ class SignOperation(CryptoOperation):
class VerifyOperation(CryptoOperation):
"""Verify a signature."""
- keyname = 'public'
- usage = 'usage: %%prog [options] public_key signature_file'
- description = ('Verifies a signature, exits with status 0 upon success, '
- 'prints an error message and exits with status 1 upon error.')
- operation = 'verify'
- operation_past = 'verified'
- operation_progressive = 'Verifying'
+ keyname = "public"
+ usage = "usage: %%prog [options] public_key signature_file"
+ description = (
+ "Verifies a signature, exits with status 0 upon success, "
+ "prints an error message and exits with status 1 upon error."
+ )
+ operation = "verify"
+ operation_past = "verified"
+ operation_progressive = "Verifying"
key_class = rsa.PublicKey
expected_cli_args = 2
has_output = False
- def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey,
- cli_args: Indexable) -> None:
+ def perform_operation(
+ self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable
+ ) -> None:
"""Verifies files."""
assert isinstance(pub_key, rsa.key.PublicKey)
signature_file = cli_args[1]
- with open(signature_file, 'rb') as sigfile:
+ with open(signature_file, "rb") as sigfile:
signature = sigfile.read()
try:
rsa.verify(indata, signature, pub_key)
except rsa.VerificationError as ex:
- raise SystemExit('Verification failed.') from ex
+ raise SystemExit("Verification failed.") from ex
- print('Verification OK', file=sys.stderr)
+ print("Verification OK", file=sys.stderr)
encrypt = EncryptOperation()
diff --git a/rsa/common.py b/rsa/common.py
index b5a966a..59d5e62 100644
--- a/rsa/common.py
+++ b/rsa/common.py
@@ -18,7 +18,7 @@ import typing
class NotRelativePrimeError(ValueError):
- def __init__(self, a: int, b: int, d: int, msg: str = '') -> None:
+ def __init__(self, a: int, b: int, d: int, msg: str = "") -> None:
super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d))
self.a = a
self.b = b
@@ -50,7 +50,7 @@ def bit_size(num: int) -> int:
try:
return num.bit_length()
except AttributeError as ex:
- raise TypeError('bit_size(num) only supports integers, not %r' % type(num)) from ex
+ raise TypeError("bit_size(num) only supports integers, not %r" % type(num)) from ex
def byte_size(number: int) -> int:
@@ -103,8 +103,7 @@ def ceil_div(num: int, div: int) -> int:
def extended_gcd(a: int, b: int) -> typing.Tuple[int, int, int]:
- """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
- """
+ """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb"""
# r = gcd(a,b) i = multiplicitive inverse of a mod b
# or j = multiplicitive inverse of b mod a
# Neg return values for i or j are made positive mod b or a respectively
@@ -179,7 +178,7 @@ def crt(a_values: typing.Iterable[int], modulo_values: typing.Iterable[int]) ->
return x
-if __name__ == '__main__':
+if __name__ == "__main__":
import doctest
doctest.testmod()
diff --git a/rsa/core.py b/rsa/core.py
index 23032e3..84ed3f8 100644
--- a/rsa/core.py
+++ b/rsa/core.py
@@ -23,18 +23,18 @@ def assert_int(var: int, name: str) -> None:
if isinstance(var, int):
return
- raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
+ raise TypeError("%s should be an integer, not %s" % (name, var.__class__))
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')
+ assert_int(message, "message")
+ assert_int(ekey, "ekey")
+ assert_int(n, "n")
if message < 0:
- raise ValueError('Only non-negative numbers are supported')
+ raise ValueError("Only non-negative numbers are supported")
if message > n:
raise OverflowError("The message %i is too long for n=%i" % (message, n))
@@ -45,9 +45,9 @@ def encrypt_int(message: int, ekey: int, n: int) -> int:
def decrypt_int(cyphertext: int, dkey: int, n: int) -> int:
"""Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
- assert_int(cyphertext, 'cyphertext')
- assert_int(dkey, 'dkey')
- assert_int(n, 'n')
+ assert_int(cyphertext, "cyphertext")
+ assert_int(dkey, "dkey")
+ assert_int(n, "n")
message = pow(cyphertext, dkey, n)
return message
diff --git a/rsa/key.py b/rsa/key.py
index 620ab5a..63f3f70 100644
--- a/rsa/key.py
+++ b/rsa/key.py
@@ -50,7 +50,7 @@ DEFAULT_EXPONENT = 65537
class AbstractKey:
"""Abstract superclass for private and public keys."""
- __slots__ = ('n', 'e', 'blindfac', 'blindfac_inverse', 'mutex')
+ __slots__ = ("n", "e", "blindfac", "blindfac_inverse", "mutex")
def __init__(self, n: int, e: int) -> None:
self.n = n
@@ -64,7 +64,7 @@ class AbstractKey:
self.mutex = threading.Lock()
@classmethod
- def _load_pkcs1_pem(cls, keyfile: bytes) -> 'AbstractKey':
+ def _load_pkcs1_pem(cls, keyfile: bytes) -> "AbstractKey":
"""Loads a key in PKCS#1 PEM format, implement in a subclass.
:param keyfile: contents of a PEM-encoded file that contains
@@ -76,7 +76,7 @@ class AbstractKey:
"""
@classmethod
- def _load_pkcs1_der(cls, keyfile: bytes) -> 'AbstractKey':
+ def _load_pkcs1_der(cls, keyfile: bytes) -> "AbstractKey":
"""Loads a key in PKCS#1 PEM format, implement in a subclass.
:param keyfile: contents of a DER-encoded file that contains
@@ -102,7 +102,7 @@ class AbstractKey:
"""
@classmethod
- def load_pkcs1(cls, keyfile: bytes, format: str = 'PEM') -> 'AbstractKey':
+ def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> "AbstractKey":
"""Loads a key in PKCS#1 DER or PEM format.
:param keyfile: contents of a DER- or PEM-encoded file that contains
@@ -116,27 +116,28 @@ class AbstractKey:
"""
methods = {
- 'PEM': cls._load_pkcs1_pem,
- 'DER': cls._load_pkcs1_der,
+ "PEM": cls._load_pkcs1_pem,
+ "DER": cls._load_pkcs1_der,
}
method = cls._assert_format_exists(format, methods)
return method(keyfile)
@staticmethod
- def _assert_format_exists(file_format: str, methods: typing.Mapping[str, typing.Callable]) \
- -> typing.Callable:
- """Checks whether the given file format exists in 'methods'.
- """
+ def _assert_format_exists(
+ file_format: str, methods: typing.Mapping[str, typing.Callable]
+ ) -> typing.Callable:
+ """Checks whether the given file format exists in 'methods'."""
try:
return methods[file_format]
except KeyError as ex:
- formats = ', '.join(sorted(methods.keys()))
- raise ValueError('Unsupported format: %r, try one of %s' % (file_format,
- formats)) from ex
+ formats = ", ".join(sorted(methods.keys()))
+ raise ValueError(
+ "Unsupported format: %r, try one of %s" % (file_format, formats)
+ ) from ex
- def save_pkcs1(self, format: str = 'PEM') -> bytes:
+ def save_pkcs1(self, format: str = "PEM") -> bytes:
"""Saves the key in PKCS#1 DER or PEM format.
:param format: the format to save; 'PEM' or 'DER'
@@ -146,8 +147,8 @@ class AbstractKey:
"""
methods = {
- 'PEM': self._save_pkcs1_pem,
- 'DER': self._save_pkcs1_der,
+ "PEM": self._save_pkcs1_pem,
+ "DER": self._save_pkcs1_der,
}
method = self._assert_format_exists(format, methods)
@@ -186,7 +187,7 @@ class AbstractKey:
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')
+ raise RuntimeError("unable to find blinding factor")
def _update_blinding_factor(self) -> typing.Tuple[int, int]:
"""Update blinding factors.
@@ -212,6 +213,7 @@ class AbstractKey:
return self.blindfac, self.blindfac_inverse
+
class PublicKey(AbstractKey):
"""Represents a public RSA key.
@@ -236,13 +238,13 @@ class PublicKey(AbstractKey):
"""
- __slots__ = ('n', 'e')
+ __slots__ = ("n", "e")
def __getitem__(self, key: str) -> int:
return getattr(self, key)
def __repr__(self) -> str:
- return 'PublicKey(%i, %i)' % (self.n, self.e)
+ return "PublicKey(%i, %i)" % (self.n, self.e)
def __getstate__(self) -> typing.Tuple[int, int]:
"""Returns the key as tuple for pickling."""
@@ -269,7 +271,7 @@ class PublicKey(AbstractKey):
return hash((self.n, self.e))
@classmethod
- def _load_pkcs1_der(cls, keyfile: bytes) -> 'PublicKey':
+ def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey":
"""Loads a key in PKCS#1 DER format.
:param keyfile: contents of a DER-encoded file that contains the public
@@ -293,7 +295,7 @@ class PublicKey(AbstractKey):
from rsa.asn1 import AsnPubKey
(priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey())
- return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))
+ return cls(n=int(priv["modulus"]), e=int(priv["publicExponent"]))
def _save_pkcs1_der(self) -> bytes:
"""Saves the public key in PKCS#1 DER format.
@@ -307,13 +309,13 @@ class PublicKey(AbstractKey):
# Create the ASN object
asn_key = AsnPubKey()
- asn_key.setComponentByName('modulus', self.n)
- asn_key.setComponentByName('publicExponent', self.e)
+ asn_key.setComponentByName("modulus", self.n)
+ asn_key.setComponentByName("publicExponent", self.e)
return encoder.encode(asn_key)
@classmethod
- def _load_pkcs1_pem(cls, keyfile: bytes) -> 'PublicKey':
+ def _load_pkcs1_pem(cls, keyfile: bytes) -> "PublicKey":
"""Loads a PKCS#1 PEM-encoded public key file.
The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and
@@ -324,7 +326,7 @@ class PublicKey(AbstractKey):
:return: a PublicKey object
"""
- der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY')
+ der = rsa.pem.load_pem(keyfile, "RSA PUBLIC KEY")
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self) -> bytes:
@@ -335,10 +337,10 @@ class PublicKey(AbstractKey):
"""
der = self._save_pkcs1_der()
- return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
+ return rsa.pem.save_pem(der, "RSA PUBLIC KEY")
@classmethod
- def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> 'PublicKey':
+ def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> "PublicKey":
"""Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.
These files can be recognised in that they start with BEGIN PUBLIC KEY
@@ -353,11 +355,11 @@ class PublicKey(AbstractKey):
:return: a PublicKey object
"""
- der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
+ der = rsa.pem.load_pem(keyfile, "PUBLIC KEY")
return cls.load_pkcs1_openssl_der(der)
@classmethod
- def load_pkcs1_openssl_der(cls, keyfile: bytes) -> 'PublicKey':
+ def load_pkcs1_openssl_der(cls, keyfile: bytes) -> "PublicKey":
"""Loads a PKCS#1 DER-encoded public key file from OpenSSL.
:param keyfile: contents of a DER-encoded file that contains the public
@@ -371,10 +373,10 @@ class PublicKey(AbstractKey):
(keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey())
- if keyinfo['header']['oid'] != univ.ObjectIdentifier('1.2.840.113549.1.1.1'):
+ if keyinfo["header"]["oid"] != univ.ObjectIdentifier("1.2.840.113549.1.1.1"):
raise TypeError("This is not a DER-encoded OpenSSL-compatible public key")
- return cls._load_pkcs1_der(keyinfo['key'][1:])
+ return cls._load_pkcs1_der(keyinfo["key"][1:])
class PrivateKey(AbstractKey):
@@ -401,7 +403,7 @@ class PrivateKey(AbstractKey):
"""
- __slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')
+ __slots__ = ("n", "e", "d", "p", "q", "exp1", "exp2", "coef")
def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None:
AbstractKey.__init__(self, n, e)
@@ -418,7 +420,13 @@ class PrivateKey(AbstractKey):
return getattr(self, key)
def __repr__(self) -> str:
- return 'PrivateKey(%i, %i, %i, %i, %i)' % (self.n, self.e, self.d, self.p, self.q)
+ return "PrivateKey(%i, %i, %i, %i, %i)" % (
+ self.n,
+ self.e,
+ self.d,
+ self.p,
+ self.q,
+ )
def __getstate__(self) -> typing.Tuple[int, int, int, int, int, int, int, int]:
"""Returns the key as tuple for pickling."""
@@ -436,14 +444,16 @@ class PrivateKey(AbstractKey):
if not isinstance(other, PrivateKey):
return False
- return (self.n == other.n and
- self.e == other.e and
- self.d == other.d and
- self.p == other.p and
- self.q == other.q and
- self.exp1 == other.exp1 and
- self.exp2 == other.exp2 and
- self.coef == other.coef)
+ return (
+ self.n == other.n
+ and self.e == other.e
+ and self.d == other.d
+ and self.p == other.p
+ and self.q == other.q
+ and self.exp1 == other.exp1
+ and self.exp2 == other.exp2
+ and self.coef == other.coef
+ )
def __ne__(self, other: typing.Any) -> bool:
return not (self == other)
@@ -481,7 +491,7 @@ class PrivateKey(AbstractKey):
return self.unblind(encrypted, blindfac_inverse)
@classmethod
- def _load_pkcs1_der(cls, keyfile: bytes) -> 'PrivateKey':
+ def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey":
"""Loads a key in PKCS#1 DER format.
:param keyfile: contents of a DER-encoded file that contains the private
@@ -503,6 +513,7 @@ class PrivateKey(AbstractKey):
"""
from pyasn1.codec.der import decoder
+
(priv, _) = decoder.decode(keyfile)
# ASN.1 contents of DER encoded private key:
@@ -521,7 +532,7 @@ class PrivateKey(AbstractKey):
# }
if priv[0] != 0:
- raise ValueError('Unable to read this file, version %s != 0' % priv[0])
+ raise ValueError("Unable to read this file, version %s != 0" % priv[0])
as_ints = map(int, priv[1:6])
key = cls(*as_ints)
@@ -530,9 +541,9 @@ class PrivateKey(AbstractKey):
if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef):
warnings.warn(
- 'You have provided a malformed keyfile. Either the exponents '
- 'or the coefficient are incorrect. Using the correct values '
- 'instead.',
+ "You have provided a malformed keyfile. Either the exponents "
+ "or the coefficient are incorrect. Using the correct values "
+ "instead.",
UserWarning,
)
@@ -550,33 +561,33 @@ class PrivateKey(AbstractKey):
class AsnPrivKey(univ.Sequence):
componentType = namedtype.NamedTypes(
- namedtype.NamedType('version', univ.Integer()),
- namedtype.NamedType('modulus', univ.Integer()),
- namedtype.NamedType('publicExponent', univ.Integer()),
- namedtype.NamedType('privateExponent', univ.Integer()),
- namedtype.NamedType('prime1', univ.Integer()),
- namedtype.NamedType('prime2', univ.Integer()),
- namedtype.NamedType('exponent1', univ.Integer()),
- namedtype.NamedType('exponent2', univ.Integer()),
- namedtype.NamedType('coefficient', univ.Integer()),
+ namedtype.NamedType("version", univ.Integer()),
+ namedtype.NamedType("modulus", univ.Integer()),
+ namedtype.NamedType("publicExponent", univ.Integer()),
+ namedtype.NamedType("privateExponent", univ.Integer()),
+ namedtype.NamedType("prime1", univ.Integer()),
+ namedtype.NamedType("prime2", univ.Integer()),
+ namedtype.NamedType("exponent1", univ.Integer()),
+ namedtype.NamedType("exponent2", univ.Integer()),
+ namedtype.NamedType("coefficient", univ.Integer()),
)
# Create the ASN object
asn_key = AsnPrivKey()
- asn_key.setComponentByName('version', 0)
- asn_key.setComponentByName('modulus', self.n)
- asn_key.setComponentByName('publicExponent', self.e)
- asn_key.setComponentByName('privateExponent', self.d)
- asn_key.setComponentByName('prime1', self.p)
- asn_key.setComponentByName('prime2', self.q)
- asn_key.setComponentByName('exponent1', self.exp1)
- asn_key.setComponentByName('exponent2', self.exp2)
- asn_key.setComponentByName('coefficient', self.coef)
+ asn_key.setComponentByName("version", 0)
+ asn_key.setComponentByName("modulus", self.n)
+ asn_key.setComponentByName("publicExponent", self.e)
+ asn_key.setComponentByName("privateExponent", self.d)
+ asn_key.setComponentByName("prime1", self.p)
+ asn_key.setComponentByName("prime2", self.q)
+ asn_key.setComponentByName("exponent1", self.exp1)
+ asn_key.setComponentByName("exponent2", self.exp2)
+ asn_key.setComponentByName("coefficient", self.coef)
return encoder.encode(asn_key)
@classmethod
- def _load_pkcs1_pem(cls, keyfile: bytes) -> 'PrivateKey':
+ def _load_pkcs1_pem(cls, keyfile: bytes) -> "PrivateKey":
"""Loads a PKCS#1 PEM-encoded private key file.
The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and
@@ -588,7 +599,7 @@ class PrivateKey(AbstractKey):
:return: a PrivateKey object
"""
- der = rsa.pem.load_pem(keyfile, b'RSA PRIVATE KEY')
+ der = rsa.pem.load_pem(keyfile, b"RSA PRIVATE KEY")
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self) -> bytes:
@@ -599,12 +610,14 @@ class PrivateKey(AbstractKey):
"""
der = self._save_pkcs1_der()
- return rsa.pem.save_pem(der, b'RSA PRIVATE KEY')
+ return rsa.pem.save_pem(der, b"RSA PRIVATE KEY")
-def find_p_q(nbits: int,
- getprime_func: typing.Callable[[int], int] = rsa.prime.getprime,
- accurate: bool = True) -> typing.Tuple[int, int]:
+def find_p_q(
+ nbits: int,
+ getprime_func: typing.Callable[[int], int] = rsa.prime.getprime,
+ accurate: bool = True,
+) -> typing.Tuple[int, int]:
"""Returns a tuple of two different primes of nbits bits each.
The resulting p * q has exacty 2 * nbits bits, and the returned p and q
@@ -644,16 +657,16 @@ def find_p_q(nbits: int,
qbits = nbits - shift
# Choose the two initial primes
- log.debug('find_p_q(%i): Finding p', nbits)
+ log.debug("find_p_q(%i): Finding p", nbits)
p = getprime_func(pbits)
- log.debug('find_p_q(%i): Finding q', nbits)
+ log.debug("find_p_q(%i): Finding q", nbits)
q = getprime_func(qbits)
def is_acceptable(p: int, q: int) -> bool:
"""Returns True iff p and q are acceptable:
- - p and q differ
- - (p * q) has the right nr of bits (when accurate=True)
+ - p and q differ
+ - (p * q) has the right nr of bits (when accurate=True)
"""
if p == q:
@@ -701,13 +714,17 @@ def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tupl
d = rsa.common.inverse(exponent, phi_n)
except rsa.common.NotRelativePrimeError as ex:
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)) from ex
+ exponent,
+ phi_n,
+ ex.d,
+ msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)"
+ % (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 "
- "phi_n (%d)" % (exponent, d, phi_n))
+ raise ValueError(
+ "e (%d) and d (%d) are not mult. inv. modulo " "phi_n (%d)" % (exponent, d, phi_n)
+ )
return exponent, d
@@ -725,10 +742,12 @@ def calculate_keys(p: int, q: int) -> typing.Tuple[int, int]:
return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT)
-def gen_keys(nbits: int,
- getprime_func: typing.Callable[[int], int],
- accurate: bool = True,
- exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[int, int, int, int]:
+def gen_keys(
+ nbits: int,
+ getprime_func: typing.Callable[[int], int],
+ accurate: bool = True,
+ exponent: int = DEFAULT_EXPONENT,
+) -> typing.Tuple[int, int, int, int]:
"""Generate RSA keys of nbits bits. Returns (p, q, e, d).
Note: this can take a long time, depending on the key size.
@@ -756,10 +775,12 @@ def gen_keys(nbits: int,
return p, q, e, d
-def newkeys(nbits: int,
- accurate: bool = True,
- poolsize: int = 1,
- exponent: int = DEFAULT_EXPONENT) -> typing.Tuple[PublicKey, PrivateKey]:
+def newkeys(
+ nbits: int,
+ accurate: bool = True,
+ poolsize: int = 1,
+ exponent: int = DEFAULT_EXPONENT,
+) -> typing.Tuple[PublicKey, PrivateKey]:
"""Generates public and private keys, and returns them as (pub, priv).
The public key is also known as the 'encryption key', and is a
@@ -786,10 +807,10 @@ def newkeys(nbits: int,
"""
if nbits < 16:
- raise ValueError('Key too small')
+ raise ValueError("Key too small")
if poolsize < 1:
- raise ValueError('Pool size (%i) should be >= 1' % poolsize)
+ raise ValueError("Pool size (%i) should be >= 1" % poolsize)
# Determine which getprime function to use
if poolsize > 1:
@@ -797,6 +818,7 @@ def newkeys(nbits: int,
def getprime_func(nbits: int) -> int:
return parallel.getprime(nbits, poolsize=poolsize)
+
else:
getprime_func = rsa.prime.getprime
@@ -806,15 +828,12 @@ def newkeys(nbits: int,
# Create the key objects
n = p * q
- return (
- PublicKey(n, e),
- PrivateKey(n, e, d, p, q)
- )
+ return (PublicKey(n, e), PrivateKey(n, e, d, p, q))
-__all__ = ['PublicKey', 'PrivateKey', 'newkeys']
+__all__ = ["PublicKey", "PrivateKey", "newkeys"]
-if __name__ == '__main__':
+if __name__ == "__main__":
import doctest
try:
@@ -824,8 +843,8 @@ if __name__ == '__main__':
break
if (count % 10 == 0 and count) or count == 1:
- print('%i times' % count)
+ print("%i times" % count)
except KeyboardInterrupt:
- print('Aborted')
+ print("Aborted")
else:
- print('Doctests done')
+ print("Doctests done")
diff --git a/rsa/parallel.py b/rsa/parallel.py
index f9afedb..5020edb 100644
--- a/rsa/parallel.py
+++ b/rsa/parallel.py
@@ -62,8 +62,7 @@ def getprime(nbits: int, poolsize: int) -> int:
# Create processes
try:
- procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send))
- for _ in range(poolsize)]
+ procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send)) for _ in range(poolsize)]
# Start processes
for p in procs:
p.start()
@@ -80,10 +79,10 @@ def getprime(nbits: int, poolsize: int) -> int:
return result
-__all__ = ['getprime']
+__all__ = ["getprime"]
-if __name__ == '__main__':
- print('Running doctests 1000x or until failure')
+if __name__ == "__main__":
+ print("Running doctests 1000x or until failure")
import doctest
for count in range(100):
@@ -92,6 +91,6 @@ if __name__ == '__main__':
break
if count % 10 == 0 and count:
- print('%i times' % count)
+ print("%i times" % count)
- print('Doctests done')
+ print("Doctests done")
diff --git a/rsa/pem.py b/rsa/pem.py
index 1ffb446..5d26e6e 100644
--- a/rsa/pem.py
+++ b/rsa/pem.py
@@ -27,10 +27,12 @@ def _markers(pem_marker: FlexiText) -> typing.Tuple[bytes, bytes]:
"""
if not isinstance(pem_marker, bytes):
- pem_marker = pem_marker.encode('ascii')
+ pem_marker = pem_marker.encode("ascii")
- return (b'-----BEGIN ' + pem_marker + b'-----',
- b'-----END ' + pem_marker + b'-----')
+ return (
+ b"-----BEGIN " + pem_marker + b"-----",
+ b"-----END " + pem_marker + b"-----",
+ )
def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iterator[bytes]:
@@ -65,7 +67,7 @@ def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iter
break
# Load fields
- if b':' in line:
+ if b":" in line:
continue
yield line
@@ -95,13 +97,13 @@ def load_pem(contents: FlexiText, pem_marker: FlexiText) -> bytes:
# We want bytes, not text. If it's text, it can be converted to ASCII bytes.
if not isinstance(contents, bytes):
- contents = contents.encode('ascii')
+ contents = contents.encode("ascii")
(pem_start, pem_end) = _markers(pem_marker)
pem_lines = [line for line in _pem_lines(contents, pem_start, pem_end)]
# Base64-decode the contents
- pem = b''.join(pem_lines)
+ pem = b"".join(pem_lines)
return base64.standard_b64decode(pem)
@@ -119,14 +121,14 @@ def save_pem(contents: bytes, pem_marker: FlexiText) -> bytes:
(pem_start, pem_end) = _markers(pem_marker)
- b64 = base64.standard_b64encode(contents).replace(b'\n', b'')
+ b64 = base64.standard_b64encode(contents).replace(b"\n", b"")
pem_lines = [pem_start]
for block_start in range(0, len(b64), 64):
- block = b64[block_start:block_start + 64]
+ block = b64[block_start : block_start + 64]
pem_lines.append(block)
pem_lines.append(pem_end)
- pem_lines.append(b'')
+ pem_lines.append(b"")
- return b'\n'.join(pem_lines)
+ return b"\n".join(pem_lines)
diff --git a/rsa/pkcs1.py b/rsa/pkcs1.py
index 9adad90..5992c7f 100644
--- a/rsa/pkcs1.py
+++ b/rsa/pkcs1.py
@@ -41,37 +41,41 @@ else:
# ASN.1 codes that describe the hash algorithm used.
HASH_ASN1 = {
- 'MD5': b'\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10',
- 'SHA-1': b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14',
- 'SHA-224': b'\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c',
- 'SHA-256': b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20',
- 'SHA-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30',
- 'SHA-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40',
+ "MD5": b"\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10",
+ "SHA-1": b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14",
+ "SHA-224": b"\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c",
+ "SHA-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20",
+ "SHA-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30",
+ "SHA-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40",
}
HASH_METHODS: typing.Dict[str, typing.Callable[[], HashType]] = {
- 'MD5': hashlib.md5,
- 'SHA-1': hashlib.sha1,
- 'SHA-224': hashlib.sha224,
- 'SHA-256': hashlib.sha256,
- 'SHA-384': hashlib.sha384,
- 'SHA-512': hashlib.sha512,
+ "MD5": hashlib.md5,
+ "SHA-1": hashlib.sha1,
+ "SHA-224": hashlib.sha224,
+ "SHA-256": hashlib.sha256,
+ "SHA-384": hashlib.sha384,
+ "SHA-512": hashlib.sha512,
}
if sys.version_info >= (3, 6):
# Python 3.6 introduced SHA3 support.
- HASH_ASN1.update({
- 'SHA3-256': b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x08\x05\x00\x04\x20',
- 'SHA3-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x09\x05\x00\x04\x30',
- 'SHA3-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x0a\x05\x00\x04\x40',
- })
-
- HASH_METHODS.update({
- 'SHA3-256': hashlib.sha3_256,
- 'SHA3-384': hashlib.sha3_384,
- 'SHA3-512': hashlib.sha3_512,
- })
+ HASH_ASN1.update(
+ {
+ "SHA3-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x08\x05\x00\x04\x20",
+ "SHA3-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x09\x05\x00\x04\x30",
+ "SHA3-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x0a\x05\x00\x04\x40",
+ }
+ )
+
+ HASH_METHODS.update(
+ {
+ "SHA3-256": hashlib.sha3_256,
+ "SHA3-384": hashlib.sha3_384,
+ "SHA3-512": hashlib.sha3_512,
+ }
+ )
class CryptoError(Exception):
@@ -105,11 +109,13 @@ def _pad_for_encryption(message: bytes, target_length: int) -> bytes:
msglength = len(message)
if msglength > max_msglength:
- raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
+ raise OverflowError(
+ "%i bytes needed for message, but there is only"
+ " space for %i" % (msglength, max_msglength)
+ )
# Get random padding
- padding = b''
+ padding = b""
padding_length = target_length - msglength - 3
# We remove 0-bytes, so we'll end up with less padding than we've asked for,
@@ -121,15 +127,12 @@ def _pad_for_encryption(message: bytes, target_length: int) -> bytes:
# after removing the 0-bytes. This increases the chance of getting
# enough bytes, especially when needed_bytes is small
new_padding = os.urandom(needed_bytes + 5)
- new_padding = new_padding.replace(b'\x00', b'')
+ new_padding = new_padding.replace(b"\x00", b"")
padding = padding + new_padding[:needed_bytes]
assert len(padding) == padding_length
- return b''.join([b'\x00\x02',
- padding,
- b'\x00',
- message])
+ return b"".join([b"\x00\x02", padding, b"\x00", message])
def _pad_for_signing(message: bytes, target_length: int) -> bytes:
@@ -155,15 +158,14 @@ def _pad_for_signing(message: bytes, target_length: int) -> bytes:
msglength = len(message)
if msglength > max_msglength:
- raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
+ raise OverflowError(
+ "%i bytes needed for message, but there is only"
+ " space for %i" % (msglength, max_msglength)
+ )
padding_length = target_length - msglength - 3
- return b''.join([b'\x00\x01',
- padding_length * b'\xff',
- b'\x00',
- message])
+ return b"".join([b"\x00\x01", padding_length * b"\xff", b"\x00", message])
def encrypt(message: bytes, pub_key: key.PublicKey) -> bytes:
@@ -259,13 +261,13 @@ def decrypt(crypto: bytes, priv_key: key.PrivateKey) -> bytes:
# integer). This fixes CVE-2020-13757.
if len(crypto) > blocksize:
# This is operating on public information, so doesn't need to be constant-time.
- raise DecryptionError('Decryption failed')
+ raise DecryptionError("Decryption failed")
# If we can't find the cleartext marker, decryption failed.
- cleartext_marker_bad = not compare_digest(cleartext[:2], b'\x00\x02')
+ cleartext_marker_bad = not compare_digest(cleartext[:2], b"\x00\x02")
# Find the 00 separator between the padding and the message
- sep_idx = cleartext.find(b'\x00', 2)
+ sep_idx = cleartext.find(b"\x00", 2)
# sep_idx indicates the position of the `\x00` separator that separates the
# padding from the actual message. The padding should be at least 8 bytes
@@ -276,9 +278,9 @@ def decrypt(crypto: bytes, priv_key: key.PrivateKey) -> bytes:
anything_bad = cleartext_marker_bad | sep_idx_bad
if anything_bad:
- raise DecryptionError('Decryption failed')
+ raise DecryptionError("Decryption failed")
- return cleartext[sep_idx + 1:]
+ return cleartext[sep_idx + 1 :]
def sign_hash(hash_value: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes:
@@ -299,7 +301,7 @@ def sign_hash(hash_value: bytes, priv_key: key.PrivateKey, hash_method: str) ->
# Get the ASN1 code for this hash method
if hash_method not in HASH_ASN1:
- raise ValueError('Invalid hash method: %s' % hash_method)
+ raise ValueError("Invalid hash method: %s" % hash_method)
asn1code = HASH_ASN1[hash_method]
# Encrypt the hash with the private key
@@ -365,11 +367,11 @@ def verify(message: bytes, signature: bytes, pub_key: key.PublicKey) -> str:
expected = _pad_for_signing(cleartext, keylength)
if len(signature) != keylength:
- raise VerificationError('Verification failed')
+ raise VerificationError("Verification failed")
# Compare with the signed one
if expected != clearsig:
- raise VerificationError('Verification failed')
+ raise VerificationError("Verification failed")
return method_name
@@ -426,7 +428,7 @@ def compute_hash(message: typing.Union[bytes, typing.BinaryIO], method_name: str
"""
if method_name not in HASH_METHODS:
- raise ValueError('Invalid hash method: %s' % method_name)
+ raise ValueError("Invalid hash method: %s" % method_name)
method = HASH_METHODS[method_name]
hasher = method()
@@ -434,7 +436,7 @@ def compute_hash(message: typing.Union[bytes, typing.BinaryIO], method_name: str
if isinstance(message, bytes):
hasher.update(message)
else:
- assert hasattr(message, 'read') and hasattr(message.read, '__call__')
+ assert hasattr(message, "read") and hasattr(message.read, "__call__")
# read as 1K blocks
for block in yield_fixedblocks(message, 1024):
hasher.update(block)
@@ -454,14 +456,21 @@ def _find_method_hash(clearsig: bytes) -> str:
if asn1code in clearsig:
return hashname
- raise VerificationError('Verification failed')
+ raise VerificationError("Verification failed")
-__all__ = ['encrypt', 'decrypt', 'sign', 'verify',
- 'DecryptionError', 'VerificationError', 'CryptoError']
+__all__ = [
+ "encrypt",
+ "decrypt",
+ "sign",
+ "verify",
+ "DecryptionError",
+ "VerificationError",
+ "CryptoError",
+]
-if __name__ == '__main__':
- print('Running doctests 1000x or until failure')
+if __name__ == "__main__":
+ print("Running doctests 1000x or until failure")
import doctest
for count in range(1000):
@@ -470,6 +479,6 @@ if __name__ == '__main__':
break
if count % 100 == 0 and count:
- print('%i times' % count)
+ print("%i times" % count)
- print('Doctests done')
+ print("Doctests done")
diff --git a/rsa/pkcs1_v2.py b/rsa/pkcs1_v2.py
index ed616f5..d68b907 100644
--- a/rsa/pkcs1_v2.py
+++ b/rsa/pkcs1_v2.py
@@ -25,7 +25,7 @@ from rsa import (
)
-def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:
+def mgf1(seed: bytes, length: int, hasher: str = "SHA-1") -> bytes:
"""
MGF1 is a Mask Generation Function based on a hash function.
@@ -51,13 +51,13 @@ def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:
hash_length = pkcs1.HASH_METHODS[hasher]().digest_size
except KeyError as ex:
raise ValueError(
- 'Invalid `hasher` specified. Please select one of: {hash_list}'.format(
- hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys()))
+ "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):
+ if length > (2 ** 32 * hash_length):
raise OverflowError(
"Desired length should be at most 2**32 times the hasher's output "
"length ({hash_length} for {hasher} function)".format(
@@ -69,7 +69,7 @@ def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:
# Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the
# hashes formed by (`seed` + C), being `C` an octet string of length 4
# generated by converting `counter` with the primitive I2OSP
- output = b''.join(
+ output = b"".join(
pkcs1.compute_hash(
seed + transform.int2bytes(counter, fill_size=4),
method_name=hasher,
@@ -82,11 +82,11 @@ def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes:
__all__ = [
- 'mgf1',
+ "mgf1",
]
-if __name__ == '__main__':
- print('Running doctests 1000x or until failure')
+if __name__ == "__main__":
+ print("Running doctests 1000x or until failure")
import doctest
for count in range(1000):
@@ -95,6 +95,6 @@ if __name__ == '__main__':
break
if count % 100 == 0 and count:
- print('%i times' % count)
+ print("%i times" % count)
- print('Doctests done')
+ print("Doctests done")
diff --git a/rsa/prime.py b/rsa/prime.py
index 853aca5..d8980d0 100644
--- a/rsa/prime.py
+++ b/rsa/prime.py
@@ -21,7 +21,7 @@ Roberto Tamassia, 2002.
import rsa.common
import rsa.randnum
-__all__ = ['getprime', 'are_relatively_prime']
+__all__ = ["getprime", "are_relatively_prime"]
def gcd(p: int, q: int) -> int:
@@ -183,8 +183,8 @@ def are_relatively_prime(a: int, b: int) -> bool:
return d == 1
-if __name__ == '__main__':
- print('Running doctests 1000x or until failure')
+if __name__ == "__main__":
+ print("Running doctests 1000x or until failure")
import doctest
for count in range(1000):
@@ -193,6 +193,6 @@ if __name__ == '__main__':
break
if count % 100 == 0 and count:
- print('%i times' % count)
+ print("%i times" % count)
- print('Doctests done')
+ print("Doctests done")
diff --git a/rsa/randnum.py b/rsa/randnum.py
index a5bb850..c65facd 100644
--- a/rsa/randnum.py
+++ b/rsa/randnum.py
@@ -37,15 +37,14 @@ def read_random_bits(nbits: int) -> bytes:
# Add the remaining random bits
if rbits > 0:
randomvalue = ord(os.urandom(1))
- randomvalue >>= (8 - rbits)
+ randomvalue >>= 8 - rbits
randomdata = struct.pack("B", randomvalue) + randomdata
return randomdata
def read_random_int(nbits: int) -> int:
- """Reads a random integer of approximately nbits bits.
- """
+ """Reads a random integer of approximately nbits bits."""
randomdata = read_random_bits(nbits)
value = transform.bytes2int(randomdata)
diff --git a/rsa/transform.py b/rsa/transform.py
index 03c4a77..c609b65 100644
--- a/rsa/transform.py
+++ b/rsa/transform.py
@@ -31,7 +31,7 @@ def bytes2int(raw_bytes: bytes) -> int:
8405007
"""
- return int.from_bytes(raw_bytes, 'big', signed=False)
+ return int.from_bytes(raw_bytes, "big", signed=False)
def int2bytes(number: int, fill_size: int = 0) -> bytes:
@@ -61,12 +61,12 @@ def int2bytes(number: int, fill_size: int = 0) -> bytes:
bytes_required = max(1, math.ceil(number.bit_length() / 8))
if fill_size > 0:
- return number.to_bytes(fill_size, 'big')
+ return number.to_bytes(fill_size, "big")
- return number.to_bytes(bytes_required, 'big')
+ return number.to_bytes(bytes_required, "big")
-if __name__ == '__main__':
+if __name__ == "__main__":
import doctest
doctest.testmod()
diff --git a/rsa/util.py b/rsa/util.py
index cb31c46..087caf8 100644
--- a/rsa/util.py
+++ b/rsa/util.py
@@ -24,36 +24,57 @@ def private_to_public() -> None:
"""Reads a private key and outputs the corresponding public key."""
# Parse the CLI options
- parser = OptionParser(usage='usage: %prog [options]',
- description='Reads a private key and outputs the '
- 'corresponding public key. Both private and public keys use '
- 'the format described in PKCS#1 v1.5')
+ parser = OptionParser(
+ usage="usage: %prog [options]",
+ description="Reads a private key and outputs the "
+ "corresponding public key. Both private and public keys use "
+ "the format described in PKCS#1 v1.5",
+ )
- parser.add_option('-i', '--input', dest='infilename', type='string',
- help='Input filename. Reads from stdin if not specified')
- parser.add_option('-o', '--output', dest='outfilename', type='string',
- help='Output filename. Writes to stdout of not specified')
+ parser.add_option(
+ "-i",
+ "--input",
+ dest="infilename",
+ type="string",
+ help="Input filename. Reads from stdin if not specified",
+ )
+ parser.add_option(
+ "-o",
+ "--output",
+ dest="outfilename",
+ type="string",
+ help="Output filename. Writes to stdout of not specified",
+ )
- parser.add_option('--inform', dest='inform',
- help='key format of input - default PEM',
- choices=('PEM', 'DER'), default='PEM')
+ parser.add_option(
+ "--inform",
+ dest="inform",
+ help="key format of input - default PEM",
+ choices=("PEM", "DER"),
+ default="PEM",
+ )
- parser.add_option('--outform', dest='outform',
- help='key format of output - default PEM',
- choices=('PEM', 'DER'), default='PEM')
+ parser.add_option(
+ "--outform",
+ dest="outform",
+ help="key format of output - default PEM",
+ choices=("PEM", "DER"),
+ default="PEM",
+ )
(cli, cli_args) = parser.parse_args(sys.argv)
# Read the input data
if cli.infilename:
- print('Reading private key from %s in %s format' %
- (cli.infilename, cli.inform), file=sys.stderr)
- with open(cli.infilename, 'rb') as infile:
+ print(
+ "Reading private key from %s in %s format" % (cli.infilename, cli.inform),
+ file=sys.stderr,
+ )
+ with open(cli.infilename, "rb") as infile:
in_data = infile.read()
else:
- print('Reading private key from stdin in %s format' % cli.inform,
- file=sys.stderr)
- in_data = sys.stdin.read().encode('ascii')
+ print("Reading private key from stdin in %s format" % cli.inform, file=sys.stderr)
+ in_data = sys.stdin.read().encode("ascii")
assert type(in_data) == bytes, type(in_data)
@@ -65,11 +86,12 @@ def private_to_public() -> None:
out_data = pub_key.save_pkcs1(cli.outform)
if cli.outfilename:
- print('Writing public key to %s in %s format' %
- (cli.outfilename, cli.outform), file=sys.stderr)
- with open(cli.outfilename, 'wb') as outfile:
+ print(
+ "Writing public key to %s in %s format" % (cli.outfilename, cli.outform),
+ file=sys.stderr,
+ )
+ with open(cli.outfilename, "wb") as outfile:
outfile.write(out_data)
else:
- print('Writing public key to stdout in %s format' % cli.outform,
- file=sys.stderr)
- sys.stdout.write(out_data.decode('ascii'))
+ print("Writing public key to stdout in %s format" % cli.outform, file=sys.stderr)
+ sys.stdout.write(out_data.decode("ascii"))
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 00f77ac..bb872ea 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -83,20 +83,20 @@ class AbstractCliTest(unittest.TestCase):
def setUpClass(cls):
# Ensure there is a key to use
cls.pub_key, cls.priv_key = rsa.newkeys(512)
- cls.pub_fname = '%s.pub' % cls.__name__
- cls.priv_fname = '%s.key' % cls.__name__
+ cls.pub_fname = "%s.pub" % cls.__name__
+ cls.priv_fname = "%s.key" % cls.__name__
- with open(cls.pub_fname, 'wb') as outfile:
+ with open(cls.pub_fname, "wb") as outfile:
outfile.write(cls.pub_key.save_pkcs1())
- with open(cls.priv_fname, 'wb') as outfile:
+ with open(cls.priv_fname, "wb") as outfile:
outfile.write(cls.priv_key.save_pkcs1())
@classmethod
def tearDownClass(cls):
- if hasattr(cls, 'pub_fname'):
+ if hasattr(cls, "pub_fname"):
remove_if_exists(cls.pub_fname)
- if hasattr(cls, 'priv_fname'):
+ if hasattr(cls, "priv_fname"):
remove_if_exists(cls.priv_fname)
def assertExits(self, status_code, func, *args, **kwargs):
@@ -105,10 +105,12 @@ class AbstractCliTest(unittest.TestCase):
except SystemExit as ex:
if status_code == ex.code:
return
- self.fail('SystemExit() raised by %r, but exited with code %r, expected %r' % (
- func, ex.code, status_code))
+ self.fail(
+ "SystemExit() raised by %r, but exited with code %r, expected %r"
+ % (func, ex.code, status_code)
+ )
else:
- self.fail('SystemExit() not raised by %r' % func)
+ self.fail("SystemExit() not raised by %r" % func)
class KeygenTest(AbstractCliTest):
@@ -122,61 +124,64 @@ class KeygenTest(AbstractCliTest):
rsa.cli.keygen()
lines = get_bytes_out(out).splitlines()
- self.assertEqual(b'-----BEGIN RSA PRIVATE KEY-----', lines[0])
- self.assertEqual(b'-----END RSA PRIVATE KEY-----', lines[-1])
+ self.assertEqual(b"-----BEGIN RSA PRIVATE KEY-----", lines[0])
+ self.assertEqual(b"-----END RSA PRIVATE KEY-----", lines[-1])
# The key size should be shown on stderr
- self.assertTrue('128-bit key' in err.getvalue())
+ self.assertTrue("128-bit key" in err.getvalue())
- @cleanup_files('test_cli_privkey_out.pem')
+ @cleanup_files("test_cli_privkey_out.pem")
def test_keygen_priv_out_pem(self):
with captured_output() as (out, err):
- with cli_args('--out=test_cli_privkey_out.pem', '--form=PEM', 128):
+ with cli_args("--out=test_cli_privkey_out.pem", "--form=PEM", 128):
rsa.cli.keygen()
# The key size should be shown on stderr
- self.assertTrue('128-bit key' in err.getvalue())
+ self.assertTrue("128-bit key" in err.getvalue())
# The output file should be shown on stderr
- self.assertTrue('test_cli_privkey_out.pem' in err.getvalue())
+ self.assertTrue("test_cli_privkey_out.pem" in err.getvalue())
# If we can load the file as PEM, it's good enough.
- with open('test_cli_privkey_out.pem', 'rb') as pemfile:
+ with open("test_cli_privkey_out.pem", "rb") as pemfile:
rsa.PrivateKey.load_pkcs1(pemfile.read())
- @cleanup_files('test_cli_privkey_out.der')
+ @cleanup_files("test_cli_privkey_out.der")
def test_keygen_priv_out_der(self):
with captured_output() as (out, err):
- with cli_args('--out=test_cli_privkey_out.der', '--form=DER', 128):
+ with cli_args("--out=test_cli_privkey_out.der", "--form=DER", 128):
rsa.cli.keygen()
# The key size should be shown on stderr
- self.assertTrue('128-bit key' in err.getvalue())
+ self.assertTrue("128-bit key" in err.getvalue())
# The output file should be shown on stderr
- self.assertTrue('test_cli_privkey_out.der' in err.getvalue())
+ self.assertTrue("test_cli_privkey_out.der" in err.getvalue())
# If we can load the file as der, it's good enough.
- with open('test_cli_privkey_out.der', 'rb') as derfile:
- rsa.PrivateKey.load_pkcs1(derfile.read(), format='DER')
+ with open("test_cli_privkey_out.der", "rb") as derfile:
+ rsa.PrivateKey.load_pkcs1(derfile.read(), format="DER")
- @cleanup_files('test_cli_privkey_out.pem', 'test_cli_pubkey_out.pem')
+ @cleanup_files("test_cli_privkey_out.pem", "test_cli_pubkey_out.pem")
def test_keygen_pub_out_pem(self):
with captured_output() as (out, err):
- with cli_args('--out=test_cli_privkey_out.pem',
- '--pubout=test_cli_pubkey_out.pem',
- '--form=PEM', 256):
+ with cli_args(
+ "--out=test_cli_privkey_out.pem",
+ "--pubout=test_cli_pubkey_out.pem",
+ "--form=PEM",
+ 256,
+ ):
rsa.cli.keygen()
# The key size should be shown on stderr
- self.assertTrue('256-bit key' in err.getvalue())
+ self.assertTrue("256-bit key" in err.getvalue())
# The output files should be shown on stderr
- self.assertTrue('test_cli_privkey_out.pem' in err.getvalue())
- self.assertTrue('test_cli_pubkey_out.pem' in err.getvalue())
+ self.assertTrue("test_cli_privkey_out.pem" in err.getvalue())
+ self.assertTrue("test_cli_pubkey_out.pem" in err.getvalue())
# If we can load the file as PEM, it's good enough.
- with open('test_cli_pubkey_out.pem', 'rb') as pemfile:
+ with open("test_cli_pubkey_out.pem", "rb") as pemfile:
rsa.PublicKey.load_pkcs1(pemfile.read())
@@ -189,38 +194,38 @@ class EncryptDecryptTest(AbstractCliTest):
with captured_output(), cli_args():
self.assertExits(1, rsa.cli.encrypt)
- @cleanup_files('encrypted.txt', 'cleartext.txt')
+ @cleanup_files("encrypted.txt", "cleartext.txt")
def test_encrypt_decrypt(self):
- with open('cleartext.txt', 'wb') as outfile:
- outfile.write(b'Hello cleartext RSA users!')
+ with open("cleartext.txt", "wb") as outfile:
+ outfile.write(b"Hello cleartext RSA users!")
- with cli_args('-i', 'cleartext.txt', '--out=encrypted.txt', self.pub_fname):
+ with cli_args("-i", "cleartext.txt", "--out=encrypted.txt", self.pub_fname):
with captured_output():
rsa.cli.encrypt()
- with cli_args('-i', 'encrypted.txt', self.priv_fname):
+ with cli_args("-i", "encrypted.txt", self.priv_fname):
with captured_output() as (out, err):
rsa.cli.decrypt()
# We should have the original cleartext on stdout now.
output = get_bytes_out(out)
- self.assertEqual(b'Hello cleartext RSA users!', output)
+ self.assertEqual(b"Hello cleartext RSA users!", output)
- @cleanup_files('encrypted.txt', 'cleartext.txt')
+ @cleanup_files("encrypted.txt", "cleartext.txt")
def test_encrypt_decrypt_unhappy(self):
- with open('cleartext.txt', 'wb') as outfile:
- outfile.write(b'Hello cleartext RSA users!')
+ with open("cleartext.txt", "wb") as outfile:
+ outfile.write(b"Hello cleartext RSA users!")
- with cli_args('-i', 'cleartext.txt', '--out=encrypted.txt', self.pub_fname):
+ with cli_args("-i", "cleartext.txt", "--out=encrypted.txt", self.pub_fname):
with captured_output():
rsa.cli.encrypt()
# Change a few bytes in the encrypted stream.
- with open('encrypted.txt', 'r+b') as encfile:
+ with open("encrypted.txt", "r+b") as encfile:
encfile.seek(40)
- encfile.write(b'hahaha')
+ encfile.write(b"hahaha")
- with cli_args('-i', 'encrypted.txt', self.priv_fname):
+ with cli_args("-i", "encrypted.txt", self.priv_fname):
with captured_output() as (out, err):
self.assertRaises(rsa.DecryptionError, rsa.cli.decrypt)
@@ -234,52 +239,52 @@ class SignVerifyTest(AbstractCliTest):
with captured_output(), cli_args():
self.assertExits(1, rsa.cli.sign)
- @cleanup_files('signature.txt', 'cleartext.txt')
+ @cleanup_files("signature.txt", "cleartext.txt")
def test_sign_verify(self):
- with open('cleartext.txt', 'wb') as outfile:
- outfile.write(b'Hello RSA users!')
+ with open("cleartext.txt", "wb") as outfile:
+ outfile.write(b"Hello RSA users!")
- with cli_args('-i', 'cleartext.txt', '--out=signature.txt', self.priv_fname, 'SHA-256'):
+ with cli_args("-i", "cleartext.txt", "--out=signature.txt", self.priv_fname, "SHA-256"):
with captured_output():
rsa.cli.sign()
- with cli_args('-i', 'cleartext.txt', self.pub_fname, 'signature.txt'):
+ with cli_args("-i", "cleartext.txt", self.pub_fname, "signature.txt"):
with captured_output() as (out, err):
rsa.cli.verify()
- self.assertFalse(b'Verification OK' in get_bytes_out(out))
+ self.assertFalse(b"Verification OK" in get_bytes_out(out))
- @cleanup_files('signature.txt', 'cleartext.txt')
+ @cleanup_files("signature.txt", "cleartext.txt")
def test_sign_verify_unhappy(self):
- with open('cleartext.txt', 'wb') as outfile:
- outfile.write(b'Hello RSA users!')
+ with open("cleartext.txt", "wb") as outfile:
+ outfile.write(b"Hello RSA users!")
- with cli_args('-i', 'cleartext.txt', '--out=signature.txt', self.priv_fname, 'SHA-256'):
+ with cli_args("-i", "cleartext.txt", "--out=signature.txt", self.priv_fname, "SHA-256"):
with captured_output():
rsa.cli.sign()
# Change a few bytes in the cleartext file.
- with open('cleartext.txt', 'r+b') as encfile:
+ with open("cleartext.txt", "r+b") as encfile:
encfile.seek(6)
- encfile.write(b'DSA')
+ encfile.write(b"DSA")
- with cli_args('-i', 'cleartext.txt', self.pub_fname, 'signature.txt'):
+ with cli_args("-i", "cleartext.txt", self.pub_fname, "signature.txt"):
with captured_output() as (out, err):
- self.assertExits('Verification failed.', rsa.cli.verify)
+ self.assertExits("Verification failed.", rsa.cli.verify)
class PrivatePublicTest(AbstractCliTest):
"""Test CLI command to convert a private to a public key."""
- @cleanup_files('test_private_to_public.pem')
+ @cleanup_files("test_private_to_public.pem")
def test_private_to_public(self):
- with cli_args('-i', self.priv_fname, '-o', 'test_private_to_public.pem'):
+ with cli_args("-i", self.priv_fname, "-o", "test_private_to_public.pem"):
with captured_output():
rsa.util.private_to_public()
# Check that the key is indeed valid.
- with open('test_private_to_public.pem', 'rb') as pemfile:
+ with open("test_private_to_public.pem", "rb") as pemfile:
key = rsa.PublicKey.load_pkcs1(pemfile.read())
self.assertEqual(self.priv_key.n, key.n)
diff --git a/tests/test_common.py b/tests/test_common.py
index 71b81d0..ac56bcd 100644
--- a/tests/test_common.py
+++ b/tests/test_common.py
@@ -21,8 +21,8 @@ from rsa.common import byte_size, bit_size, inverse
class TestByte(unittest.TestCase):
def test_values(self):
- self.assertEqual(byte(0), b'\x00')
- self.assertEqual(byte(255), b'\xff')
+ self.assertEqual(byte(0), b"\x00")
+ self.assertEqual(byte(255), b"\xff")
def test_struct_error_when_out_of_bounds(self):
self.assertRaises(struct.error, byte, 256)
@@ -36,13 +36,13 @@ class TestByteSize(unittest.TestCase):
self.assertEqual(byte_size(1 << 1024), 129)
self.assertEqual(byte_size(255), 1)
self.assertEqual(byte_size(256), 2)
- self.assertEqual(byte_size(0xffff), 2)
- self.assertEqual(byte_size(0xffffff), 3)
- self.assertEqual(byte_size(0xffffffff), 4)
- self.assertEqual(byte_size(0xffffffffff), 5)
- self.assertEqual(byte_size(0xffffffffffff), 6)
- self.assertEqual(byte_size(0xffffffffffffff), 7)
- self.assertEqual(byte_size(0xffffffffffffffff), 8)
+ self.assertEqual(byte_size(0xFFFF), 2)
+ self.assertEqual(byte_size(0xFFFFFF), 3)
+ self.assertEqual(byte_size(0xFFFFFFFF), 4)
+ self.assertEqual(byte_size(0xFFFFFFFFFF), 5)
+ self.assertEqual(byte_size(0xFFFFFFFFFFFF), 6)
+ self.assertEqual(byte_size(0xFFFFFFFFFFFFFF), 7)
+ self.assertEqual(byte_size(0xFFFFFFFFFFFFFFFF), 8)
def test_zero(self):
self.assertEqual(byte_size(0), 1)
diff --git a/tests/test_compat.py b/tests/test_compat.py
index e74f046..9c65315 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -32,41 +32,41 @@ class TestByte(unittest.TestCase):
self.assertRaises(struct.error, byte, -1)
def test_byte_literal(self):
- self.assertIsInstance(b'abc', bytes)
+ self.assertIsInstance(b"abc", bytes)
class TestBytes(unittest.TestCase):
"""Tests for bytes objects."""
def setUp(self):
- self.b1 = b'\xff\xff\xff\xff'
- self.b2 = b'\x00\x00\x00\x00'
- self.b3 = b'\xf0\xf0\xf0\xf0'
- self.b4 = b'\x4d\x23\xca\xe2'
- self.b5 = b'\x9b\x61\x3b\xdc'
- self.b6 = b'\xff\xff'
+ self.b1 = b"\xff\xff\xff\xff"
+ self.b2 = b"\x00\x00\x00\x00"
+ self.b3 = b"\xf0\xf0\xf0\xf0"
+ self.b4 = b"\x4d\x23\xca\xe2"
+ self.b5 = b"\x9b\x61\x3b\xdc"
+ self.b6 = b"\xff\xff"
self.byte_strings = (self.b1, self.b2, self.b3, self.b4, self.b5, self.b6)
def test_xor_bytes(self):
- self.assertEqual(xor_bytes(self.b1, self.b2), b'\xff\xff\xff\xff')
- self.assertEqual(xor_bytes(self.b1, self.b3), b'\x0f\x0f\x0f\x0f')
- self.assertEqual(xor_bytes(self.b1, self.b4), b'\xb2\xdc\x35\x1d')
- self.assertEqual(xor_bytes(self.b1, self.b5), b'\x64\x9e\xc4\x23')
- self.assertEqual(xor_bytes(self.b2, self.b3), b'\xf0\xf0\xf0\xf0')
- self.assertEqual(xor_bytes(self.b2, self.b4), b'\x4d\x23\xca\xe2')
- self.assertEqual(xor_bytes(self.b2, self.b5), b'\x9b\x61\x3b\xdc')
- self.assertEqual(xor_bytes(self.b3, self.b4), b'\xbd\xd3\x3a\x12')
- self.assertEqual(xor_bytes(self.b3, self.b5), b'\x6b\x91\xcb\x2c')
- self.assertEqual(xor_bytes(self.b4, self.b5), b'\xd6\x42\xf1\x3e')
+ self.assertEqual(xor_bytes(self.b1, self.b2), b"\xff\xff\xff\xff")
+ self.assertEqual(xor_bytes(self.b1, self.b3), b"\x0f\x0f\x0f\x0f")
+ self.assertEqual(xor_bytes(self.b1, self.b4), b"\xb2\xdc\x35\x1d")
+ self.assertEqual(xor_bytes(self.b1, self.b5), b"\x64\x9e\xc4\x23")
+ self.assertEqual(xor_bytes(self.b2, self.b3), b"\xf0\xf0\xf0\xf0")
+ self.assertEqual(xor_bytes(self.b2, self.b4), b"\x4d\x23\xca\xe2")
+ self.assertEqual(xor_bytes(self.b2, self.b5), b"\x9b\x61\x3b\xdc")
+ self.assertEqual(xor_bytes(self.b3, self.b4), b"\xbd\xd3\x3a\x12")
+ self.assertEqual(xor_bytes(self.b3, self.b5), b"\x6b\x91\xcb\x2c")
+ self.assertEqual(xor_bytes(self.b4, self.b5), b"\xd6\x42\xf1\x3e")
def test_xor_bytes_length(self):
- self.assertEqual(xor_bytes(self.b1, self.b6), b'\x00\x00')
- self.assertEqual(xor_bytes(self.b2, self.b6), b'\xff\xff')
- self.assertEqual(xor_bytes(self.b3, self.b6), b'\x0f\x0f')
- self.assertEqual(xor_bytes(self.b4, self.b6), b'\xb2\xdc')
- self.assertEqual(xor_bytes(self.b5, self.b6), b'\x64\x9e')
- self.assertEqual(xor_bytes(self.b6, b''), b'')
+ self.assertEqual(xor_bytes(self.b1, self.b6), b"\x00\x00")
+ self.assertEqual(xor_bytes(self.b2, self.b6), b"\xff\xff")
+ self.assertEqual(xor_bytes(self.b3, self.b6), b"\x0f\x0f")
+ self.assertEqual(xor_bytes(self.b4, self.b6), b"\xb2\xdc")
+ self.assertEqual(xor_bytes(self.b5, self.b6), b"\x64\x9e")
+ self.assertEqual(xor_bytes(self.b6, b""), b"")
def test_xor_bytes_commutative(self):
for first in self.byte_strings:
diff --git a/tests/test_load_save_keys.py b/tests/test_load_save_keys.py
index d881d20..3e90999 100644
--- a/tests/test_load_save_keys.py
+++ b/tests/test_load_save_keys.py
@@ -23,51 +23,67 @@ from unittest import mock
import rsa.key
-B64PRIV_DER = b'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt'
+B64PRIV_DER = b"MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt"
PRIVATE_DER = base64.standard_b64decode(B64PRIV_DER)
-B64PUB_DER = b'MAwCBQDeKYlRAgMBAAE='
+B64PUB_DER = b"MAwCBQDeKYlRAgMBAAE="
PUBLIC_DER = base64.standard_b64decode(B64PUB_DER)
-PRIVATE_PEM = b'''\
+PRIVATE_PEM = (
+ b"""\
-----BEGIN CONFUSING STUFF-----
Cruft before the key
-----BEGIN RSA PRIVATE KEY-----
Comment: something blah
-''' + B64PRIV_DER + b'''
+"""
+ + B64PRIV_DER
+ + b"""
-----END RSA PRIVATE KEY-----
Stuff after the key
-----END CONFUSING STUFF-----
-'''
+"""
+)
-CLEAN_PRIVATE_PEM = b'''\
+CLEAN_PRIVATE_PEM = (
+ b"""\
-----BEGIN RSA PRIVATE KEY-----
-''' + B64PRIV_DER + b'''
+"""
+ + B64PRIV_DER
+ + b"""
-----END RSA PRIVATE KEY-----
-'''
+"""
+)
-PUBLIC_PEM = b'''\
+PUBLIC_PEM = (
+ b"""\
-----BEGIN CONFUSING STUFF-----
Cruft before the key
-----BEGIN RSA PUBLIC KEY-----
Comment: something blah
-''' + B64PUB_DER + b'''
+"""
+ + B64PUB_DER
+ + b"""
-----END RSA PUBLIC KEY-----
Stuff after the key
-----END CONFUSING STUFF-----
-'''
+"""
+)
-CLEAN_PUBLIC_PEM = b'''\
+CLEAN_PUBLIC_PEM = (
+ b"""\
-----BEGIN RSA PUBLIC KEY-----
-''' + B64PUB_DER + b'''
+"""
+ + B64PUB_DER
+ + b"""
-----END RSA PUBLIC KEY-----
-'''
+"""
+)
class DerTest(unittest.TestCase):
@@ -76,7 +92,7 @@ class DerTest(unittest.TestCase):
def test_load_private_key(self):
"""Test loading private DER keys."""
- key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_DER, 'DER')
+ key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_DER, "DER")
expected = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
self.assertEqual(expected, key)
@@ -84,7 +100,7 @@ class DerTest(unittest.TestCase):
self.assertEqual(key.exp2, 10095)
self.assertEqual(key.coef, 50797)
- @mock.patch('pyasn1.codec.der.decoder.decode')
+ @mock.patch("pyasn1.codec.der.decoder.decode")
def test_load_malformed_private_key(self, der_decode):
"""Test loading malformed private DER keys."""
@@ -96,18 +112,18 @@ class DerTest(unittest.TestCase):
with warnings.catch_warnings(record=True) as w:
# Always print warnings
- warnings.simplefilter('always')
+ warnings.simplefilter("always")
# Load 3 keys
for _ in range(3):
- key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_DER, 'DER')
+ key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_DER, "DER")
# Check that 3 warnings were generated.
self.assertEqual(3, len(w))
for warning in w:
self.assertTrue(issubclass(warning.category, UserWarning))
- self.assertIn('malformed', str(warning.message))
+ self.assertIn("malformed", str(warning.message))
# Check that we are creating the key with correct values
self.assertEqual(key.exp1, 55063)
@@ -118,7 +134,7 @@ class DerTest(unittest.TestCase):
"""Test saving private DER keys."""
key = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
- der = key.save_pkcs1('DER')
+ der = key.save_pkcs1("DER")
self.assertIsInstance(der, bytes)
self.assertEqual(PRIVATE_DER, der)
@@ -126,7 +142,7 @@ class DerTest(unittest.TestCase):
def test_load_public_key(self):
"""Test loading public DER keys."""
- key = rsa.key.PublicKey.load_pkcs1(PUBLIC_DER, 'DER')
+ key = rsa.key.PublicKey.load_pkcs1(PUBLIC_DER, "DER")
expected = rsa.key.PublicKey(3727264081, 65537)
self.assertEqual(expected, key)
@@ -135,7 +151,7 @@ class DerTest(unittest.TestCase):
"""Test saving public DER keys."""
key = rsa.key.PublicKey(3727264081, 65537)
- der = key.save_pkcs1('DER')
+ der = key.save_pkcs1("DER")
self.assertIsInstance(der, bytes)
self.assertEqual(PUBLIC_DER, der)
@@ -147,7 +163,7 @@ class PemTest(unittest.TestCase):
def test_load_private_key(self):
"""Test loading private PEM files."""
- key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_PEM, 'PEM')
+ key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_PEM, "PEM")
expected = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
self.assertEqual(expected, key)
@@ -159,7 +175,7 @@ class PemTest(unittest.TestCase):
"""Test saving private PEM files."""
key = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
- pem = key.save_pkcs1('PEM')
+ pem = key.save_pkcs1("PEM")
self.assertIsInstance(pem, bytes)
self.assertEqual(CLEAN_PRIVATE_PEM, pem)
@@ -167,7 +183,7 @@ class PemTest(unittest.TestCase):
def test_load_public_key(self):
"""Test loading public PEM files."""
- key = rsa.key.PublicKey.load_pkcs1(PUBLIC_PEM, 'PEM')
+ key = rsa.key.PublicKey.load_pkcs1(PUBLIC_PEM, "PEM")
expected = rsa.key.PublicKey(3727264081, 65537)
self.assertEqual(expected, key)
@@ -176,7 +192,7 @@ class PemTest(unittest.TestCase):
"""Test saving public PEM files."""
key = rsa.key.PublicKey(3727264081, 65537)
- pem = key.save_pkcs1('PEM')
+ pem = key.save_pkcs1("PEM")
self.assertIsInstance(pem, bytes)
self.assertEqual(CLEAN_PUBLIC_PEM, pem)
@@ -184,8 +200,8 @@ class PemTest(unittest.TestCase):
def test_load_from_disk(self):
"""Test loading a PEM file from disk."""
- fname = os.path.join(os.path.dirname(__file__), 'private.pem')
- with open(fname, mode='rb') as privatefile:
+ fname = os.path.join(os.path.dirname(__file__), "private.pem")
+ with open(fname, mode="rb") as privatefile:
keydata = privatefile.read()
privkey = rsa.key.PrivateKey.load_pkcs1(keydata)
diff --git a/tests/test_mypy.py b/tests/test_mypy.py
index b13cdcc..8cc0d59 100644
--- a/tests/test_mypy.py
+++ b/tests/test_mypy.py
@@ -4,16 +4,16 @@ import unittest
import mypy.api
-test_modules = ['rsa', 'tests']
+test_modules = ["rsa", "tests"]
class MypyRunnerTest(unittest.TestCase):
def test_run_mypy(self):
proj_root = pathlib.Path(__file__).parent.parent
args = [
- '--incremental',
- '--ignore-missing-imports',
- f'--python-version={sys.version_info.major}.{sys.version_info.minor}'
+ "--incremental",
+ "--ignore-missing-imports",
+ f"--python-version={sys.version_info.major}.{sys.version_info.minor}",
] + [str(proj_root / dirname) for dirname in test_modules]
result = mypy.api.run(args)
@@ -26,6 +26,6 @@ class MypyRunnerTest(unittest.TestCase):
if stdout:
messages.append(stdout)
if status:
- messages.append('Mypy failed with status %d' % status)
- if messages and not all('Success' in message for message in messages):
- self.fail('\n'.join(['Mypy errors:'] + messages))
+ messages.append("Mypy failed with status %d" % status)
+ if messages and not all("Success" in message for message in messages):
+ self.fail("\n".join(["Mypy errors:"] + messages))
diff --git a/tests/test_pem.py b/tests/test_pem.py
index dd03cca..7440431 100644
--- a/tests/test_pem.py
+++ b/tests/test_pem.py
@@ -19,14 +19,14 @@ from rsa.pem import _markers
import rsa.key
# 512-bit key. Too small for practical purposes, but good enough for testing with.
-public_key_pem = '''
+public_key_pem = """
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKH0aYP9ZFuctlPnXhEyHjgc8ltKKx9M
0c+h4sKMXwjhjbQAZdtWIw8RRghpUJnKj+6bN2XzZDazyULxgPhtax0CAwEAAQ==
-----END PUBLIC KEY-----
-'''
+"""
-private_key_pem = '''
+private_key_pem = """
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAKH0aYP9ZFuctlPnXhEyHjgc8ltKKx9M0c+h4sKMXwjhjbQAZdtW
Iw8RRghpUJnKj+6bN2XzZDazyULxgPhtax0CAwEAAQJADwR36EpNzQTqDzusCFIq
@@ -36,7 +36,7 @@ F8p1J98BEbtjU2mEZIVCMn6vQuhWdl8CIDRL4IJl4eGKlB0QP0JJF1wpeGO/R76l
DaPF5cMM7k3NAiEAss28m/ck9BWBfFVdNjx/vsdFZkx2O9AX9EJWoBSnSgECIQCa
+sVQMUVJFGsdE/31C7wCIbE3IpB7ziABZ7mN+V3Dhg==
-----END RSA PRIVATE KEY-----
-'''
+"""
# Private key components
prime1 = 96275860229939261876671084930484419185939191875438854026071315955024109172739
@@ -45,9 +45,10 @@ prime2 = 88103681619592083641803383393198542599284510949756076218404908654323473
class TestMarkers(unittest.TestCase):
def test_values(self):
- self.assertEqual(_markers('RSA PRIVATE KEY'),
- (b'-----BEGIN RSA PRIVATE KEY-----',
- b'-----END RSA PRIVATE KEY-----'))
+ self.assertEqual(
+ _markers("RSA PRIVATE KEY"),
+ (b"-----BEGIN RSA PRIVATE KEY-----", b"-----END RSA PRIVATE KEY-----"),
+ )
class TestBytesAndStrings(unittest.TestCase):
@@ -58,7 +59,7 @@ class TestBytesAndStrings(unittest.TestCase):
self.assertEqual(prime1 * prime2, key.n)
def test_bytes_public(self):
- key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_pem.encode('ascii'))
+ key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_pem.encode("ascii"))
self.assertEqual(prime1 * prime2, key.n)
def test_unicode_private(self):
@@ -66,7 +67,7 @@ class TestBytesAndStrings(unittest.TestCase):
self.assertEqual(prime1 * prime2, key.n)
def test_bytes_private(self):
- key = rsa.key.PrivateKey.load_pkcs1(private_key_pem.encode('ascii'))
+ key = rsa.key.PrivateKey.load_pkcs1(private_key_pem.encode("ascii"))
self.assertEqual(prime1, key.p)
self.assertEqual(prime2, key.q)
@@ -76,24 +77,24 @@ class TestByteOutput(unittest.TestCase):
def test_bytes_public(self):
key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_pem)
- self.assertIsInstance(key.save_pkcs1(format='DER'), bytes)
- self.assertIsInstance(key.save_pkcs1(format='PEM'), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="DER"), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="PEM"), bytes)
def test_bytes_private(self):
key = rsa.key.PrivateKey.load_pkcs1(private_key_pem)
- self.assertIsInstance(key.save_pkcs1(format='DER'), bytes)
- self.assertIsInstance(key.save_pkcs1(format='PEM'), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="DER"), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="PEM"), bytes)
class TestByteInput(unittest.TestCase):
"""Tests that PEM and DER can be loaded from bytes."""
def test_bytes_public(self):
- key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_pem.encode('ascii'))
- self.assertIsInstance(key.save_pkcs1(format='DER'), bytes)
- self.assertIsInstance(key.save_pkcs1(format='PEM'), bytes)
+ key = rsa.key.PublicKey.load_pkcs1_openssl_pem(public_key_pem.encode("ascii"))
+ self.assertIsInstance(key.save_pkcs1(format="DER"), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="PEM"), bytes)
def test_bytes_private(self):
- key = rsa.key.PrivateKey.load_pkcs1(private_key_pem.encode('ascii'))
- self.assertIsInstance(key.save_pkcs1(format='DER'), bytes)
- self.assertIsInstance(key.save_pkcs1(format='PEM'), bytes)
+ key = rsa.key.PrivateKey.load_pkcs1(private_key_pem.encode("ascii"))
+ self.assertIsInstance(key.save_pkcs1(format="DER"), bytes)
+ self.assertIsInstance(key.save_pkcs1(format="PEM"), bytes)
diff --git a/tests/test_pkcs1.py b/tests/test_pkcs1.py
index 272e2bc..f2d4957 100644
--- a/tests/test_pkcs1.py
+++ b/tests/test_pkcs1.py
@@ -28,7 +28,7 @@ class BinaryTest(unittest.TestCase):
(self.pub, self.priv) = rsa.newkeys(256)
def test_enc_dec(self):
- message = struct.pack('>IIII', 0, 0, 0, 1)
+ message = struct.pack(">IIII", 0, 0, 0, 1)
print("\n\tMessage: %r" % message)
encrypted = pkcs1.encrypt(message, self.pub)
@@ -40,7 +40,7 @@ class BinaryTest(unittest.TestCase):
self.assertEqual(message, decrypted)
def test_decoding_failure(self):
- message = struct.pack('>IIII', 0, 0, 0, 1)
+ message = struct.pack(">IIII", 0, 0, 0, 1)
encrypted = pkcs1.encrypt(message, self.pub)
# Alter the encrypted stream
@@ -50,15 +50,14 @@ class BinaryTest(unittest.TestCase):
altered_a = (a + 1) % 256
encrypted = encrypted[:5] + byte(altered_a) + encrypted[6:]
- self.assertRaises(pkcs1.DecryptionError, pkcs1.decrypt, encrypted,
- self.priv)
+ self.assertRaises(pkcs1.DecryptionError, pkcs1.decrypt, encrypted, self.priv)
def test_randomness(self):
"""Encrypting the same message twice should result in different
cryptos.
"""
- message = struct.pack('>IIII', 0, 0, 0, 1)
+ message = struct.pack(">IIII", 0, 0, 0, 1)
encrypted1 = pkcs1.encrypt(message, self.pub)
encrypted2 = pkcs1.encrypt(message, self.pub)
@@ -70,7 +69,8 @@ class ExtraZeroesTest(unittest.TestCase):
# Key, cyphertext, and plaintext taken from https://github.com/sybrenstuvel/python-rsa/issues/146
self.private_key = rsa.PrivateKey.load_pkcs1(
"-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAs1EKK81M5kTFtZSuUFnhKy8FS2WNXaWVmi/fGHG4CLw98+Yo\n0nkuUarVwSS0O9pFPcpc3kvPKOe9Tv+6DLS3Qru21aATy2PRqjqJ4CYn71OYtSwM\n/ZfSCKvrjXybzgu+sBmobdtYm+sppbdL+GEHXGd8gdQw8DDCZSR6+dPJFAzLZTCd\nB+Ctwe/RXPF+ewVdfaOGjkZIzDoYDw7n+OHnsYCYozkbTOcWHpjVevipR+IBpGPi\n1rvKgFnlcG6d/tj0hWRl/6cS7RqhjoiNEtxqoJzpXs/Kg8xbCxXbCchkf11STA8u\ndiCjQWuWI8rcDwl69XMmHJjIQAqhKvOOQ8rYTQIDAQABAoIBABpQLQ7qbHtp4h1Y\nORAfcFRW7Q74UvtH/iEHH1TF8zyM6wZsYtcn4y0mxYE3Mp+J0xlTJbeVJkwZXYVH\nL3UH29CWHSlR+TWiazTwrCTRVJDhEoqbcTiRW8fb+o/jljVxMcVDrpyYUHNo2c6w\njBxhmKPtp66hhaDpds1Cwi0A8APZ8Z2W6kya/L/hRBzMgCz7Bon1nYBMak5PQEwV\nF0dF7Wy4vIjvCzO6DSqA415DvJDzUAUucgFudbANNXo4HJwNRnBpymYIh8mHdmNJ\n/MQ0YLSqUWvOB57dh7oWQwe3UsJ37ZUorTugvxh3NJ7Tt5ZqbCQBEECb9ND63gxo\n/a3YR/0CgYEA7BJc834xCi/0YmO5suBinWOQAF7IiRPU+3G9TdhWEkSYquupg9e6\nK9lC5k0iP+t6I69NYF7+6mvXDTmv6Z01o6oV50oXaHeAk74O3UqNCbLe9tybZ/+F\ndkYlwuGSNttMQBzjCiVy0+y0+Wm3rRnFIsAtd0RlZ24aN3bFTWJINIsCgYEAwnQq\nvNmJe9SwtnH5c/yCqPhKv1cF/4jdQZSGI6/p3KYNxlQzkHZ/6uvrU5V27ov6YbX8\nvKlKfO91oJFQxUD6lpTdgAStI3GMiJBJIZNpyZ9EWNSvwUj28H34cySpbZz3s4Xd\nhiJBShgy+fKURvBQwtWmQHZJ3EGrcOI7PcwiyYcCgYEAlql5jSUCY0ALtidzQogW\nJ+B87N+RGHsBuJ/0cxQYinwg+ySAAVbSyF1WZujfbO/5+YBN362A/1dn3lbswCnH\nK/bHF9+fZNqvwprPnceQj5oK1n4g6JSZNsy6GNAhosT+uwQ0misgR8SQE4W25dDG\nkdEYsz+BgCsyrCcu8J5C+tUCgYAFVPQbC4f2ikVyKzvgz0qx4WUDTBqRACq48p6e\n+eLatv7nskVbr7QgN+nS9+Uz80ihR0Ev1yCAvnwmM/XYAskcOea87OPmdeWZlQM8\nVXNwINrZ6LMNBLgorfuTBK1UoRo1pPUHCYdqxbEYI2unak18mikd2WB7Fp3h0YI4\nVpGZnwKBgBxkAYnZv+jGI4MyEKdsQgxvROXXYOJZkWzsKuKxVkVpYP2V4nR2YMOJ\nViJQ8FUEnPq35cMDlUk4SnoqrrHIJNOvcJSCqM+bWHAioAsfByLbUPM8sm3CDdIk\nXVJl32HuKYPJOMIWfc7hIfxLRHnCN+coz2M6tgqMDs0E/OfjuqVZ\n-----END RSA PRIVATE KEY-----",
- format='PEM')
+ format="PEM",
+ )
self.cyphertext = bytes.fromhex(
"4501b4d669e01b9ef2dc800aa1b06d49196f5a09fe8fbcd037323c60eaf027bfb98432be4e4a26c567ffec718bcbea977dd26812fa071c33808b4d5ebb742d9879806094b6fbeea63d25ea3141733b60e31c6912106e1b758a7fe0014f075193faa8b4622bfd5d3013f0a32190a95de61a3604711bc62945f95a6522bd4dfed0a994ef185b28c281f7b5e4c8ed41176d12d9fc1b837e6a0111d0132d08a6d6f0580de0c9eed8ed105531799482d1e466c68c23b0c222af7fc12ac279bc4ff57e7b4586d209371b38c4c1035edd418dc5f960441cb21ea2bedbfea86de0d7861e81021b650a1de51002c315f1e7c12debe4dcebf790caaa54a2f26b149cf9e77d"
)
@@ -98,89 +98,88 @@ class SignatureTest(unittest.TestCase):
def test_sign_verify(self):
"""Test happy flow of sign and verify"""
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA-256')
- self.assertEqual('SHA-256', pkcs1.verify(message, signature, self.pub))
-
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA-256")
+ self.assertEqual("SHA-256", pkcs1.verify(message, signature, self.pub))
@unittest.skipIf(sys.version_info < (3, 6), "SHA3 requires Python 3.6+")
def test_sign_verify_sha3(self):
"""Test happy flow of sign and verify with SHA3-256"""
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA3-256')
- self.assertEqual('SHA3-256', pkcs1.verify(message, signature, self.pub))
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA3-256")
+ self.assertEqual("SHA3-256", pkcs1.verify(message, signature, self.pub))
def test_find_signature_hash(self):
"""Test happy flow of sign and find_signature_hash"""
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA-256')
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA-256")
- self.assertEqual('SHA-256', pkcs1.find_signature_hash(signature, self.pub))
+ self.assertEqual("SHA-256", pkcs1.find_signature_hash(signature, self.pub))
def test_alter_message(self):
"""Altering the message should let the verification fail."""
- signature = pkcs1.sign(b'je moeder', self.priv, 'SHA-256')
- self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
- b'mijn moeder', signature, self.pub)
+ signature = pkcs1.sign(b"je moeder", self.priv, "SHA-256")
+ self.assertRaises(
+ pkcs1.VerificationError, pkcs1.verify, b"mijn moeder", signature, self.pub
+ )
def test_sign_different_key(self):
"""Signing with another key should let the verification fail."""
(otherpub, _) = rsa.newkeys(512)
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA-256')
- self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
- message, signature, otherpub)
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA-256")
+ self.assertRaises(pkcs1.VerificationError, pkcs1.verify, message, signature, otherpub)
def test_multiple_signings(self):
"""Signing the same message twice should return the same signatures."""
- message = struct.pack('>IIII', 0, 0, 0, 1)
- signature1 = pkcs1.sign(message, self.priv, 'SHA-1')
- signature2 = pkcs1.sign(message, self.priv, 'SHA-1')
+ message = struct.pack(">IIII", 0, 0, 0, 1)
+ signature1 = pkcs1.sign(message, self.priv, "SHA-1")
+ signature2 = pkcs1.sign(message, self.priv, "SHA-1")
self.assertEqual(signature1, signature2)
def test_split_hash_sign(self):
"""Hashing and then signing should match with directly signing the message. """
- message = b'je moeder'
- msg_hash = pkcs1.compute_hash(message, 'SHA-256')
- signature1 = pkcs1.sign_hash(msg_hash, self.priv, 'SHA-256')
+ message = b"je moeder"
+ msg_hash = pkcs1.compute_hash(message, "SHA-256")
+ signature1 = pkcs1.sign_hash(msg_hash, self.priv, "SHA-256")
# Calculate the signature using the unified method
- signature2 = pkcs1.sign(message, self.priv, 'SHA-256')
+ signature2 = pkcs1.sign(message, self.priv, "SHA-256")
self.assertEqual(signature1, signature2)
def test_hash_sign_verify(self):
"""Test happy flow of hash, sign, and verify"""
- message = b'je moeder'
- msg_hash = pkcs1.compute_hash(message, 'SHA-224')
- signature = pkcs1.sign_hash(msg_hash, self.priv, 'SHA-224')
+ message = b"je moeder"
+ msg_hash = pkcs1.compute_hash(message, "SHA-224")
+ signature = pkcs1.sign_hash(msg_hash, self.priv, "SHA-224")
self.assertTrue(pkcs1.verify(message, signature, self.pub))
def test_prepend_zeroes(self):
"""Prepending the signature with zeroes should be detected."""
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA-256')
- signature = bytes.fromhex('0000') + signature
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA-256")
+ signature = bytes.fromhex("0000") + signature
with self.assertRaises(rsa.VerificationError):
pkcs1.verify(message, signature, self.pub)
def test_apppend_zeroes(self):
"""Apppending the signature with zeroes should be detected."""
- message = b'je moeder'
- signature = pkcs1.sign(message, self.priv, 'SHA-256')
- signature = signature + bytes.fromhex('0000')
+ message = b"je moeder"
+ signature = pkcs1.sign(message, self.priv, "SHA-256")
+ signature = signature + bytes.fromhex("0000")
with self.assertRaises(rsa.VerificationError):
pkcs1.verify(message, signature, self.pub)
@@ -191,16 +190,18 @@ class PaddingSizeTest(unittest.TestCase):
# Construct key that will be small enough to need only 7 bytes of padding.
# This key is 168 bit long, and was generated with rsa.newkeys(nbits=168).
- self.private_key = rsa.PrivateKey.load_pkcs1(b'''
+ self.private_key = rsa.PrivateKey.load_pkcs1(
+ b"""
-----BEGIN RSA PRIVATE KEY-----
MHkCAQACFgCIGbbNSkIRLtprxka9NgOf5UxgxCMCAwEAAQIVQqymO0gHubdEVS68
CdCiWmOJxVfRAgwBQM+e1JJwMKmxSF0CCmya6CFxO8Evdn8CDACMM3AlVC4FhlN8
3QIKC9cjoam/swMirwIMAR7Br9tdouoH7jAE
-----END RSA PRIVATE KEY-----
- ''')
+ """
+ )
self.public_key = rsa.PublicKey(n=self.private_key.n, e=self.private_key.e)
- cyphertext = self.encrypt_with_short_padding(b'op je hoofd')
+ cyphertext = self.encrypt_with_short_padding(b"op je hoofd")
with self.assertRaises(rsa.DecryptionError):
rsa.decrypt(cyphertext, self.private_key)
@@ -209,7 +210,7 @@ CdCiWmOJxVfRAgwBQM+e1JJwMKmxSF0CCmya6CFxO8Evdn8CDACMM3AlVC4FhlN8
keylength = rsa.common.byte_size(self.public_key.n)
# The word 'padding' has 7 letters, so is one byte short of a valid padding length.
- padded = b'\x00\x02padding\x00' + message
+ padded = b"\x00\x02padding\x00" + message
payload = rsa.transform.bytes2int(padded)
encrypted_value = rsa.core.encrypt_int(payload, self.public_key.e, self.public_key.n)
diff --git a/tests/test_pkcs1_v2.py b/tests/test_pkcs1_v2.py
index bba525e..ead1393 100644
--- a/tests/test_pkcs1_v2.py
+++ b/tests/test_pkcs1_v2.py
@@ -26,38 +26,37 @@ from rsa import pkcs1_v2
class MGFTest(unittest.TestCase):
def test_oaep_int_db_mask(self):
seed = (
- b'\xaa\xfd\x12\xf6\x59\xca\xe6\x34\x89\xb4\x79\xe5\x07\x6d\xde\xc2'
- b'\xf0\x6c\xb5\x8f'
+ b"\xaa\xfd\x12\xf6\x59\xca\xe6\x34\x89\xb4\x79\xe5\x07\x6d\xde\xc2" b"\xf0\x6c\xb5\x8f"
)
db = (
- b'\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90'
- b'\xaf\xd8\x07\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
- b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xd4\x36\xe9\x95\x69'
- b'\xfd\x32\xa7\xc8\xa0\x5b\xbc\x90\xd3\x2c\x49'
+ b"\xda\x39\xa3\xee\x5e\x6b\x4b\x0d\x32\x55\xbf\xef\x95\x60\x18\x90"
+ b"\xaf\xd8\x07\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xd4\x36\xe9\x95\x69"
+ b"\xfd\x32\xa7\xc8\xa0\x5b\xbc\x90\xd3\x2c\x49"
)
masked_db = (
- b'\xdc\xd8\x7d\x5c\x68\xf1\xee\xa8\xf5\x52\x67\xc3\x1b\x2e\x8b\xb4'
- b'\x25\x1f\x84\xd7\xe0\xb2\xc0\x46\x26\xf5\xaf\xf9\x3e\xdc\xfb\x25'
- b'\xc9\xc2\xb3\xff\x8a\xe1\x0e\x83\x9a\x2d\xdb\x4c\xdc\xfe\x4f\xf4'
- b'\x77\x28\xb4\xa1\xb7\xc1\x36\x2b\xaa\xd2\x9a\xb4\x8d\x28\x69\xd5'
- b'\x02\x41\x21\x43\x58\x11\x59\x1b\xe3\x92\xf9\x82\xfb\x3e\x87\xd0'
- b'\x95\xae\xb4\x04\x48\xdb\x97\x2f\x3a\xc1\x4f\x7b\xc2\x75\x19\x52'
- b'\x81\xce\x32\xd2\xf1\xb7\x6d\x4d\x35\x3e\x2d'
+ b"\xdc\xd8\x7d\x5c\x68\xf1\xee\xa8\xf5\x52\x67\xc3\x1b\x2e\x8b\xb4"
+ b"\x25\x1f\x84\xd7\xe0\xb2\xc0\x46\x26\xf5\xaf\xf9\x3e\xdc\xfb\x25"
+ b"\xc9\xc2\xb3\xff\x8a\xe1\x0e\x83\x9a\x2d\xdb\x4c\xdc\xfe\x4f\xf4"
+ b"\x77\x28\xb4\xa1\xb7\xc1\x36\x2b\xaa\xd2\x9a\xb4\x8d\x28\x69\xd5"
+ b"\x02\x41\x21\x43\x58\x11\x59\x1b\xe3\x92\xf9\x82\xfb\x3e\x87\xd0"
+ b"\x95\xae\xb4\x04\x48\xdb\x97\x2f\x3a\xc1\x4f\x7b\xc2\x75\x19\x52"
+ b"\x81\xce\x32\xd2\xf1\xb7\x6d\x4d\x35\x3e\x2d"
)
# dbMask = MGF(seed, length(DB))
db_mask = pkcs1_v2.mgf1(seed, length=len(db))
expected_db_mask = (
- b'\x06\xe1\xde\xb2\x36\x9a\xa5\xa5\xc7\x07\xd8\x2c\x8e\x4e\x93\x24'
- b'\x8a\xc7\x83\xde\xe0\xb2\xc0\x46\x26\xf5\xaf\xf9\x3e\xdc\xfb\x25'
- b'\xc9\xc2\xb3\xff\x8a\xe1\x0e\x83\x9a\x2d\xdb\x4c\xdc\xfe\x4f\xf4'
- b'\x77\x28\xb4\xa1\xb7\xc1\x36\x2b\xaa\xd2\x9a\xb4\x8d\x28\x69\xd5'
- b'\x02\x41\x21\x43\x58\x11\x59\x1b\xe3\x92\xf9\x82\xfb\x3e\x87\xd0'
- b'\x95\xae\xb4\x04\x48\xdb\x97\x2f\x3a\xc1\x4e\xaf\xf4\x9c\x8c\x3b'
- b'\x7c\xfc\x95\x1a\x51\xec\xd1\xdd\xe6\x12\x64'
+ b"\x06\xe1\xde\xb2\x36\x9a\xa5\xa5\xc7\x07\xd8\x2c\x8e\x4e\x93\x24"
+ b"\x8a\xc7\x83\xde\xe0\xb2\xc0\x46\x26\xf5\xaf\xf9\x3e\xdc\xfb\x25"
+ b"\xc9\xc2\xb3\xff\x8a\xe1\x0e\x83\x9a\x2d\xdb\x4c\xdc\xfe\x4f\xf4"
+ b"\x77\x28\xb4\xa1\xb7\xc1\x36\x2b\xaa\xd2\x9a\xb4\x8d\x28\x69\xd5"
+ b"\x02\x41\x21\x43\x58\x11\x59\x1b\xe3\x92\xf9\x82\xfb\x3e\x87\xd0"
+ b"\x95\xae\xb4\x04\x48\xdb\x97\x2f\x3a\xc1\x4e\xaf\xf4\x9c\x8c\x3b"
+ b"\x7c\xfc\x95\x1a\x51\xec\xd1\xdd\xe6\x12\x64"
)
self.assertEqual(db_mask, expected_db_mask)
@@ -65,8 +64,7 @@ class MGFTest(unittest.TestCase):
# seedMask = MGF(maskedDB, length(seed))
seed_mask = pkcs1_v2.mgf1(masked_db, length=len(seed))
expected_seed_mask = (
- b'\x41\x87\x0b\x5a\xb0\x29\xe6\x57\xd9\x57\x50\xb5\x4c\x28\x3c\x08'
- b'\x72\x5d\xbe\xa9'
+ b"\x41\x87\x0b\x5a\xb0\x29\xe6\x57\xd9\x57\x50\xb5\x4c\x28\x3c\x08" b"\x72\x5d\xbe\xa9"
)
self.assertEqual(seed_mask, expected_seed_mask)
@@ -74,8 +72,8 @@ class MGFTest(unittest.TestCase):
def test_invalid_hasher(self):
"""Tests an invalid hasher generates an exception"""
with self.assertRaises(ValueError):
- pkcs1_v2.mgf1(b'\x06\xe1\xde\xb2', length=8, hasher='SHA2')
+ pkcs1_v2.mgf1(b"\x06\xe1\xde\xb2", length=8, hasher="SHA2")
def test_invalid_length(self):
with self.assertRaises(OverflowError):
- pkcs1_v2.mgf1(b'\x06\xe1\xde\xb2', length=2**50)
+ pkcs1_v2.mgf1(b"\x06\xe1\xde\xb2", length=2 ** 50)
diff --git a/tests/test_prime.py b/tests/test_prime.py
index 5577f67..42d8af1 100644
--- a/tests/test_prime.py
+++ b/tests/test_prime.py
@@ -35,7 +35,7 @@ class PrimeTest(unittest.TestCase):
# Test some slightly larger numbers
self.assertEqual(
[907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997],
- [x for x in range(901, 1000) if rsa.prime.is_prime(x)]
+ [x for x in range(901, 1000) if rsa.prime.is_prime(x)],
)
# Test around the 50th millionth known prime.
@@ -62,13 +62,23 @@ class PrimeTest(unittest.TestCase):
self.assertEqual([], randints)
# 'Exit inner loop and continue with next witness'
- randints.extend([
- 2119139098, # causes 'Exit inner loop and continue with next witness'
- # the next witnesses for the above case:
- 3051067716, 3603501763, 3230895847, 3687808133, 3760099987, 4026931495, 3022471882,
- ])
- self.assertEqual(True, rsa.prime.miller_rabin_primality_testing(2211417913,
- len(randints)))
+ randints.extend(
+ [
+ 2119139098, # causes 'Exit inner loop and continue with next witness'
+ # the next witnesses for the above case:
+ 3051067716,
+ 3603501763,
+ 3230895847,
+ 3687808133,
+ 3760099987,
+ 4026931495,
+ 3022471882,
+ ]
+ )
+ self.assertEqual(
+ True,
+ rsa.prime.miller_rabin_primality_testing(2211417913, len(randints)),
+ )
self.assertEqual([], randints)
finally:
rsa.randnum.randint = orig_randint
@@ -84,22 +94,38 @@ class PrimeTest(unittest.TestCase):
# List of known Mersenne exponents.
known_mersenne_exponents = [
- 2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279,
- 2203, 2281, 4423,
+ 2,
+ 3,
+ 5,
+ 7,
+ 13,
+ 17,
+ 19,
+ 31,
+ 61,
+ 89,
+ 107,
+ 127,
+ 521,
+ 607,
+ 1279,
+ 2203,
+ 2281,
+ 4423,
]
# Test Mersenne primes.
for exp in known_mersenne_exponents:
- self.assertTrue(rsa.prime.is_prime(2**exp - 1))
+ self.assertTrue(rsa.prime.is_prime(2 ** exp - 1))
def test_get_primality_testing_rounds(self):
"""Test round calculation for primality testing."""
- self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 63), 10)
+ self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 63), 10)
self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 127), 10)
self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 255), 10)
- self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 511), 7)
- self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 767), 7)
+ self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 511), 7)
+ self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 767), 7)
self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 1023), 4)
self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 1279), 4)
self.assertEqual(rsa.prime.get_primality_testing_rounds(1 << 1535), 3)
diff --git a/tests/test_strings.py b/tests/test_strings.py
index e392627..ae8ffe1 100644
--- a/tests/test_strings.py
+++ b/tests/test_strings.py
@@ -28,7 +28,7 @@ class StringTest(unittest.TestCase):
(self.pub, self.priv) = rsa.newkeys(384)
def test_enc_dec(self):
- message = unicode_string.encode('utf-8')
+ message = unicode_string.encode("utf-8")
print("\n\tMessage: %r" % message)
encrypted = rsa.encrypt(message, self.pub)
diff --git a/tests/test_transform.py b/tests/test_transform.py
index 7b9335e..1404619 100644
--- a/tests/test_transform.py
+++ b/tests/test_transform.py
@@ -18,20 +18,19 @@ from rsa.transform import int2bytes, bytes2int
class Test_int2bytes(unittest.TestCase):
def test_accuracy(self):
- self.assertEqual(int2bytes(123456789), b'\x07[\xcd\x15')
+ self.assertEqual(int2bytes(123456789), b"\x07[\xcd\x15")
def test_codec_identity(self):
self.assertEqual(bytes2int(int2bytes(123456789, 128)), 123456789)
def test_chunk_size(self):
- self.assertEqual(int2bytes(123456789, 6), b'\x00\x00\x07[\xcd\x15')
- self.assertEqual(int2bytes(123456789, 7),
- b'\x00\x00\x00\x07[\xcd\x15')
+ self.assertEqual(int2bytes(123456789, 6), b"\x00\x00\x07[\xcd\x15")
+ self.assertEqual(int2bytes(123456789, 7), b"\x00\x00\x00\x07[\xcd\x15")
def test_zero(self):
- self.assertEqual(int2bytes(0, 4), b'\x00' * 4)
- self.assertEqual(int2bytes(0, 7), b'\x00' * 7)
- self.assertEqual(int2bytes(0), b'\x00')
+ self.assertEqual(int2bytes(0, 4), b"\x00" * 4)
+ self.assertEqual(int2bytes(0, 7), b"\x00" * 7)
+ self.assertEqual(int2bytes(0), b"\x00")
def test_correctness_against_base_implementation(self):
# Slow test.
@@ -41,9 +40,7 @@ class Test_int2bytes(unittest.TestCase):
1 << 77,
]
for value in values:
- self.assertEqual(bytes2int(int2bytes(value)),
- value,
- "Boom %d" % value)
+ self.assertEqual(bytes2int(int2bytes(value)), value, "Boom %d" % value)
def test_raises_OverflowError_when_chunk_size_is_insufficient(self):
self.assertRaises(OverflowError, int2bytes, 123456789, 3)