summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xcreate_timing_table.py9
-rw-r--r--rsa/__init__.py12
-rw-r--r--rsa/_compat.py3
-rw-r--r--rsa/asn1.py30
-rw-r--r--rsa/bigfile.py24
-rw-r--r--rsa/cli.py136
-rw-r--r--rsa/common.py69
-rw-r--r--rsa/core.py17
-rw-r--r--rsa/key.py167
-rw-r--r--rsa/parallel.py23
-rw-r--r--rsa/pem.py19
-rw-r--r--rsa/pkcs1.py169
-rw-r--r--rsa/prime.py60
-rw-r--r--rsa/randnum.py20
-rw-r--r--rsa/transform.py34
-rw-r--r--rsa/util.py30
-rw-r--r--rsa/varblock.py29
-rw-r--r--tests/constants.py1
-rw-r--r--tests/test_bigfile.py13
-rw-r--r--tests/test_common.py8
-rw-r--r--tests/test_compat.py3
-rw-r--r--tests/test_integers.py12
-rw-r--r--tests/test_load_save_keys.py23
-rw-r--r--tests/test_pem.py2
-rw-r--r--tests/test_pkcs1.py41
-rw-r--r--tests/test_strings.py6
-rw-r--r--tests/test_varblock.py16
27 files changed, 486 insertions, 490 deletions
diff --git a/create_timing_table.py b/create_timing_table.py
index b6f8884..48cd1ff 100755
--- a/create_timing_table.py
+++ b/create_timing_table.py
@@ -21,8 +21,8 @@ import rsa
poolsize = 8
accurate = True
-def run_speed_test(bitsize):
+def run_speed_test(bitsize):
iterations = 0
start = end = time.time()
@@ -35,10 +35,9 @@ def run_speed_test(bitsize):
duration = end - start
dur_per_call = duration / iterations
- print '%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' % (bitsize,
- dur_per_call, iterations, duration)
+ print('%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' %
+ (bitsize, dur_per_call, iterations, duration))
+
for bitsize in (128, 256, 384, 512, 1024, 2048, 3072, 4096):
run_speed_test(bitsize)
-
-
diff --git a/rsa/__init__.py b/rsa/__init__.py
index c4654e9..c996f00 100644
--- a/rsa/__init__.py
+++ b/rsa/__init__.py
@@ -27,19 +27,19 @@ If you want to have a more secure implementation, use the functions from the
"""
-__author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly"
-__date__ = "2016-01-13"
-__version__ = '3.3'
-
from rsa.key import newkeys, PrivateKey, PublicKey
from rsa.pkcs1 import encrypt, decrypt, sign, verify, DecryptionError, \
VerificationError
+__author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly"
+__date__ = "2016-01-13"
+__version__ = '3.3'
+
# Do doctest if we're run directly
if __name__ == "__main__":
import doctest
+
doctest.testmod()
__all__ = ["newkeys", "encrypt", "decrypt", "sign", "verify", 'PublicKey',
- 'PrivateKey', 'DecryptionError', 'VerificationError']
-
+ 'PrivateKey', 'DecryptionError', 'VerificationError']
diff --git a/rsa/_compat.py b/rsa/_compat.py
index 3c4eb81..c654770 100644
--- a/rsa/_compat.py
+++ b/rsa/_compat.py
@@ -16,7 +16,6 @@
"""Python compatibility wrappers."""
-
from __future__ import absolute_import
import sys
@@ -42,7 +41,6 @@ else:
# Else we just assume 64-bit processor keeping up with modern times.
MACHINE_WORD_SIZE = 64
-
try:
# < Python3
unicode_type = unicode
@@ -75,7 +73,6 @@ except NameError:
# Python 2.5
bytes_type = str
-
# To avoid calling b() multiple times in tight loops.
ZERO_BYTE = b('\x00')
EMPTY_BYTE = b('')
diff --git a/rsa/asn1.py b/rsa/asn1.py
index 6eb6da5..b757450 100644
--- a/rsa/asn1.py
+++ b/rsa/asn1.py
@@ -14,38 +14,40 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''ASN.1 definitions.
+"""ASN.1 definitions.
Not all ASN.1-handling code use these definitions, but when it does, they should be here.
-'''
+"""
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))),
)
class AsnPubKey(univ.Sequence):
- '''ASN.1 contents of DER encoded public key:
-
+ """ASN.1 contents of DER encoded public key:
+
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER, -- e
- '''
+ """
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/bigfile.py b/rsa/bigfile.py
index 516cf56..c2c2234 100644
--- a/rsa/bigfile.py
+++ b/rsa/bigfile.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Large file support
+"""Large file support
- break a file into smaller blocks, and encrypt them, and store the
encrypted blocks in another file.
@@ -37,25 +37,26 @@ The encrypted file format is as follows, where || denotes byte concatenation:
This file format is called the VARBLOCK format, in line with the varint format
used to denote the block sizes.
-'''
+"""
from rsa import key, common, pkcs1, varblock
from rsa._compat import byte
+
def encrypt_bigfile(infile, outfile, pub_key):
- '''Encrypts a file, writing it to 'outfile' in VARBLOCK format.
-
+ """Encrypts a file, writing it to 'outfile' in VARBLOCK format.
+
:param infile: file-like object to read the cleartext from
:param outfile: file-like object to write the crypto in VARBLOCK format to
:param pub_key: :py:class:`rsa.PublicKey` to encrypt with
- '''
+ """
if not isinstance(pub_key, key.PublicKey):
raise TypeError('Public key required, but got %r' % pub_key)
key_bytes = common.bit_size(pub_key.n) // 8
- blocksize = key_bytes - 11 # keep space for PKCS#1 padding
+ blocksize = key_bytes - 11 # keep space for PKCS#1 padding
# Write the version number to the VARBLOCK file
outfile.write(byte(varblock.VARBLOCK_VERSION))
@@ -67,21 +68,22 @@ def encrypt_bigfile(infile, outfile, pub_key):
varblock.write_varint(outfile, len(crypto))
outfile.write(crypto)
+
def decrypt_bigfile(infile, outfile, priv_key):
- '''Decrypts an encrypted VARBLOCK file, writing it to 'outfile'
-
+ """Decrypts an encrypted VARBLOCK file, writing it to 'outfile'
+
:param infile: file-like object to read the crypto in VARBLOCK format from
:param outfile: file-like object to write the cleartext to
:param priv_key: :py:class:`rsa.PrivateKey` to decrypt with
- '''
+ """
if not isinstance(priv_key, key.PrivateKey):
raise TypeError('Private key required, but got %r' % priv_key)
-
+
for block in varblock.yield_varblocks(infile):
cleartext = pkcs1.decrypt(block, priv_key)
outfile.write(cleartext)
-__all__ = ['encrypt_bigfile', 'decrypt_bigfile']
+__all__ = ['encrypt_bigfile', 'decrypt_bigfile']
diff --git a/rsa/cli.py b/rsa/cli.py
index 527cc49..566195e 100644
--- a/rsa/cli.py
+++ b/rsa/cli.py
@@ -14,10 +14,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Commandline scripts.
+"""Commandline scripts.
These scripts are called by the executables defined in setup.py.
-'''
+"""
from __future__ import with_statement, print_function
@@ -31,32 +31,33 @@ import rsa.pkcs1
HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
+
def keygen():
- '''Key generator.'''
+ """Key generator."""
# Parse the CLI options
parser = OptionParser(usage='usage: %prog [options] keysize',
- description='Generates a new RSA keypair of "keysize" bits.')
-
+ 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.')
-
+ 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.')
+ 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')
+ 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:])
if len(cli_args) != 1:
parser.print_help()
raise SystemExit(1)
-
+
try:
keysize = int(cli_args[0])
except ValueError:
@@ -67,7 +68,6 @@ def keygen():
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)
@@ -77,7 +77,7 @@ def keygen():
# 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:
@@ -88,20 +88,20 @@ def keygen():
class CryptoOperation(object):
- '''CLI callable that operates with input, output, and a key.'''
+ """CLI callable that operates with input, output, and a key."""
__metaclass__ = abc.ABCMeta
- keyname = 'public' # or 'private'
+ keyname = 'public' # or 'private'
usage = 'usage: %%prog [options] %(keyname)s_key'
description = None
operation = 'decrypt'
operation_past = 'decrypted'
operation_progressive = 'decrypting'
input_help = 'Name of the file to %(operation)s. Reads from stdin if ' \
- 'not specified.'
+ '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.'
+ 'to. Written to stdout if this option is not present.'
expected_cli_args = 1
has_output = True
@@ -114,15 +114,15 @@ class CryptoOperation(object):
@abc.abstractmethod
def perform_operation(self, indata, key, cli_args=None):
- '''Performs the program's operation.
+ """Performs the program's operation.
Implement in a subclass.
:returns: the data to write to the output.
- '''
+ """
def __call__(self):
- '''Runs the program.'''
+ """Runs the program."""
(cli, cli_args) = self.parse_cli()
@@ -137,21 +137,21 @@ class CryptoOperation(object):
self.write_outfile(outdata, cli.output)
def parse_cli(self):
- '''Parse the CLI options
-
+ """Parse the CLI options
+
:returns: (cli_opts, cli_args)
- '''
+ """
parser = OptionParser(usage=self.usage, description=self.description)
-
+
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('--keyform',
- help='Key format of the %s key - default PEM' % self.keyname,
- choices=('PEM', 'DER'), default='PEM')
+ 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:])
@@ -159,19 +159,19 @@ class CryptoOperation(object):
parser.print_help()
raise SystemExit(1)
- return (cli, cli_args)
+ return cli, cli_args
def read_key(self, filename, keyform):
- '''Reads a public or private key.'''
+ """Reads a public or private key."""
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)
-
+
def read_infile(self, inname):
- '''Read the input file'''
+ """Read the input file"""
if inname:
print('Reading input from %s' % inname, file=sys.stderr)
@@ -182,7 +182,7 @@ class CryptoOperation(object):
return sys.stdin.read()
def write_outfile(self, outdata, outname):
- '''Write the output file'''
+ """Write the output file"""
if outname:
print('Writing output to %s' % outname, file=sys.stderr)
@@ -192,47 +192,49 @@ class CryptoOperation(object):
print('Writing output to stdout', file=sys.stderr)
sys.stdout.write(outdata)
+
class EncryptOperation(CryptoOperation):
- '''Encrypts a file.'''
+ """Encrypts a file."""
keyname = 'public'
description = ('Encrypts a file. The file must be shorter than the key '
- 'length in order to be encrypted. For larger files, use the '
- 'pyrsa-encrypt-bigfile command.')
+ 'length in order to be encrypted. For larger files, use the '
+ 'pyrsa-encrypt-bigfile command.')
operation = 'encrypt'
operation_past = 'encrypted'
operation_progressive = 'encrypting'
-
def perform_operation(self, indata, pub_key, cli_args=None):
- '''Encrypts files.'''
+ """Encrypts files."""
return rsa.encrypt(indata, pub_key)
+
class DecryptOperation(CryptoOperation):
- '''Decrypts a file.'''
+ """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. For larger '
- 'files, use the pyrsa-decrypt-bigfile command.')
+ 'the key length in order to have been encrypted. For larger '
+ 'files, use the pyrsa-decrypt-bigfile command.')
operation = 'decrypt'
operation_past = 'decrypted'
operation_progressive = 'decrypting'
key_class = rsa.PrivateKey
def perform_operation(self, indata, priv_key, cli_args=None):
- '''Decrypts files.'''
+ """Decrypts files."""
return rsa.decrypt(indata, priv_key)
+
class SignOperation(CryptoOperation):
- '''Signs a file.'''
+ """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))
+ 'method from %s' % ', '.join(HASH_METHODS))
operation = 'sign'
operation_past = 'signature'
operation_progressive = 'Signing'
@@ -240,25 +242,26 @@ class SignOperation(CryptoOperation):
expected_cli_args = 2
output_help = ('Name of the file to write the signature to. Written '
- 'to stdout if this option is not present.')
+ 'to stdout if this option is not present.')
def perform_operation(self, indata, priv_key, cli_args):
- '''Decrypts files.'''
+ """Signs files."""
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)
+
class VerifyOperation(CryptoOperation):
- '''Verify a signature.'''
+ """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.')
+ 'prints an error message and exits with status 1 upon error.')
operation = 'verify'
operation_past = 'verified'
operation_progressive = 'Verifying'
@@ -267,10 +270,10 @@ class VerifyOperation(CryptoOperation):
has_output = False
def perform_operation(self, indata, pub_key, cli_args):
- '''Decrypts files.'''
+ """Verifies files."""
signature_file = cli_args[1]
-
+
with open(signature_file, 'rb') as sigfile:
signature = sigfile.read()
@@ -283,7 +286,7 @@ class VerifyOperation(CryptoOperation):
class BigfileOperation(CryptoOperation):
- '''CryptoOperation that doesn't read the entire file into memory.'''
+ """CryptoOperation that doesn't read the entire file into memory."""
def __init__(self):
CryptoOperation.__init__(self)
@@ -291,13 +294,13 @@ class BigfileOperation(CryptoOperation):
self.file_objects = []
def __del__(self):
- '''Closes any open file handles.'''
+ """Closes any open file handles."""
for fobj in self.file_objects:
fobj.close()
def __call__(self):
- '''Runs the program.'''
+ """Runs the program."""
(cli, cli_args) = self.parse_cli()
@@ -312,7 +315,7 @@ class BigfileOperation(CryptoOperation):
self.perform_operation(infile, outfile, key, cli_args)
def get_infile(self, inname):
- '''Returns the input file object'''
+ """Returns the input file object"""
if inname:
print('Reading input from %s' % inname, file=sys.stderr)
@@ -325,7 +328,7 @@ class BigfileOperation(CryptoOperation):
return fobj
def get_outfile(self, outname):
- '''Returns the output file object'''
+ """Returns the output file object"""
if outname:
print('Will write output to %s' % outname, file=sys.stderr)
@@ -337,35 +340,37 @@ class BigfileOperation(CryptoOperation):
return fobj
+
class EncryptBigfileOperation(BigfileOperation):
- '''Encrypts a file to VARBLOCK format.'''
+ """Encrypts a file to VARBLOCK format."""
keyname = 'public'
description = ('Encrypts a file to an encrypted VARBLOCK file. The file '
- 'can be larger than the key length, but the output file is only '
- 'compatible with Python-RSA.')
+ 'can be larger than the key length, but the output file is only '
+ 'compatible with Python-RSA.')
operation = 'encrypt'
operation_past = 'encrypted'
operation_progressive = 'encrypting'
def perform_operation(self, infile, outfile, pub_key, cli_args=None):
- '''Encrypts files to VARBLOCK.'''
+ """Encrypts files to VARBLOCK."""
return rsa.bigfile.encrypt_bigfile(infile, outfile, pub_key)
+
class DecryptBigfileOperation(BigfileOperation):
- '''Decrypts a file in VARBLOCK format.'''
+ """Decrypts a file in VARBLOCK format."""
keyname = 'private'
description = ('Decrypts an encrypted VARBLOCK file that was encrypted '
- 'with pyrsa-encrypt-bigfile')
+ 'with pyrsa-encrypt-bigfile')
operation = 'decrypt'
operation_past = 'decrypted'
operation_progressive = 'decrypting'
key_class = rsa.PrivateKey
def perform_operation(self, infile, outfile, priv_key, cli_args=None):
- '''Decrypts a VARBLOCK file.'''
+ """Decrypts a VARBLOCK file."""
return rsa.bigfile.decrypt_bigfile(infile, outfile, priv_key)
@@ -376,4 +381,3 @@ sign = SignOperation()
verify = VerifyOperation()
encrypt_bigfile = EncryptBigfileOperation()
decrypt_bigfile = DecryptBigfileOperation()
-
diff --git a/rsa/common.py b/rsa/common.py
index 39feb8c..bdbc90a 100644
--- a/rsa/common.py
+++ b/rsa/common.py
@@ -14,11 +14,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Common functionality shared by several modules.'''
+"""Common functionality shared by several modules."""
def bit_size(num):
- '''
+ """
Number of bits needed to represent a integer excluding any prefix
0 bits.
@@ -26,7 +26,7 @@ def bit_size(num):
to match the behavior of the Python 3 API.
Usage::
-
+
>>> bit_size(1023)
10
>>> bit_size(1024)
@@ -40,7 +40,7 @@ def bit_size(num):
before the number's bit length is determined.
:returns:
Returns the number of bits in the integer.
- '''
+ """
if num == 0:
return 0
if num < 0:
@@ -51,23 +51,23 @@ def bit_size(num):
hex_num = "%x" % num
return ((len(hex_num) - 1) * 4) + {
- '0':0, '1':1, '2':2, '3':2,
- '4':3, '5':3, '6':3, '7':3,
- '8':4, '9':4, 'a':4, 'b':4,
- 'c':4, 'd':4, 'e':4, 'f':4,
- }[hex_num[0]]
+ '0': 0, '1': 1, '2': 2, '3': 2,
+ '4': 3, '5': 3, '6': 3, '7': 3,
+ '8': 4, '9': 4, 'a': 4, 'b': 4,
+ 'c': 4, 'd': 4, 'e': 4, 'f': 4,
+ }[hex_num[0]]
def _bit_size(number):
- '''
+ """
Returns the number of bits required to hold a specific long number.
- '''
+ """
if number < 0:
raise ValueError('Only nonnegative numbers possible: %s' % number)
if number == 0:
return 0
-
+
# This works, even with very large numbers. When using math.log(number, 2),
# you'll get rounding errors and it'll fail.
bits = 0
@@ -79,9 +79,9 @@ def _bit_size(number):
def byte_size(number):
- '''
+ """
Returns the number of bytes required to hold a specific long number.
-
+
The number of bytes is rounded up.
Usage::
@@ -97,17 +97,17 @@ def byte_size(number):
An unsigned integer
:returns:
The number of bytes required to hold a specific long number.
- '''
+ """
quanta, mod = divmod(bit_size(number), 8)
if mod or number == 0:
quanta += 1
return quanta
- #return int(math.ceil(bit_size(number) / 8.0))
+ # return int(math.ceil(bit_size(number) / 8.0))
def extended_gcd(a, b):
- '''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
@@ -116,26 +116,28 @@ def extended_gcd(a, b):
y = 1
lx = 1
ly = 0
- oa = a #Remember original a/b to remove
- ob = b #negative values from return results
+ oa = a # Remember original a/b to remove
+ ob = b # negative values from return results
while b != 0:
q = a // b
- (a, b) = (b, a % b)
- (x, lx) = ((lx - (q * x)),x)
- (y, ly) = ((ly - (q * y)),y)
- if (lx < 0): lx += ob #If neg wrap modulo orignal b
- if (ly < 0): ly += oa #If neg wrap modulo orignal a
- return (a, lx, ly) #Return only positive values
+ (a, b) = (b, a % b)
+ (x, lx) = ((lx - (q * x)), x)
+ (y, ly) = ((ly - (q * y)), y)
+ if lx < 0:
+ lx += ob # If neg wrap modulo orignal b
+ if ly < 0:
+ ly += oa # If neg wrap modulo orignal a
+ return a, lx, ly # Return only positive values
def inverse(x, n):
- '''Returns x^-1 (mod n)
+ """Returns x^-1 (mod n)
>>> inverse(7, 4)
3
>>> (inverse(143, 4) * 143) % 4
1
- '''
+ """
(divider, inv, _) = extended_gcd(x, n)
@@ -146,14 +148,14 @@ def inverse(x, n):
def crt(a_values, modulo_values):
- '''Chinese Remainder Theorem.
+ """Chinese Remainder Theorem.
Calculates x such that x = a[i] (mod m[i]) for each i.
:param a_values: the a-values of the above equation
:param modulo_values: the m-values of the above equation
:returns: x such that x = a[i] (mod m[i]) for each i
-
+
>>> crt([2, 3], [3, 5])
8
@@ -163,10 +165,10 @@ def crt(a_values, modulo_values):
>>> crt([2, 3, 0], [7, 11, 15])
135
- '''
+ """
m = 1
- x = 0
+ x = 0
for modulo in modulo_values:
m *= modulo
@@ -179,7 +181,8 @@ def crt(a_values, modulo_values):
return x
+
if __name__ == '__main__':
import doctest
- doctest.testmod()
+ doctest.testmod()
diff --git a/rsa/core.py b/rsa/core.py
index 90dfee8..9b5c107 100644
--- a/rsa/core.py
+++ b/rsa/core.py
@@ -14,24 +14,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Core mathematical operations.
+"""Core mathematical operations.
This is the actual core RSA implementation, which is only defined
mathematically on integers.
-'''
-
+"""
from rsa._compat import is_integer
-def assert_int(var, name):
+def assert_int(var, name):
if is_integer(var):
return
raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
+
def encrypt_int(message, ekey, n):
- '''Encrypts a message using encryption key 'ekey', working modulo n'''
+ """Encrypts a message using encryption key 'ekey', working modulo n"""
assert_int(message, 'message')
assert_int(ekey, 'ekey')
@@ -39,15 +39,15 @@ def encrypt_int(message, ekey, n):
if message < 0:
raise ValueError('Only non-negative numbers are supported')
-
+
if message > n:
raise OverflowError("The message %i is too long for n=%i" % (message, n))
return pow(message, ekey, n)
+
def decrypt_int(cyphertext, dkey, n):
- '''Decrypts a cypher text using the decryption key 'dkey', working
- modulo n'''
+ """Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
assert_int(cyphertext, 'cyphertext')
assert_int(dkey, 'dkey')
@@ -55,4 +55,3 @@ def decrypt_int(cyphertext, dkey, n):
message = pow(cyphertext, dkey, n)
return message
-
diff --git a/rsa/key.py b/rsa/key.py
index fc2ff84..b659cc9 100644
--- a/rsa/key.py
+++ b/rsa/key.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''RSA key generation code.
+"""RSA key generation code.
Create new keys with the newkeys() function. It will give you a PublicKey and a
PrivateKey object.
@@ -23,7 +23,7 @@ Loading and saving keys requires the pyasn1 module. This module is imported as
late as possible, such that other functionality will remain working in absence
of pyasn1.
-'''
+"""
import logging
from rsa._compat import b, bytes_type
@@ -35,21 +35,19 @@ import rsa.common
log = logging.getLogger(__name__)
-
class AbstractKey(object):
- '''Abstract superclass for private and public keys.'''
+ """Abstract superclass for private and public keys."""
@classmethod
def load_pkcs1(cls, keyfile, format='PEM'):
- r'''Loads a key in PKCS#1 DER or PEM format.
+ """Loads a key in PKCS#1 DER or PEM format.
:param keyfile: contents of a DER- or PEM-encoded file that contains
the public key.
:param format: the format of the file to load; 'PEM' or 'DER'
:return: a PublicKey object
-
- '''
+ """
methods = {
'PEM': cls._load_pkcs1_pem,
@@ -59,18 +57,17 @@ class AbstractKey(object):
if format not in methods:
formats = ', '.join(sorted(methods.keys()))
raise ValueError('Unsupported format: %r, try one of %s' % (format,
- formats))
+ formats))
method = methods[format]
return method(keyfile)
def save_pkcs1(self, format='PEM'):
- '''Saves the public key in PKCS#1 DER or PEM format.
+ """Saves the public key in PKCS#1 DER or PEM format.
:param format: the format to save; 'PEM' or 'DER'
:returns: the DER- or PEM-encoded public key.
-
- '''
+ """
methods = {
'PEM': self._save_pkcs1_pem,
@@ -80,13 +77,14 @@ class AbstractKey(object):
if format not in methods:
formats = ', '.join(sorted(methods.keys()))
raise ValueError('Unsupported format: %r, try one of %s' % (format,
- formats))
+ formats))
method = methods[format]
return method()
+
class PublicKey(AbstractKey):
- '''Represents a public RSA key.
+ """Represents a public RSA key.
This key is also known as the 'encryption key'. It contains the 'n' and 'e'
values.
@@ -107,7 +105,7 @@ class PublicKey(AbstractKey):
>>> key['e']
3
- '''
+ """
__slots__ = ('n', 'e')
@@ -135,7 +133,7 @@ class PublicKey(AbstractKey):
@classmethod
def _load_pkcs1_der(cls, keyfile):
- r'''Loads a key in PKCS#1 DER format.
+ """Loads a key in PKCS#1 DER format.
@param keyfile: contents of a DER-encoded file that contains the public
key.
@@ -152,19 +150,19 @@ class PublicKey(AbstractKey):
>>> PublicKey._load_pkcs1_der(der)
PublicKey(2367317549, 65537)
- '''
+ """
from pyasn1.codec.der import decoder
from rsa.asn1 import AsnPubKey
-
+
(priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey())
return cls(n=int(priv['modulus']), e=int(priv['publicExponent']))
def _save_pkcs1_der(self):
- '''Saves the public key in PKCS#1 DER format.
+ """Saves the public key in PKCS#1 DER format.
@returns: the DER-encoded public key.
- '''
+ """
from pyasn1.codec.der import encoder
from rsa.asn1 import AsnPubKey
@@ -178,7 +176,7 @@ class PublicKey(AbstractKey):
@classmethod
def _load_pkcs1_pem(cls, keyfile):
- '''Loads a PKCS#1 PEM-encoded public key file.
+ """Loads a PKCS#1 PEM-encoded public key file.
The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and
after the "-----END RSA PUBLIC KEY-----" lines is ignored.
@@ -186,63 +184,61 @@ class PublicKey(AbstractKey):
@param keyfile: contents of a PEM-encoded file that contains the public
key.
@return: a PublicKey object
- '''
+ """
der = rsa.pem.load_pem(keyfile, 'RSA PUBLIC KEY')
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self):
- '''Saves a PKCS#1 PEM-encoded public key file.
+ """Saves a PKCS#1 PEM-encoded public key file.
@return: contents of a PEM-encoded file that contains the public key.
- '''
+ """
der = self._save_pkcs1_der()
return rsa.pem.save_pem(der, 'RSA PUBLIC KEY')
@classmethod
def load_pkcs1_openssl_pem(cls, keyfile):
- '''Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.
-
+ """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
rather than BEGIN RSA PUBLIC KEY.
-
+
The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
after the "-----END PUBLIC KEY-----" lines is ignored.
@param keyfile: contents of a PEM-encoded file that contains the public
key, from OpenSSL.
@return: a PublicKey object
- '''
+ """
der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
return cls.load_pkcs1_openssl_der(der)
@classmethod
def load_pkcs1_openssl_der(cls, keyfile):
- '''Loads a PKCS#1 DER-encoded public key file from OpenSSL.
+ """Loads a PKCS#1 DER-encoded public key file from OpenSSL.
@param keyfile: contents of a DER-encoded file that contains the public
key, from OpenSSL.
@return: a PublicKey object
- '''
-
+ """
+
from rsa.asn1 import OpenSSLPubKey
from pyasn1.codec.der import decoder
from pyasn1.type import univ
-
+
(keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey())
-
+
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:])
-
-
class PrivateKey(AbstractKey):
- '''Represents a private RSA key.
+ """Represents a private RSA key.
This key is also known as the 'decryption key'. It contains the 'n', 'e',
'd', 'p', 'q' and other values.
@@ -273,7 +269,7 @@ class PrivateKey(AbstractKey):
>>> pk.coef
8
- '''
+ """
__slots__ = ('n', 'e', 'd', 'p', 'q', 'exp1', 'exp2', 'coef')
@@ -314,20 +310,20 @@ class PrivateKey(AbstractKey):
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)
+ 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):
return not (self == other)
@classmethod
def _load_pkcs1_der(cls, keyfile):
- r'''Loads a key in PKCS#1 DER format.
+ """Loads a key in PKCS#1 DER format.
@param keyfile: contents of a DER-encoded file that contains the private
key.
@@ -344,7 +340,7 @@ class PrivateKey(AbstractKey):
>>> PrivateKey._load_pkcs1_der(der)
PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
- '''
+ """
from pyasn1.codec.der import decoder
(priv, _) = decoder.decode(keyfile)
@@ -371,25 +367,25 @@ class PrivateKey(AbstractKey):
return cls(*as_ints)
def _save_pkcs1_der(self):
- '''Saves the private key in PKCS#1 DER format.
+ """Saves the private key in PKCS#1 DER format.
@returns: the DER-encoded private key.
- '''
+ """
from pyasn1.type import univ, namedtype
from pyasn1.codec.der import encoder
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
@@ -408,7 +404,7 @@ class PrivateKey(AbstractKey):
@classmethod
def _load_pkcs1_pem(cls, keyfile):
- '''Loads a PKCS#1 PEM-encoded private key file.
+ """Loads a PKCS#1 PEM-encoded private key file.
The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and
after the "-----END RSA PRIVATE KEY-----" lines is ignored.
@@ -416,23 +412,24 @@ class PrivateKey(AbstractKey):
@param keyfile: contents of a PEM-encoded file that contains the private
key.
@return: a PrivateKey object
- '''
+ """
der = rsa.pem.load_pem(keyfile, b('RSA PRIVATE KEY'))
return cls._load_pkcs1_der(der)
def _save_pkcs1_pem(self):
- '''Saves a PKCS#1 PEM-encoded private key file.
+ """Saves a PKCS#1 PEM-encoded private key file.
@return: contents of a PEM-encoded file that contains the private key.
- '''
+ """
der = self._save_pkcs1_der()
return rsa.pem.save_pem(der, b('RSA PRIVATE KEY'))
+
def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
- ''''Returns a tuple of two different primes of nbits bits each.
-
+ """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
will not be equal.
@@ -458,9 +455,9 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
True
>>> common.bit_size(p * q) > 240
True
-
- '''
-
+
+ """
+
total_bits = nbits * 2
# Make sure that p and q aren't too close or the factoring programs can
@@ -468,7 +465,7 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
shift = nbits // 16
pbits = nbits + shift
qbits = nbits - shift
-
+
# Choose the two initial primes
log.debug('find_p_q(%i): Finding p', nbits)
p = getprime_func(pbits)
@@ -476,11 +473,11 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
q = getprime_func(qbits)
def is_acceptable(p, q):
- '''Returns True iff p and q are acceptable:
-
+ """Returns True iff p and q are acceptable:
+
- p and q differ
- (p * q) has the right nr of bits (when accurate=True)
- '''
+ """
if p == q:
return False
@@ -505,13 +502,14 @@ def find_p_q(nbits, getprime_func=rsa.prime.getprime, accurate=True):
# We want p > q as described on
# http://www.di-mgt.com.au/rsa_alg.html#crt
- return (max(p, q), min(p, q))
+ return max(p, q), min(p, q)
+
def calculate_keys(p, q, nbits):
- '''Calculates an encryption and a decryption key given p and q, and
+ """Calculates an encryption and a decryption key given p and q, and
returns them as a tuple (e, d)
- '''
+ """
phi_n = (p - 1) * (q - 1)
@@ -522,17 +520,17 @@ def calculate_keys(p, q, nbits):
d = rsa.common.inverse(e, phi_n)
except ValueError:
raise ValueError("e (%d) and phi_n (%d) are not relatively prime" %
- (e, phi_n))
+ (e, phi_n))
if (e * d) % phi_n != 1:
raise ValueError("e (%d) and d (%d) are not mult. inv. modulo "
- "phi_n (%d)" % (e, d, phi_n))
+ "phi_n (%d)" % (e, d, phi_n))
- return (e, d)
+ return e, d
def gen_keys(nbits, getprime_func, accurate=True):
- '''Generate RSA keys of nbits bits. Returns (p, q, e, d).
+ """Generate RSA keys of nbits bits. Returns (p, q, e, d).
Note: this can take a long time, depending on the key size.
@@ -540,7 +538,7 @@ def gen_keys(nbits, getprime_func, accurate=True):
``q`` will use ``nbits/2`` bits.
:param getprime_func: either :py:func:`rsa.prime.getprime` or a function
with similar signature.
- '''
+ """
# Regenerate p and q values, until calculate_keys doesn't raise a
# ValueError.
@@ -552,11 +550,11 @@ def gen_keys(nbits, getprime_func, accurate=True):
except ValueError:
pass
- return (p, q, e, d)
+ return p, q, e, d
def newkeys(nbits, accurate=True, poolsize=1):
- '''Generates public and private keys, and returns them as (pub, priv).
+ """Generates public and private keys, and returns them as (pub, priv).
The public key is also known as the 'encryption key', and is a
:py:class:`rsa.PublicKey` object. The private key is also known as the
@@ -574,8 +572,8 @@ def newkeys(nbits, accurate=True, poolsize=1):
The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires
Python 2.6 or newer.
-
- '''
+
+ """
if nbits < 16:
raise ValueError('Key too small')
@@ -594,7 +592,7 @@ def newkeys(nbits, accurate=True, poolsize=1):
# Generate the key components
(p, q, e, d) = gen_keys(nbits, getprime_func, accurate=accurate)
-
+
# Create the key objects
n = p * q
@@ -603,11 +601,12 @@ def newkeys(nbits, accurate=True, poolsize=1):
PrivateKey(n, e, d, p, q)
)
+
__all__ = ['PublicKey', 'PrivateKey', 'newkeys']
if __name__ == '__main__':
import doctest
-
+
try:
for count in range(100):
(failures, tests) = doctest.testmod()
diff --git a/rsa/parallel.py b/rsa/parallel.py
index 17a10ed..36c06ba 100644
--- a/rsa/parallel.py
+++ b/rsa/parallel.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for parallel computation on multiple cores.
+"""Functions for parallel computation on multiple cores.
Introduced in Python-RSA 3.1.
@@ -22,7 +22,7 @@ Introduced in Python-RSA 3.1.
Requires Python 2.6 or newer.
-'''
+"""
from __future__ import print_function
@@ -31,6 +31,7 @@ import multiprocessing as mp
import rsa.prime
import rsa.randnum
+
def _find_prime(nbits, pipe):
while True:
integer = rsa.randnum.read_random_int(nbits)
@@ -43,8 +44,9 @@ def _find_prime(nbits, pipe):
pipe.send(integer)
return
+
def getprime(nbits, poolsize):
- '''Returns a prime number that can be stored in 'nbits' bits.
+ """Returns a prime number that can be stored in 'nbits' bits.
Works in multiple threads at the same time.
@@ -55,12 +57,12 @@ def getprime(nbits, poolsize):
True
>>> rsa.prime.is_prime(p+1)
False
-
+
>>> from rsa import common
>>> common.bit_size(p) == 128
True
-
- '''
+
+ """
(pipe_recv, pipe_send) = mp.Pipe(duplex=False)
@@ -79,20 +81,19 @@ def getprime(nbits, poolsize):
return result
+
__all__ = ['getprime']
-
if __name__ == '__main__':
print('Running doctests 1000x or until failure')
import doctest
-
+
for count in range(100):
(failures, tests) = doctest.testmod()
if failures:
break
-
+
if count and count % 10 == 0:
print('%i times' % count)
-
- print('Doctests done')
+ print('Doctests done')
diff --git a/rsa/pem.py b/rsa/pem.py
index 0117ad1..fbf3642 100644
--- a/rsa/pem.py
+++ b/rsa/pem.py
@@ -14,15 +14,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions that load and write PEM-encoded files.'''
+"""Functions that load and write PEM-encoded files."""
import base64
from rsa._compat import b, is_bytes
+
def _markers(pem_marker):
- '''
+ """
Returns the start and end PEM markers
- '''
+ """
if is_bytes(pem_marker):
pem_marker = pem_marker.decode('utf-8')
@@ -30,8 +31,9 @@ def _markers(pem_marker):
return (b('-----BEGIN %s-----' % pem_marker),
b('-----END %s-----' % pem_marker))
+
def load_pem(contents, pem_marker):
- '''Loads a PEM file.
+ """Loads a PEM file.
@param contents: the contents of the file to interpret
@param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
@@ -43,7 +45,7 @@ def load_pem(contents, pem_marker):
@raise ValueError: when the content is invalid, for example when the start
marker cannot be found.
- '''
+ """
(pem_start, pem_end) = _markers(pem_marker)
@@ -93,7 +95,7 @@ def load_pem(contents, pem_marker):
def save_pem(contents, pem_marker):
- '''Saves a PEM file.
+ """Saves a PEM file.
@param contents: the contents to encode in PEM format
@param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
@@ -102,13 +104,13 @@ def save_pem(contents, pem_marker):
@return the base64-encoded content between the start and end markers.
- '''
+ """
(pem_start, pem_end) = _markers(pem_marker)
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]
pem_lines.append(block)
@@ -117,4 +119,3 @@ def save_pem(contents, pem_marker):
pem_lines.append(b(''))
return b('\n').join(pem_lines)
-
diff --git a/rsa/pkcs1.py b/rsa/pkcs1.py
index 0e51928..18a80c9 100644
--- a/rsa/pkcs1.py
+++ b/rsa/pkcs1.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for PKCS#1 version 1.5 encryption and signing
+"""Functions for PKCS#1 version 1.5 encryption and signing
This module implements certain functionality from PKCS#1 version 1.5. For a
very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
@@ -26,7 +26,7 @@ WARNING: this module leaks information when decryption fails. The exceptions
that are raised contain the Python traceback information, which can be used to
deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION
to your users.
-'''
+"""
import hashlib
import os
@@ -51,20 +51,24 @@ HASH_METHODS = {
'SHA-512': hashlib.sha512,
}
+
class CryptoError(Exception):
- '''Base class for all exceptions in this module.'''
+ """Base class for all exceptions in this module."""
+
class DecryptionError(CryptoError):
- '''Raised when decryption fails.'''
+ """Raised when decryption fails."""
+
class VerificationError(CryptoError):
- '''Raised when verification fails.'''
-
+ """Raised when verification fails."""
+
+
def _pad_for_encryption(message, target_length):
- r'''Pads the message for encryption, returning the padded message.
-
+ """Pads the message for encryption, returning the padded message.
+
:return: 00 02 RANDOM_DATA 00 MESSAGE
-
+
>>> block = _pad_for_encryption('hello', 16)
>>> len(block)
16
@@ -73,46 +77,46 @@ def _pad_for_encryption(message, target_length):
>>> block[-6:]
'\x00hello'
- '''
+ """
max_msglength = target_length - 11
msglength = len(message)
-
+
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
-
+ ' space for %i' % (msglength, max_msglength))
+
# Get random padding
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,
# so keep adding data until we're at the correct length.
while len(padding) < padding_length:
needed_bytes = padding_length - len(padding)
-
+
# Always read at least 8 bytes more than we need, and trim off the rest
# 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(''))
padding = padding + new_padding[:needed_bytes]
-
+
assert len(padding) == padding_length
-
+
return b('').join([b('\x00\x02'),
- padding,
- b('\x00'),
- message])
-
+ padding,
+ b('\x00'),
+ message])
+
def _pad_for_signing(message, target_length):
- r'''Pads the message for signing, returning the padded message.
-
+ """Pads the message for signing, returning the padded message.
+
The padding is always a repetition of FF bytes.
-
+
:return: 00 01 PADDING 00 MESSAGE
-
+
>>> block = _pad_for_signing('hello', 16)
>>> len(block)
16
@@ -122,62 +126,63 @@ def _pad_for_signing(message, target_length):
'\x00hello'
>>> block[2:-6]
'\xff\xff\xff\xff\xff\xff\xff\xff'
-
- '''
+
+ """
max_msglength = target_length - 11
msglength = len(message)
-
+
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
- ' space for %i' % (msglength, max_msglength))
-
+ ' 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])
-
-
+ padding_length * b('\xff'),
+ b('\x00'),
+ message])
+
+
def encrypt(message, pub_key):
- '''Encrypts the given message using PKCS#1 v1.5
-
+ """Encrypts the given message using PKCS#1 v1.5
+
:param message: the message to encrypt. Must be a byte string no longer than
``k-11`` bytes, where ``k`` is the number of bytes needed to encode
the ``n`` component of the public key.
:param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
:raise OverflowError: when the message is too large to fit in the padded
block.
-
+
>>> from rsa import key, common
>>> (pub_key, priv_key) = key.newkeys(256)
>>> message = 'hello'
>>> crypto = encrypt(message, pub_key)
-
+
The crypto text should be just as long as the public key 'n' component:
>>> len(crypto) == common.byte_size(pub_key.n)
True
-
- '''
-
+
+ """
+
keylength = common.byte_size(pub_key.n)
padded = _pad_for_encryption(message, keylength)
-
+
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
block = transform.int2bytes(encrypted, keylength)
-
+
return block
+
def decrypt(crypto, priv_key):
- r'''Decrypts the given message using PKCS#1 v1.5
-
+ """Decrypts the given message using PKCS#1 v1.5
+
The decryption is considered 'failed' when the resulting cleartext doesn't
start with the bytes 00 02, or when the 00 byte between the padding and
the message cannot be found.
-
+
:param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
:param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
:raise DecryptionError: when the decryption fails. No details are given as
@@ -193,7 +198,7 @@ def decrypt(crypto, priv_key):
>>> crypto = encrypt('hello', pub_key)
>>> decrypt(crypto, priv_key)
'hello'
-
+
And with binary data:
>>> crypto = encrypt('\x00\x00\x00\x00\x01', pub_key)
@@ -220,8 +225,8 @@ def decrypt(crypto, priv_key):
...
DecryptionError: Decryption failed
- '''
-
+ """
+
blocksize = common.byte_size(priv_key.n)
encrypted = transform.bytes2int(crypto)
decrypted = core.decrypt_int(encrypted, priv_key.d, priv_key.n)
@@ -230,21 +235,22 @@ def decrypt(crypto, priv_key):
# If we can't find the cleartext marker, decryption failed.
if cleartext[0:2] != b('\x00\x02'):
raise DecryptionError('Decryption failed')
-
+
# Find the 00 separator between the padding and the message
try:
sep_idx = cleartext.index(b('\x00'), 2)
except ValueError:
raise DecryptionError('Decryption failed')
-
- return cleartext[sep_idx+1:]
-
+
+ return cleartext[sep_idx + 1:]
+
+
def sign(message, priv_key, hash):
- '''Signs the message with the private key.
+ """Signs the message with the private key.
Hashes the message, then signs the hash with the given key. This is known
as a "detached signature", because the message itself isn't altered.
-
+
:param message: the message to sign. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
@@ -255,13 +261,13 @@ def sign(message, priv_key, hash):
:raise OverflowError: if the private key is too small to contain the
requested hash.
- '''
+ """
# Get the ASN1 code for this hash method
if hash not in HASH_ASN1:
raise ValueError('Invalid hash method: %s' % hash)
asn1code = HASH_ASN1[hash]
-
+
# Calculate the hash
hash = _hash(message, hash)
@@ -269,18 +275,19 @@ def sign(message, priv_key, hash):
cleartext = asn1code + hash
keylength = common.byte_size(priv_key.n)
padded = _pad_for_signing(cleartext, keylength)
-
+
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, priv_key.d, priv_key.n)
block = transform.int2bytes(encrypted, keylength)
-
+
return block
+
def verify(message, signature, pub_key):
- '''Verifies that the signature matches the message.
-
+ """Verifies that the signature matches the message.
+
The hash method is detected automatically from the signature.
-
+
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
@@ -288,13 +295,13 @@ def verify(message, signature, pub_key):
:param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
:raise VerificationError: when the signature doesn't match the message.
- '''
-
+ """
+
keylength = common.byte_size(pub_key.n)
encrypted = transform.bytes2int(signature)
decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
clearsig = transform.int2bytes(decrypted, keylength)
-
+
# Get the hash method
method_name = _find_method_hash(clearsig)
message_hash = _hash(message, method_name)
@@ -309,20 +316,21 @@ def verify(message, signature, pub_key):
return True
+
def _hash(message, method_name):
- '''Returns the message digest.
-
+ """Returns the message digest.
+
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
:param method_name: the hash method, must be a key of
:py:const:`HASH_METHODS`.
-
- '''
+
+ """
if method_name not in HASH_METHODS:
raise ValueError('Invalid hash method: %s' % method_name)
-
+
method = HASH_METHODS[method_name]
hasher = method()
@@ -338,20 +346,17 @@ def _hash(message, method_name):
def _find_method_hash(clearsig):
- '''Finds the hash method.
-
+ """Finds the hash method.
+
:param clearsig: full padded ASN1 and hash.
-
:return: the used hash method.
-
:raise VerificationFailed: when the hash method cannot be found
-
- '''
+ """
for (hashname, asn1code) in HASH_ASN1.items():
if asn1code in clearsig:
return hashname
-
+
raise VerificationError('Verification failed')
@@ -361,13 +366,13 @@ __all__ = ['encrypt', 'decrypt', 'sign', 'verify',
if __name__ == '__main__':
print('Running doctests 1000x or until failure')
import doctest
-
+
for count in range(1000):
(failures, tests) = doctest.testmod()
if failures:
break
-
+
if count and count % 100 == 0:
print('%i times' % count)
-
+
print('Doctests done')
diff --git a/rsa/prime.py b/rsa/prime.py
index 2e23a2d..4763d16 100644
--- a/rsa/prime.py
+++ b/rsa/prime.py
@@ -14,23 +14,23 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Numerical functions related to primes.
+"""Numerical functions related to primes.
Implementation based on the book Algorithm Design by Michael T. Goodrich and
Roberto Tamassia, 2002.
-'''
+"""
-__all__ = [ 'getprime', 'are_relatively_prime']
+__all__ = ['getprime', 'are_relatively_prime']
import rsa.randnum
def gcd(p, q):
- '''Returns the greatest common divisor of p and q
+ """Returns the greatest common divisor of p and q
>>> gcd(48, 180)
12
- '''
+ """
while q != 0:
(p, q) = (q, p % q)
@@ -38,11 +38,11 @@ def gcd(p, q):
def jacobi(a, b):
- '''Calculates the value of the Jacobi symbol (a/b) where both a and b are
+ """Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1
- '''
+ """
assert a > 0
assert b > 0
@@ -51,7 +51,7 @@ def jacobi(a, b):
result = 1
while a > 1:
if a & 1:
- if ((a-1)*(b-1) >> 2) & 1:
+ if ((a - 1) * (b - 1) >> 2) & 1:
result = -result
a, b = b % a, a
else:
@@ -61,10 +61,9 @@ def jacobi(a, b):
if a == 0: return 0
return result
+
def jacobi_witness(x, n):
- '''Returns False if n is an Euler pseudo-prime with base x, and
- True otherwise.
- '''
+ """Returns False if n is an Euler pseudo-prime with base x, and True otherwise."""
j = jacobi(x, n) % n
@@ -73,13 +72,14 @@ def jacobi_witness(x, n):
if j == f: return False
return True
+
def randomized_primality_testing(n, k):
- '''Calculates whether n is composite (which is always correct) or
+ """Calculates whether n is composite (which is always correct) or
prime (which is incorrect with error probability 2**-k)
Returns False if the number is composite, and True if it's
probably prime.
- '''
+ """
# 50% of Jacobi-witnesses can report compositness of non-prime numbers
@@ -92,24 +92,26 @@ def randomized_primality_testing(n, k):
# this means we can use range(k) rather than range(t)
for _ in range(k):
- x = rsa.randnum.randint(n-1)
+ x = rsa.randnum.randint(n - 1)
if jacobi_witness(x, n): return False
-
+
return True
+
def is_prime(number):
- '''Returns True if the number is prime, and False otherwise.
+ """Returns True if the number is prime, and False otherwise.
>>> is_prime(42)
False
>>> is_prime(41)
True
- '''
+ """
return randomized_primality_testing(number, 6)
+
def getprime(nbits):
- '''Returns a prime number that can be stored in 'nbits' bits.
+ """Returns a prime number that can be stored in 'nbits' bits.
>>> p = getprime(128)
>>> is_prime(p-1)
@@ -118,12 +120,11 @@ def getprime(nbits):
True
>>> is_prime(p+1)
False
-
+
>>> from rsa import common
>>> common.bit_size(p) == 128
True
-
- '''
+ """
while True:
integer = rsa.randnum.read_random_int(nbits)
@@ -135,32 +136,33 @@ def getprime(nbits):
if is_prime(integer):
return integer
- # Retry if not prime
+ # Retry if not prime
def are_relatively_prime(a, b):
- '''Returns True if a and b are relatively prime, and False if they
+ """Returns True if a and b are relatively prime, and False if they
are not.
>>> are_relatively_prime(2, 3)
1
>>> are_relatively_prime(2, 4)
0
- '''
+ """
d = gcd(a, b)
- return (d == 1)
-
+ return d == 1
+
+
if __name__ == '__main__':
print('Running doctests 1000x or until failure')
import doctest
-
+
for count in range(1000):
(failures, tests) = doctest.testmod()
if failures:
break
-
+
if count and count % 100 == 0:
print('%i times' % count)
-
+
print('Doctests done')
diff --git a/rsa/randnum.py b/rsa/randnum.py
index 0e78274..2bb5806 100644
--- a/rsa/randnum.py
+++ b/rsa/randnum.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Functions for generating random numbers.'''
+"""Functions for generating random numbers."""
# Source inspired by code by Yesudeep Mangalapilly <yesudeep@gmail.com>
@@ -23,12 +23,13 @@ import os
from rsa import common, transform
from rsa._compat import byte
+
def read_random_bits(nbits):
- '''Reads 'nbits' random bits.
+ """Reads 'nbits' random bits.
If nbits isn't a whole number of bytes, an extra byte will be appended with
only the lower bits set.
- '''
+ """
nbytes, rbits = divmod(nbits, 8)
@@ -45,8 +46,8 @@ def read_random_bits(nbits):
def read_random_int(nbits):
- '''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)
@@ -57,13 +58,14 @@ def read_random_int(nbits):
return value
+
def randint(maxvalue):
- '''Returns a random integer x with 1 <= x <= maxvalue
-
+ """Returns a random integer x with 1 <= x <= maxvalue
+
May take a very long time in specific situations. If maxvalue needs N bits
to store, the closer maxvalue is to (2 ** N) - 1, the faster this function
is.
- '''
+ """
bit_size = common.bit_size(maxvalue)
@@ -81,5 +83,3 @@ def randint(maxvalue):
tries += 1
return value
-
-
diff --git a/rsa/transform.py b/rsa/transform.py
index c740b2d..63cbc14 100644
--- a/rsa/transform.py
+++ b/rsa/transform.py
@@ -14,10 +14,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Data transformation functions.
+"""Data transformation functions.
From bytes to a number, number to bytes, etc.
-'''
+"""
from __future__ import absolute_import
@@ -26,6 +26,7 @@ try:
# Using psyco (if available) cuts down the execution time on Python 2.5
# at least by half.
import psyco
+
psyco.full()
except ImportError:
pass
@@ -37,7 +38,7 @@ from rsa._compat import is_integer, b, byte, get_word_alignment, ZERO_BYTE, EMPT
def bytes2int(raw_bytes):
- r'''Converts a list of bytes or an 8-bit string to an integer.
+ """Converts a list of bytes or an 8-bit string to an integer.
When using unicode strings, encode it to some encoding like UTF8 first.
@@ -46,13 +47,13 @@ def bytes2int(raw_bytes):
>>> bytes2int('\x80@\x0f')
8405007
- '''
+ """
return int(binascii.hexlify(raw_bytes), 16)
def _int2bytes(number, block_size=None):
- r'''Converts a number to a string of bytes.
+ """Converts a number to a string of bytes.
Usage::
@@ -78,11 +79,12 @@ def _int2bytes(number, block_size=None):
@throws OverflowError when block_size is given and the number takes up more
bytes than fit into the block.
- '''
+ """
+
# Type checking
if not is_integer(number):
raise TypeError("You must pass an integer for 'number', not %s" %
- number.__class__)
+ number.__class__)
if number < 0:
raise ValueError('Negative numbers cannot be used: %i' % number)
@@ -99,7 +101,7 @@ def _int2bytes(number, block_size=None):
if block_size and block_size > 0:
if needed_bytes > block_size:
raise OverflowError('Needed %i bytes for number, but block size '
- 'is %i' % (needed_bytes, block_size))
+ 'is %i' % (needed_bytes, block_size))
# Convert the number to bytes.
while number > 0:
@@ -116,7 +118,7 @@ def _int2bytes(number, block_size=None):
def bytes_leading(raw_bytes, needle=ZERO_BYTE):
- '''
+ """
Finds the number of prefixed byte occurrences in the haystack.
Useful when you want to deal with padding.
@@ -127,7 +129,8 @@ def bytes_leading(raw_bytes, needle=ZERO_BYTE):
The byte to count. Default \000.
:returns:
The number of leading needle bytes.
- '''
+ """
+
leading = 0
# Indexing keeps compatibility between Python 2.x and Python 3.x
_byte = needle[0]
@@ -140,7 +143,7 @@ def bytes_leading(raw_bytes, needle=ZERO_BYTE):
def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
- '''
+ """
Convert an unsigned integer to bytes (base-256 representation)::
Does not preserve leading zeros if you don't specify a chunk size or
@@ -172,7 +175,8 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
bytes than fit into the block. This requires the ``overflow``
argument to this function to be set to ``False`` otherwise, no
error will be raised.
- '''
+ """
+
if number < 0:
raise ValueError("Number must be an unsigned integer: %d" % number)
@@ -202,8 +206,8 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
if fill_size and fill_size > 0:
if not overflow and length > fill_size:
raise OverflowError(
- "Need %d bytes for number, but fill size is %d" %
- (length, fill_size)
+ "Need %d bytes for number, but fill size is %d" %
+ (length, fill_size)
)
raw_bytes = raw_bytes.rjust(fill_size, ZERO_BYTE)
elif chunk_size and chunk_size > 0:
@@ -216,5 +220,5 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
if __name__ == '__main__':
import doctest
- doctest.testmod()
+ doctest.testmod()
diff --git a/rsa/util.py b/rsa/util.py
index 5bbb70b..df3f6ef 100644
--- a/rsa/util.py
+++ b/rsa/util.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Utility functions.'''
+"""Utility functions."""
from __future__ import with_statement, print_function
@@ -23,34 +23,35 @@ from optparse import OptionParser
import rsa.key
+
def private_to_public():
- '''Reads a private key and outputs the corresponding public key.'''
+ """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')
+ 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')
+ 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')
+ 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')
+ 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')
+ 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)
+ (cli.infilename, cli.inform), file=sys.stderr)
with open(cli.infilename, 'rb') as infile:
in_data = infile.read()
else:
@@ -60,7 +61,6 @@ def private_to_public():
assert type(in_data) == bytes, type(in_data)
-
# Take the public fields and create a public key
priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform)
pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e)
@@ -70,12 +70,10 @@ def private_to_public():
if cli.outfilename:
print('Writing public key to %s in %s format' % \
- (cli.outfilename, cli.outform), file=sys.stderr)
+ (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'))
-
-
diff --git a/rsa/varblock.py b/rsa/varblock.py
index c7d96ae..ba72bb5 100644
--- a/rsa/varblock.py
+++ b/rsa/varblock.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''VARBLOCK file support
+"""VARBLOCK file support
The VARBLOCK file format is as follows, where || denotes byte concatenation:
@@ -31,16 +31,16 @@ The VARBLOCK file format is as follows, where || denotes byte concatenation:
This file format is called the VARBLOCK format, in line with the varint format
used to denote the block sizes.
-'''
+"""
from rsa._compat import byte, b
-
ZERO_BYTE = b('\x00')
VARBLOCK_VERSION = 1
+
def read_varint(infile):
- '''Reads a varint from the file.
+ """Reads a varint from the file.
When the first byte to be read indicates EOF, (0, 0) is returned. When an
EOF occurs when at least one byte has been read, an EOFError exception is
@@ -49,7 +49,7 @@ def read_varint(infile):
@param infile: the file-like object to read from. It should have a read()
method.
@returns (varint, length), the read varint and the number of read bytes.
- '''
+ """
varint = 0
read_bytes = 0
@@ -58,7 +58,7 @@ def read_varint(infile):
char = infile.read(1)
if len(char) == 0:
if read_bytes == 0:
- return (0, 0)
+ return 0, 0
raise EOFError('EOF while reading varint, value is %i so far' %
varint)
@@ -68,16 +68,16 @@ def read_varint(infile):
read_bytes += 1
if not byte & 0x80:
- return (varint, read_bytes)
+ return varint, read_bytes
def write_varint(outfile, value):
- '''Writes a varint to a file.
+ """Writes a varint to a file.
@param outfile: the file-like object to write to. It should have a write()
method.
@returns the number of written bytes.
- '''
+ """
# there is a big difference between 'write the value 0' (this case) and
# 'there is nothing left to write' (the false-case of the while loop)
@@ -89,7 +89,7 @@ def write_varint(outfile, value):
written_bytes = 0
while value > 0:
to_write = value & 0x7f
- value = value >> 7
+ value >>= 7
if value > 0:
to_write |= 0x80
@@ -101,12 +101,12 @@ def write_varint(outfile, value):
def yield_varblocks(infile):
- '''Generator, yields each block in the input file.
+ """Generator, yields each block in the input file.
@param infile: file to read, is expected to have the VARBLOCK format as
described in the module's docstring.
@yields the contents of each block.
- '''
+ """
# Check the version number
first_char = infile.read(1)
@@ -135,11 +135,11 @@ def yield_varblocks(infile):
def yield_fixedblocks(infile, blocksize):
- '''Generator, yields each block of ``blocksize`` bytes in the input file.
+ """Generator, yields each block of ``blocksize`` bytes in the input file.
:param infile: file to read and separate in blocks.
:returns: a generator that yields the contents of each block
- '''
+ """
while True:
block = infile.read(blocksize)
@@ -152,4 +152,3 @@ def yield_fixedblocks(infile, blocksize):
if read_bytes < blocksize:
break
-
diff --git a/tests/constants.py b/tests/constants.py
index 5eab9f2..9a96774 100644
--- a/tests/constants.py
+++ b/tests/constants.py
@@ -20,4 +20,3 @@ if have_python3:
from py3kconstants import *
else:
from py2kconstants import *
-
diff --git a/tests/test_bigfile.py b/tests/test_bigfile.py
index b45b52f..87d76f6 100644
--- a/tests/test_bigfile.py
+++ b/tests/test_bigfile.py
@@ -14,7 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Tests block operations.'''
+"""Tests block operations."""
+
from rsa._compat import b
try:
@@ -26,10 +27,9 @@ import unittest
import rsa
from rsa import bigfile, varblock, pkcs1
-class BigfileTest(unittest.TestCase):
+class BigfileTest(unittest.TestCase):
def test_encrypt_decrypt_bigfile(self):
-
# Expected block size + 11 bytes padding
pub_key, priv_key = rsa.newkeys((6 + 11) * 8)
@@ -48,16 +48,14 @@ class BigfileTest(unittest.TestCase):
bigfile.decrypt_bigfile(cryptfile, clearfile, priv_key)
self.assertEquals(clearfile.getvalue(), message)
-
+
# We have 2x6 bytes in the message, so that should result in two
# bigfile.
cryptfile.seek(0)
varblocks = list(varblock.yield_varblocks(cryptfile))
self.assertEqual(2, len(varblocks))
-
def test_sign_verify_bigfile(self):
-
# Large enough to store MD5-sum and ASN.1 code for MD5
pub_key, priv_key = rsa.newkeys((34 + 11) * 8)
@@ -72,5 +70,4 @@ class BigfileTest(unittest.TestCase):
# Alter the message, re-check
msgfile = BytesIO(b('123456sybren'))
self.assertRaises(pkcs1.VerificationError,
- pkcs1.verify, msgfile, signature, pub_key)
-
+ pkcs1.verify, msgfile, signature, pub_key)
diff --git a/tests/test_common.py b/tests/test_common.py
index a563d21..131d116 100644
--- a/tests/test_common.py
+++ b/tests/test_common.py
@@ -21,7 +21,7 @@ from rsa._compat import byte, b
from rsa.common import byte_size, bit_size, _bit_size
-class Test_byte(unittest.TestCase):
+class TestByte(unittest.TestCase):
def test_values(self):
self.assertEqual(byte(0), b('\x00'))
self.assertEqual(byte(255), b('\xff'))
@@ -30,7 +30,8 @@ class Test_byte(unittest.TestCase):
self.assertRaises(struct.error, byte, 256)
self.assertRaises(struct.error, byte, -1)
-class Test_byte_size(unittest.TestCase):
+
+class TestByteSize(unittest.TestCase):
def test_values(self):
self.assertEqual(byte_size(1 << 1023), 128)
self.assertEqual(byte_size((1 << 1024) - 1), 128)
@@ -55,7 +56,8 @@ class Test_byte_size(unittest.TestCase):
self.assertRaises(TypeError, byte_size, "")
self.assertRaises(TypeError, byte_size, None)
-class Test_bit_size(unittest.TestCase):
+
+class TestBitSize(unittest.TestCase):
def test_zero(self):
self.assertEqual(bit_size(0), 0)
diff --git a/tests/test_compat.py b/tests/test_compat.py
index 2ab7fd2..fa5e918 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -19,7 +19,8 @@ import struct
from rsa._compat import is_bytes, byte
-class Test_byte(unittest.TestCase):
+
+class TestByte(unittest.TestCase):
def test_byte(self):
for i in range(256):
byt = byte(i)
diff --git a/tests/test_integers.py b/tests/test_integers.py
index 118204a..ad55eed 100644
--- a/tests/test_integers.py
+++ b/tests/test_integers.py
@@ -14,19 +14,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Tests integer operations.'''
+"""Tests integer operations."""
import unittest
+import rsa
import rsa.core
-class IntegerTest(unittest.TestCase):
+class IntegerTest(unittest.TestCase):
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(64)
def test_enc_dec(self):
-
message = 42
print("\tMessage: %d" % message)
@@ -39,14 +39,12 @@ class IntegerTest(unittest.TestCase):
self.assertEqual(message, decrypted)
def test_sign_verify(self):
-
message = 42
- signed = rsa.core.encrypt_int(message,self.priv.d, self.pub.n)
+ signed = rsa.core.encrypt_int(message, self.priv.d, self.pub.n)
print("\tSigned: %d" % signed)
- verified = rsa.core.decrypt_int(signed, self.pub.e,self.pub.n)
+ verified = rsa.core.decrypt_int(signed, self.pub.e, self.pub.n)
print("\tVerified: %d" % verified)
self.assertEqual(message, verified)
-
diff --git a/tests/test_load_save_keys.py b/tests/test_load_save_keys.py
index 6d87cf9..8fc3b22 100644
--- a/tests/test_load_save_keys.py
+++ b/tests/test_load_save_keys.py
@@ -72,10 +72,10 @@ CLEAN_PUBLIC_PEM = b('''\
class DerTest(unittest.TestCase):
- '''Test saving and loading DER keys.'''
+ """Test saving and loading DER keys."""
def test_load_private_key(self):
- '''Test loading private DER keys.'''
+ """Test loading private DER keys."""
key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_DER, 'DER')
expected = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
@@ -83,7 +83,7 @@ class DerTest(unittest.TestCase):
self.assertEqual(expected, key)
def test_save_private_key(self):
- '''Test saving private DER keys.'''
+ """Test saving private DER keys."""
key = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
der = key.save_pkcs1('DER')
@@ -91,7 +91,7 @@ class DerTest(unittest.TestCase):
self.assertEqual(PRIVATE_DER, der)
def test_load_public_key(self):
- '''Test loading public DER keys.'''
+ """Test loading public DER keys."""
key = rsa.key.PublicKey.load_pkcs1(PUBLIC_DER, 'DER')
expected = rsa.key.PublicKey(3727264081, 65537)
@@ -99,19 +99,19 @@ class DerTest(unittest.TestCase):
self.assertEqual(expected, key)
def test_save_public_key(self):
- '''Test saving public DER keys.'''
+ """Test saving public DER keys."""
key = rsa.key.PublicKey(3727264081, 65537)
der = key.save_pkcs1('DER')
self.assertEqual(PUBLIC_DER, der)
-class PemTest(unittest.TestCase):
- '''Test saving and loading PEM keys.'''
+class PemTest(unittest.TestCase):
+ """Test saving and loading PEM keys."""
def test_load_private_key(self):
- '''Test loading private PEM files.'''
+ """Test loading private PEM files."""
key = rsa.key.PrivateKey.load_pkcs1(PRIVATE_PEM, 'PEM')
expected = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
@@ -119,7 +119,7 @@ class PemTest(unittest.TestCase):
self.assertEqual(expected, key)
def test_save_private_key(self):
- '''Test saving private PEM files.'''
+ """Test saving private PEM files."""
key = rsa.key.PrivateKey(3727264081, 65537, 3349121513, 65063, 57287)
pem = key.save_pkcs1('PEM')
@@ -127,7 +127,7 @@ class PemTest(unittest.TestCase):
self.assertEqual(CLEAN_PRIVATE_PEM, pem)
def test_load_public_key(self):
- '''Test loading public PEM files.'''
+ """Test loading public PEM files."""
key = rsa.key.PublicKey.load_pkcs1(PUBLIC_PEM, 'PEM')
expected = rsa.key.PublicKey(3727264081, 65537)
@@ -135,14 +135,13 @@ class PemTest(unittest.TestCase):
self.assertEqual(expected, key)
def test_save_public_key(self):
- '''Test saving public PEM files.'''
+ """Test saving public PEM files."""
key = rsa.key.PublicKey(3727264081, 65537)
pem = key.save_pkcs1('PEM')
self.assertEqual(CLEAN_PUBLIC_PEM, pem)
-
def test_load_from_disk(self):
"""Test loading a PEM file from disk."""
diff --git a/tests/test_pem.py b/tests/test_pem.py
index de1b8a6..ca4278e 100644
--- a/tests/test_pem.py
+++ b/tests/test_pem.py
@@ -20,7 +20,7 @@ from rsa._compat import b
from rsa.pem import _markers
-class Test__markers(unittest.TestCase):
+class TestMarkers(unittest.TestCase):
def test_values(self):
self.assertEqual(_markers('RSA PRIVATE KEY'),
(b('-----BEGIN RSA PRIVATE KEY-----'),
diff --git a/tests/test_pkcs1.py b/tests/test_pkcs1.py
index 7b92197..1bff0fb 100644
--- a/tests/test_pkcs1.py
+++ b/tests/test_pkcs1.py
@@ -14,22 +14,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Tests string operations.'''
+"""Tests string operations."""
import struct
import unittest
import rsa
from rsa import pkcs1
-from rsa._compat import byte, is_integer, b, is_bytes
+from rsa._compat import byte, b, is_bytes
-class BinaryTest(unittest.TestCase):
+class BinaryTest(unittest.TestCase):
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(256)
def test_enc_dec(self):
-
message = struct.pack('>IIII', 0, 0, 0, 1)
print("\tMessage: %r" % message)
@@ -42,7 +41,6 @@ class BinaryTest(unittest.TestCase):
self.assertEqual(message, decrypted)
def test_decoding_failure(self):
-
message = struct.pack('>IIII', 0, 0, 0, 1)
encrypted = pkcs1.encrypt(message, self.pub)
@@ -51,29 +49,29 @@ class BinaryTest(unittest.TestCase):
if is_bytes(a):
a = ord(a)
encrypted = encrypted[:5] + byte(a + 1) + encrypted[6:]
-
+
self.assertRaises(pkcs1.DecryptionError, pkcs1.decrypt, encrypted,
self.priv)
def test_randomness(self):
- '''Encrypting the same message twice should result in different
+ """Encrypting the same message twice should result in different
cryptos.
- '''
-
+ """
+
message = struct.pack('>IIII', 0, 0, 0, 1)
encrypted1 = pkcs1.encrypt(message, self.pub)
encrypted2 = pkcs1.encrypt(message, self.pub)
-
+
self.assertNotEqual(encrypted1, encrypted2)
-class SignatureTest(unittest.TestCase):
+class SignatureTest(unittest.TestCase):
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(512)
def test_sign_verify(self):
- '''Test happy flow of sign and verify'''
-
+ """Test happy flow of sign and verify"""
+
message = b('je moeder')
print("\tMessage: %r" % message)
@@ -83,28 +81,27 @@ class SignatureTest(unittest.TestCase):
self.assertTrue(pkcs1.verify(message, signature, self.pub))
def test_alter_message(self):
- '''Altering the message should let the verification fail.'''
-
+ """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)
def test_sign_different_key(self):
- '''Signing with another key should let the verification fail.'''
-
+ """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)
def test_multiple_signings(self):
- '''Signing the same message twice should return the same signatures.'''
-
+ """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')
-
- self.assertEqual(signature1, signature2)
+ self.assertEqual(signature1, signature2)
diff --git a/tests/test_strings.py b/tests/test_strings.py
index c4ee4c4..541b317 100644
--- a/tests/test_strings.py
+++ b/tests/test_strings.py
@@ -14,7 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Tests string operations.'''
+"""Tests string operations."""
from __future__ import absolute_import
@@ -24,13 +24,12 @@ import rsa
from constants import unicode_string
-class StringTest(unittest.TestCase):
+class StringTest(unittest.TestCase):
def setUp(self):
(self.pub, self.priv) = rsa.newkeys(384)
def test_enc_dec(self):
-
message = unicode_string.encode('utf-8')
print("\tMessage: %s" % message)
@@ -41,4 +40,3 @@ class StringTest(unittest.TestCase):
print("\tDecrypted: %s" % decrypted)
self.assertEqual(message, decrypted)
-
diff --git a/tests/test_varblock.py b/tests/test_varblock.py
index c6f2485..ac482f6 100644
--- a/tests/test_varblock.py
+++ b/tests/test_varblock.py
@@ -14,8 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-'''Tests varblock operations.'''
-
+"""Tests varblock operations."""
try:
from StringIO import StringIO as BytesIO
@@ -23,14 +22,12 @@ except ImportError:
from io import BytesIO
import unittest
-import rsa
from rsa._compat import b
from rsa import varblock
-class VarintTest(unittest.TestCase):
+class VarintTest(unittest.TestCase):
def test_read_varint(self):
-
encoded = b('\xac\x02crummy')
infile = BytesIO(encoded)
@@ -44,7 +41,6 @@ class VarintTest(unittest.TestCase):
self.assertEqual(b('crummy'), infile.read())
def test_read_zero(self):
-
encoded = b('\x00crummy')
infile = BytesIO(encoded)
@@ -58,7 +54,6 @@ class VarintTest(unittest.TestCase):
self.assertEqual(b('crummy'), infile.read())
def test_write_varint(self):
-
expected = b('\xac\x02')
outfile = BytesIO()
@@ -68,9 +63,7 @@ class VarintTest(unittest.TestCase):
self.assertEqual(expected, outfile.getvalue())
self.assertEqual(2, written)
-
def test_write_zero(self):
-
outfile = BytesIO()
written = varblock.write_varint(outfile, 0)
@@ -80,19 +73,16 @@ class VarintTest(unittest.TestCase):
class VarblockTest(unittest.TestCase):
-
def test_yield_varblock(self):
infile = BytesIO(b('\x01\x0512345\x06Sybren'))
varblocks = list(varblock.yield_varblocks(infile))
self.assertEqual([b('12345'), b('Sybren')], varblocks)
-class FixedblockTest(unittest.TestCase):
+class FixedblockTest(unittest.TestCase):
def test_yield_fixedblock(self):
-
infile = BytesIO(b('123456Sybren'))
fixedblocks = list(varblock.yield_fixedblocks(infile, 6))
self.assertEqual([b('123456'), b('Sybren')], fixedblocks)
-